From 34565130e021d61ca9e5e03363a51fdc271366eb Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 19:52:06 +0900 Subject: [PATCH 01/17] =?UTF-8?q?fix!:=20=EC=84=B1=EC=88=99=EB=8F=84=20?= =?UTF-8?q?=EB=A6=AC=EB=B7=B0=EC=9D=98=20High=C2=B7P1=20=EA=B2=B0=ED=95=A8?= =?UTF-8?q?=2019=EA=B1=B4=EC=9D=84=20=EA=B3=A0=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 2026-11-01 성숙도 리뷰에서 High 21건·P1 25건이 나왔다. 결과를 모르는 일을 "확실함"으로 기록했다(발송 중 죽은 알림 재발송, 커밋 중 끊긴 쓰기를 재시도 가능으로 응답, 재시도 가능한 거부를 DEAD로). 중복을 DB가 아니라 코드 순서로 막았다(정산 job, 포스터 제목). 짝 프론트와 wire 계약이 달랐고(처리 중 409, Envelope null), JWT audience 검증이 기본으로 꺼져 있었고, 트레이스가 나가지 않았고, CI가 strict lane 14개를 한 번도 돌리지 않았다. 방법: 발견마다 실패하는 테스트를 먼저 쓰고 고쳤다. 주요 선택: - 알림 attempt는 처음부터 "시작 여부 모름"으로 쓴다(호출 직전 갱신은 쓰기가 하나 늘어 버림). - 정산 job claim은 lease·fence를 갱신하는 UPDATE 한 문장(처리 전체를 트랜잭션으로 감싸는 안은 외부 호출 동안 잠금을 잡아 버림). - 커밋 단계 연결 끊김은 DB_COMPLETION_UNKNOWN(재시도 불가). - 처리 중 409는 retryable=true + Retry-After: 2, Envelope null 필드는 web Jackson mixin으로 생략(shared-contract는 stdlib only). - 트레이싱은 자체 Tracer를 지우고 Boot 4 tracing·OTLP로. - strict lane을 단계에 연결하고 verifyStrictLaneStages가 고아를 막는다. 발견별 RED·GREEN·버린 대안은 리뷰 README 13절 표에 있다. 위험·한계: JWT 모드는 APP_SECURITY_JWT_AUDIENCE가 없으면 기동하지 않는다. 짝 프론트는 409 retryable과 Envelope 키 규칙을 맞춰야 한다. 이 커밋 시점에는 MinIO 공식 이미지가 사라져 MinIO 2 lane이 실패한다 (다음 커밋에서 대체 이미지로 해결). 검증: ci 통과. mainCheck·integrationCheck는 MinIO 2 lane만 실패(이미지 pull 거부). -p optional-platforms ci integrationCheck, performanceCheck, releaseCheck(-PgitRevision) 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 2·13절 BREAKING CHANGE: JWT 모드에서 APP_SECURITY_JWT_AUDIENCE가 필수가 되고 role은 audience client와 realm 것만 읽는다. IDEMPOTENT_IN_FLIGHT가 retryable=true, Retry-After: 2로 바뀌고 Envelope는 null 필드를 보내지 않는다. --- .github/workflows/ci-quality-gates.yml | 6 + .github/workflows/integration-main.yml | 221 ++----- .github/workflows/release.yml | 12 +- docker-compose.infra.yml | 17 +- ...retry-ownership-and-durable-idempotency.md | 20 + docs/adr/ADR-JPA-003-completion-unknown.md | 16 +- docs/capability-status.md | 8 +- docs/httpclient/operations.md | 2 +- docs/jpa/entity-mapping-guide.md | 49 +- docs/jpa/transaction-guide.md | 2 +- docs/messaging/delivery-guarantees.md | 7 +- docs/registries/env-keys.yaml | 5 +- docs/registries/error-codes.yaml | 7 +- .../01-core-and-feature-pattern.md | 490 +++++++++++++++ .../02-inbound-web.md | 420 +++++++++++++ .../03-inbound-realtime-graphql-grpc.md | 434 ++++++++++++++ .../04-persistence.md | 480 +++++++++++++++ .../05-outbound-capabilities.md | 566 ++++++++++++++++++ .../06-messaging.md | 495 +++++++++++++++ .../07-bootstrap-composition-config.md | 422 +++++++++++++ .../08-build-ci-test.md | 389 ++++++++++++ .../09-performance-measurement.md | 556 +++++++++++++++++ .../2026-11-01-maturity-review/README.md | 380 ++++++++++++ docs/runbooks/auth-audience-mismatch.md | 3 +- docs/runbooks/grpc-platform-operations.md | 11 +- docs/runbooks/outbox-dead-letter.md | 11 +- docs/runbooks/outbox-publish-failed.md | 8 +- docs/study/graphql-walkthrough.ko.md | 17 +- docs/web/http-contract.md | 98 +++ docs/web/runbook.md | 6 +- src/README.md | 8 +- src/adapter/inbound/graphql/README.md | 35 ++ .../cost/GraphQlComplexityCalculator.java | 96 ++- .../cost/GraphQlDocumentComplexityScorer.java | 194 ++++-- .../cost/GraphQlFieldCostDescriptor.java | 23 +- .../GraphQlPlatformExecutionPathTest.java | 63 +- .../graphql-platform/platform.graphqls | 8 +- .../GraphQlDocumentComplexityScorerTest.java | 262 ++++++++ src/adapter/inbound/web-advanced/build.gradle | 6 + src/adapter/inbound/web/CLAUDE.md | 5 +- src/adapter/inbound/web/README.md | 31 +- .../inbound/web/auth/JwtDecoderConfig.java | 26 +- .../JwtToAuthenticatedPrincipalConverter.java | 20 +- .../envelope/EnvelopeWireFormatConfig.java | 38 ++ .../WebAdapterAutoConfiguration.java | 7 +- .../WebMethodSecurityAutoConfiguration.java | 25 + .../WebMvcPlatformAutoConfiguration.java | 13 +- .../WebSecurityAutoConfiguration.java | 27 +- .../web/mvc/filter/WebMvcRequestIdFilter.java | 26 +- .../web/observability/RetryAfterAdvisor.java | 3 + .../web/settings/SecuritySettings.java | 30 +- ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../web/auth/JwtDecoderConfigTest.java | 50 +- ...ToAuthenticatedPrincipalConverterTest.java | 63 +- .../web/auth/RedisSessionWebConfigTest.java | 4 +- .../web/auth/SecurityModeWebContractTest.java | 2 + .../web/envelope/EnvelopeBodyAdviceTest.java | 13 +- .../web/envelope/EnvelopeWireShapeTest.java | 195 ++++++ .../IdempotencyExceptionMappingTest.java | 12 +- .../WebAutoConfigurationRegistrationTest.java | 1 + .../mvc/filter/WebMvcRequestIdFilterTest.java | 25 + .../observability/RetryAfterAdvisorTest.java | 10 +- .../web/settings/SecuritySettingsTest.java | 71 ++- .../ContractFixtureApplication.java | 3 +- src/adapter/outbound/cache-redis/README.md | 32 +- .../cache/redis/cache/CacheScripts.java | 99 +++ .../redis/cache/RedisCacheRegionAdapter.java | 121 ++-- .../redis/idempotency/IdempotencyScripts.java | 55 ++ .../RedisIdempotencyStoreAdapter.java | 49 +- .../redis/LiveRedisSemanticPortsTest.java | 124 ++++ .../cache/RedisCacheRegionAdapterTest.java | 117 ++++ .../RedisIdempotencyStoreAdapterTest.java | 110 ++++ src/adapter/outbound/httpclient/README.md | 8 +- src/adapter/outbound/httpclient/build.gradle | 8 + .../ApacheBlockingTransportProvider.java | 3 +- .../DeadlineAwareApacheRequestFactory.java | 34 ++ .../dynamic/DefaultDynamicTargetGateway.java | 1 + .../jdk/DeadlineAwareJdkRequestFactory.java | 44 ++ .../jdk/JdkBlockingTransportProvider.java | 5 +- .../CircuitBreakerStatusPolicy.java | 33 + .../restclient/BlockingAttemptExecutor.java | 110 +++- .../restclient/DefaultGenericHttpGateway.java | 1 + .../httpclient/transport/AttemptDeadline.java | 158 +++++ .../CircuitBreakerStatusPolicyTest.java | 41 ++ .../AttemptDeadlineEnforcementTest.java | 81 +++ .../CircuitBreakerStatusAccountingTest.java | 89 +++ .../transport/AttemptDeadlineTest.java | 96 +++ .../httpclient/testkit/MockHttpServer.java | 15 + src/adapter/outbound/messaging/README.md | 13 +- ...latformIntegrationEventPublishAdapter.java | 14 + ...ormIntegrationEventPublishAdapterTest.java | 45 ++ .../NotificationPlatformWorkerConfig.java | 4 + .../dispatch/ReconciliationJobWorker.java | 14 +- .../dispatch/ReconciliationJobWorkerTest.java | 26 +- src/adapter/outbound/objectstorage/README.md | 27 + .../outbound/objectstorage/build.gradle | 21 +- .../MinioManagedObjectContractTest.java | 5 +- .../MinioManagedObjectFaultTest.java | 15 +- .../qualification/QualificationImages.java | 34 ++ .../minio-provider-evidence.json | 25 - .../MinioQualificationImage.java | 138 +++++ .../MinioQualificationImageTest.java | 105 ++++ .../PinnedImageUnavailableException.java | 9 + .../outbound/persistence-jpa/CLAUDE.md | 8 + .../outbound/persistence-jpa/README.md | 12 +- .../PersistenceExceptionTranslator.java | 76 +++ .../failure/SqlStateErrorMapping.java | 13 + .../failure/StandardSqlStateErrorMapping.java | 13 +- .../PostgreSqlSqlStateErrorMapping.java | 13 + .../error/PostgreSqlFailureClassifier.java | 3 + .../postgresql/error/PostgreSqlState.java | 11 +- .../startup/JpaStartupAutoConfiguration.java | 16 +- .../transaction/SpringTransaction.java | 56 +- .../notification/NotificationFixtures.java | 4 +- .../ReconciliationJobClaimContractTest.java | 257 ++++++++ .../JpaLifecycleAssociationContractTest.java | 29 +- ...ficationBackgroundPassIntegrationTest.java | 96 ++- .../PostgreSqlOptionalStreamLifecycle.java | 4 +- .../PostgreSqlTransactionIntegrationTest.java | 14 +- .../PersistenceExceptionTranslatorTest.java | 115 ++++ .../PostgreSqlSqlStateErrorMappingTest.java | 38 ++ .../PostgreSqlFailureClassifierTest.java | 4 +- .../JpaStartupAutoConfigurationTest.java | 51 ++ .../arch/JpaArchitectureRulesTest.java | 101 ++++ .../entity/InverseCollectionParentEntity.java | 34 ++ .../arch/entity/InverseManyToManyEntity.java | 29 + .../arch/entity/InverseOneToOneEntity.java | 27 + .../arch/entity/OwningChildEntity.java | 35 ++ .../arch/entity/OwningManyToManyEntity.java | 28 + .../arch/entity/OwningOneToOneEntity.java | 30 + .../UnidirectionalCollectionEntity.java | 36 ++ .../transaction/SpringTransactionTest.java | 128 ++++ .../resources/db/applied-migrations.sha256 | 1 + .../testkit/arch/JpaArchitectureRules.java | 28 + .../arch/SingleSidedAssociationCondition.java | 70 +++ .../persistence/testkit/fetch/PagedChild.java | 22 +- .../testkit/fetch/PagedParent.java | 20 +- .../testkit/lifecycle/LifecycleChild.java | 25 +- .../testkit/lifecycle/LifecycleParent.java | 16 +- .../platform/JdbcReconciliationJobStore.java | 69 ++- ...otification_reconciliation_claim_lease.sql | 26 + .../InMemorySemanticRedisCommands.java | 89 +++ .../outbound/support/startup/StartupRule.java | 12 +- .../startup/StartupRuleAutoConfiguration.java | 10 +- .../support/startup/StartupRuleRunner.java | 53 +- .../startup/StartupRuleRunnerTest.java | 30 + src/app-bootstrap/CLAUDE.md | 5 +- src/app-bootstrap/README.md | 8 +- src/app-bootstrap/build.gradle | 4 +- src/app-bootstrap/gradle.lockfile | 5 +- .../JpaProductionArchitectureTest.java | 5 + .../runtime/RuntimeSafetyConfig.java | 4 +- .../src/main/resources/application.yml | 3 +- .../main/resources/config/observability.yml | 10 +- .../src/main/resources/config/security.yml | 3 +- .../composition/TracingExportSystemTest.java | 162 +++++ .../TracingActivationContextTest.java | 6 +- src/application-core/README.md | 36 +- .../IdempotencyInFlightException.java | 5 +- .../outbox/OutboxBackoffPolicy.java | 33 +- .../outbox/OutboxPublishOutcome.java | 26 +- .../outbox/OutboxPublishRefusedException.java | 34 +- .../PublishPendingOutboxEventsUseCase.java | 85 ++- .../outbox/OutboxPublishOutcomeTest.java | 25 +- .../TransientPublishFailureRelayTest.java | 207 +++++++ .../lifecycle/CopyFileApplicationUseCase.java | 149 +++-- .../quota/TransferAdmissionController.java | 12 + .../AppendUploadApplicationUseCase.java | 3 +- .../CreateUploadApplicationUseCase.java | 2 +- .../fileserver/upload/UploadSessions.java | 12 - .../download/DownloadUseCasesTest.java | 25 + .../lifecycle/FileLifecycleUseCasesTest.java | 120 +++- .../testkit/FakeFileAccessPolicy.java | 14 +- .../testkit/FakeFileQuotaService.java | 4 + .../dispatch/DeliveryAttemptFactory.java | 14 +- .../dispatch/LeaseRecoveryService.java | 4 +- .../platform/dispatch/ReconciliationJob.java | 11 +- .../dispatch/ReconciliationJobStorePort.java | 23 +- .../provider/ProviderExecutionEvidence.java | 11 + .../dispatch/DeliveryAttemptFactoryTest.java | 96 +-- .../dispatch/DeliveryAttemptFixtures.java | 101 ++++ .../dispatch/DispatchOutcomeRecorderTest.java | 5 +- .../dispatch/LeaseRecoveryServiceTest.java | 25 + .../dispatch/NotificationPlatformNoops.java | 3 +- src/build-logic/README.md | 1 + src/build-logic/build.gradle | 4 + .../strictlane/StrictLaneStagesExtension.java | 21 + .../strictlane/StrictLaneStagesPlugin.java | 188 ++++++ .../strictlane/WorkflowGradleInvocations.java | 217 +++++++ .../StrictLaneStagesFunctionalTest.java | 188 ++++++ .../WorkflowGradleInvocationsTest.java | 148 +++++ src/build.gradle | 26 + .../FileserverFileUseCaseConfiguration.java | 14 +- src/composition/outbox-relay/README.md | 17 +- src/composition/outbox-relay/build.gradle | 2 + .../outbox/OutboxRelayScheduler.java | 96 ++- .../OutboxRelaySchedulerLoggingTest.java | 4 +- .../outbox/OutboxRelayShutdownOrderTest.java | 197 ++++++ src/composition/service-runtime/README.md | 61 +- src/composition/service-runtime/build.gradle | 8 +- .../service-runtime/gradle.lockfile | 14 + .../tracing/MicrometerActiveTrace.java | 35 ++ .../runtime/tracing/TracingConfig.java | 61 +- .../TracingEnvironmentPostProcessor.java | 74 +++ ...acingSamplingEnvironmentPostProcessor.java | 49 -- .../tracing/TracingSwitchImportFilter.java | 45 ++ .../main/resources/META-INF/spring.factories | 5 +- .../ServiceRuntimeRegistrationTest.java | 23 +- .../tracing/MicrometerActiveTraceTest.java | 68 +++ .../TracingEnvironmentPostProcessorTest.java | 107 ++++ ...gSamplingEnvironmentPostProcessorTest.java | 59 -- .../TracingSwitchImportFilterTest.java | 54 ++ src/config/jpa/readiness-cards.yaml | 2 +- src/grpc/CLAUDE.md | 6 + .../grpc/api/ledger/GrpcOperationLedger.java | 30 + .../ledger/GrpcOperationLedgerContract.java | 160 +++++ .../api/ledger/InMemoryOperationLedger.java | 27 +- .../JpaGrpcOperationLedgerContractIT.java | 50 ++ .../ledger/GrpcOperationLedgerRepository.java | 30 + .../grpc/ledger/JpaGrpcOperationLedger.java | 15 + .../GrpcOperationLedgerRepositoryTest.java | 7 + .../GrpcIdempotencyInterceptor.java | 55 +- .../GrpcCompletionReconcilerTest.java | 25 +- .../GrpcIdempotencyInterceptorTest.java | 106 +++- .../kafka/KafkaMessagingTransport.java | 11 +- .../kafka/KafkaPublishFailureClassifier.java | 24 +- .../kafka/KafkaMessagingTransportTest.java | 43 ++ .../KafkaPublishFailureClassifierTest.java | 69 +++ .../runtime/DefaultMessagePublisher.java | 12 +- .../runtime/DefaultMessagePublisherTest.java | 31 + src/sample-portfolio/README.md | 68 ++- src/sample-portfolio/build.gradle | 4 +- src/sample-portfolio/gradle.lockfile | 41 +- ...osterRepositoryAdapterIntegrationTest.java | 19 + ...reatePosterConcurrencyIntegrationTest.java | 182 ++++++ .../SampleMigrationStreamIsolationTest.java | 4 +- ...TitleUniqueMigrationQualificationTest.java | 113 ++++ .../portfolio/SamplePortfolioApplication.java | 11 +- .../repository/PosterRepositoryAdapter.java | 35 +- .../poster/CreatePosterUseCase.java | 6 + .../security/SampleDemoAccounts.java | 53 ++ .../security/SampleDemoSecurityConfig.java | 69 +++ .../SamplePublicAccessSecurityConfig.java | 30 - .../domain/poster/PosterRepository.java | 7 + .../V8_1__poster_title_unique.sql | 31 + .../SampleWorkLogAuthorizationSystemTest.java | 165 +++++ .../architecture/SampleArchitectureTest.java | 11 + ...java => SampleDemoSecurityConfigTest.java} | 60 +- src/shared-contract/README.md | 16 +- .../shared/error/OperationalError.java | 2 +- .../caskeleton/shared/response/Envelope.java | 3 +- .../shared/tracing/ActiveTrace.java | 25 + .../shared/error/OperationalErrorTest.java | 10 +- 253 files changed, 13849 insertions(+), 1140 deletions(-) create mode 100644 docs/reviews/2026-11-01-maturity-review/01-core-and-feature-pattern.md create mode 100644 docs/reviews/2026-11-01-maturity-review/02-inbound-web.md create mode 100644 docs/reviews/2026-11-01-maturity-review/03-inbound-realtime-graphql-grpc.md create mode 100644 docs/reviews/2026-11-01-maturity-review/04-persistence.md create mode 100644 docs/reviews/2026-11-01-maturity-review/05-outbound-capabilities.md create mode 100644 docs/reviews/2026-11-01-maturity-review/06-messaging.md create mode 100644 docs/reviews/2026-11-01-maturity-review/07-bootstrap-composition-config.md create mode 100644 docs/reviews/2026-11-01-maturity-review/08-build-ci-test.md create mode 100644 docs/reviews/2026-11-01-maturity-review/09-performance-measurement.md create mode 100644 docs/reviews/2026-11-01-maturity-review/README.md create mode 100644 docs/web/http-contract.md create mode 100644 src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorerTest.java create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMethodSecurityAutoConfiguration.java create mode 100644 src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/DeadlineAwareApacheRequestFactory.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/CircuitBreakerStatusPolicy.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/CircuitBreakerStatusPolicyTest.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/AttemptDeadlineEnforcementTest.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java create mode 100644 src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/QualificationImages.java delete mode 100644 src/adapter/outbound/objectstorage/src/integrationTest/resources/object-storage/minio-provider-evidence.json create mode 100644 src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioQualificationImage.java create mode 100644 src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioQualificationImageTest.java create mode 100644 src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/PinnedImageUnavailableException.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ReconciliationJobClaimContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseCollectionParentEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseManyToManyEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseOneToOneEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningChildEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningManyToManyEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningOneToOneEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/UnidirectionalCollectionEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java create mode 100644 src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql create mode 100644 src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/TracingExportSystemTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFixtures.java create mode 100644 src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java create mode 100644 src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java create mode 100644 src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java create mode 100644 src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java create mode 100644 src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java create mode 100644 src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java create mode 100644 src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/MicrometerActiveTrace.java create mode 100644 src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessor.java delete mode 100644 src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessor.java create mode 100644 src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSwitchImportFilter.java create mode 100644 src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/MicrometerActiveTraceTest.java create mode 100644 src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessorTest.java delete mode 100644 src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessorTest.java create mode 100644 src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSwitchImportFilterTest.java create mode 100644 src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaMessagingTransportTest.java create mode 100644 src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifierTest.java create mode 100644 src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java create mode 100644 src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterTitleUniqueMigrationQualificationTest.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccounts.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfig.java create mode 100644 src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql create mode 100644 src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java rename src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/{SamplePublicAccessSecurityConfigTest.java => SampleDemoSecurityConfigTest.java} (77%) create mode 100644 src/shared-contract/src/main/java/dev/caskeleton/shared/tracing/ActiveTrace.java diff --git a/.github/workflows/ci-quality-gates.yml b/.github/workflows/ci-quality-gates.yml index 19f23a9e..6c25d1a3 100644 --- a/.github/workflows/ci-quality-gates.yml +++ b/.github/workflows/ci-quality-gates.yml @@ -49,6 +49,12 @@ jobs: - name: Run the pull-request gate working-directory: src run: ./gradlew :ci :verifyDependencyLocks --warning-mode=fail --stacktrace + # Plans every stage (`--dry-run`: nothing executes) and fails when a strict lane is in no stage + # a workflow executes, or a stage is executed by no workflow (review 2026-11-01 08-01). A new + # lane fails here, on its own pull request, instead of running nowhere after it merges. + - name: Require every strict lane to be in an executed stage + working-directory: src + run: ./gradlew :verifyStrictLaneStages --dry-run --stacktrace - name: Verify Compose profile contracts render exactly as declared run: bash scripts/verify-compose-profile-contracts.sh diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml index 004633b3..f8e52026 100644 --- a/.github/workflows/integration-main.yml +++ b/.github/workflows/integration-main.yml @@ -15,11 +15,13 @@ name: integration-main # shared. They now run on every push to main as well as nightly, which is strictly more often # than before. # -# 2. Lanes that were registered in Gradle and invoked by nothing — the MongoDB container lanes and -# app-bootstrap's Testcontainers `integrationTest` — existed, failed closed, and executed in no -# workflow. A lane nobody runs is not coverage; it is a file that looks like coverage. They -# are here rather than in stage 1 because every one of them either starts containers or re-runs -# suites the PR gate already covers, and the pull-request budget is minutes for the whole gate. +# 2. The container-backed lanes, run as the root category aggregates `:integrationCheck` and +# `:performanceCheck` rather than one workflow line per lane. A lane nobody runs is not coverage; +# it is a file that looks like coverage — and naming lanes here one by one is how fourteen of +# them came to run nowhere (review 2026-11-01 08-01). The pull-request gate's +# `verifyStrictLaneStages` now fails when a strict lane is in no stage a workflow executes. They +# are here rather than in stage 1 because every one of them starts containers or real servers, +# and the pull-request budget is minutes for the whole gate. # # What is deliberately NOT here: the web "Advanced capability" nightly lane that used to exist as # web-advanced-nightly.yml (websocket-advanced-nightly.yml went with the websocket Advanced code, @@ -78,8 +80,13 @@ jobs: - uses: ./.github/actions/setup-gradle-java - name: Run the main-branch stage working-directory: src - run: ./gradlew :mainCheck --warning-mode=fail --stacktrace + # `--continue`: one failed lane (an external image that cannot be pulled, say) must not stop + # the other main-stage gates from reporting (review 2026-11-01 08-04). + run: ./gradlew :mainCheck --continue --warning-mode=fail --stacktrace + # Storability only: the `--dry-run` below plans `integrationCheck` without running a lane. The + # lanes run in `integration-check`. + # # Two questions. Can every task in the repository-wide gates be *stored* (a property of the task # graph, so `--dry-run` answers it for all of them in seconds)? And is a stored entry *reused* while # the build still executes its work (checked on the two core leaves)? @@ -128,63 +135,71 @@ jobs: exit 1 } - # Load, abuse and graceful shutdown measure behaviour that degrades gradually rather than breaking - # outright — which is exactly the kind of regression a per-PR gate never catches. - web-load-abuse-and-shutdown: + # The integration stage: every integration-category strict lane (`:integrationCheck`). + # + # This job replaced six jobs that named lanes one by one — the MongoDB lanes, app-bootstrap's + # Testcontainers lane, the moved messaging/object-storage/sample contracts, six of the + # persistence-jpa PostgreSQL contracts and the httpclient fault injection. Naming lanes was how + # eleven persistence-jpa readiness lanes ended up running nowhere: a lane added to Gradle without a + # workflow line was declared, failed closed, and executed on no machine (review 2026-11-01 08-01). + # The aggregate is the list now. A lane joins it by declaring `integration()`, and the root + # `verifyStrictLaneStages` (pull-request gate) fails when a strict lane is in no stage a workflow + # executes. + # + # `--continue` so that one red lane does not hide the others: every failed lane is named in the + # same run. Lanes that need an input this job does not have (the Redis topology coordinates, the + # protected AWS sandbox) are `explicitOnly`; the aggregate prints which ones it left out. + # The container lanes take the build-wide `exclusiveRealServerLane` slot one at a time, so the + # job's length is the sum of the lanes. Split the aggregate across jobs when it outgrows its + # timeout rather than going back to naming lanes. + integration-check: runs-on: ubuntu-latest - timeout-minutes: 60 + timeout-minutes: 240 + env: + # Reuse would hand the failover lane a replica set another lane had already faulted. + TESTCONTAINERS_REUSE_ENABLE: "false" steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java - - name: Run the load, abuse and shutdown lanes on every container + - name: Run every integration-category strict lane working-directory: src - run: >- - ./gradlew - :adapter:inbound:web:test - :adapter:inbound:web:webJettyCompatTest - - --stacktrace - - name: Publish the test reports + run: ./gradlew :integrationCheck --continue --stacktrace + - name: Publish the integration lane reports if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 with: - name: web-integration-reports - path: src/adapter/inbound/web/build/reports/tests/ + name: integration-check-reports + path: src/**/build/reports/tests/ if-no-files-found: warn - # Needs a container runtime and real time (design §29). Separated from the per-PR gate rather than - # made optional inside it: a lane that cannot run here fails, it does not skip. - httpclient-fault-injection: + # The performance stage: every performance-category strict lane (`:performanceCheck`) — Tomcat and + # Jetty load, slow-client and graceful shutdown, the Hikari pool contract, the httpclient pool, + # streaming, retry and rotation bounds, the MongoDB resource budget. They measure behaviour that + # degrades gradually rather than breaking outright, which is the kind of regression a per-PR gate + # never catches. This job replaced `web-load-abuse-and-shutdown`, which despite its name ran + # `:adapter:inbound:web:test` and `webJettyCompatTest` — two lanes the pull-request and main stages + # already run — and never the load lanes (review 2026-11-01 08-01), and `httpclient-performance`. + performance-check: runs-on: ubuntu-latest - timeout-minutes: 45 - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Inject TCP faults against a real upstream - working-directory: src - run: >- - ./gradlew - :adapter:outbound:httpclient:httpClientFailureInjectionTest - - --stacktrace - - httpclient-performance: - runs-on: ubuntu-latest - timeout-minutes: 45 + timeout-minutes: 120 env: # A project property rather than a command-line flag, so the run command stays a plain, # verifiable task invocation while the machine-dependent bounds are still asserted. GRADLE_OPTS: -Dorg.gradle.project.performance.assertions.enabled=true + TESTCONTAINERS_REUSE_ENABLE: "false" steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java - - name: Certify pool, streaming, retry, and rotation bounds + - name: Run every performance-category strict lane working-directory: src - run: >- - ./gradlew - :adapter:outbound:httpclient:httpClientPerformanceTest - - --stacktrace + run: ./gradlew :performanceCheck --continue --stacktrace + - name: Publish the performance lane reports + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 + with: + name: performance-check-reports + path: src/**/build/reports/tests/ + if-no-files-found: warn httpclient-http3-experimental: runs-on: ubuntu-latest @@ -198,123 +213,7 @@ jobs: - uses: ./.github/actions/setup-gradle-java - name: Exercise the experimental HTTP/3 opt-in working-directory: src - run: >- - ./gradlew - :adapter:outbound:httpclient:test - -Phttp3.tests.enabled=true - - --stacktrace - - # The six Docker-backed MongoDB lanes. Until now they ran in no workflow at all: the leaf excludes - # every one of their tags from `test` (build.gradle "Docker-backed lanes are excluded from the - # default unit run"), `check` gains only the hermetic `mongoStableContractTest`, and the only thing - # that named them was scripts/verify-mongodb-platform.sh, which nothing in .github invokes. Six - # lanes that fail closed without Docker, and no machine with Docker was ever asked to run them. - # - # Stage 2 rather than stage 1 because each lane starts real MongoDB containers — mongo:8.0.16, - # mongo:7.0.28 and a Toxiproxy in front of a three-node replica set. That is minutes per lane, and - # the pull-request budget is minutes for the whole gate. - # - # One single-line `./gradlew ` step per lane, not one folded command running six, because - # These command lines name each lane explicitly so that a lane which stops being invoked is - # actually executed — a folded command would leave six matrix rows unverifiable. It also means a - # red replica-set lane does not hide the compatibility lane behind it. - mongo-container-lanes: - runs-on: ubuntu-latest - timeout-minutes: 90 - env: - # Reuse would hand the failover lane a replica set another lane had already faulted. - TESTCONTAINERS_REUSE_ENABLE: "false" - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Single-node replica set contract lane - working-directory: src - run: ./gradlew :adapter:outbound:persistence-mongo:mongoReplicaSetTest --stacktrace - - name: Run MongoDB integration lanes - working-directory: src - run: >- - ./gradlew - :adapter:outbound:persistence-mongo:mongoReplicaSetTest - :adapter:outbound:persistence-mongo:mongoFailoverTest - :adapter:outbound:persistence-mongo:mongoMigrationTest - :adapter:outbound:persistence-mongo:mongoCompatibilityTest - :adapter:outbound:persistence-mongo:mongoSecurityIntegrationTest - :adapter:outbound:persistence-mongo:mongoPerformanceTest - --stacktrace - - name: Publish the MongoDB lane reports - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 - with: - name: mongo-lane-reports - path: src/adapter/outbound/persistence-mongo/build/reports/tests/ - if-no-files-found: warn - - # app-bootstrap's Testcontainers lane. The leaf gave it a source set of its own precisely so that - # `./gradlew :app-bootstrap:test` would not require a Docker daemon — and the consequence nobody - # closed is that a source set outside `test` is also outside `check`, so the real-PostgreSQL - # outbox and idempotency contracts compiled on every build and executed on none. - bootstrap-integration: - runs-on: ubuntu-latest - timeout-minutes: 45 - env: - TESTCONTAINERS_REUSE_ENABLE: "false" - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Run the real-PostgreSQL integration contracts - working-directory: src - run: ./gradlew :app-bootstrap:integrationTest --stacktrace - - # Container contracts moved out of the default `test` source sets must remain executed after the - # ownership split. One step per lane keeps a failure attributable to the capability that broke. - moved-container-contracts: - runs-on: ubuntu-latest - timeout-minutes: 90 - env: - TESTCONTAINERS_REUSE_ENABLE: "false" - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Messaging outbox, inbox and admin-journal PostgreSQL contracts - working-directory: src - run: ./gradlew :messaging:messaging-reliability-jdbc-postgresql:integrationTest --stacktrace - - name: Messaging starter Kafka round trip - working-directory: src - run: ./gradlew :messaging:messaging-spring-boot-starter:integrationTest --stacktrace - - name: Object storage MinIO contract - working-directory: src - run: ./gradlew :adapter:outbound:objectstorage:integrationTest --stacktrace - - name: Standalone sample PostgreSQL contract - working-directory: src - run: ./gradlew :sample-portfolio:integrationTestLaneCheck --stacktrace - - # These six PostgreSQL contracts moved from app-bootstrap into persistence-jpa. They are named - # directly instead of relying on readiness-card membership: provider ownership and evidence - # grading are different questions, and CI execution must not disappear when a card changes. - jpa-provider-ownership-contracts: - runs-on: ubuntu-latest - timeout-minutes: 90 - env: - TESTCONTAINERS_REUSE_ENABLE: "false" - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Distributed lock contract - working-directory: src - run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlDistributedLockIntegrationTest --stacktrace - - name: Integer lock migration compatibility - working-directory: src - run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlIntLockMigrationCompatibilityIntegrationTest --stacktrace - - name: Outbox transactional append - working-directory: src - run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxAppendTransactionalIntegrationTest --stacktrace - - name: Outbox concurrent relay - working-directory: src - run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxConcurrentRelayIntegrationTest --stacktrace - - name: Outbox row lifecycle - working-directory: src - run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxRowLifecycleIntegrationTest --stacktrace + run: ./gradlew :adapter:outbound:httpclient:test -Phttp3.tests.enabled=true --stacktrace # The optional gRPC platform build declares one strict INTEGRATION lane — # `grpc-operation-ledger-jpa:integrationTest`, which certifies the atomic diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5f0cc963..751fba40 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -139,12 +139,22 @@ jobs: :grpc:grpc-testkit:grpcNettyContractTest :grpc:grpc-testkit:grpcFaultTest --stacktrace + # The operation ledger's real-PostgreSQL lane ran only on main and nightly + # (integration-main.yml), so a tag could be cut from a main whose ledger lane was red. It needs + # Docker, which a release runner has (review 2026-11-01 03-12). + - name: Certify the gRPC operation ledger against real PostgreSQL + working-directory: src + env: + TESTCONTAINERS_REUSE_ENABLE: "false" + run: ./gradlew -p optional-platforms integrationCheck --stacktrace - name: Publish the gRPC release evidence if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 with: name: grpc-release-evidence - path: src/grpc/grpc-testkit/build/reports/tests/ + path: | + src/grpc/grpc-testkit/build/reports/tests/ + src/grpc/grpc-operation-ledger-jpa/build/reports/tests/ if-no-files-found: warn # Each gate runs as its own single-line `./gradlew ` step so that a failure names the gate diff --git a/docker-compose.infra.yml b/docker-compose.infra.yml index ccf966a8..218bb48b 100644 --- a/docker-compose.infra.yml +++ b/docker-compose.infra.yml @@ -11,6 +11,19 @@ # checks this file against them. # ============================================================================= +# The local MinIO runtime, used by the server and by the object-storage smoke client below. +# +# It is deliberately not the image the MinIO qualification lanes run. Those read their image from +# src/adapter/outbound/objectstorage/src/test/resources/object-storage/minio-provider-evidence.json, +# whose digest is the release the recorded findings (status UNSUPPORTED, the excluded create-only +# profiles) were measured on. This one is a later release because the healthcheck runs `mc ready` +# and the smoke script runs the bundled mc, and moving it onto the evidence release is unverified. +# A local runtime is not evidence, so the two may differ; they must not be mistaken for each other. +# +# Both come from Docker Hub's minio/minio, which stopped serving it (review 05-09). LOCAL_MINIO_IMAGE +# points this runtime at a mirror; the lanes take OBJECT_STORAGE_MINIO_IMAGE, digest-checked. +x-local-minio-image: &local-minio-image "${LOCAL_MINIO_IMAGE:-minio/minio:RELEASE.2024-09-13T20-26-02Z}" + services: # ---- PostgreSQL -------------------------------------------------------------- db: @@ -180,7 +193,7 @@ services: profiles: - shared-infra - prod-smoke - image: minio/minio:RELEASE.2024-09-13T20-26-02Z + image: *local-minio-image command: ["server", "/data"] environment: MINIO_ROOT_USER: "${MINIO_ROOT_USER:-caskeleton}" @@ -422,7 +435,7 @@ services: profiles: - shared-infra - prod-smoke - image: minio/minio:RELEASE.2024-09-13T20-26-02Z + image: *local-minio-image depends_on: minio-init: condition: service_completed_successfully diff --git a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md index a7e2ebfd..deb788bd 100644 --- a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md +++ b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md @@ -47,6 +47,26 @@ retries when everything is failing, which is the behaviour that lets a dependenc transaction annotations, deliberately: a `REQUIRES_NEW` would put the claim in its own transaction and reintroduce the window where the write is durable and the claim is not. +**A claim expires instead of blocking its key forever** (review 2026-11-01, 03-10). A claim still +`IN_PROGRESS` after the claim TTL is presumed abandoned by a dead owner, and the next retry of the same +request takes it over with `GrpcOperationLedger.reclaimStale` — one conditional +`UPDATE … WHERE state = 'IN_PROGRESS' AND claimed_at < :cutoff`, so of two concurrent takeovers exactly +one wins, the same shape as `reclaimFailed`. The TTL is the `claimTtl` argument of +`GrpcIdempotencyInterceptor`, refused at construction when it is not longer than every keyed method's +deadline. It is not a configuration key: the starter does not assemble the interceptor yet (03-11), so +there is nothing for a key to configure. + +The takeover is safe only because the commit is recorded in the mutation's own transaction: then a +claim still `IN_PROGRESS` means the mutation never committed. An adopter that commits them separately +turns an abandoned claim into an unknown outcome, and a takeover can run the mutation twice. A takeover +of an owner that is merely slow does the same, which is why the TTL must exceed the slowest keyed +method and not just its deadline. + +Rejected: an owner token with a heartbeat lease (the outbox lease model) — needed only when a keyed +method can run longer than any fixed TTL; revisit when one exists. A sweeper job that deletes stale +rows — it needs a scheduler this family does not have, and deleting a claim makes the next retry a +fresh claim with no record that an attempt was abandoned. Retention of terminal rows is still open. + **A key reused for a different request is a caller error, not a duplicate.** The stored request fingerprint turns that into `FAILED_PRECONDITION` rather than silently returning the first request's answer. diff --git a/docs/adr/ADR-JPA-003-completion-unknown.md b/docs/adr/ADR-JPA-003-completion-unknown.md index b78a0d25..4c1d5b1e 100644 --- a/docs/adr/ADR-JPA-003-completion-unknown.md +++ b/docs/adr/ADR-JPA-003-completion-unknown.md @@ -39,6 +39,16 @@ which idempotency record, business row, or outbox entry proves the write happene ## Enforcement -`JpaFailureContextTest`; -`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried` -(also the `jpa-failure` lane, i.e. release gate `completion-unknown-no-retry`). +Production path: `SpringTransaction` records when the action has returned in a write transaction it +began; a failure after that point goes through +`PersistenceExceptionTranslator#translateCommitFailure`, which builds this exception for `08*`, +`40003`, a vendor termination state (`SqlStateErrorMapping#commitOutcomeUnknownStates`, PostgreSQL +`57P01`/`57P02`) or a transport break. Hibernate's flush inside the commit is not separated from the +COMMIT itself, so a connection lost during that flush is also reported as unknown — the safe side. +Until review 04-01 (2026-11-01) nothing constructed the exception and a commit-phase `08*` reached +callers as the retryable `DB_UNAVAILABLE`. + +`JpaFailureContextTest`; `SpringTransactionTest`; `PersistenceExceptionTranslatorTest`; +`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried` +(asserts `DB_COMPLETION_UNKNOWN`; also the `jpa-failure` lane, i.e. release gate +`completion-unknown-no-retry`). diff --git a/docs/capability-status.md b/docs/capability-status.md index e3dcd686..1ad7bc5f 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -27,15 +27,15 @@ lanes and CI; it is not a deployment artifact. | Capability | Enabled key (property / env, default) | IMPLEMENTED | WIRED | QUALIFIED | Evidence | | --- | --- | --- | --- | --- | --- | -| Relational persistence (JPA/PostgreSQL) | `ca-skeleton.persistence-jpa.enabled` / `APP_PERSISTENCE_JPA_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-jpa')`) | yes | Not in the default composition. The one line brings everything — its own `AutoConfiguration.imports` (`PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig`, `JpaStartupAutoConfiguration`), its environment handling (`JpaActivationEnvironmentPostProcessor`, `spring.factories`: readiness `db` while on; with `false` it also excludes Boot's JDBC, Hibernate, Spring Data JPA and Flyway auto-configuration, so no DataSource is bound), the startup guards (Flyway strategy, datasource/OSIV/DDL/pool/TLS/vendor checks, exit codes unchanged) and its settings (`config/module-defaults/persistence-jpa.yml`). `persistence-jpa:PersistenceJpaCapabilityAssemblyTest` proves the module assembles on its own; six `postgresql*IntegrationTest` lanes, run by `integration-main.yml` → `jpa-provider-ownership-contracts`, qualify it against PostgreSQL. `sample-portfolio` selects it by its build dependency and the module's auto-configuration (no broad scan of the persistence package). `bootRunH2` adds the module to its own classpath only. | -| Document persistence (MongoDB) | `ca-skeleton.persistence-mongo.enabled` / `APP_PERSISTENCE_MONGO_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-mongo')`) | yes | On when present; `false` also excludes Boot's Mongo auto-configuration (`MongoCapabilityActivationTest`). The connection-source rule (`SPRING_MONGODB_URI` or the selected profile's `uri-secret`) is checked by the module's own `MongoDefaultsEnvironmentPostProcessor`. Six container lanes (`mongoReplicaSetTest`, `mongoFailoverTest`, …), run by `integration-main.yml` → `mongo-container-lanes` | +| Relational persistence (JPA/PostgreSQL) | `ca-skeleton.persistence-jpa.enabled` / `APP_PERSISTENCE_JPA_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-jpa')`) | yes | Not in the default composition. The one line brings everything — its own `AutoConfiguration.imports` (`PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig`, `JpaStartupAutoConfiguration`), its environment handling (`JpaActivationEnvironmentPostProcessor`, `spring.factories`: readiness `db` while on; with `false` it also excludes Boot's JDBC, Hibernate, Spring Data JPA and Flyway auto-configuration, so no DataSource is bound), the startup guards (Flyway strategy, datasource/OSIV/DDL/pool/TLS/vendor checks, exit codes unchanged) and its settings (`config/module-defaults/persistence-jpa.yml`). `persistence-jpa:PersistenceJpaCapabilityAssemblyTest` proves the module assembles on its own; the `postgresql*IntegrationTest` readiness lanes, run by `integration-main.yml` → `integration-check` (`:integrationCheck`), qualify it against PostgreSQL. `sample-portfolio` selects it by its build dependency and the module's auto-configuration (no broad scan of the persistence package). `bootRunH2` adds the module to its own classpath only. | +| Document persistence (MongoDB) | `ca-skeleton.persistence-mongo.enabled` / `APP_PERSISTENCE_MONGO_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-mongo')`) | yes | On when present; `false` also excludes Boot's Mongo auto-configuration (`MongoCapabilityActivationTest`). The connection-source rule (`SPRING_MONGODB_URI` or the selected profile's `uri-secret`) is checked by the module's own `MongoDefaultsEnvironmentPostProcessor`. Six container lanes (`mongoReplicaSetTest`, `mongoFailoverTest`, …), run by `integration-main.yml` → `integration-check` (`:integrationCheck`) | | Messaging (Kafka) | `app.messaging.enabled` / `APP_MESSAGING_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:messaging-kafka')`, which brings the application bridge, the legacy `KafkaSender` seam and the vendored platform with its Kafka transport) | Kafka only | On when present (`KafkaCapabilityActivationTest`). `messaging-kafka:messagingCertificationTest` behind `verifyMessagingCertificationEvidence`, run by `messaging-certification.yml`; the starter's `integrationTest` is the live Kafka round trip. Kafka is the only registered broker; the RabbitMQ broker keys were removed (no transport). | | Redis capabilities (cache / rate-limit / lease / idempotency) | `app.redis.enabled` / `APP_REDIS_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:cache-redis')`, which brings `redis-runtime`) | yes | `cache-redis:redisTopologyTest`, run by `redis-sdk-topology.yml`. Not in the default composition. On when present; `false` contributes no Redis bean — no settings, client, connection, thread or health contributor. The module owns its readiness contribution (`RedisReadinessGroupPostProcessor`, `spring.factories`) and its settings (`config/module-defaults/cache-redis.yml`: `app.redis.enabled`, `app.rate-limit.*`, the Redis `ca-skeleton.capabilities.*`). No `app-bootstrap` main source names a Redis type. | | Request idempotency | `APP_IDEMPOTENCY_PROVIDER` (`disabled` \| `redis` \| `postgresql`; a selector, not an on/off key) | yes | yes | Redis only | One generation: the application `IdempotencyExecutor`, built once by `app-bootstrap` `IdempotencyProviderSelectionConfig` over the one store the selected provider contributes (`cache-redis` or `persistence-jpa`); startup is refused unless exactly one store exists. `sample-portfolio` cannot depend on `app-bootstrap`, so its own `SampleIdempotencyConfig` builds its one executor from the same keys. Redis is covered by the row above. PostgreSQL has `persistence-jpa:postgresqlIdempotencyIntegrationTest`, but no workflow runs it. The `postgresql` provider refuses a non-PostgreSQL data source, so `bootRunH2` uses `disabled` or `redis`.. The executor stays in the composition root on purpose — it needs only application-core and its settings — while each store comes with its module: `postgresql` needs the persistence-jpa line, `redis` the cache-redis one. | | Transactional outbox relay | `ca-skeleton.outbox.enabled` / `APP_OUTBOX_ENABLED`, `false` (+ `APP_OUTBOX_RELAY_ENABLED`, `false`; persistence-jpa settings) | yes | yes (with the persistence-jpa line; the scheduler also needs the messaging-kafka line) | yes | The store and its settings are persistence-jpa's; the relay (`OutboxConfig`) is application composition in `app-bootstrap` because a driven adapter must not build or call a use case. It turns on only when an `OutboxStorePort` bean exists, and the scheduler only when an `OutboxMessagePublishPort` does (the messaging bridge), each ordered after its contributor by `afterName` — so an environment with no publisher keeps its PENDING rows. The bridge registers no stand-in publisher: a present-and-enabled bridge with a blank broker and no canonical transport is refused at startup. `postgresqlLegacyOutboxConcurrentRelayIntegrationTest` qualifies claim/fencing against PostgreSQL. | | Notification platform | `ca-skeleton.notification.platform.enabled` / `APP_NOTIFICATION_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:notification-platform')`, plus the persistence-jpa line) | claim-scoped | Not in the default composition. The one line brings the use-case assembly, `adapter:outbound:notification`, the HTTP surface `adapter:inbound:web-notification` and its own settings (`config/module-defaults/notification.yml`), each registered through the module's own `AutoConfiguration.imports`; `adapter:inbound:web` no longer depends on `application-notification`. `verifyNotificationEvidence` refuses a grade in `docs/notification/support-matrix.md` that no proven claim backs; run by `notification-platform.yml`. There is no real-SMTP lane, and the matrix says so rather than implying one. | -| File server platform | `app.fileserver-platform.enabled` / `APP_FILESERVER_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:fileserver-platform')`, plus the persistence-jpa line) | yes | On when present; module-owned `config/module-defaults/fileserver.yml` also carries the servlet multipart ceiling. `app-bootstrap:integrationTest` → `FileserverCompositionIntegrationTest` (required by the strict lane), run by `integration-main.yml` → `bootstrap-integration` | -| Outbound HTTP client | `app.httpclient.enabled` / `APP_HTTPCLIENT_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:httpclient')`) | yes | On when present (`HttpClientPlatformActivationTest`). `httpclient:httpClientFailureInjectionTest` against a faulted upstream, run by `integration-main.yml` → `httpclient-fault-injection` | +| File server platform | `app.fileserver-platform.enabled` / `APP_FILESERVER_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:fileserver-platform')`, plus the persistence-jpa line) | yes | On when present; module-owned `config/module-defaults/fileserver.yml` also carries the servlet multipart ceiling. `app-bootstrap:integrationTest` → `FileserverCompositionIntegrationTest` (required by the strict lane), run by `integration-main.yml` → `integration-check` (`:integrationCheck`) | +| Outbound HTTP client | `app.httpclient.enabled` / `APP_HTTPCLIENT_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:httpclient')`) | yes | On when present (`HttpClientPlatformActivationTest`). `httpclient:httpClientFailureInjectionTest` against a faulted upstream, run by `integration-main.yml` → `integration-check` (`:integrationCheck`) | | GraphQL transport | `backend.graphql.enabled` / `APP_GRAPHQL_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:graphql')`) | leaf-level | On when present; `false` also excludes Spring GraphQL's own auto-configuration, so no `/graphql` (`GraphQlCapabilityActivationTest`). `graphqlTransportQualificationTest` runs the HTTP boundary. The deployment-mode/runtime-profile rule is the module's own `GraphQlPlatformStartupValidator`. The default jar does not ship GraphQL, so a compose lane that exercises it runs the qualification jar. | | Object storage | `app.object-storage.enabled` (no `APP_*` row), `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:objectstorage')`) | MinIO only | Own `ObjectStorageAutoConfiguration` (was bound through bootstrap's properties scan); on when present, `false` leaves only the explicit legacy seam (`ObjectStorageAutoConfigurationTest`). `app-bootstrap:integrationTest` assembles it against digest-pinned MinIO. | | gRPC platform | — (build-level) | yes | **no** | yes | Absent from the main build entirely: `optional-platforms` is a separate Gradle build, so the switch is the `include`, not an environment variable. `-p optional-platforms ci` runs on every PR and `integrationCheck` certifies the operation ledger against real PostgreSQL. | diff --git a/docs/httpclient/operations.md b/docs/httpclient/operations.md index f735e861..b4bfc59d 100644 --- a/docs/httpclient/operations.md +++ b/docs/httpclient/operations.md @@ -36,7 +36,7 @@ diverge, retries are absorbing failures — which is the first thing to look at | logical calls fine, attempts spiking | upstream degraded, retries absorbing it | `http.client.retry.count` by reason | | `http.client.ambiguous` non-zero | non-idempotent writes reaching `SENT_NO_RESPONSE` | reconcile with the upstream; consider an idempotency key | | pool pending climbing | pool too small or upstream slow | `http.client.pool.acquire.duration`, `pool.connections` | -| circuit open | sustained upstream failure | `http.client.circuit.state`; local rejections do not open it | +| circuit open | sustained upstream failure: transport errors, 5xx, 408, 429 | `http.client.circuit.state`; local rejections and other 4xx do not open it | | `http.client.ssrf.rejected` non-zero | a caller is submitting internal URLs | Dynamic Target policy and audit trail | ## Actuator diff --git a/docs/jpa/entity-mapping-guide.md b/docs/jpa/entity-mapping-guide.md index 61a00665..9aec101d 100644 --- a/docs/jpa/entity-mapping-guide.md +++ b/docs/jpa/entity-mapping-guide.md @@ -49,12 +49,49 @@ never stays in cache and write amplification grows with the table. ## Associations -- To-one associations are `LAZY`. JPA's default is `EAGER`, which means every query that loads a - child also queries for its parent — the most common accidental N+1 in a JPA application. -- The owning side holds the foreign key. Adding to the inverse collection alone leaves the row - unlinked, so aggregates expose an association helper that sets both sides. -- `CascadeType.ALL` with `orphanRemoval` is correct only for a child the aggregate genuinely owns. - Between independent aggregates it deletes rows another part of the system still owns. +Map each association from **one side only**. A JPA association between two entities is one foreign +key column. A bidirectional pair (`@ManyToOne` on the child plus `@OneToMany(mappedBy = ...)` on +the parent) stores that one column in two Java fields, and JPA writes only the owning one. The pair +stays consistent only while every caller remembers to update both fields, and nothing fails when +someone forgets. + +What to use, in order of preference: + +1. **An ID reference between aggregates.** Hold the other aggregate's identifier as a plain column + (`UUID ownerId`). This is what every production entity in the template does today. Loading the + other aggregate is an explicit repository call, so a cross-aggregate load is visible in the code. +2. **A unidirectional `@ManyToOne` inside one aggregate**, always `fetch = FetchType.LAZY`. JPA's + default for a to-one association is `EAGER`, so every query that loads a child also queries for + its parent — the most common accidental N+1 in a JPA application. +3. **A collection is a query, not a field.** "The children of X" is a repository method + (`findByParentId`, or a fetch-join or projection query that pages in SQL). The query states its + own fetch plan and page, where a mapped collection hides both. +4. **Values the aggregate owns** — a list of tags, a set of codes — are `@ElementCollection` + (`LAZY`), not entities. + +A unidirectional `@OneToMany` with its own `@JoinColumn` is the exception, not the default. Use it +only for child entities the root genuinely owns and changes only through itself (the testkit's +`LifecycleParent` and `PagedParent` are this shape). It still costs an `UPDATE` per child when the +join column is nullable, and the collection still loads as a unit. + +`CascadeType.ALL` with `orphanRemoval` is correct only for a child the aggregate genuinely owns. +Between independent aggregates it deletes rows another part of the system still owns — another +reason those are ID references. + +`JpaArchitectureRules.associationsAreMappedFromOneSideOnly()` (testkit) fails the build on any +`@OneToMany`, `@OneToOne` or `@ManyToMany` that declares `mappedBy`, on `@Entity`, +`@MappedSuperclass` and `@Embeddable` types. `JpaProductionArchitectureTest` (app-bootstrap +`architectureTest`) runs it over the production graph and `SampleArchitectureTest` over the sample. +The failure message names the field and these alternatives. + +Chosen and rejected: + +| Option | Decision | Why | +| --- | --- | --- | +| One side only (ID reference, unidirectional `@ManyToOne`, collection by query), enforced by ArchUnit | Chosen | The link lives in one field, so there is nothing to keep in step. The rule turns a developer-memory convention into a build failure | +| Bidirectional with `mappedBy` and an `addChild`/`removeChild` helper that sets both sides | Rejected | The helper is the only thing keeping the two fields in step, and it must be remembered by every caller, every serializer (cycles in `toString`/JSON) and every cascade decision. A missed update leaves a row unlinked or a graph that disagrees with the database, with no error | +| Ban `@OneToMany` entirely | Rejected for now | It also bans a root-owned child collection, which has no second field to forget. Revisit if a real need for child entities that are read or changed on their own appears — that need is a sign they are a separate aggregate | +| Document only | Rejected | A convention the build does not check is invisible where the mapping is written, and the next copy of the template inherits whatever the examples show | ## Entities never leave the transaction diff --git a/docs/jpa/transaction-guide.md b/docs/jpa/transaction-guide.md index 2b7d6f71..747931c8 100644 --- a/docs/jpa/transaction-guide.md +++ b/docs/jpa/transaction-guide.md @@ -45,7 +45,7 @@ A connection can break while a commit is in flight; the server may have committe acknowledgement was lost. `TransactionCompletionUnknownException` is never retried, and the type system enforces it: `JpaFailureContext` refuses to represent a retryable completion-unknown failure. The port itself retries nothing, so such a commit surfaces to the caller as a failure exactly once -(`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried`). +(`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried`). Recovery is reconciliation, not retry: diff --git a/docs/messaging/delivery-guarantees.md b/docs/messaging/delivery-guarantees.md index 518aa3e2..d9809328 100644 --- a/docs/messaging/delivery-guarantees.md +++ b/docs/messaging/delivery-guarantees.md @@ -19,7 +19,12 @@ public enum PublishCompletion { CONFIRMED, REJECTED, AMBIGUOUS } ``` `REJECTED`와 `AMBIGUOUS`를 하나의 "실패"로 합치면 중복 주문이 만들어진다. -전자는 broker가 저장하지 않았음이 **확정**되어 포기해도 안전하고, 후자는 그렇지 않다. +전자는 broker가 저장하지 않았음이 **확정**되어 중복 걱정 없이 다시 보내거나 포기할 수 있고, 후자는 그렇지 않다. + +`REJECTED`가 곧 "포기해도 된다"는 뜻은 아니다. 거부 이유가 그 순간에 속하면(종료 중 +`SHUTTING_DOWN`, permit 대기 초과, `PUBLISH_RUNTIME_UNAVAILABLE`, `KAFKA_TRANSPORT_CLOSED`, Kafka +인증·인가 실패) `failure().retryable()`이 true이고, 호출자는 같은 메시지를 나중에 다시 보내야 한다. +포기해도 되는 것은 `retryable=false`인 거부뿐이다. | 상황 | 결과 | |---|---| diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 612406ac..70a33d25 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -543,6 +543,9 @@ env_keys: - name: OTEL_EXPORTER_OTLP_ENDPOINT # source: feature-distributed-tracing-contract 2026-05-22 # "Micrometer Tracing + OpenTelemetry exporter를 기본 기준으로 둠" + # OTLP base address (OpenTelemetry spec). TracingEnvironmentPostProcessor bridges it to + # management.opentelemetry.tracing.export.otlp.endpoint as /v1/traces (OTLP/HTTP); + # blank = no span exporter bean (review 07-01, 2026-11-01). type: url default: null allowed_values: null @@ -573,7 +576,7 @@ env_keys: # "trace sampling rate default = prod 1%, dev/local 100%" # D-1 ISSUE-1 fix (2026-06-16): blank = per-profile resolver 기본값 사용. # RuntimeEnvironment is the profile SSOT; resolver policy is prod=0.01, dev/local=1.0. - # TracingSamplingEnvironmentPostProcessor bridges resolved rate to + # TracingEnvironmentPostProcessor bridges resolved rate to # management.tracing.sampling.probability. type: string default: "" diff --git a/docs/registries/error-codes.yaml b/docs/registries/error-codes.yaml index 39d76e7b..9c70a5a4 100644 --- a/docs/registries/error-codes.yaml +++ b/docs/registries/error-codes.yaml @@ -399,12 +399,13 @@ errors: compatibility_impact: none required_test: contract-verification:rate-limit - # source: feature-rate-limit-idempotency-contract L71 — "200ms 초과 시 409 IDEMPOTENT_IN_FLIGHT (retryable=false, client는 polling)" + # source: docs/web/http-contract.md §2 (2026-11-01 소유자 결정, 리뷰 02-01 대안 A) — 결과 불명. 같은 Idempotency-Key로 Retry-After 뒤 재전송. 새 키 금지. + # 2초 = 기본 processing lease(30s)보다 짧은 고정값. 이전 "client는 polling"(retryable=false)은 조회 엔드포인트가 없어 폐기. - code: IDEMPOTENT_IN_FLIGHT category: CONFLICT http_status: 409 - retryable: false - retry_after_seconds: null + retryable: true + retry_after_seconds: 2 owner_branch: feature-rate-limit-idempotency-contract owner_layer: application client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." diff --git a/docs/reviews/2026-11-01-maturity-review/01-core-and-feature-pattern.md b/docs/reviews/2026-11-01-maturity-review/01-core-and-feature-pattern.md new file mode 100644 index 00000000..46540e38 --- /dev/null +++ b/docs/reviews/2026-11-01-maturity-review/01-core-and-feature-pattern.md @@ -0,0 +1,490 @@ +# 01. 코어(domain-core · shared-contract · application-core)와 기능 개발 패턴 리뷰 + +대상 leaf: `domain-core`(`:domain-core`), `shared-contract`(`:shared-contract`), `application-core`(`:application-core`). +추가 범위: repo 전체의 폴더 구조, 중복 복사본·갈라진 유틸, 새 기능을 추가하는 작업 순서(sample-portfolio 포함). + +경로는 `src/`를 생략한다. 패키지 앞부분이 긴 경로는 `.../`로 줄인다. + +## 1. 범위 + +| 항목 | 기록 | +| --- | --- | +| 대상 | `clean-architecture-backend-template`, 브랜치 `main`, 커밋 `01a8a2a70` | +| 확인 시점 | 2026-11-01 | +| 목적과 실행 구성 | 템플릿(파생 서비스의 시작점). 코어 세 leaf는 모든 조립에 들어간다(`app-bootstrap/build.gradle:149-150,214`). 업무 도메인은 비어 있고 예시는 `sample-portfolio`에 있다. | +| 규모·운영 목표 | 합의된 SLO·처리량 없음. 이 영역은 성능 목표보다 "새 기능을 넣는 사람이 틀리지 않는가"를 본다. | +| 읽은 범위 | 세 leaf의 main·test·testFixtures 전부(domain-core main 7파일 110줄, shared-contract main 42파일 2,115줄, application-core main 130파일 5,080줄). 세 leaf의 `CLAUDE.md`·`README.md`, 루트 `AGENTS.md`·`CLAUDE.md`, `config/architecture/modules.json`. 기능 패턴을 따라가려고 sample-portfolio의 domain·application 전부와 web·persistence·bootstrap 중 WorkLog·Poster 경로, `app-bootstrap`의 `DurableOperationConfig`, onboarding fixture(`app-bootstrap/src/test/java/dev/caskeleton/onboarding/**`)와 `DomainFeatureOnboardingContractTest`, ArchUnit 규칙(`ApplicationBoundaryArchitectureTest`, `NamingConventionTest`, `ForbiddenApiArchitectureTest`, `RequiresPermissionProxyabilityTest`), web의 `MethodSecurityConfig`·`RequiresPermissionAuthorizationManager`·`GlobalExceptionHandler`, support의 `JsonIntegrationEventEncoder`. 중복 탐색은 repo 전체 main을 grep으로 훑었다(같은 단순 이름 클래스, SHA-256·HMAC 직접 구현, 식별자 문법). | +| 실행한 것 | ① 게이트 결과 읽기: `ci` rc=0(세 leaf `test`·`check`, `:app-bootstrap:architectureTest` 181개 통과), `mainCheck` rc=1(objectstorage MinIO 이미지 pull 404, 이 영역 밖). ② `build/test-results` XML 집계(ci가 20:36~20:38에 만든 결과). ③ 별도 worktree(`wt-01`)에서 `flock` 잠금으로 기준 실행 1회와 변이 실험 5회(아래 표). worktree는 끝나고 지웠다. | +| 확인 못 한 것 | 실제 Postgres·Redis로 도는 포트 어댑터 계약 lane(이 영역 소유 아님), 앱 기동 상태에서의 인가 프록시 동작(정적 근거와 기존 테스트로만 판단), 부하 측정. 지난 리뷰의 실행 결과는 증거로 쓰지 않았다. | +| 비교 가능한 범위 | techlead `01-core.md`, followup-status 「A Core」「S1 Core」「X1/X2」. 파생 서비스 `tech-log-backend`의 현재 작업 트리를 참고 자료로 읽었다(이 repo의 커밋이 아니므로 판정 근거가 아니라 "실제로 어떻게 쓰였는가"의 사례로만 쓴다). | + +### 변이 실험 (worktree `wt-01`, 실행 후 원복·삭제) + +기준 실행: `./gradlew :domain-core:test :shared-contract:test :application-core:test` rc=0 (부하 21.4, 캐시 적중으로 1초). + +| # | 바꾼 코드 | 돌린 테스트 (부하) | 결과 | +| --- | --- | --- | --- | +| M1 | `DurableOperationAccessPolicy.java` `mayAccess`에서 tenant 비교 삭제 | `:application-core:test` (13.0) | 잡힘 — 217개 중 5개 실패 | +| M2 | `TenantId.java:22` 문법에 `/` 허용 | `:application-core:test` | **살아남음** — 전부 통과 (01-03) | +| M3 | `PublishPendingOutboxEventsUseCase.java:112` 정렬을 역순으로 | `:application-core:test` | 잡힘 — 3개 실패 | +| M4 | `Backoff.java` `ceiling`의 overflow 방어 삭제 | `:shared-contract:test` | 잡힘 — 260개 중 2개 실패 | +| M5 | `IntegrationEventDraft.java:49` correlation 길이 상한 96→200 | `:application-core:test` | **살아남음** — 전부 통과 (01-07) | + +테스트 실행 시간(ci 결과): domain-core 2개 0.13초, shared-contract 260개 0.81초, application-core 217개 1.38초. `:app-bootstrap:architectureTest` 181개 17.1초. 변이 1회당 leaf 재실행은 2~4초였다. 과하지 않다. + +## 2. 지난 발견 재확인 + +상태: 해결 / 남음 / 바뀜(형태가 달라짐) / 일부. + +| ID | 상태 | 근거 | +| --- | --- | --- | +| techlead C1 application-core가 HTTP 프로토콜 구현 | 해결 | application-core main에 HTTP 타입 0건. "http"는 `SubmitDurableOperationUseCase` 주석과 schema 파일에만 있다. fileserver 프로토콜은 `application-fileserver`·`adapter:inbound:web-fileserver`로 갔다 | +| techlead C2 HTTP 요청 DTO가 inbound port 인자 | 해결 | ArchUnit `APPLICATION_METHODS_DO_NOT_ACCEPT_WEB_DTOS`(`ApplicationBoundaryArchitectureTest.java:855`)가 ci에서 통과 | +| techlead H1 `inNew` 프로덕션 미사용 | 바뀜 | 이제 `CreateUploadApplicationUseCase.java:143`, `FinalizeUploadApplicationUseCase.java:332`(application-fileserver)가 쓴다 | +| techlead H4 application-core 76%가 고르지 않은 제품 | 바뀜 | main 35,894줄 → 5,080줄. 알림·파일·객체 저장소는 별도 leaf로 나갔다. 남은 플랫폼 기능(outbox·idempotency·operation·lease·lock·cache·realtime)은 01-10 | +| techlead H5 캐시 엔진·lease watchdog 미조립 | 일부 | 캐시 엔진·watchdog 삭제. `lease/*`는 남았고 main 호출자는 Redis 구현뿐(`RedisLeaseConfig.java:29`). 소유자 결정 8(유지)로 의도된 확장 지점 | +| techlead H8 알림 멱등키 `Objects.hash` | > 05 영역 | application-notification으로 이동. 이 영역 밖 | +| techlead M6 application-core 정적 `ThreadLocal` | 해결 | `static.*ThreadLocal` 0건 | +| techlead M10 domain-core 테스트 0줄 | 해결(형식만) | `DomainCoreContractTest` 2개. 마커의 retention·target만 본다. domain-core에 행위가 없어서 충분하다 | +| A-2b `RuntimeProfileSnapshot` "유일한 reader" 주장 | 남음 | `adapter/outbound/support/.../runtime/RuntimeProfileSnapshot.java:12-13` 그대로. 실제 reader는 5곳(`RuntimeProfileAccessArchitectureTest` 허용 목록) | +| A-2d `RuntimeEnvironment` Javadoc이 bridge를 app-bootstrap 소유로 서술 | 남음 | `shared-contract/.../runtime/RuntimeEnvironment.java:32-33` "app-bootstrap's RuntimeProfileSnapshot" (실제 support leaf) | +| A-5a README "1001번째 tenant부터 bucket folding 자동" | 남음 | `shared-contract/README.md:374`. 적용 코드 없음 | +| A-6a application-core 문서가 알림 타입을 core 것으로 설명, operation·cache·lease·realtime 절 없음 | 남음 | `application-core/CLAUDE.md:78-82`, `README.md:501-537`(알림 절). README에 operation·cache·lease·realtime·tenant·outbound 절 없음 | +| A-6e shared-contract README의 없는 `RateLimiter` 인용 | 해결 | `RateLimiter` 0건 | +| S1-#3b `lease/*` use case 호출자 0 | 바뀜 | 소유자 결정 8로 capability 유지. 계약 키트 `DistributedLeaseContract`(testFixtures)를 in-memory·Redis 둘 다 상속 | +| S1-#15d shared-contract CLAUDE.md 책임 목록이 일부 패키지만 설명 | 남음 | `concurrency`·`operation`·`ratelimit`·`runtime`·`security` 패키지가 `shared-contract/CLAUDE.md`에 없다. 빈 패키지 `annotation`·`headers`·`registry`(`.gitkeep`만)도 설명 없음 | +| S1-#19 이력 주석 | 일부 | 코어 main에서 리뷰 ID를 적은 주석 2곳(`TenantId.java:12`, `MdcKeys.java`) | +| X1-#3a `TransactionPort` fake를 testFixtures 1개로 | 일부 | `DirectTransactionPort`(testFixtures)가 생겼고 sample·web이 쓴다. 그러나 다른 구현 9개가 남음: application-core 테스트 4곳(`SubmitDurableOperationUseCaseTest`, `OutcomeAwareRelayTest`, `PublishPendingOutboxEventsUseCaseTest`, `TransactionPortTest`), `application-fileserver/.../testkit/DirectTransactions.java`, application-notification 테스트 4곳 | +| X1-#3b 포트별 계약 키트를 소유 leaf testFixtures에 | 일부 | 있음: `DurableOperationStoreContract`, `DistributedLeaseContract`, `OutboxLeaseFencingContract`. 없음: `IdempotencyStorePort`, `DistributedLockPort`, `TransactionPort`, `CacheRegionPort`, `LiveEventReplayPort`, `IntegrationEventEncoderPort`. 01-05 | +| X1-#3d `DistributedLockPortContractTest`가 테스트 안 fake를 검증 | 남음 | `application-core/src/test/.../lock/DistributedLockPortContractTest.java:35-46` | +| X1-#6b lock과 lease 중 하나만 | 바뀜 | 소유자 결정 8: 둘 다 유지 + 공통 계약 테스트. lease는 키트가 있고 lock은 없다(위 X1-#3d) | +| X1-#6d `ClaimFencingContract`를 row lease store마다 | 일부 | outbox는 `OutboxLeaseFencingContract`를 in-memory·JPA가 실행. durable operation lease에 fencing 시나리오가 있는지는 확인 못 함 | +| X1-#10b / X2-P1-5 SHA-256 헬퍼 → `Sha256` | 일부 | 대부분 정리. 잔존 복사본은 01-11 | +| X2-P1-2b httpclient `RuntimeEnvironment`가 정본과 이름이 같음 | 남음 | `adapter/outbound/httpclient/.../profile/RuntimeEnvironment.java` | +| X2-P2-6a 같은 이름 `TenantContext` 2개, 문법이 다름 | 바뀜 | web·GraphQL은 `application-core` `TenantId` 하나로 통일. 그러나 `TenantId` 자체가 3벌, 문법 3가지 — 01-03 | + +## 3. 새 발견 + +High 이상은 없다. Medium은 필요한 필드를 모두, Low는 필요한 필드만 쓴다. 설계 선택이 아닌 단순 결함은 "대안 비교: 적용 제외 — 이유"로 둔다. + +### 01-01 새 기능을 어느 leaf에 두는지 세 가지 모양이 있고, 고르는 기준이 없다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 2, 3, 4, 20, 23, 25 | +| 근거 | ① 공유 계층 leaf 안의 패키지: durable operation은 `application-core/.../operation/*` + `persistence-jpa` + web `DurableOperationController` + `app-bootstrap/.../DurableOperationConfig.java`. ② 기능 전용 application leaf: `application-notification`, `application-fileserver`, `application-objectstorage`와 짝이 되는 `persistence-notification`·`persistence-fileserver`·`composition:*`. ③ 한 leaf 수직 슬라이스: `sample-portfolio`가 domain·application·adapter·bootstrap 패키지를 한 leaf에 둔다. `AGENTS.md:128-141` 「기능 개발 프로토콜」은 "새 비즈니스 개념은 domain-core에 먼저 둔다"고만 쓰고, 언제 ②를 고르는지는 어디에도 없다. 유일하게 끝까지 동작하는 예시(sample)는 ③이고 `AGENTS.md:259`는 그것을 "격리된 예시"라고 부른다. 계층 leaf에 기능을 넣는 모양(①)은 테스트 fixture(`app-bootstrap/src/test/java/dev/caskeleton/onboarding/**`)에만 있다. | +| 사례(참고) | 파생 서비스 `tech-log-backend` 작업 트리: 기능 파일이 `application-core` 273개, web 53개, persistence-jpa 41개, app-bootstrap 6개, **domain-core 0개**. 도메인 모델은 `application/techlog/*/model`에 있고 `@AggregateRoot`·`ResourceId` 사용 0건. 템플릿의 domain-core 경로가 실제로는 쓰이지 않았다. 이 repo 커밋의 증거가 아니라 사례로만 적는다. | +| 발생 조건 | 개발자가 첫 업무 기능을 추가한다. | +| 영향 | 기능마다 배치가 달라진다. 계층 leaf(①)에 넣으면 upstream 템플릿 파일과 같은 leaf·같은 패키지 트리에서 병합 충돌이 난다(`persistence-jpa`는 capability 모듈 규칙 7 "이 모듈을 아는 곳은 모듈 자신뿐"과도 부딪힌다). ②를 고르면 `modules.json`·`settings.gradle`·`app-bootstrap/build.gradle`을 고쳐야 한다. domain-core를 건너뛰는 선택은 ArchUnit의 domain 순수성 규칙 밖으로 빠진다(규칙은 `..domain..` 패키지만 본다). | +| 심각도·우선순위 | Medium / P2. 기능이 깨지지는 않지만 템플릿의 핵심 약속("경계를 지키며 기능을 추가")을 사용자가 매번 스스로 해석해야 한다. 파생 서비스로 그대로 복제된다. | +| 확실성 | 세 모양은 코드로 확인(E1). 각 모양의 병합 비용은 측정 안 함. | +| 결정의 근거 | 기록된 의도: 메모와 `AGENTS.md:259`는 "sample은 삭제 가능한 fixture", 실제 기능은 계층 leaf로. 소유자 결정 3·33·34는 ②(별도 leaf)를 기능 플랫폼에 썼다. 두 방향이 문서로 합쳐지지 않았다. | +| 이해 비용 | 첫 기능 작성자가 sample·onboarding fixture·durable operation·notification 네 곳을 읽고 공통점을 직접 뽑아야 한다. | +| 최소 개선 방향 | `docs/manual/`(또는 `AGENTS.md` 「기능 개발 프로토콜」)에 배치 규칙 표 하나를 둔다: 업무 기능 기본 = ①(domain-core·application-core 아래 `` 패키지, persistence는 기능 전용 adapter leaf 또는 persistence-jpa 아래 `` 패키지 중 하나로 고정), 독립 배포·선택 조립이 필요하면 ②. 그리고 ①의 끝까지 동작하는 예시를 하나 둔다(아래 01-02의 onboarding fixture를 그 예시로 키우는 것이 가장 싸다). | +| 대안 비교 | (a) 위 방법: 문서 1개 + 예시 1개. (b) sample을 계층 leaf로 쪼갠다: 예시가 실제 모양과 같아지지만 sample 삭제가 어려워진다(지금은 leaf 하나 지우면 끝). (c) 업무 기능도 항상 ② 별도 leaf: 경계가 가장 선명하지만 기능마다 registry 3파일을 고친다. (a)를 고른다. sample의 "통째로 지운다" 성질을 지키면서 판단 기준만 추가한다. | +| 비용·부작용 | 문서 유지. 예시 fixture를 실제 컴파일·기동 대상으로 올리면 테스트 시간이 조금 는다. | +| 재검토 조건 | 파생 서비스가 2개 이상 생기거나 기능 leaf 추가가 반복되면 (c)와 registry 오버레이(메모의 `modules.project.json` 안)를 다시 비교한다. | +| 완료 기준 | 새 기능 작성자가 문서 하나로 "어느 leaf, 어느 패키지, 어떤 이름"을 정할 수 있고, 그 모양의 예시가 ci에서 컴파일·테스트된다. | +| 검증 방법 | 예시 기능에 대해 `DomainFeatureOnboardingContractTest`류 검사가 production 규칙(`ProductionClassImportOption` 대상 규칙 포함)을 그대로 통과하는지 본다. | + +### 01-02 onboarding fixture가 "새 기능의 계약 모양"으로 박아 둔 유스케이스가 실제로는 기동에 실패하는 모양이다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 10, 20, 21, 23 | +| 근거 | ① `app-bootstrap/src/test/java/dev/caskeleton/onboarding/application/usecase/CreateFeatureAggregateUseCase.java:15,20` — `@RequiresPermission` + `public final class`. ② 같은 조합을 금지하는 규칙 `RequiresPermissionProxyabilityTest.java:44`는 `ProductionClassImportOption`으로 test 클래스를 뺀다. 그래서 fixture는 검사받지 않는다. ③ 규칙의 설명(`:26-34`)은 "final 클래스를 bean으로 만들면 'Cannot subclass final class'로 기동 실패, 16개 유스케이스가 이 상태였다"고 적는다. ④ fixture의 `FeatureAggregateIdFactory`는 `IdFactory`를 상속하지 않는다(sample `WorkLogIdFactory`는 상속). ⑤ fixture의 쓰기 포트는 application 쪽 `FeatureAggregateWritePort`, sample은 domain 쪽 `WorkLogRepository` — 같은 역할에 이름·위치가 다르다. `DomainFeatureOnboardingContractTest.java:63-78`는 이 이름들을 "최소 계약"으로 고정한다. | +| 발생 조건 | 개발자가 onboarding fixture를 복사해 첫 쓰기 유스케이스를 만들고 bean으로 등록한다. | +| 영향 | 앱이 기동하지 않는다(시끄럽지만 늦게 드러난다). bean으로 등록하지 않고 직접 `new` 하면 권한 검사가 조용히 빠진다. | +| 심각도·우선순위 | Medium / P2. 템플릿이 "이 모양으로 만들라"고 제시하는 유일한 계층 예시라 복제 범위가 넓다. production ArchUnit이 같은 규칙으로 잡으므로(production 코드로 옮기면 ci가 실패) 피해는 개발 시간 손실이다. | +| 확실성 | 정적 확인(E1). fixture를 bean으로 띄워 보지는 않았다. 규칙 설명의 실패 메시지는 규칙 작성자의 기록이다. | +| 결정의 근거 | 적용 제외 — fixture가 production 규칙을 따라가지 못한 단순 drift다. | +| 최소 개선 방향 | `CreateFeatureAggregateUseCase`에서 `final`을 빼고, `FeatureAggregateIdFactory extends IdFactory`로, 쓰기 포트 이름·위치를 sample과 같은 규칙으로 맞춘다(01-12에서 규칙을 정한 뒤). `DomainFeatureOnboardingContractTest`에 `RequiresPermissionProxyabilityTest`의 두 규칙과 `NamingConventionTest`를 fixture에도 평가하는 단언을 추가한다. | +| 완료 기준 | fixture가 production에 적용되는 모든 application·domain ArchUnit 규칙을 통과한다. | +| 검증 방법 | fixture에 `final`을 다시 넣었을 때 `DomainFeatureOnboardingContractTest`가 실패하는지 변이로 확인한다. | + +### 01-03 `TenantId`가 3벌이고 받아들이는 문법이 셋 다 다르다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(갈라진 중복 복사본) | +| 관련 관점 | 11, 15, 17, 23 | +| 근거 | ① `application-core/.../tenant/TenantId.java:22` `[A-Za-z0-9][A-Za-z0-9_.-]{0,63}` (1~64자, 대문자·점 허용). web·GraphQL 전송이 인증 토큰에서 만든다(`JwtToAuthenticatedPrincipalConverter.java:60-62`). ② `application-notification/.../platform/api/TenantId.java:6-12` 공백 아님 + 100자 이하뿐(어떤 문자든 허용). 41개 파일이 쓴다. 값은 요청 tenant가 아니라 설정의 `SingleTenantContext`(`adapter/outbound/notification/.../SingleTenantContext.java:20`)에서 오고, `EmailAttachments.java:47`은 환경 이름(`profile().environment()`)으로 TenantId를 만든다. ③ `persistence-jpa/.../experimental/tenant/TenantId.java:17` `[a-z0-9][a-z0-9_-]{1,62}` (2~63자, 소문자만, 점 불가). RLS binder가 쓴다. ④ 변이 M2: 정본 문법에 `/`를 허용해도 `TenantIdTest` 전부 통과. `../public` 케이스는 첫 글자 규칙에서 막혀 `/` 검사를 증명하지 못한다. X2-P2-6a는 `TenantContext` 2개를 하나로 합치며 "완료"됐지만 그 아래 값 타입은 그대로 갈라져 있다. | +| 발생 조건 | 파생 서비스가 멀티 테넌시를 켠다. 예: 토큰의 tenant가 `Acme.EU`면 web은 받고, experimental RLS binder는 거부한다. 알림은 요청 tenant를 아예 모른다. | +| 영향 | tenant는 보안 경계다. 같은 tenant가 계층마다 다르게 읽히거나 거부되면, 거부 쪽은 기능 실패, 허용 쪽은 경로·키 구성에 들어가는 문자(`/`, 공백)를 막지 못한다. 알림 쪽은 tenant가 요청과 연결되지 않아 tenant 격리 검사를 둘 자리가 없다. | +| 심각도·우선순위 | Medium / P2. 기본 조립은 단일 tenant라 지금 피해는 없다. 멀티 테넌시를 켜는 순간 세 문법을 사용자가 직접 맞춰야 하고, 템플릿이 이를 알려 주지 않는다. | +| 확실성 | 세 문법은 코드로 확인(E1), 테스트 공백은 변이로 확인(E2). 알림이 요청 tenant를 써야 하는지는 05 영역 판단이 필요하다. | +| 결정의 근거 | 정본 `TenantId`의 Javadoc(`:7-12`)은 "모든 전송이 받는 하나의 문법"을 목표로 적는다. 알림·experimental은 그 정리 이전에 만들어졌다. 둘 다 `application-core` edge가 있어(`modules.json`) 정본을 쓸 수 있다. | +| 최소 개선 방향 | 알림·experimental의 `TenantId`를 정본으로 바꾼다. RLS가 더 좁은 문법(소문자)을 원하면 binder가 정본을 받아 자기 제약을 추가 검사한다(새 타입을 만들지 않는다). `TenantIdTest` 거부 목록에 `acme/eu`, `acme:eu`를 넣는다. | +| 대안 비교 | (a) 위 방법. (b) 문법 문자열만 정본에서 가져다 쓰기: 타입이 셋으로 남아 같은 값을 세 번 검사한다. (c) 현상 유지 + 문서화: 멀티 테넌시를 켜는 사람이 세 곳을 기억해야 한다(원칙상 결함). (a)를 고른다. | +| 단순화의 보존 조건 | 알림 DB에 이미 저장된 tenant 값이 정본 문법을 만족하는지 먼저 확인한다(기본값 확인 필요). 만족하지 않으면 읽기 경로에서 거부되므로 이행 순서를 정한다. | +| 완료 기준 | `record TenantId` 정의가 repo에 하나뿐이다(messaging vendored 제외). 거부 목록 테스트가 `/`를 포함한다. | +| 검증 방법 | 변이 M2를 다시 돌려 테스트가 실패하는지 본다. `git ls-files '*/main/*TenantId.java'`가 1건. | + +### 01-04 `IllegalArgumentException` 하나가 "입력이 틀렸다"와 "서버 조립이 틀렸다"를 함께 뜻하고, web은 둘 다 로그 없이 400으로 바꾼다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 5, 6, 8, 17 | +| 근거 | ① `adapter/inbound/web/.../error/GlobalExceptionHandler.java:75-81` — `IllegalArgumentException`이면 `BAD_PARAMETER`(400, retryable false)로 응답하고 로그를 남기지 않는다(같은 파일의 `log.error`는 `:154-194` 다른 경로에만). ② 서버 조립 결함도 IAE로 던져진다: `adapter/outbound/support/.../JsonIntegrationEventEncoder.java:100-102` "no integration event contract is registered", `:104-110` 목적지 불일치, `:113-116` payload 타입 불일치, `:119-127` 크기 초과. ③ 코어 값 객체도 불변식 위반에 IAE를 쓴다(`ValidatedIntegrationEvent`, `ContractDescriptor.java:20-47`, `SchemaResourceId`). 이 값 객체는 요청 입력이 아니라 서버 코드가 만든다. ④ 유스케이스 테스트의 표준 fake `FakeIntegrationEventEncoder`(application-core testFixtures)는 어떤 계약이든 받아 준다(01-05). | +| 발생 조건 | 개발자가 새 이벤트 계약을 만들고 bean 등록(`SampleApplicationUseCaseConfig.java:60-93`처럼 계약마다 `@Bean`)을 빠뜨린다. 또는 payload record를 바꾸고 계약의 `exactPayloadRecordType`을 안 바꾼다. | +| 영향 | 그 기능의 모든 쓰기 요청이 400 "잘못된 요청"으로 끝난다. 트랜잭션은 롤백되어 데이터 손상은 없다. 서버 로그에 아무것도 없고 5xx 경보도 울리지 않는다. 클라이언트는 자기 요청을 고치려 한다. fake로 쓴 유스케이스 테스트는 통과한다. | +| 심각도·우선순위 | Medium / P2. 기능 전체가 멈추지만 실제 encoder로 도는 통합 테스트가 있으면 잡힌다. 진단이 어렵다는 점이 핵심이다. | +| 확실성 | 경로는 정적 확인(E1). 실제 요청으로 재현하지는 않았다. | +| 결정의 근거 | `X2-P2-2b`(IAE는 모든 전송에서 400)는 현황표의 "에이전트가 정한 것(소유자가 뒤집을 수 있음)" 목록에 있다. 이 발견은 그 결정을 뒤집자는 것이 아니라, 결정이 전제한 "IAE = 입력 오류"가 코어·adapter 코드에서 지켜지지 않는다는 것이다. | +| 이해 비용 | 400 하나를 받은 운영자가 원인을 찾으려면 디버거를 붙여야 한다. | +| 최소 개선 방향 | 서버 조립 결함을 IAE가 아닌 `IllegalStateException`(→ 기존 catch-all 500 + `log.error`)으로 바꾼다: encoder의 미등록 계약·타입 불일치, 서버가 만드는 값 객체(`ValidatedIntegrationEvent`, `ContractDescriptor`)의 불변식. 요청 크기 초과처럼 입력 탓일 수 있는 것은 IAE로 둔다. 그리고 400 응답에도 WARN 한 줄(예외 타입만)을 남긴다. | +| 대안 비교 | (a) 위 방법: 던지는 쪽을 고친다. 소유자 결정을 유지한다. (b) 전송이 IAE를 500으로: 진짜 입력 오류가 500이 된다 — X2-P2-2b와 충돌. (c) 전용 `ServerMisconfigurationException`(shared-contract) 추가: 의미는 가장 선명하지만 타입이 하나 는다. 지금 규모에서는 (a)로 충분하고, IAE/ISE 구분이 반복해서 흐려지면 (c)로 간다. | +| 비용·부작용 | encoder·값 객체 테스트의 예외 타입 단언을 바꿔야 한다. | +| 완료 기준 | 미등록 계약으로 encode하면 500 + `log.error`가 남는다. | +| 검증 방법 | web slice 테스트: 미등록 계약 draft를 append하는 유스케이스를 부르면 500 `INTERNAL_ERROR`, 로그에 원인 메시지. | + +### 01-05 application-core가 소유한 포트 중 절반이 "fake와 실제 adapter가 같은 계약 테스트를 통과한다"는 규칙 밖에 있다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 10, 21, 23 | +| 근거 | `AGENTS.md:168-170` 테스트 규칙 6: 포트당 fake 하나를 소유 leaf testFixtures에, fake와 adapter가 같은 추상 계약 테스트를 통과. application-core 포트 17개(`*Port` 인터페이스) 중 계약 키트가 있는 것: `DurableOperationStorePort`(in-memory·JPA), `DistributedLeasePort`(in-memory·Redis), `OutboxStorePort` fencing(in-memory·JPA). 없는 것 중 adapter가 있는 포트: `IdempotencyStorePort`(Redis·PostgreSQL 두 adapter + `InMemoryIdempotencyStore` fake, 공통 계약 없음), `TransactionPort`(`SpringTransaction` vs `DirectTransactionPort` + 다른 구현 9개), `DistributedLockPort`(JPA adapter, fake는 테스트 안 private 클래스 `DistributedLockPortContractTest.java:46`), `CacheRegionPort`(Redis만), `LiveEventReplayPort`(JPA만), `IntegrationEventEncoderPort`(`JsonIntegrationEventEncoder` vs `FakeIntegrationEventEncoder`). `OutboxAppendContract`는 JPA만 상속하고 `InMemoryOutboxStore`는 상속하지 않는다. | +| 발생 조건 | 사용 프로젝트가 fake로 유스케이스 테스트를 쓰고 실제 adapter로 배포한다. | +| 영향 | fake가 실제와 다르게 동작하면 테스트가 거짓 녹색이다. 예: `FakeIntegrationEventEncoder`는 미등록 계약·목적지 불일치·payload 타입 불일치를 거부하지 않는다 — 01-04의 결함이 단위 테스트에서 안 보이는 이유. 멱등성은 05-02(Redis renew 결함을 fake가 그대로 따라 함)가 실제 사례다. | +| 심각도·우선순위 | Medium / P2. 결함 자체가 아니라 결함을 못 잡는 구조다. 멱등성·트랜잭션은 중복 실행·부분 커밋과 직결된다. | +| 확실성 | 키트 유무는 grep으로 전수 확인(E1). | +| 결정의 근거 | 규칙과 일부 키트(outbox·operation·lease)는 이미 있다. 나머지가 비어 있는 것은 작업 미완(X1-#3a/b/d 남음)이다. | +| 최소 개선 방향 | 우선순위: ① `IdempotencyStoreContract`(05-02와 같은 작업), ② `TransactionPortContract`(inRootWrite 중첩 거부, 예외 시 롤백, inNew 독립 커밋) — `SpringTransaction` IT와 `DirectTransactionPort`가 상속, 다른 구현 9개는 `DirectTransactionPort`로 교체, ③ `FakeIntegrationEventEncoder`가 생성자에서 계약 목록을 받아 미등록·목적지·타입을 실제와 같은 예외로 거부, ④ lock fake를 testFixtures로 옮기고 키트화. | +| 대안 비교 | (a) 위 순서. (b) fake를 없애고 Testcontainers만: 계약은 맞지만 유스케이스 테스트가 느려지고 application-core가 Spring·DB를 알게 된다. (c) 현상 유지. (a)를 고른다. 규칙과 기존 키트 모양을 그대로 따른다. | +| 완료 기준 | adapter가 있는 application-core 포트마다 testFixtures에 `XxxContract`가 있고, fake와 모든 adapter 테스트가 상속한다. `implements TransactionPort`가 main 1개 + testFixtures 1개뿐이다. | +| 검증 방법 | 키트마다 fake에 결함 하나를 넣어 키트가 실패하는지 변이로 확인한다. | + +### 01-06 `@RequiresPermission`은 application 계약인데, 검사는 web leaf가 켜 주는 AOP에만 있다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 5, 15, 21, 27 | +| 근거 | ① 선언: `application-core/.../security/RequiresPermission.java`. ArchUnit `MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`(`ApplicationBoundaryArchitectureTest.java:404-425`)이 쓰기 유스케이스에 선언을 강제한다. ② 검사: `adapter/inbound/web/.../authz/MethodSecurityConfig.java:26-60`의 advisor 하나. `WebSecurityAutoConfiguration.java:47`이 import한다. web 외 전송(GraphQL·gRPC·WebSocket)과 composition 모듈에는 검사 장치가 없다. web이 빠진 조립에서 선언만 남는지 확인하는 기동 검사도 없다(app-bootstrap main에서 `RequiresPermission` 참조는 `DurableOperationConfig` 주석뿐). ③ 시스템이 부르는 유스케이스: `PublishPendingOutboxEventsUseCase.java:31` `@RequiresPermission("outbox:relay")`는 relay가 bean이 아니라 `new`로 만들어져(`composition/outbox-relay/.../OutboxRelayAutoConfiguration.java:76-77`) 한 번도 검사되지 않는다. 규칙을 통과하려고 붙인 선언이다. ④ 그 이유를 설명하는 `application-core/README.md:389-391`은 "final 클래스라 프록시 불가"라고 적지만 지금 클래스는 final이 아니다(`:37`). 남은 진짜 이유(스케줄러 스레드엔 Authentication이 없어 bean으로 만들면 매 tick 거부)는 README에만 있고 코드에는 없다. | +| 발생 조건 | (가) 파생 서비스가 gRPC 전용·배치 전용으로 `adapter:inbound:web`을 뺀다(`app-bootstrap/build.gradle:213`). (나) 누군가 relay 유스케이스를 bean으로 등록한다. | +| 영향 | (가) 권한 선언이 있는 모든 유스케이스가 검사 없이 실행된다. 기동은 정상이다. (나) relay가 매 tick 거부되어 outbox가 쌓인다. | +| 심각도·우선순위 | Medium / P3. 기본 조립에는 web이 `implementation`으로 고정이라 (가)는 사용자가 구조를 바꿀 때만 생긴다. 생기면 조용한 인가 우회다. | +| 확실성 | 정적 확인(E1). web 없는 조립을 띄워 보지는 않았다. | +| 결정의 근거 | `application-core/README.md:161-188`: 결정(포트)은 framework-free, 메커니즘(AOP)은 web. 이 분리 자체는 타당하다. 빠진 것은 "메커니즘이 없을 때 실패하는 장치"와 "시스템 호출자의 권한 표현"이다. 41절 검토는 5.1. | +| 최소 개선 방향 | ① `@RequiresPermission` 선언 bean이 있는데 advisor bean이 없으면 기동 실패하는 검사를 support 또는 composition:service-runtime에 둔다. ② 시스템 호출 유스케이스는 `@RequiresPermission` 대신 `@UseCaseCapability`에 "시스템 전용" 표시를 두고 ArchUnit 규칙이 그 경우를 면제한다. 그리고 그 클래스 Javadoc에 "bean으로 만들지 말 것, 이유"를 적는다. ③ README:389-391을 고친다. | +| 대안 비교 | (a) 위 방법. (b) 유스케이스 본문에서 `AuthorizationPort`를 직접 부른다: 전송과 무관하게 검사되지만 principal을 command에 실어야 하고 모든 유스케이스 시그니처가 바뀐다. (c) composition이 유스케이스를 데코레이터로 감싼다: AOP 의존은 없어지지만 bean 등록 규칙이 하나 더 생긴다. (a)를 고른다. 지금 구조를 유지하면서 빠지는 경우만 시끄럽게 만든다. | +| 완료 기준 | web을 뺀 조립에서 선언 bean이 있으면 기동이 실패한다. relay 유스케이스에 장식용 권한 선언이 없다. | +| 검증 방법 | `ApplicationContextRunner`로 web 없이 `@RequiresPermission` bean 하나를 등록해 기동 실패를 단언한다. | + +### 01-07 이벤트 식별자 문법이 다섯 곳에 복사되어 있고 길이 상한이 둘로 갈린다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(갈라진 중복) | +| 관련 관점 | 10, 17, 23 | +| 근거 | `[A-Za-z0-9][A-Za-z0-9._:-]` 문법: `EventId.java:6,9`(96자), `IntegrationEventDraft.java:22,49` correlation(96자), `ValidatedIntegrationEvent.java:37` correlation·causation(128자), `SubmitDurableOperationUseCase.java:67-68`(복사, 96자), sample `PortfolioEventOutbox.java:41-42`(복사, 96자). 변이 M5: draft 상한 96→200이어도 테스트 전부 통과. 같은 encoder를 가리키는 `ContractDescriptor.serializerId`가 `"json-envelope-v1"`(`PortfolioEventContract.java:46`, `DurableOperationSubmittedContract.java:44`)과 `"json-schema-envelope-v1"`(`WorkLogReservedContractContribution.java:28`) 두 표기다. serializerId는 검증 없이 catalog revision 해시에만 들어간다(`JsonIntegrationEventEncoder.java:267`). | +| 발생 조건 | 누가 한 곳의 상한을 바꾼다. 또는 draft를 거치지 않고 DB에서 복원한 이벤트(128자 correlation)를 다시 draft 경로로 보낸다. | +| 영향 | 같은 값이 경로에 따라 통과·거부가 갈린다. serializerId 표기 차이는 지금은 해시 값만 바꾸지만, 나중에 serializer 선택에 쓰이면 한 계약이 조용히 다른 serializer를 고른다. | +| 심각도·우선순위 | Low / P3. 지금 상한은 draft(96) ≤ validated(128)라 정상 경로에서 충돌하지 않는다. | +| 결정의 근거 | 적용 제외 — 같은 규칙의 복사본을 하나로 모으는 단순 정리다. | +| 최소 개선 방향 | application-core `messaging.event`에 `IntegrationIdentity.GRAMMAR`·`MAX_LENGTH`(또는 `isCanonical(String)`) 하나를 두고 다섯 곳이 쓴다. correlation 상한은 DB 열(varchar 128)에 맞춰 하나로 정한다. serializerId는 encoder가 아는 값 목록과 대조해 모르는 값이면 기동 시 거부한다. draft 상한 경계값 테스트를 추가한다. | +| 완료 기준 | 문법 문자열 리터럴이 main에 한 번만 나온다. M5 변이가 실패한다. | +| 검증 방법 | grep + 변이 M5 재실행. | + +### 01-08 장기 실행 작업(LRO) 공개 계약이 두 벌이다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험(갈라진 중복) | +| 관련 관점 | 17, 23, 24, 27 | +| 근거 | ① shared-contract `operation/Operation.java`·`OperationStatus.java`: 필드 `status`, 값 `PENDING·RUNNING·SUCCEEDED·FAILED·CANCELLED`, Javadoc이 `GET /v1/operations/{id}`의 본문이라고 선언. main 소비자는 sample의 `OperationsController`·`SampleOperationStore`뿐. ② application-core `DurableOperation`·`DurableOperationState`(`CANCELED`·`EXPIRED` 포함, 철자 다름) + web `OperationHttpResponse`(필드 `state`, `submittedAt`·`progress`·`expiresAt` 등) — 같은 경로 `GET /operations/{operationId}`(`DurableOperationController.java:48,106`). 소유자 결정 15·26은 ②를 정본 HTTP 어댑터로 정했다. | +| 발생 조건 | 파생 서비스가 LRO를 만들 때 shared-contract의 이름이 "skeleton-wide 계약"이라 ①을 고른다. 또는 sample 경로와 durable operation을 함께 켠다(두 컨트롤러가 같은 경로를 잡는다). | +| 영향 | 같은 개념에 두 개의 공개 응답 모양과 두 개의 상태 어휘가 생긴다. 클라이언트 SDK가 둘 다 처리해야 한다. 같은 앱에 둘 다 있으면 경로 충돌로 기동이 실패한다(sample 앱은 app-bootstrap을 쓰지 않아 지금은 충돌 없음). sample은 모르는 id에 IAE를 던져 404가 아니라 400을 준다(`OperationsController.java` `poll`). | +| 심각도·우선순위 | Medium / P3. 공개 계약의 일관성 문제이고, 템플릿 사용자가 고를 때 틀린 쪽을 고르기 쉽다. | +| 결정의 근거 | 기록된 결정은 ②를 정본으로 만들었고 ①을 정리하는 결정은 없다. | +| 최소 개선 방향 | ①을 sample leaf로 옮기거나 삭제한다. sample LRO 예시는 ②의 유스케이스로 다시 쓰거나, sample 전용 타입으로 남기고 shared-contract에서는 뺀다. shared-contract README의 operation 절(`README.md:293-`)을 정리한다. | +| 대안 비교 | (a) ①을 sample로 내림: shared-contract가 줄고 정본이 하나가 된다. sample의 wire 모양은 유지. (b) ①을 정본으로 하고 ②의 HTTP 응답을 ①에 맞춤: 소유자 결정 26과 충돌. (c) 둘 다 유지 + 문서: 원칙상 결함 유지. (a)를 고른다. | +| 단순화의 보존 조건 | sample의 `POST /worklogs:export` 응답 모양(202 + Location + 상태 enum)과 그 계약 테스트는 그대로 통과해야 한다. | +| 완료 기준 | shared-contract에 `operation` 패키지가 없거나, 있으면 production 소비자가 있다. | +| 검증 방법 | sample web contract 테스트 통과, `git grep shared.operation`이 sample 밖에서 0건. | + +### 01-09 통합 이벤트를 만드는 규칙(tenant 범위·순서·correlation)을 기능마다 다시 정한다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 3, 11, 20, 22, 23 | +| 근거 | `IntegrationEventDraft`는 10개 필드를 받는다. 채우는 규칙이 두 곳에서 다르게 정해졌다. ① durable operation `SubmitDurableOperationUseCase.java:64,66,143-157`: tenant 범위는 상수 `"global"`(요청에는 `command.tenantId()`가 있는데 쓰지 않음), 순서 `(1,0)` 고정, correlation = 이벤트 id. ② sample `PortfolioEventOutbox.java:39-42,72-97`: tenant 범위 `"portfolio"`, 순서 = 발생 시각 마이크로초, correlation = 요청 correlation(문법에 안 맞으면 이벤트 id). 조립 헬퍼(②)는 sample에만 있어 production 기능은 ①처럼 직접 조립한다. 도메인 이벤트 쪽도 틀만 있다: `@DomainEvent` 마커는 있지만 aggregate가 이벤트를 모으는 수단은 없고, sample `CreateWorkLogUseCase.java:79-84`는 `WorkLogReserved`(category·periodStart 포함)를 만들어 id만 꺼내 쓴다. | +| 발생 조건 | 새 기능이 이벤트를 발행한다. | +| 영향 | 같은 outbox·relay를 지나는 이벤트가 tenant 범위와 순서의 의미를 기능마다 다르게 가진다. 소비자가 tenant로 나누거나 순서로 중복을 거르면 기능마다 다르게 동작한다. tenant가 있는 durable operation 이벤트가 `"global"`로 나가 소비자 쪽 tenant 격리 근거가 사라진다. | +| 심각도·우선순위 | Medium / P3. 지금 소비자가 템플릿 안에 없다. 이벤트를 쓰는 첫 파생 기능부터 갈라진다. | +| 결정의 근거 | `PortfolioEventOutbox` Javadoc(`:19-35`)이 규칙과 이유를 잘 적어 두었다. 그 결정을 application-core로 올리지 않은 것이 빠진 부분이다. | +| 최소 개선 방향 | application-core에 `IntegrationEventAppender`(이름은 예시) 하나: 입력은 계약·aggregate 종류·aggregate id·tenant(`TenantId` 또는 "단일 tenant" 상수)·payload, 순서·correlation 규칙은 한 곳에서. sample과 durable operation이 이것을 쓴다. 도메인 이벤트→통합 이벤트 변환 위치는 01-01 문서의 판단 지점으로 적는다. | +| 대안 비교 | (a) 헬퍼 승격. (b) 규칙을 문서로만: 기능마다 다시 구현한다. (c) aggregate가 도메인 이벤트를 모으고 저장 시 adapter가 변환(Spring Data `@DomainEvents` 방식): 도메인이 프레임워크 없이 이벤트를 들 수 있지만 domain-core에 베이스 클래스가 생기고 변환 위치가 persistence로 간다. (a)를 고른다. (c)는 두 번째 이벤트 소비자가 생기면 다시 본다. | +| 완료 기준 | `new IntegrationEventDraft<>(`가 main에서 헬퍼 한 곳에만 있다. | +| 검증 방법 | 헬퍼 단위 테스트(tenant·순서·correlation 규칙)와 grep. | + +### 01-10 application-core 한 이름공간에 커널·플랫폼 기능·(파생 시) 업무 기능이 섞인다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 개선 제안 | +| 관련 관점 | 2, 4, 24, 25 | +| 근거 | `application-core/src/main/java/dev/caskeleton/application/` 아래 17개 패키지: 커널(`usecase`·`command`·`query`·`capability`·`transaction`·`security`·`tenant`), 플랫폼 기능(`outbox`·`idempotency`·`operation`·`lease`·`lock`·`cache`·`realtime`·`messaging`), 묶음 이름만 있는 `outbound`(`CallBudget`·`SecretReference`·`SecretSourcePort` — 서로 관계없음), `observability`. 01-01의 ①을 따르면 업무 기능도 같은 수준(`application/`)에 들어간다(파생 사례: `application/techlog`). | +| 영향 | 업무 기능 이름이 플랫폼 패키지와 겹칠 수 있다(`operation`, `lock`, `cache`). 새 사람은 어느 패키지가 "건드리지 말 템플릿"이고 어느 것이 "우리 기능"인지 경로로 구분할 수 없다. upstream 병합 시 충돌 범위도 같은 트리다. | +| 심각도·우선순위 | Low / P3. | +| 최소 개선 방향 | 업무 기능 패키지 규칙을 01-01 문서에서 정한다(예: `dev.caskeleton.application.feature.` 또는 파생 서비스 루트 패키지). `outbound` 패키지는 내용별로 흩는다(`SecretSourcePort`·`SecretReference` → `secret`, `CallBudget` → 사용처). 이름 변경은 API surface 파일과 함께 한 번에. | +| 대안 비교 | (a) 패키지 규칙만. (b) 플랫폼 기능을 `application-platform` leaf로 분리: 경계는 선명하지만 registry·edge가 늘고 결정 34(edge를 늘리지 않음)와 같은 비용 판단이 필요. (a)를 고른다. | + +### 01-11 공용 다이제스트 헬퍼가 있는데 복사본이 남아 있고, 일부 leaf는 registry 때문에 복사가 강제된다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(갈라진 중복) | +| 관련 관점 | 16, 23 | +| 근거 | shared-contract `digest/Sha256`·`HmacSha256`이 정본이다(`shared-contract/CLAUDE.md` 책임 목록). shared-contract edge가 **있는데** 복사한 곳: `application-fileserver/.../observability/SafeFileFingerprint.java:37-43`(`HmacSha256.sign` + hex 앞 16자와 같음), `cache-redis/.../capability/RedisKeys.java:59-71`(inline FQN `javax.crypto.Mac`). edge가 **없어서** 복사할 수밖에 없는 곳: `identifier/HmacUserPrincipalPseudonymizer.java:38`, `persistence-mongo`의 `MongoTenantContext.java:28`·`MongoCredentialReference.java:57`·`MongoAdminCommand.java:98`·`MongoKeysetCursorCodec.java:160`, `application-objectstorage`의 `ObjectIdentitySupport.java:77`·`ObjectDigest.java:35`, `redis-sdk/ConfiguredRedisPolicyAuthority.java:85`. X1-#10b·X2-P1-5는 "완료"로 닫혔다. | +| 영향 | 다음 수정(예: 키 길이 검사, constant-time 비교)이 정본에만 들어가고 복사본은 남는다. | +| 심각도·우선순위 | Low / P3. 지금 복사본에 알려진 결함은 없다. | +| 최소 개선 방향 | edge가 있는 두 곳은 정본으로 바꾼다. edge가 없는 leaf는 registry에 `shared-contract` edge를 줄지(stdlib 전용 leaf라 방향상 문제 없음), 복사를 허용하고 그 사실을 leaf CLAUDE.md에 적을지 정한다. | +| 대안 비교 | (a) edge 추가: 복사 제거, 대신 shared-contract가 더 많은 leaf의 공통 의존이 된다. (b) 복사 허용 + 문서: edge 그래프 유지. messaging·gRPC는 이미 (b)를 의도로 적었다(`shared-contract/CLAUDE.md` "keep their own copies"). 템플릿 자체 leaf는 (a), vendored 플랫폼은 (b)를 권한다. | + +### 01-12 이름 규칙의 정본 문서가 없고, 같은 역할에 이름이 여러 가지다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(문서) + 개선 제안 | +| 관련 관점 | 4, 23, 24 | +| 근거 | `NamingConventionTest.java:12-17`이 이름 규칙의 SSOT로 `.agents/plugins/ca-superpowers/rules/code-conventions.md`를 가리키고 "[판단] 규칙(N2/N7/N8...)은 리뷰가 맡는다"고 적는다. 그 파일은 repo에 없다(`git ls-files` 0건). 실제 이름: 유스케이스 `*UseCase`(application-core 7, sample 21) vs `*ApplicationUseCase`(fileserver 21, notification 7) + `*Service`(notification 8, fileserver 4). 저장 포트 `*Repository`(sample domain) vs `*StorePort`(application-core 3, notification 12) vs `*WritePort`(onboarding fixture) vs `*QueryPort`. id 팩토리는 `IdFactory` 상속(sample) vs 상속 안 함(onboarding, `OutboxEventIdFactory`). | +| 영향 | 새 기능 작성자가 어느 이름을 따라야 할지 정할 근거가 없다. 판단 규칙을 "리뷰가 맡는다"고 했는데 리뷰가 볼 문서가 없다. | +| 심각도·우선순위 | Low / P3. | +| 최소 개선 방향 | 이름 규칙 표를 `application-core/CLAUDE.md`(이미 "Naming convention" 절이 있음, `:84-90`)에 합치고 `NamingConventionTest`의 링크를 그쪽으로 바꾼다. 저장 포트는 "domain이 소유하면 `*Repository`, application이 소유하면 `*StorePort`" 같은 한 줄 기준을 적는다. | + +### 01-13 참조 예시의 수정 유스케이스에 소유자 검사가 없다는 사실이 코드에 보이지 않는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 개선 제안(위험 가시성) | +| 관련 관점 | 5, 15, 20 | +| 근거 | `sample-portfolio/.../UpdateWorkLogUseCase.java:31-74`는 `worklog:write` 권한만 보고 `WorkLog.owner()`를 확인하지 않는다. 다른 사용자의 work log를 고칠 수 있다. `sample-portfolio/README.md:259-263`은 "소유자 범위 인가(ABAC)는 의도적으로 뒤로 미룬 확장"이라고 적는다. 코드에는 그 표시가 없다. 템플릿의 객체 인가 포트 `application-core/.../security/ObjectAccessPolicy.java`는 sample에서 쓰이지 않고, durable operation은 자기 전용 `DurableOperationAccessPolicy`를 쓴다. 객체 인가의 모양이 셋(없음 / 전용 정책 / `ObjectAccessPolicy`)이다. | +| 영향 | 사용자가 sample을 복사하면 객체 인가 없는 수정이 그대로 복제된다(가이드 31절 "다른 사용자 리소스 접근"). | +| 심각도·우선순위 | Low / P3. sample은 fixture이고 의도가 README에 있다. 그러나 원칙상 코드에 드러나야 한다. | +| 최소 개선 방향 | `UpdateWorkLogUseCase` Javadoc 첫 줄에 "소유자 검사 없음 — 의도적, README 링크"를 적는다. 더 나은 방법은 sample의 수정·삭제 하나를 `ObjectAccessPolicy`로 보호해 객체 인가 예시를 만드는 것이다. | + +### 01-14 작은 결함 묶음 (각각 독립, Low / P3) + +| 항목 | 근거 | 개선 | +| --- | --- | --- | +| README가 relay 유스케이스를 final이라고 설명 | `application-core/README.md:389-391` vs 클래스 `PublishPendingOutboxEventsUseCase.java:37`(non-final) | 01-06의 ③ | +| shared-contract 빈 패키지 3개 | `shared/annotation`·`headers`·`registry`에 `.gitkeep`만. 무엇을 둘 자리인지 설명 없음 | 쓰임을 CLAUDE.md에 적거나 삭제 | +| `IdempotencyContractTest`·`CacheRegionContractTest`가 이름은 계약 테스트인데 값 타입 테스트다 | `application-core/src/test/.../idempotency/IdempotencyContractTest.java`, `cache/CacheRegionContractTest.java` — 포트 구현을 받지 않는다. 01-05의 진짜 계약 키트와 이름이 겹친다 | `*ValueTest` 등으로 이름 변경 | +| sample `OutboxEventIdFactory`가 domain 패키지에 있다 | `sample-portfolio/.../domain/worklog/OutboxEventIdFactory.java` — outbox는 도메인 개념이 아니고 이 팩토리는 `application/event/PortfolioEventOutbox`만 쓴다 | application 쪽으로 이동 | +| `WorkLogInvariantException.TITLE_BLANK`이 409로 나간다 | `DomainExceptionHandler.java` `handleWorkLogInvariant` → `WORKLOG_CONFLICT` | reason별 매핑(Poster처럼) | + +## 4. 31절 시나리오 추적 + +### 4.1 정상 쓰기 요청 — sample `POST /worklogs` (적용) + +```text +HTTP 요청 + → (web 보안 필터) JWT 검증 → AuthenticatedPrincipal(roles, tenant) + → WorkLogController.create(@Valid CreateWorkLogRequest) ── 입력 검증(Bean Validation) + → WorkLogWebMapper.toCommand(body, 소유자=토큰 subject) ── DTO → Command + → [AOP 프록시] RequiresPermissionAuthorizationManager ── "worklog:write" 권한 검사 + → CreateWorkLogUseCase.handle + tx.inWrite { ── 트랜잭션 시작 + WorkLog.create(...) ── 불변식(제목 공백 등) + WorkLogRepository.save → WorkLogRepositoryAdapter(JPA) ── INSERT + 감사 필드 + PortfolioEventOutbox.append → encoder → OutboxAppendPort ── 같은 트랜잭션에 outbox INSERT + } ── 커밋 + → 200 + ETag + WorkLogResponse + (커밋 뒤) outbox relay가 따로 claim → 발행 +``` + +| 항목 | 관찰 | +| --- | --- | +| 입력 신뢰 수준 | 본문은 신뢰하지 않음 → `@Valid`와 `CreateWorkLogCommand` compact constructor(`CreateWorkLogCommand.java:24-30`)가 두 번 검사. 소유자는 본문이 아니라 검증된 토큰에서 온다(`WorkLogController.java:217-`). | +| 인가 위치 | 유스케이스 bean의 AOP 프록시. 유스케이스 코드 안에는 없다(01-06). 객체 인가는 생성이라 해당 없음. | +| 규칙 소유 객체 | `WorkLog`(aggregate). 기본 소유자 상수 `"sample-owner"`(`WorkLog.java:16`)가 남아 있어 owner 없는 `create` 오버로드가 호출되면 가짜 소유자가 찍힌다 — 현재 호출자는 owner 있는 쪽만. | +| 트랜잭션 | `tx.inWrite` 하나. 저장과 outbox append가 한 커밋이다(이중 쓰기 없음). | +| 외부 부작용 | 요청 안에서는 없다. 발행은 relay가 커밋 뒤에 한다. | +| 성공의 의미 | 200은 "DB와 outbox에 커밋됨"이다. 이벤트 발행 완료는 아니다. 생성인데 201이 아니라 200이다. | +| 오류 변환 | 불변식 → `DomainExceptionHandler`(sample, web 전용) → `PortfolioErrorCode`. GraphQL·gRPC로 같은 유스케이스를 열면 이 매핑을 다시 써야 한다(4.4·7절 판단 지점). 서버 조립 오류는 400으로 숨는다(01-04). | +| 진단 정보 | correlation id가 MDC와 이벤트 correlation에 같이 실린다(`PortfolioEventOutbox`). 400 경로에는 로그가 없다. | +| 성능 | 생성 1건 = INSERT 2(work_log, outbox). 수정은 `WorkLogRepositoryAdapter.save`가 감사 필드를 옮기려고 `findById`를 한 번 더 부른다(유스케이스의 `findById` 포함 SELECT 2 + UPDATE 1). 같은 영속성 컨텍스트라 두 번째 SELECT는 1차 캐시에서 끝날 수 있지만 코드상 보장은 아니다. | + +### 4.2 다른 사용자 리소스 접근 (적용) + +- sample `PATCH /worklogs/{id}`: 권한만 보고 소유자는 안 본다. 다른 사용자의 글을 고칠 수 있다(01-13, README상 의도). +- core `GET /operations/{id}`: `DurableOperationAccessPolicy.mayAccess`가 principal과 tenant를 둘 다 비교하고, 실패하면 없는 것과 같은 404를 준다. 변이 M1(tenant 비교 삭제)을 테스트 5개가 잡았다. 템플릿 안에서 객체 인가가 가장 잘 된 경로다. + +### 4.3 중복·동시 요청 (적용, 범위 한정) + +- sample 생성은 `NOT_IDEMPOTENT`로 선언하고 `Idempotency-Key`를 받지 않는다(`sample-portfolio/README.md:253-255`). 선언과 동작이 맞다. +- sample 수정은 `If-Match` 버전을 트랜잭션 안에서 비교한다(`UpdateWorkLogUseCase.java:39-41`) + JPA `@Version`. 동시 수정은 412 또는 낙관적 락 충돌로 끝난다. +- durable operation 제출은 store가 `ON CONFLICT`로 "이미 있음"을 답하고, 새로 만든 경우에만 outbox에 append한다(`SubmitDurableOperationUseCase.java:124-131`). +- 멱등성 executor 자체의 경쟁은 05 영역(05-02)에서 다룬다. + +### 4.4 선택 어댑터 제거 — `adapter:inbound:web`을 뺀다 (적용, 정적 추적) + +`@RequiresPermission` 검사기가 함께 사라지고, 기동 검사가 없어 선언만 남는다(01-06). 이 영역 코어 타입(shared-contract `ApiErrorCarrier`·`ApiErrorCode`)은 GraphQL·gRPC 오류 매퍼도 쓰므로 web을 빼도 오류 모델은 남는다. + +### 적용 제외·다른 영역 + +| 시나리오 | 사유 | +| --- | --- | +| 외부 응답 지연·유실 | > 05(httpclient·알림). 코어는 `CallBudget` 값 타입만 소유 | +| DB 오류·경쟁 | > 03(persistence). 코어는 `TransactionPort` 계약만 소유 — 계약 키트 공백은 01-05 | +| 메시지 중복·역순 | > 메시징 영역. 코어 쪽 영향(순서·tenant 규칙 분기)은 01-09 | +| 신·구 버전 공존 | 이벤트 payload 버전(`payloadVersion`)과 schema 해시 고정은 확인. 실제 v1→v2 공존 예시가 없어 미검증 | +| 여러 서버의 작업 실행 | > outbox relay·lock(03/메시징). 코어 쪽 fencing 키트는 2절 X1-#6d | +| 세션·토큰 갱신 경쟁 | > web 영역 | +| 큰 입력·목록 조회 | sample 배치 생성 1000건 상한 확인(`README.md:256-258`). 페이지 조회는 web·persistence 영역 | +| 종료·재시작 | > bootstrap 영역 | + +## 5. 41절 설계 선택 검토 + +### 5.1 `@RequiresPermission`: 선언은 application, 검사는 web의 AOP + +| 질문 | 답 | +| --- | --- | +| 1. 무엇이 필요한가 | 쓰기 유스케이스가 권한 없이 실행되지 않는다. application-core는 Spring을 모른다. | +| 2. 지킬 성질 | 선언된 모든 유스케이스 호출은 검사를 거친다. 검사 장치가 없으면 실행되지 않는다(fail-closed). | +| 3. 현재 보장 | 선언 강제(ArchUnit D4), 프록시 가능성 강제(`RequiresPermissionProxyabilityTest`), 검사(`MethodSecurityConfig`), 인증 없으면 거부. **보장하지 않는 것**: web이 없을 때, bean이 아니게 만들었을 때, self-invocation. 마지막 둘은 README가 "정적 분석 사각지대"로 적었다. | +| 4. 대안 | (a) 현행 + 장치 부재 시 기동 실패. (b) 유스케이스 본문에서 `AuthorizationPort` 직접 호출. (c) composition이 데코레이터로 감싸기. | +| 5. 득실 | (a) 변경 작고 기존 구조 유지, AOP 사각지대는 남음. (b) 전송·bean 여부와 무관하게 검사, 대신 principal을 command에 실어야 하고 모든 유스케이스·테스트가 바뀜. (c) AOP 없이 명시적, 대신 bean 등록 규칙 하나 추가. | +| 6. 현재 조건에서의 선택 | 기본 조립에 web이 고정이므로 (a)가 비용 대비 맞다. 01-06. | +| 7. 바뀔 조건 | web 없는 조립(gRPC 전용·배치 전용)이 실제로 생기거나, 시스템 호출 유스케이스가 늘면 (b)를 다시 본다. | + +### 5.2 새 기능의 배치: 계층 leaf 패키지 vs 기능 leaf vs 수직 슬라이스 + +| 질문 | 답 | +| --- | --- | +| 1. 무엇이 필요한가 | 파생 서비스가 업무 기능을 추가해도 upstream 변경을 계속 받고(메모의 운영 방식), 경계 검사가 기능 코드에도 적용된다. | +| 2. 지킬 성질 | 의존 방향(registry), domain 순수성, 유스케이스 계약. 그리고 템플릿 파일과 기능 파일이 섞이지 않아 병합이 쉽다. | +| 3. 현재 보장 | 의존 방향은 leaf 단위로 강제된다. 패키지 수준 규칙은 `..domain..`·`..application..`·`..adapter..` 이름에 걸린다 — 어느 leaf에 두든 패키지 이름을 지키면 검사된다. 배치 자체에 대한 규칙·문서는 없다(01-01). | +| 4. 대안 | ① 공유 계층 leaf 안 `` 패키지. ② 기능별 leaf(`application-`, `persistence-`, `composition:`). ③ 한 leaf 수직 슬라이스(sample). | +| 5. 득실 | ① 파일 추가만으로 끝나 시작이 빠르다. 템플릿 leaf와 같은 트리라 병합 충돌 면이 넓고, persistence-jpa 같은 capability 모듈에 업무 코드가 섞인다. ② 경계·삭제가 가장 선명하다. 기능마다 registry 3파일을 고친다. ③ 기능 하나를 통째로 지울 수 있다. 대신 leaf 하나가 모든 계층에 의존해 leaf 단위 방향 검사가 기능 안에서는 무력하고 ArchUnit 패키지 규칙에만 기댄다. | +| 6. 현재 조건에서의 선택 | 업무 기능 기본은 ①(파생 사례도 이쪽), 단 persistence 위치는 하나로 고정. 선택 조립이 필요한 플랫폼 기능은 ②(이미 그렇게 함). ③은 fixture 전용. 이 선택을 문서와 예시로 고정하는 것이 01-01. | +| 7. 바뀔 조건 | 파생 서비스가 여럿이 되어 같은 업무 기능을 공유하거나, 한 서비스의 기능 수가 늘어 application-core 컴파일·테스트 시간이 문제가 되면 ②로 옮긴다. | + +### 5.3 `TransactionPort`: 콜백 포트로 트랜잭션 경계를 유스케이스 본문에 둔다 + +| 질문 | 답 | +| --- | --- | +| 1. 무엇이 필요한가 | 유스케이스가 트랜잭션 경계를 정하되 Spring `@Transactional`을 import하지 않는다. | +| 2. 지킬 성질 | 저장과 outbox append가 한 커밋. 외부 호출은 트랜잭션 밖. root write는 바깥 트랜잭션이 있으면 거부. | +| 3. 현재 보장 | 인터페이스(`TransactionPort.java`), ArchUnit `USE_CASE_CAPABILITY_MATCHES_TRANSACTION_PORT_BOUNDARY`·`APPLICATION_DOES_NOT_USE_SPRING_TRANSACTIONAL_ANNOTATION`, `@UseCaseCapability.transactionMode` 선언과 실제 호출의 대조. **보장하지 않는 것**: fake와 `SpringTransaction`이 같은 의미라는 것(공통 계약 없음, 01-05). Runnable 기본 메서드는 `TransactionPortTest`가 위임을 검사한다. | +| 4. 대안 | (a) 현행 콜백 포트. (b) composition이 유스케이스 bean에 `@Transactional` 프록시를 씌움. (c) 유스케이스마다 "unit of work" 객체를 주입. | +| 5. 득실 | (a) 경계가 본문에 보이고, 트랜잭션 밖 외부 호출을 코드 모양으로 강제할 수 있다(relay가 그렇게 씀). 람다 중첩이 생기고 checked 예외를 못 던진다(문서화됨). (b) 본문이 깨끗하지만 경계가 선언으로 숨어 "어디까지가 한 커밋인가"를 코드로 못 본다. 01-06과 같은 AOP 사각지대도 생긴다. (c) 더 유연하지만 지금 요구보다 무겁다. | +| 6. 현재 조건에서의 선택 | (a)가 맞다. "위험은 코드에 드러나야 한다"는 기준에 가장 잘 맞는다. 남은 일은 계약 키트(01-05)다. | +| 7. 바뀔 조건 | 한 유스케이스 안에서 여러 저장소(JPA + Mongo)를 묶는 요구가 생기면 `TransactionPort` 의미(어느 리소스의 트랜잭션인가)를 다시 정해야 한다. | + +## 6. 리팩토링 후보 + +| # | 무엇을 | 왜 | 보존해야 할 것 | +| --- | --- | --- | --- | +| R1 | `TenantId` 3벌 → application-core 하나 (01-03) | 보안 경계 값의 문법 통일 | 이미 저장된 알림 tenant 값 읽기, RLS가 원하는 소문자 제약(binder의 추가 검사로) | +| R2 | 이벤트 식별자 문법 5곳 → `IntegrationIdentity` 하나 (01-07) | 상한 분기 제거 | event id 96자, outbox correlation 열 128자, 기존 테스트의 거부 메시지 | +| R3 | `PortfolioEventOutbox` 규칙을 application-core 헬퍼로 승격 (01-09) | 기능마다 tenant·순서·correlation 재정의 방지 | 저장과 append가 같은 트랜잭션, 문법 밖 correlation이 쓰기를 실패시키지 않음, durable operation의 "같은 operation → 같은 event id" | +| R4 | shared-contract `operation` → sample로 (01-08) | 공개 계약 하나 | sample `POST /worklogs:export` wire 모양과 계약 테스트 | +| R5 | `TransactionPort` 구현 10개 → `SpringTransaction` + `DirectTransactionPort` (01-05) | fake 의미 통일 | 각 테스트가 단언하던 경계 기록(`committed()` 순서), notification 테스트의 nesting 거부 | +| R6 | `SafeFileFingerprint` → `HmacSha256.sign` (01-11) | 복사 제거 | 출력: hex 앞 16자, 키 최소 16바이트 거부 | +| R7 | `PublishPendingOutboxEventsUseCase`의 장식용 `@RequiresPermission` 제거 + 시스템 전용 표시 (01-06) | 거짓 선언 제거 | ArchUnit D4가 다른 쓰기 유스케이스에는 계속 선언을 강제 | + +## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료) + +### 7.1 템플릿이 주는 틀 — 단계별 + +```text +domain-core ─▶ application-core ─▶ outbound adapter ─▶ inbound adapter ─▶ bootstrap 조립 + (모델·불변식) (유스케이스·포트) (저장·외부) (전송·DTO·오류) (bean·조건) +``` + +| 단계 | 템플릿이 주는 것 | 빠진 것 | +| --- | --- | --- | +| domain | `@AggregateRoot`·`@ValueObject`·`@DomainEvent` 마커(ArchUnit이 setter·no-arg 생성자·전송 타입 import를 검사), `ResourceId`(Long id 금지 규칙 D17), `IdFactory` 포트. 예시: sample `WorkLog`·`WorkLogId`·`WorkLogInvariantException(Reason)` | aggregate가 도메인 이벤트를 모으는 수단, 도메인 예외의 공통 모양(각자 `RuntimeException` + `Reason` enum), domain-core가 shared-contract를 못 봐서 도메인 예외는 오류 코드를 가질 수 없다는 안내 | +| application | `CommandUseCase`/`QueryUseCase`, `Command`/`Query` 마커, `@UseCaseCapability`(필수, ArchUnit이 트랜잭션 호출과 대조), `@RequiresPermission`(쓰기 필수), `TransactionPort`, `IdempotencyExecutor`, `OutboxAppendPort` + `IntegrationEventEncoderPort`, `ObjectAccessPolicy`, `CorrelationIdPort`, `TenantId`. `*QueryPort`는 projection만 반환(ArchUnit). testFixtures: `DirectTransactionPort`, `InMemoryOutboxStore`, `FakeIntegrationEventEncoder`, `InMemoryIdempotencyStore`, `InMemoryDurableOperationStore` | 이벤트 draft 조립 헬퍼(01-09), application 예외가 `ApiErrorCarrier`를 구현하는 예시(sample은 web 핸들러로 매핑), 저장 포트 이름·위치 규칙(01-12), 객체 인가 예시(01-13) | +| outbound | persistence-jpa의 `SpringTransaction`, outbox store, `CallerTransaction.require`, Flyway. 계약 키트 3개(operation·lease·outbox fencing). 예시: sample `WorkLogRepositoryAdapter` + `WorkLogEntity` + mapper + `WorkLogRepositoryAdapterContractTest`(integrationTest) + `InMemoryWorkLogRepositoryContractTest` | 기능 adapter를 둘 leaf의 기준(01-01), Flyway 번호대 규칙(메모에만 있음: 프로덕션·sample 번호 충돌), 감사 필드 처리 위치 안내 | +| inbound | web `GlobalExceptionHandler`(`ApiErrorCarrier`·`ApiErrorCode`·`Envelope`), `ErrorResponseFactory`, `Patch`(PATCH 3상태), `MethodSecurityConfig`, `TenantContext`. 예시: sample `WorkLogController`·`WorkLogWebMapper`·DTO·`DomainExceptionHandler`·`PortfolioErrorCode` | 비-web 전송에서 같은 유스케이스를 여는 예시, 기능 오류 코드를 어디에 두는지(sample은 web 패키지) | +| bootstrap | `DurableOperationConfig` 모양: `@AutoConfiguration` + `@ConditionalOnBean(포트들)` + 유스케이스 `@Bean`(프록시를 위해 bean 필수) + 이벤트 계약 `@Bean` 등록 | 계약 bean 등록 누락을 기동 때 잡는 장치(01-04), role→permission 매핑 추가 위치 안내 | + +### 7.2 개발자가 내려야 하는 판단 (순서대로) + +1. **배치**: 이 기능은 공유 계층 leaf의 패키지인가, 별도 leaf인가? (선택 조립·삭제가 필요하면 별도 leaf, 아니면 계층 leaf.) 업무 패키지 이름이 플랫폼 패키지(`operation`·`lock`·`cache`)와 겹치지 않는가? +2. **id**: 서버가 만드는가(`IdFactory` 상속 포트 + identifier adapter), 클라이언트가 주는가? id 문법은 어디서 검사하는가(값 객체 생성자)? +3. **불변식 위치**: aggregate 메서드인가, 유스케이스인가? 둘 이상의 aggregate에 걸치면 유스케이스 + 트랜잭션. +4. **저장 포트 소유자**: domain(`*Repository`, aggregate 단위 저장)인가 application(`*StorePort`, 기술적 저장·조회)인가? 읽기 모양이 쓰기와 다르면 `*QueryPort` + projection. +5. **트랜잭션 모양**: `inWrite`(기본) / `inRootWrite`(커밋 후 결과 노출, 중첩 금지) / `inRead` / `inNew`(감사·보상만, 루프 금지). 외부 호출은 트랜잭션 밖. +6. **멱등성**: `NOT_IDEMPOTENT`·`IDEMPOTENT`·`KEYED` 중 무엇인가? KEYED면 scope digest와 fingerprint를 무엇으로 만드는가? +7. **인가**: 권한 이름(`resource:action`)과 role 매핑. 객체 인가가 필요한가(소유자·tenant)? 필요하면 `ObjectAccessPolicy` 구현을 어디에 두는가? 실패 시 403인가 404인가(존재 숨김)? +8. **tenant**: 이 데이터는 tenant 범위인가? `TenantId`를 command에 싣는가? 이벤트 tenant 범위는 무엇인가? +9. **이벤트**: 도메인 이벤트가 필요한가, 통합 이벤트만 필요한가? payload에 무엇을 넣는가(id만 vs 상태)? 계약 id·버전·schema 파일·해시·descriptor(크기 상한·순서 필요·민감도)를 정하고 계약을 bean으로 등록했는가? +10. **오류 모델**: 실패마다 "클라이언트 탓(4xx)인가 서버 탓(5xx)인가"를 정한다. 클라이언트 탓이면 `ApiErrorCode` 하나와 carrier 예외, 서버 탓이면 `IllegalStateException`(01-04). 도메인 예외의 매핑을 application에서 할지 전송 핸들러에서 할지 정한다(여러 전송이면 application 쪽 carrier가 낫다). +11. **성공의 의미**: 200/201/202 중 무엇이고, 응답 시점에 무엇이 보장되는가(커밋됨 vs 발행됨)? +12. **테스트**: 포트마다 fake + 추상 계약 테스트를 testFixtures에, adapter는 같은 계약을 실제 저장소로 상속. 유스케이스는 `DirectTransactionPort`와 fake로. +13. **조립**: 유스케이스는 bean으로(권한 프록시), `@ConditionalOnBean`으로 필요한 포트가 있을 때만. Flyway 번호대, env 키(`docs/registries/env-keys.yaml`), 공개 경로 스냅숏이 바뀌면 해당 검사를 돌린다. + +### 7.3 스캐폴드 명령이 만든다면 (후보 목록, 만들지 않음) + +입력: 기능 이름 `X`, 배치(계층 leaf / 별도 leaf), 쓰기·읽기 여부, 이벤트 여부. + +| 계층 | 생성 파일 | +| --- | --- | +| domain | `X`(`@AggregateRoot`, private 생성자 + `create`/`restore`), `XId`(`record implements ResourceId`, `@ValueObject`, 문법 검사), `XIdFactory extends IdFactory`, `XRepository`, `XInvariantException`(+ `Reason` enum), 선택 `XCreated`(`@DomainEvent` record) | +| application | `CreateXCommand implements Command`, `GetXQuery implements Query`, `CreateXUseCase`(non-final, `@UseCaseCapability(WRITE, NOT_IDEMPOTENT, WRITE_REPOSITORY)`, `@RequiresPermission("x:write")`, `tx.inWrite`), `GetXUseCase`(`READ_ONLY`, `READ_REPOSITORY`, `tx.inRead`), `XNotFoundException implements ApiErrorCarrier`, `XErrorCode implements ApiErrorCode`. 이벤트면 `XCreatedPayload implements IntegrationPayload`, 계약 contribution, `contracts/messaging/x.created/v1.schema.json`과 해시 고정 테스트 | +| testFixtures | `InMemoryXRepository`, `XRepositoryContract`(abstract), `InMemoryXRepositoryContractTest` | +| test | `CreateXUseCaseTest`·`GetXUseCaseTest`(`DirectTransactionPort` + fake, GWT 주석), `XTest`(불변식), `XIdTest` | +| outbound | `XEntity`, `XPersistenceMapper`, `XJpaRepository`, `XRepositoryAdapter`, `UuidXIdFactory`(identifier), Flyway `V<번호대>__x.sql`, `JpaXRepositoryContractTest extends XRepositoryContract`(Testcontainers) | +| inbound | `XController`, `CreateXRequest`·`XResponse`, `XWebMapper`, web slice 테스트(400·403·404·성공) | +| bootstrap | `XUseCaseConfig`(`@AutoConfiguration`, `@ConditionalOnBean`, 유스케이스·계약 `@Bean`), `AutoConfiguration.imports` 한 줄, role→permission 정책에 `x:write`·`x:read` | +| 검증 | 생성 직후 `:app-bootstrap:architectureTest`, 소유 leaf `test`, 공개 경로가 바뀌면 `verifyPublicPathSnapshot` | + +스캐폴드의 템플릿 원본은 onboarding fixture를 01-02대로 고친 뒤 그것으로 삼는 것이 가장 싸다. fixture가 이미 `DomainFeatureOnboardingContractTest`로 production 규칙과 대조되고 있기 때문이다. + +## 8. 28개 관점 판정표 + +기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역. + +| # | 관점 | 판정 | 한 줄 이유 | +| --- | --- | --- | --- | +| 1 | 코드 성숙도 | O | 코어 값 객체가 생성자에서 검사하고, 지난 리뷰의 죽은 코드가 정리됐다(main 5,080줄) | +| 2 | 구조적 성숙도 | P | leaf 방향은 강제되나 기능 배치 모양이 셋(01-01), application-core 이름공간 혼합(01-10) | +| 3 | 변경 용이성 | P | 이벤트 조립 규칙·식별자 문법이 여러 곳에 복사(01-07, 01-09) | +| 4 | 인지 부하 | P | 첫 기능 작성자가 네 예시에서 공통점을 뽑아야 함, 이름 규칙 문서 없음(01-12) | +| 5 | 위험 가시성 | P | 설계 이유는 README에 잘 적혔으나 일부 제약이 코드에 없음(01-06 relay, 01-13 소유자 검사) | +| 6 | 실패 성숙도 | P | 결과 불명을 타입으로 표현(outbox·idempotency outcome)하나, 서버 조립 오류가 400으로 숨는다(01-04) | +| 7 | 운영 성숙도 | > | bootstrap·운영 영역 | +| 8 | 디버깅 가능성 | P | correlation 전파는 있음, IAE 400 경로에 로그 없음(01-04) | +| 9 | 유지보수 성숙도 | P | 문서 drift 남음(A-2b, A-2d, A-5a, A-6a, 01-14) | +| 10 | 테스트 성숙도 | P | 코어 테스트 빠르고 변이 5개 중 3개를 잡음. 계약 키트 절반 공백(01-05), fixture가 규칙 밖(01-02) | +| 11 | 데이터 성숙도 | P | 저장+outbox 한 트랜잭션은 강제, 이벤트 tenant 범위 규칙이 기능마다 다름(01-09) | +| 12 | 동시성 성숙도 | P | inRootWrite 중첩 거부·outbox fencing 키트 있음, lock 계약 키트 없음 | +| 13 | 확장성 | - | 코어 영역에 규모 목표 없음 | +| 14 | 성능 성숙도 | O | 코어는 CPU 작업뿐(이벤트당 SHA-256 3~4회, 128KB 상한). 테스트 2.3초 | +| 15 | 보안 성숙도 | P | 쓰기 권한 선언 강제·fail-closed, 단 검사기가 web에 묶임(01-06), TenantId 3벌(01-03) | +| 16 | 의존성 성숙도 | O | domain-core·shared-contract stdlib 전용, 방향 게이트 통과(ci). 복사 강제 leaf는 01-11 | +| 17 | API / Contract 성숙도 | P | Envelope·ApiErrorCode 하나로 통일됨, LRO 계약 2벌(01-08) | +| 18 | 배포 성숙도 | > | CI·배포 영역 | +| 19 | 설정 성숙도 | - | 코어는 설정을 읽지 않는다(ArchUnit D11·K6) | +| 20 | 개발자 경험 | X | 새 기능을 끝까지 따라갈 문서·예시·스캐폴드가 없음(01-01, 01-02, 7절) | +| 21 | Guardrail 성숙도 | P | ArchUnit 규칙이 촘촘함, 단 test fixture는 production 규칙 밖(01-02), web 없는 조립 검사 없음(01-06) | +| 22 | 추상화 성숙도 | P | 포트·값 타입은 적절, draft 조립 헬퍼가 없어 10필드 생성자를 직접 다룸(01-09) | +| 23 | 일관성 | X | TenantId 3벌, LRO 2벌, 식별자 문법 5곳, 이름 규칙 여러 개(01-03, 01-07, 01-08, 01-12) | +| 24 | 네이밍 / 의미 성숙도 | P | `*ApplicationUseCase`/`*UseCase`, `*Repository`/`*StorePort`/`*WritePort`, "Contract"라는 이름의 값 테스트(01-12, 01-14) | +| 25 | 조직 확장성 | P | 파생 서비스 기능이 템플릿과 같은 leaf·트리에 섞여 병합 충돌 면이 넓다(01-01, 01-10) | +| 26 | Ownership 성숙도 | P | leaf별 CLAUDE.md·README 있음, 코어 README가 다른 leaf 타입을 설명(A-6a) | +| 27 | 삭제 가능성 | P | sample은 leaf 하나로 지울 수 있음, shared-contract `operation`이 sample 전용인데 코어에 있음(01-08) | +| 28 | 회복 가능성 | > | persistence·운영 영역 | + +## 발견 요약 + +| 심각도 | 건수 | ID | +| --- | --- | --- | +| Critical | 0 | | +| High | 0 | | +| Medium | 8 | 01-01, 01-02, 01-03, 01-04, 01-05, 01-06, 01-08, 01-09 | +| Low | 6 | 01-07, 01-10, 01-11, 01-12, 01-13, 01-14 | + +| 우선순위 | 건수 | ID | +| --- | --- | --- | +| P2 | 5 | 01-01, 01-02, 01-03, 01-04, 01-05 | +| P3 | 9 | 01-06 ~ 01-14 | diff --git a/docs/reviews/2026-11-01-maturity-review/02-inbound-web.md b/docs/reviews/2026-11-01-maturity-review/02-inbound-web.md new file mode 100644 index 00000000..97e3277c --- /dev/null +++ b/docs/reviews/2026-11-01-maturity-review/02-inbound-web.md @@ -0,0 +1,420 @@ +# 02 inbound HTTP (web · web-notification · web-fileserver · web-advanced · 멱등성 HTTP 계약) + +## 1. 범위 + +| 항목 | 기록 | +| --- | --- | +| 대상 | `clean-architecture-backend-template`, `main` 커밋 `01a8a2a70` | +| 맡은 leaf | `:adapter:inbound:web`, `:adapter:inbound:web-notification`, `:adapter:inbound:web-fileserver`, `:adapter:inbound:web-advanced`, 그리고 `:composition:idempotency`가 만든 executor의 HTTP 쪽 계약 | +| 목적·지원 구성 | 서비스가 파생해 쓰는 템플릿. 기본 조립은 servlet(Spring MVC) + JWT 보안 체인. 짝 프론트 템플릿(`clean-architecture-frontend-template`)이 이 서버를 부른다고 가정한다 | +| 읽은 코드 | web main 68파일 전부, testFixtures 중 계약·장애 fixture, web-notification main 16파일, web-fileserver의 보안·오류·tus·admin 컨트롤러, web-advanced의 예외 10종·자동 구성 3개·`VirtualThreadMvcConfiguration`, `composition:idempotency` main 2파일과 README, application-core `idempotency/` 예외 4종과 `IdempotencyExecutor`의 claim·complete 분기, sample `PosterImagePublicationController`·`PublishPosterImageUseCase`(멱등 HTTP 경로 추적용) | +| 읽은 문서 | `AGENTS.md`·`CLAUDE.md`, web `README.md`·`CLAUDE.md`, web-advanced `README.md`, `composition/idempotency/README.md`, `docs/web/*.md`, `docs/registries/error-codes.yaml`·`env-keys.yaml`, 지난 리뷰 `2026-09-18-techlead-review/02-inbound-web.md`, `2026-09-25-review-followup-status.md`(I Web, S5, 소유자 결정, P6-new-2). 짝 프론트의 `docs/architecture/backend-api-and-server-state-contract.md` §4·§6과 `src/adapters/http/schema-registry.ts` | +| 게이트 결과(오케스트레이터 실행, 다시 돌리지 않음) | `ci` rc=0. web 테스트 259건·web-fileserver 142건·web-advanced 184건·web-notification 16건 모두 통과(`build/test-results/test` XML, 11:39Z). `mainCheck` rc=1 — 원인은 objectstorage MinIO 이미지 pull 404(이 영역 아님). 같은 실행에서 `:adapter:inbound:web:systemTest`, `webJettyCompatTest`는 통과 | +| 직접 실행(격리 worktree, `flock` 사용) | ① 실제 Tomcat에서 429 본문 문자셋 실험 ② `@WebMvcTest`로 실제 Envelope JSON과 in-flight 409 관찰 ③ MockMvc로 `HandlerMethodValidationException`·`AsyncRequestTimeoutException`·`String` 반환·`AdmissionRefusedException`의 응답 관찰 ④ 변이 실험 3건. 실행 직전 load average 5.6~21. 결과는 각 발견에 적었다. 실험 코드는 scratchpad `review02-experiments/`에 보관, worktree는 삭제 | +| 확인 못 한 것 | 짝 프론트를 실제 백엔드에 붙여 실행하지 않았다(프론트 쪽은 코드 읽기만). actuator 응답이 `EnvelopeBodyAdvice`로 감싸지는지 실행하지 않았다. Redis·PostgreSQL 멱등성 저장소에서 같은 키 동시 요청을 실제로 보내 보지 않았다(application·persistence 영역). 성능은 테스트 시간만 쟀고 부하는 걸지 않았다 | + +## 2. 지난 발견 재확인 + +followup-status에서 이 영역에 `남음`·`보류`로 남았던 항목과, 이번에 관련 코드를 다시 본 항목만 적는다. 나머지 I-*·S5-* `완료`/`해당 없음` 항목은 표의 근거 경로를 열어 같은 상태임을 확인했다. + +| ID | 상태 | 근거 | +| --- | --- | --- | +| I-2c / TEST-F-2d (콜백 크기 테스트가 컨버터 경로를 건너뜀) | 바뀜 | 컨트롤러가 `HttpServletRequest`를 직접 읽게 바뀌어 컨버터 버퍼링 경로는 사라졌다(`web-notification/.../callback/NotificationCallbackMvcController.java` `callback`). 테스트는 여전히 컨트롤러를 직접 호출한다(`NotificationCallbackMvcControllerTest.java:109-140`). 남은 위험은 "필터 체인의 무엇인가가 form 본문을 먼저 파싱해 서명할 원본 바이트를 잃는 경우"이며 MockMvc 경로 테스트가 없다 | +| I-3c (필수 파라미터·헤더 누락, `HandlerMethodValidationException` 형식 테스트 0) | 바뀜(일부 해결) | 누락 헤더·파라미터 테스트 추가됨 `TransportErrorHandlingTest.java:105,114`. `HandlerMethodValidationException`은 여전히 테스트가 없고, 실행해 보니 `BAD_PARAMETER`·details 없음으로 나간다 → 02-08 | +| I-7 (`wire-type-manifest.yaml`이 런타임에 없는 wire 계약 공개) | 남음 | `web-advanced/src/main/resources/META-INF/web/wire-type-manifest.yaml`, `web-advanced/.../advanced/contract/WebWireTypeManifest.java`. 적용하는 Jackson 설정은 여전히 없다 | +| S5-#12 (profile-name record 5개가 같은 정규식 복사) | 남음 | `web-advanced/.../operation/{Admission,Authorization,Response}ProfileName.java:17`, `CachePolicyName.java:17`, `budget/WebBudgetProfileName.java:17` | +| S5-#14c (web-fileserver·web-notification에 README/CLAUDE.md 없음) | 남음 | 두 leaf 루트에 `*.md` 0개 | +| TEST-FAKE-UploadApplicationService (tus fake와 실제 서비스가 같은 계약이 아님) | 남음 | `web-fileserver/src/test/.../testkit/InMemoryUploadApplicationService.java`. 공통 추상 계약 테스트 없음 | +| P6-new-2 (complete가 UNAVAILABLE이면 action 뒤에도 `IdempotencyUnavailableException`) — 결정 24 "현재 동작 유지 + 문서화" | 남음(문서화 안 됨) | `IdempotencyExecutor.java:233`이 action 실행 뒤 complete 단계에서 던진다. 그런데 예외 Javadoc은 "raised before an action"(`IdempotencyUnavailableException.java:7`), web README는 "action 전에 거부"(`adapter/inbound/web/README.md:214`). HTTP 계약 표가 이 경우를 거짓으로 설명한다 | +| L-11a (테스트·sample yml이 `ca-skeleton.rate-limit.*`) | 해결 | `sample-portfolio/src/main/resources/application.yml:189`, `app-bootstrap/src/test/resources/application-test.yml:113` 모두 `app.rate-limit` | +| I-3a (Spring MVC 예외가 problem+json으로 샘) | 해결 유지 | `GlobalExceptionHandler.java:332-351`. 다만 상태→코드 표가 503을 500으로 바꾼다 → 02-08 | +| I-4a·I-4b (요청 ID가 보안 체인 뒤에서 생성, trace 두 벌) | 해결 유지 | `WebMvcRequestIdFilter.java:103-122`(HIGHEST+10, 보안 체인 앞) | +| I-5a (XFF 맨 왼쪽으로 rate-limit 키) | 해결 유지 | `RateLimitKeyResolver.java`는 `getRemoteAddr()`만, `RateLimitWebConfig`가 `forward-headers-strategy=framework`면 기동 거부 | + +지난 리뷰에서 남은 High/P1은 이 영역에 없다. 새로 찾은 High 3건은 아래에 있다. + +## 3. 새 발견 + +| ID | 제목 | 심각도·우선순위 | +| --- | --- | --- | +| 02-01 | "처리 중" 409(`IDEMPOTENT_IN_FLIGHT`)의 클라이언트 행동이 코드·문서·짝 계약에서 서로 다르다 | High · P1 | +| 02-02 | 실제 Envelope JSON이 `data:null`·`error:null`·`meta.page`를 항상 싣는데 짝 프론트 계약은 이를 거절한다 | High · P1 | +| 02-03 | JWT audience 검증이 기본으로 꺼져 있고, 모든 client의 role을 합친다 | High · P1 | +| 02-04 | rate-limit 거부 본문이 실제 Tomcat에서 ISO-8859-1로 나가 한국어 문구가 `???`가 된다 | Medium · P2 | +| 02-05 | CORS에 노출 헤더가 없어 브라우저가 `Retry-After`·`X-Request-Id`·`Location`·tus 헤더를 못 읽는다 | Medium · P2 | +| 02-06 | `String`을 반환하는 컨트롤러는 `Accept: application/json`에서 500(ClassCastException)이 된다 | Medium · P2 | +| 02-07 | web-advanced 예외 10종이 문서에 적힌 상태(409·503 등) 대신 500 `INTERNAL_ERROR`로 나간다 | Medium · P2 | +| 02-08 | Spring MVC 예외의 상태→코드 변환이 의미를 잃는다(503→500, 메서드 검증→details 없는 `BAD_PARAMETER`) | Low · P2 | +| 02-09 | JSON 본문 상한의 두 갈래가 테스트로 묶여 있지 않고(변이 2건 생존), JSON 아닌 본문은 상한이 없다 | Low · P2 | +| 02-10 | `GlobalExceptionHandler`가 두 경로로 등록되어 `app.web.mvc.enabled=false`가 말한 대로 동작하지 않는다 | Low · P3 | +| 02-11 | `X-Correlation-Id` 허용 문자·길이가 요청 ID 규칙·짝 계약과 다르다 | Low · P3 | +| 02-12 | `Idempotency-Key` 헤더 검증이 공용 부품 없이 컨트롤러마다 새로 쓰인다 | Low · P3 | + +집계: High 3, Medium 4, Low 5 / P1 3, P2 6, P3 3. + +### 02-01 "처리 중" 409의 클라이언트 행동이 코드·문서·짝 계약에서 서로 다르다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(계약 불일치) | +| 관련 관점 | 17, 6, 5, 23, 12, 28 | +| 근거 | **코드가 실제로 내는 응답**: `@WebMvcTest` 실행 결과 `status=409`, `Retry-After` 없음, 본문 `{"success":false,"data":null,"error":{"code":"IDEMPOTENT_IN_FLIGHT","category":"CONFLICT","message":"현재 상태에서는 요청을 처리할 수 없습니다.","retryable":false,"details":null},"meta":{…}}`. 정의 `shared-contract/.../OperationalError.java:47`(`CONFLICT, 409, false`), 발생 `IdempotencyExecutor.java:104-105`(claim 단계), `:136-137`(재조정 단계). executor는 기다리지 않는다. `Retry-After` 표에 이 코드가 없다(`RetryAfterAdvisor.java:14-23`), retryable=false라 표를 보지도 않는다(`:36-38`). 메시지는 일반 충돌과 같은 CONFLICT 문구다. **백엔드 문서**: web README 표 `adapter/inbound/web/README.md:216`은 409·retryable=false·"executor는 기다리지 않는다"까지만 적고 클라이언트가 할 일은 없다. `docs/registries/error-codes.yaml:402-406`은 근거 주석에 "200ms 초과 시 409 … client는 polling"이라 적었지만 executor에는 대기도, 키로 조회하는 HTTP 엔드포인트도 없다. `docs/web/runbook.md:41-42`는 "the caller should retry after `Retry-After`"라고 적었지만 이 응답에는 그 헤더가 없다. "같은 키로 다시 보내라"는 문장은 백엔드 어디에도 없다. `docs/web/repository-adaptation.md` §6(`:75-104`)은 모듈 소유권만 다룬다. **짝 프론트 계약**: `clean-architecture-frontend-template/docs/architecture/backend-api-and-server-state-contract.md:211`은 409를 "fingerprint, revision 또는 semantic conflict"로, `:298`은 키 재사용을 `409 IDEMPOTENCY_KEY_REUSED`로, `:299-300`은 처리 중을 "bounded `IN_PROGRESS` 결과"로만 적는다. 백엔드의 키 재사용은 `422 IDEMPOTENT_REQUEST_MISMATCH`다(`OperationalError.java:48`) | +| 발생 조건 | 쓰기 응답을 잃은 클라이언트(게이트웨이 504, 클라이언트 타임아웃)가 첫 요청이 아직 처리 중일 때 같은 키로 다시 보낸다. 느린 쓰기에서 흔한 순서다 | +| 영향 | `retryable:false`는 "이 요청은 실패했고 다시 보내지 말라"로 읽힌다. 이 필드만 보는 클라이언트(파생 서비스의 다른 앱, 프론트의 다른 기능 패키지)는 사용자에게 다시 제출하게 하고, 그 제출은 새 키라 서버가 막지 못한다. 첫 요청이 끝나면 같은 작업이 두 번 적용된다. 프론트는 코드 이름으로 이 경우를 따로 처리하게 바뀌었지만(`reference-feature-contract-contribution.ts:33-51`), 그 근거가 백엔드 문서에 없으니 다른 소비자는 같은 판단을 할 수 없다 | +| 심각도·우선순위 | High · P1. 35.2의 "결과 불명 작업의 무방비 재실행"에 해당하고, 기본 응답과 기본 문서만으로 생기는 경로다. 실제 중복을 관측하지는 않았다 | +| 통제·증거 | 통제 M1(README 표에 status·code는 있음, 클라이언트 행동은 없음) · 증거 E2(백엔드 `@WebMvcTest` 출력, `IdempotencyExceptionMappingTest.inFlightMapsToNonRetryable409ConflictWithTheConflictMessage`) + E1(문서·짝 계약 읽기) | +| 확실성과 남은 가정 | status·code·retryable·헤더 없음은 실행으로 확인했다. 파생 서비스(tech-log)가 같은 값을 쓰는지는 이번에 보지 않았다 | +| 결정의 근거 | `[사실]` retryable=false는 2026-05의 "client polls" 결정에서 왔다(`error-codes.yaml:402` 주석, `OperationalErrorTest.java:232` 주석). `[사실]` 그 뒤 poll 대상이 될 키 조회 엔드포인트는 만들어지지 않았다. `[추론]` "다시 보내지 말고 조회하라"는 전제가 없어진 채 플래그만 남았다 | +| 이해 비용 | 새 KEYED 엔드포인트를 만드는 사람은 README 표, error-codes.yaml, runbook, `IdempotencyExecutor` 분기, 짝 프론트 §6을 모두 읽어야 409의 뜻을 안다. 다섯 곳의 말이 다르다 | +| 최소 개선 방향 | 백엔드 HTTP 계약 문서 한 곳(아래 대안 A)에 멱등성 응답 4종을 status·code·retryable·`Retry-After`·클라이언트 행동으로 고정한다. in-flight는 "결과 불명. 같은 `Idempotency-Key`로 `Retry-After` 뒤 재전송. 새 키 금지"로 적는다. 그에 맞게 `IDEMPOTENT_IN_FLIGHT`에 `Retry-After`(예: processing-lease 이하의 고정 초)를 붙이고, runbook·error-codes.yaml 주석을 같은 문장으로 고친다 | +| 대안 비교 | A) **retryable=true + `Retry-After` + 문서 고정**(권장): 일반 클라이언트도 "같은 요청을 나중에 다시"로 읽는다. 같은 키 재전송은 서버가 replay·in-flight·mismatch로 안전하게 판정하므로 retryable=true가 거짓이 아니다. 비용은 registry·enum·테스트 3곳 수정. B) **retryable=false 유지 + 문서에만 "같은 키 재전송"**: 코드 변경이 없지만 필드와 문서가 반대 말을 한다. 필드만 읽는 소비자는 계속 틀린다. C) **executor가 짧게 기다렸다가 결과를 replay**: 클라이언트 단순화. 대가로 요청 스레드 점유와 대기 상한 설계가 필요하고, 결국 시간 초과면 409가 다시 나간다. D) **키 조회 엔드포인트 추가 후 "poll"을 실제로 만들기**: 원래 의도대로지만 엔드포인트·인가·보존 기간이 새로 생긴다. 지금 요구에는 과하다 | +| 단순화의 보존 조건 | 같은 키·같은 fingerprint는 replay, 다른 fingerprint는 422, 진단 정보(scope digest)는 클라이언트에 나가지 않는다 | +| 비용·부작용 | A는 retryable 의미 변경이므로 짝 프론트의 분류기·테스트(`reference-http-problem-mapping.test.ts:152`)와 같이 바꿔야 한다 | +| 재검토 조건 | executor가 대기 방식으로 바뀌거나 키 조회 엔드포인트가 생기면 다시 비교한다 | +| 완료 기준 | 백엔드 계약 문서 한 곳과 README·runbook·error-codes.yaml이 in-flight에 대해 같은 status·code·retryable·헤더·행동을 말한다. 짝 프론트 §6이 그 문서를 가리킨다 | +| 검증 방법 | `IdempotencyExceptionMappingTest`에 `Retry-After`·retryable 단언 추가. 문서 문장은 리뷰로 확인 | + +### 02-02 실제 Envelope JSON이 `data:null`·`error:null`·`meta.page`를 싣는데 짝 프론트 계약은 이를 거절한다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(짝 계약 불일치) + 테스트 공백 | +| 관련 관점 | 17, 10, 23, 5 | +| 근거 | `@WebMvcTest`(Boot의 ObjectMapper) 실행 결과: 성공 `{"success":true,"data":{"k":"v"},"error":null,"meta":{"requestId":…,"traceId":…,"correlationId":…,"page":null}}`, 실패 `{"success":false,"data":null,"error":{…,"details":null},"meta":{…,"page":null}}`. `shared-contract/.../response/Envelope.java`는 record 4필드 그대로이고 저장소 전체에 `JsonInclude`·`non_null` 설정이 없다(grep 0). 짝 프론트는 `successEnvelopeSchema`·`failureEnvelopeSchema`를 `.strict()`로 둬(`frontend/src/adapters/http/schema-registry.ts:12-34`) 성공에 `error` 키, 실패에 `data` 키가 있으면 거절한다. 프론트 계약 §4.1도 "Envelope 최상위 unknown field는 현재 거절된다"(`backend-api-and-server-state-contract.md:195`). 백엔드 테스트 `EnvelopeBodyAdviceTest.rawBodyIsWrappedInEnvelope`는 `jsonPath("$.error").doesNotExist()`(`:57`)로 단언하는데, Spring의 `doesNotExist`는 값이 `null`이어도 통과하므로 이 차이를 잡지 못한다 | +| 발생 조건 | 짝 프론트의 기본 HTTP 클라이언트(`client.ts:917`의 `validateEnvelope`)가 이 백엔드의 아무 JSON 응답이나 받을 때 | +| 영향 | 성공 응답이 `ENVELOPE_MISMATCH`, 실패 응답이 `HTTP_FAILURE`로 바뀐다. 실패 쪽에서는 `error.code`가 분류기에 닿지 않아 02-01의 `IDEMPOTENT_IN_FLIGHT` 구분도 동작하지 않는다. 두 템플릿을 그대로 붙인 첫 화면에서 드러날 결함이라 탐지는 쉽지만, 원인이 "null 필드"라는 것은 양쪽 테스트가 모두 숨긴다 | +| 심각도·우선순위 | High · P1. 짝 템플릿을 같이 쓰는 기본 조합에서 모든 응답이 계약 위반이다 | +| 통제·증거 | 백엔드 쪽 통제 M0(wire 모양을 고정하는 문서·테스트 없음) · 증거 E2(백엔드 실행) + E1(프론트 코드 읽기, 프론트 실행 안 함) | +| 확실성과 남은 가정 | 백엔드 JSON은 실행으로 확인했다. 프론트가 `validateEnvelope` 전에 null을 지우는 단계가 있는지는 `client.ts:899-917`까지 읽어 없음을 확인했지만 실제 결합 실행은 안 했다 | +| 결정의 근거 | `[사실]` Envelope 하나로 통일은 소유자 결정 2다. 이 발견은 결정을 뒤집지 않는다. `[사실]` 백엔드에는 소비자가 읽을 wire 계약 문서가 없고(README의 예외 표뿐), 프론트가 자기 문서에 백엔드 모양을 추측해 적었다 | +| 이해 비용 | 파생 서비스 개발자는 Envelope record를 보고는 null 필드가 나가는지 알 수 없다. ObjectMapper 기본값을 알아야 한다 | +| 최소 개선 방향 | 백엔드에 HTTP wire 계약 문서를 하나 둔다(`docs/web/http-contract.md` 같은 이름). Envelope의 필드 존재 규칙(성공은 `success·data·meta`, 실패는 `success·error·meta`, null 필드 생략)과 `meta`의 키를 적고, `Envelope`·`ApiError`·`ResponseMeta`에 `@JsonInclude(NON_NULL)`을 붙인다. 테스트는 `doesNotExist` 대신 원문 JSON의 키 집합을 단언한다 | +| 대안 비교 | A) **백엔드가 null 필드를 생략**(권장): shared-contract 타입 3개에 한 줄씩. GraphQL·STOMP 등 다른 전송도 같은 타입을 쓰면 함께 바뀌므로 그쪽 계약도 확인해야 한다. B) **프론트가 `.strict()`를 풀거나 null 허용**: 백엔드 변경 없음. 대신 "unknown field 거절"이라는 프론트의 방어 규칙을 약하게 만든다. C) **둘 다 문서만 맞춤**: 실행 결과가 바뀌지 않는다. 기각 | +| 단순화의 보존 조건 | `success` 판별자, `error.code` 안정성, 빈 목록(`[]`)과 null의 구분(목록 필드는 생략하지 않음) | +| 비용·부작용 | A는 shared-contract 변경이라 모든 전송의 직렬화 테스트를 한 번 돌려야 한다. `details:null`을 기대하는 기존 테스트가 있으면 같이 고친다 | +| 재검토 조건 | 프론트가 envelope 검증을 느슨하게 바꾸기로 결정하면 B로 간다 | +| 완료 기준 | 성공 응답 원문에 `error` 키가 없고 실패 응답 원문에 `data` 키가 없다. 계약 문서에 키 목록이 있고 짝 프론트 §4.1이 그 문서를 가리킨다 | +| 검증 방법 | `EnvelopeBodyAdviceTest`와 `GlobalExceptionHandlerTest`에 응답 원문 JSON의 최상위 키 집합 단언. 프론트 fixture를 백엔드 실제 응답 문자열로 한 번 교체해 `validateEnvelope` 통과 확인 | + +### 02-03 JWT audience 검증이 기본으로 꺼져 있고, 모든 client의 role을 합친다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(안전하지 않은 기본값, 문서와 코드 불일치) | +| 관련 관점 | 15, 19, 21, 5 | +| 근거 | `SecuritySettings.java:35-42`: audience가 null이면 WARN 한 줄을 남기고 `""`로 둔다. 빈 문자열이면 경고도 없다. `JwtDecoderConfig.java:80-82`: 비어 있으면 audience validator를 넣지 않는다. 기본 설정은 `config/security.yml:11-12`(`audience: ${APP_SECURITY_JWT_AUDIENCE}`, 주석 "blank to skip"), `.env.example:97`(`APP_SECURITY_JWT_AUDIENCE=` 빈 값). 반면 env 레지스트리는 `required: true`, `validation: csv_non_empty`, 타입 `csv_list`(`docs/registries/env-keys.yaml:1177-1187`). 코드는 값 하나만 비교하므로(`JwtDecoderConfig.java:101-104`, `contains(audience)`) `a,b`처럼 목록을 주면 모든 토큰이 거절된다. role 추출은 `resource_access`의 **모든 client** role을 합친다(`JwtToAuthenticatedPrincipalConverter.java:79-87`) | +| 발생 조건 | 같은 issuer(예: Keycloak realm 하나)에 이 서비스 말고 다른 client가 있다. 운영자가 `APP_SECURITY_JWT_AUDIENCE`를 비워 둔 채 배포한다(템플릿 기본값) | +| 영향 | 다른 앱을 위해 발급된 토큰도 이 API에서 인증된다. 그 토큰의 `resource_access.<다른 client>.roles`에 이 서비스의 role 이름(예: `operation-submit`, `ROLE_FILE_ADMIN`)과 같은 값이 있으면 권한까지 얻는다. 기본 role-permission 표(`security.yml` `app.authz.role-permissions`)가 일반적인 이름을 쓰므로 겹칠 여지가 있다 | +| 심각도·우선순위 | High · P1. 인증 경계의 기본값이 열려 있고, 레지스트리는 "필수"라고 말해 운영자가 안심한다. 실제 다른 client 토큰으로 접근한 실험은 하지 않아 Critical로 올리지 않았다 | +| 통제·증거 | 통제 M1(레지스트리에 required로 명시, 코드는 강제 안 함) · 증거 E1(코드·설정 읽기). audience 불일치 거부 자체는 기존 테스트가 있다(`JwtDecoderConfigTest`) | +| 확실성과 남은 가정 | 코드 경로는 확정. `verifyEnvKeys`가 런타임 값의 비어 있음을 막지 않는다는 것은 레지스트리 형식과 `.env.example` 빈 값으로 추론했다(실행 안 함) | +| 결정의 근거 | `[기록된 의도]` "blank to skip audience check"(`security.yml:11`). `[추론]` 로컬·테스트 편의를 위한 기본값이 운영 기본값으로 남았다. local·test 프로필은 audience를 채운다(`application-local.yml:174`, `application-test.yml:54`) | +| 이해 비용 | 운영자는 레지스트리의 `required: true`를 믿고, 개발자는 WARN 로그를 보지 않는다. 두 문서를 대조해야 위험이 보인다 | +| 최소 개선 방향 | JWT 모드에서 audience가 비면 기동을 거부한다(issuer와 같은 방식, `SecuritySettings.java:30-33`). 목록을 받으려면 `List`으로 바인딩하고 "하나라도 포함"으로 비교한다. role 추출은 `resource_access` 중 audience(또는 설정한 client id)의 role만 읽는다 | +| 대안 비교 | A) **audience 필수 + 자기 client role만**(권장): 기본값이 닫힌다. 비용은 기존 배포가 env 하나를 채워야 한다는 것. B) **prod 프로필에서만 필수**: 로컬 편의 유지. 대신 프로필 이름에 보안이 걸리고 dev·staging이 열린다. C) **현상 유지 + 문서 강조**: 숨은 위험이 그대로 남는다. 사용자 원칙("위험은 코드에 드러나야 한다")에 어긋나 기각 | +| 단순화의 보존 조건 | issuer·timestamp 검증, 오류 코드 `AUTH_AUDIENCE_MISMATCH` 401, realm role 읽기 | +| 비용·부작용 | 기존 파생 서비스의 기동이 env 누락으로 실패할 수 있다. 실패 메시지에 env 키 이름을 넣는다 | +| 재검토 조건 | issuer를 서비스 전용으로 쓰는 배포만 지원한다고 명시하면 A의 role 범위 부분은 완화할 수 있다 | +| 완료 기준 | JWT 모드에서 audience가 비면 기동 실패. 다른 client의 role만 가진 토큰이 권한을 얻지 못한다 | +| 검증 방법 | `SecuritySettingsTest`에 빈 audience 거부, `JwtToAuthenticatedPrincipalConverterTest`에 "다른 client의 role은 무시" 케이스 | + +### 02-04 rate-limit 거부 본문이 실제 Tomcat에서 ISO-8859-1로 나가 한국어 문구가 깨진다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 1, 17, 23, 10 | +| 근거 | `RateLimitInterceptor.java:77-81`은 `setContentType("application/json")` 뒤 `getWriter()`로 쓴다. 문자셋을 정하지 않는다. 같은 일을 하는 `AuthErrorResponseWriter.java:43-44`와 `GraphQlRequestBodyLimitFilter.java:119-120`은 UTF-8을 지정한다. **실험(E3)**: 실제 embedded Tomcat + Spring Boot 기본값과 같은 `CharacterEncodingFilter("UTF-8", forceRequest=true, forceResponse=false)`로 거부 응답을 받으니 `content-type=application/json;charset=ISO-8859-1`, 본문 `"message":"??? ?? ????. ?? ? ?? ??? ???."`. 기존 `RateLimitInterceptorTest`는 code·category·retryable만 단언해 이 문제를 못 잡는다 | +| 발생 조건 | `app.rate-limit.enabled=true`에서 429 `RATE_LIMIT_EXCEEDED`, 503 `RATE_LIMIT_UNAVAILABLE`·`RATE_LIMIT_INCOMPATIBLE` 응답 | +| 영향 | 사용자에게 보일 문구가 `?`로 바뀐다. `content-type`의 문자셋도 틀린다. code·retryable은 ASCII라 기계 판정은 유지된다 | +| 심각도·우선순위 | Medium · P2. 기능 판정은 살아 있고 문구만 망가진다 | +| 통제·증거 | M0(이 경로의 문자셋 통제 없음) · E3(실제 Tomcat 실험) | +| 확실성과 남은 가정 | Boot의 Tomcat factory가 응답 문자셋을 따로 정하지 않는다는 것은 `spring-boot-tomcat-4.0.8.jar`에서 `setResponseCharacterEncoding` 호출이 없음을 확인해 판단했다 | +| 결정의 근거 | 적용 제외 — 같은 저장소의 다른 writer가 이미 UTF-8을 지정하고 있어 고를 선택지가 없는 단순 누락 | +| 이해 비용 | 필터·인터셉터에서 본문을 직접 쓰는 곳이 셋이고 각각 문자셋을 기억해야 한다(41절 C 참고) | +| 최소 개선 방향 | `RateLimitInterceptor.reject`에 `setCharacterEncoding(UTF_8)`. 더 나은 방법은 "직접 쓰는 Envelope 응답" writer 하나를 두고 셋이 그것을 쓰게 하는 것(리팩토링 후보 R-1) | +| 대안 비교 | 적용 제외 — 단순 결함 수정 | +| 완료 기준 | 실제 Tomcat에서 429 본문이 UTF-8이고 문구가 `ClientErrorMessages`와 같다 | +| 검증 방법 | `RateLimitInterceptorTest`에 `getContentAsString(UTF_8)`의 message 단언 + `getCharacterEncoding()`이 UTF-8임을 단언 | + +### 02-05 CORS에 노출 헤더가 없어 브라우저가 계약 헤더를 못 읽는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(설정 공백) | +| 관련 관점 | 17, 15, 19, 8 | +| 근거 | `SecurityConfig.java:150-156`은 origins·methods·headers·credentials·maxAge만 설정하고 `setExposedHeaders`가 없다. `CorsSettings`에도 해당 필드가 없다. 저장소 전체에서 `exposedHeaders`는 gRPC-Web 계약 클래스에만 있다 | +| 발생 조건 | 브라우저 앱이 API와 다른 origin에서 부른다(`app.cors.enabled=true`, sample 기본값 `http://localhost:3000`) | +| 영향 | 브라우저는 CORS 안전 목록 밖의 응답 헤더를 숨긴다. `Retry-After`(429·503, 그리고 02-01의 개선안), `X-Request-Id`(지원 문의용), `Location`(202 operation, poster publication), `ETag`(조건부 쓰기), `X-RateLimit-*`, tus의 `Upload-Offset`·`Location`·`Tus-Resumable`이 모두 `null`로 보인다. 짝 프론트는 `Retry-After`를 읽는다(`frontend/src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts:20`). cross-origin tus 업로드는 offset을 못 읽어 재개가 깨진다 | +| 심각도·우선순위 | Medium · P2. same-origin(BFF·리버스 프록시) 배포에는 영향이 없다 | +| 통제·증거 | M0 · E1(코드·설정 읽기). 브라우저 실행은 안 함 | +| 확실성과 남은 가정 | CORS 안전 목록 동작은 Fetch 표준의 정의다. 배포가 프록시에서 `Access-Control-Expose-Headers`를 붙이는지는 템플릿 밖이라 모른다 | +| 결정의 근거 | 적용 제외 — 노출할 헤더는 이미 계약에 있는 헤더라 선택지가 아니라 누락이다. 다만 목록을 설정으로 열지 고정할지는 아래에서 비교 | +| 최소 개선 방향 | `CorsSettings`에 `exposedHeaders`를 추가하고 기본값을 플랫폼 계약 헤더(`ApiHeaders`의 `Retry-After`·`X-Request-Id`·`X-Correlation-Id`·`Location`·`ETag`·`X-RateLimit-*`)로 둔다. fileserver composition은 tus·draft-12 헤더를 기여한다 | +| 대안 비교 | A) 기본 목록 + 설정 확장(권장). B) env 하나로 전부 운영자에게 맡김: 기본 배포가 계속 깨진다. C) `*` 노출: credentials 모드에서 `*`는 리터럴로 취급돼 동작하지 않는다 | +| 완료 기준 | CORS preflight·실 요청 응답에 `Access-Control-Expose-Headers`가 위 목록을 담는다 | +| 검증 방법 | `CorsSecurityFilterIntegrationTest`에 노출 헤더 단언 | + +### 02-06 `String`을 반환하는 컨트롤러는 `Accept: application/json`에서 500이 된다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(숨은 함정) | +| 관련 관점 | 5, 21, 20, 1 | +| 근거 | `EnvelopeBodyAdvice.java:45-48`은 선택된 content type이 JSON이면 무엇이든 `Envelope`로 바꾼다. `String` 반환은 `StringHttpMessageConverter`가 고르므로 바뀐 `Envelope`를 String 컨버터가 받는다. **실행(E2)**: `Accept: application/json` → `500`, `ClassCastException`, 본문 `INTERNAL_ERROR`. `Accept: */*` → `200 text/plain "hello"`. 같은 엔드포인트가 curl에서는 되고 JSON 클라이언트에서는 깨진다. 이를 막는 ArchUnit 규칙(`WebArchitectureRules`)이나 문서가 없다 | +| 발생 조건 | 파생 서비스 개발자가 `@GetMapping String ...`을 만든다 | +| 영향 | 그 엔드포인트가 JSON 클라이언트에서 항상 500이고, 로그에는 ERROR로 ClassCastException이 남는다 | +| 심각도·우선순위 | Medium · P2. 개발 중 바로 보이지만 원인 추적이 어렵고, 템플릿이 숨긴 규칙이다 | +| 통제·증거 | M0 · E2 | +| 결정의 근거 | 적용 제외 — 동작 결함. 막는 방식만 고른다 | +| 최소 개선 방향 | `beforeBodyWrite`에서 `selectedConverterType`이 `StringHttpMessageConverter`면 감싸지 않거나, `supports`에서 String 반환을 제외한다. 또는 `WebArchitectureRules`에 "컨트롤러는 `String`을 반환하지 않는다" 규칙을 둔다 | +| 대안 비교 | A) advice가 String을 통과(텍스트로 응답): 간단하지만 "모든 JSON은 Envelope"가 깨진다. B) ArchUnit으로 금지(권장): 규칙이 코드에 드러난다. C) String 컨버터 앞에 Jackson을 두기: 전역 컨버터 순서를 바꿔 다른 곳에 영향 | +| 완료 기준 | String 반환 컨트롤러가 빌드에서 거부되거나 200으로 응답한다 | +| 검증 방법 | `EnvelopeBodyAdviceTest`에 String probe 추가 또는 `WebArchitectureRulesTest`에 위반 fixture | + +### 02-07 web-advanced 예외 10종이 문서의 상태 대신 500으로 나간다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(라이브러리 계약 미연결) | +| 관련 관점 | 17, 6, 23, 22 | +| 근거 | `web-advanced/src/main/java/.../advanced/` 아래 예외 10종(`AdmissionRefusedException`, `JsonPatchTestFailedException`, `JsonPatchRejectedException`, `PatchAuthorizationException`, `UnsupportedApiVersionException`, `SunsetViolationException`, `UntrustedTenantInputException`, `ReplayCursorExpiredException`, `StreamItemTooLargeException`, `RouteInventoryMismatchException`)이 모두 `RuntimeException`만 상속하고 `ApiErrorCarrier`가 아니다. leaf에 `@ExceptionHandler`도 없다. 문서는 상태를 약속한다: "maps to 503 with a Retry-After"(`AdmissionRefusedException.java:6`), "A failed `test` is 409"(`docs/web/patch-contract.md:66`). **실행(E2)**: `AdmissionRefusedException` → `500 INTERNAL_ERROR`, `Retry-After` 없음, 그리고 `GlobalExceptionHandler.handleUnknown`이 ERROR 로그를 남긴다 | +| 발생 조건 | 서비스가 web-advanced의 admission guard, JSON Patch, API 버전 정책을 컨트롤러에서 쓴다(opt-in, 현재 운영 소비자 0) | +| 영향 | 부하 거절이 500으로 보여 클라이언트가 재시도하지 않고, 알림이 장애로 울린다. patch `test` 실패가 500이라 "다시 읽고 재시도"를 못 한다 | +| 심각도·우선순위 | Medium · P2. 기본 조합에는 없지만 라이브러리를 켜는 순간 모든 서비스에 복제된다 | +| 통제·증거 | M1(Javadoc·문서) · E2(AdmissionRefused 한 종 실행, 나머지는 E1) | +| 결정의 근거 | `[사실]` S5 정리 때 problem 어휘(`WebProblem`)를 지우면서 이 예외들의 매핑도 같이 사라졌다(`docs/capability-status.md` 「제거된 코드」 표 「WebProblem 어휘」). `[추론]` 예외는 남고 변환만 빠졌다 | +| 최소 개선 방향 | 각 예외가 `ApiErrorCarrier`를 구현하고 코드 enum 하나(`WebAdvancedError`: 상태·category·retryable)를 둔다. 그러면 `GlobalExceptionHandler.handleCarrier` 한 분기로 처리되고 `Retry-After`도 `RetryAfterAdvisor` 표로 붙는다 | +| 대안 비교 | A) carrier + enum(권장): 기존 한 분기 재사용. B) web-advanced 전용 `@RestControllerAdvice`: 오류 경로가 하나 더 생긴다(지난 리뷰가 지운 모양). C) 문서에서 상태 약속 삭제: 라이브러리의 쓸모가 줄고 500은 그대로 | +| 완료 기준 | 10종 각각이 문서의 상태·코드로 나간다. 문서와 enum이 같은 값을 말한다 | +| 검증 방법 | web-advanced에 예외별 MockMvc 매핑 테스트(실험 코드 `Review02AdvancedExceptionStatusExperimentTest`를 그대로 시작점으로) | + +### 02-08 Spring MVC 예외의 상태→코드 변환이 의미를 잃는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 17, 23, 6 | +| 근거 | `GlobalExceptionHandler.java:353-369`의 표는 4xx 나머지를 `BAD_PARAMETER`, 5xx를 전부 `INTERNAL_ERROR`로 보낸다. **실행(E2)**: `AsyncRequestTimeoutException`(Spring은 503) → `500 INTERNAL_ERROR retryable=false`. `@RequestParam @Max(10) int limit`에 99 → `HandlerMethodValidationException` → `400 BAD_PARAMETER details:null`. 같은 종류의 위반을 `ConstraintViolationException` 경로는 `VALIDATION_FAILED` + 필드 details로 낸다(`GlobalExceptionHandler.java:83-88`) | +| 발생 조건 | async·streaming(web-advanced) 타임아웃, 컨트롤러 파라미터에 Bean Validation 제약 | +| 영향 | 일시적 타임아웃이 재시도 불가 내부 오류로 보인다. 클라이언트는 어느 파라미터가 틀렸는지 모른다. 같은 위반이 경로에 따라 코드가 다르다 | +| 심각도·우선순위 | Low · P2 | +| 통제·증거 | M2(변환은 있음, 의미는 틀림) · E2 | +| 결정의 근거 | 적용 제외 — 표에 두 줄을 더하는 단순 수정 | +| 최소 개선 방향 | 503 → 일시적 코드(retryable), `handleHandlerMethodValidationException` override로 `VALIDATION_FAILED` + `ClientSafeValidationDetails` | +| 완료 기준 | 위 두 요청이 각각 503 retryable, 400 `VALIDATION_FAILED` + field details | +| 검증 방법 | `TransportErrorHandlingTest`에 두 케이스(I-3c의 남은 부분도 여기서 닫힌다) | + +### 02-09 JSON 본문 상한의 두 갈래가 테스트로 묶여 있지 않고, JSON 아닌 본문은 상한이 없다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(테스트 공백) + 구조적 위험 | +| 관련 관점 | 15, 10, 14 | +| 근거 | **변이 실험**: ① `JsonBodyLimitFilter.java:87`의 선언 길이 사전 거부를 `if (false)`로 바꿈 → `JsonBodyLimitFilterTest`·`RequestBodyBoundaryTest`·`GlobalExceptionHandlerTest`·`TransportErrorHandlingTest` 모두 통과(생존). Javadoc이 약속한 "읽기 전에 거부"가 깨져도 아무 테스트도 실패하지 않는다. ② `shouldNotFilter`의 `+json` 분기 삭제(`:57-58`) → 생존. `application/merge-patch+json` 본문이 상한 없이 읽혀도 모른다. ③ 대조군: `handleCarrier`의 `Retry-After` 줄 삭제 → 5건 실패(죽음), 하네스가 정상임을 확인. 또 `shouldNotFilter`는 content type이 JSON이 아니면 통과시킨다(`:50-61`). `@RequestBody String`·`byte[]`를 `text/plain`·`application/octet-stream`·XML로 받는 엔드포인트에는 상한이 없다. Javadoc은 "Other media types keep their own ceilings"라고 적지만 multipart·form·tus·콜백 외에는 없다 | +| 발생 조건 | 누군가 사전 거부를 리팩터링으로 지우거나, 서비스가 JSON 아닌 `@RequestBody`를 받는다 | +| 영향 | 인증된 호출자가 큰 본문으로 힙을 채울 수 있다(인증 전 경로는 Tomcat이 막지 않는다) | +| 심각도·우선순위 | Low · P2. 기본 조합의 JSON 경로는 스트림 계수로 여전히 막힌다 | +| 통제·증거 | M2(구현) · M3 아님(변이 생존) · E2(변이 실험) | +| 최소 개선 방향 | 테스트 2개 추가(선언 길이 초과면 `getInputStream`을 부르기 전에 예외, `+json` 본문도 상한 적용). JSON 아닌 본문은 같은 래퍼를 "multipart·form·등록된 업로드 경로 제외 전부"에 적용하는 쪽을 검토 | +| 대안 비교 | A) 상한 대상을 "JSON"에서 "예외 목록 외 전부"로 뒤집기: 새 media type이 자동으로 보호된다. 업로드 경로를 빠뜨리면 업로드가 막히므로 예외 목록 테스트가 필요. B) JSON만 유지 + 문서에 "다른 타입은 직접 상한": 숨은 규칙이 남는다 | +| 완료 기준 | 변이 ①②가 테스트에서 죽는다 | +| 검증 방법 | 같은 변이를 다시 적용해 실패 확인 | + +### 02-10 `GlobalExceptionHandler`가 두 경로로 등록된다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(Javadoc과 동작 불일치) | +| 관련 관점 | 4, 24, 19, 27 | +| 근거 | `WebAdapterAutoConfiguration.java:47`이 `GlobalExceptionHandler.class`를 조건 없이 `@Import`한다. `WebMvcPlatformAutoConfiguration.java:46-52`는 같은 타입을 `@ConditionalOnMissingBean`으로 다시 정의하는데, 앞의 import가 먼저라 이 정의는 실행되지 않는다. `WebMvcPlatformAutoConfiguration` Javadoc은 "off means no beans"라고 하지만 `app.web.mvc.enabled=false`여도 핸들러는 남고, 꺼지는 것은 요청 ID 필터와 JSON 본문 상한뿐이다 | +| 발생 조건 | 서비스가 자기 오류 핸들러로 바꾸려고 스위치를 끄거나 같은 타입의 bean을 등록한다 | +| 영향 | 끄면 보안 관련 본문 상한만 조용히 빠진다. 같은 타입 bean을 하나 더 두면 `@RestControllerAdvice` 두 개가 생기고 어느 쪽이 이길지 순서에 달린다 | +| 심각도·우선순위 | Low · P3 | +| 통제·증거 | M1 · E1 | +| 최소 개선 방향 | 등록 경로를 하나로(Platform 쪽 `@Bean`만 남기고 `@Import` 목록에서 제거). 스위치가 무엇을 끄는지 README 한 줄 | +| 완료 기준 | `enabled=false`에서 무엇이 남는지 테스트가 단언한다 | +| 검증 방법 | `WebMvcPlatformAutoConfigurationTest`에 스위치 off 케이스 | + +### 02-11 `X-Correlation-Id` 허용 문자·길이가 요청 ID 규칙·짝 계약과 다르다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(계약 불일치) | +| 관련 관점 | 8, 17, 23 | +| 근거 | 요청 ID는 `[A-Za-z0-9._-]{1,128}`만 받는다(`WebMvcRequestIdFilter.java:62`). correlation ID는 `HeaderSanitizer`가 `0x20` 미만만 지우고 200자까지 그대로 둔다(`HeaderSanitizer.java:19`, `WebMvcRequestIdFilter.java:64,160-165`). 공백·유니코드·`DEL`이 응답 헤더와 `meta.correlationId`로 그대로 돌아간다. 짝 계약은 세 ID 모두 "1..128 안전한 opaque"(`backend-api-and-server-state-contract.md:199-200`)이고, 프론트 스키마는 `[A-Za-z0-9._:-]{1,128}`로 검증한다(`schema-registry.ts:6-8`) | +| 발생 조건 | 프록시나 다른 클라이언트가 규칙 밖의 correlation ID를 보낸다 | +| 영향 | 그 응답의 envelope 검증이 프론트에서 실패한다. 로그 검색 키가 공백·유니코드를 담는다 | +| 심각도·우선순위 | Low · P3 | +| 통제·증거 | M2(개행 제거는 됨) · E1 | +| 최소 개선 방향 | correlation ID도 요청 ID와 같은 패턴을 쓰고, 맞지 않으면 새로 발급한다 | +| 완료 기준 | 규칙 밖 값이 들어오면 서버가 만든 값이 응답에 나간다 | +| 검증 방법 | `WebMvcRequestIdFilterTest`에 공백·유니코드·129자 케이스 | + +### 02-12 `Idempotency-Key` 헤더 검증이 컨트롤러마다 새로 쓰인다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 개선 제안(구조적 위험) | +| 관련 관점 | 20, 23, 3, 25 | +| 근거 | web leaf는 헤더 이름 상수만 준다(`ApiHeaders.java:10`). 키 추출은 "구체 엔드포인트의 몫"이라고 정했다(`docs/web/repository-adaptation.md:99`). 유일한 운영 예시 `PosterImagePublicationController.java:61-69`는 blank·256자 초과면 `IllegalArgumentException`(→ `BAD_PARAMETER`), 문자 집합 규칙 없음, 헤더가 아예 없으면 Spring의 `MissingRequestHeaderException`(→ `BAD_PARAMETER`, 같은 코드). testFixtures의 `FaultFixtureController`는 또 다른 방식으로 받는다 | +| 발생 조건 | 서비스가 KEYED 엔드포인트를 늘린다 | +| 영향 | 엔드포인트마다 길이·문자·누락 처리·오류 코드가 갈라진다. 클라이언트는 "키 형식 오류"와 "다른 파라미터 오류"를 구분하지 못한다 | +| 심각도·우선순위 | Low · P3 | +| 통제·증거 | M1 · E1 | +| 결정의 근거 | `[기록된 의도]` claim·fingerprint는 use case가 소유(`README.md:460-466`). 이 제안은 그 결정을 바꾸지 않고 "헤더 → 검증된 값" 한 단계만 공용으로 만든다 | +| 최소 개선 방향 | web leaf에 `IdempotencyKeyHeader`(값 객체 + argument resolver 또는 정적 parse)를 두고 길이·문자 규칙과 전용 코드(예: `IDEMPOTENCY_KEY_INVALID` 400)를 한 곳에서 정한다. sample이 그것을 쓴다 | +| 대안 비교 | A) 공용 parse(권장). B) 현상 유지 + 문서 규칙: 복사본이 갈라지는 것을 막지 못한다. C) 필터로 모든 POST에 강제: KEYED가 아닌 엔드포인트까지 막는다 | +| 완료 기준 | KEYED 컨트롤러가 같은 parse를 쓰고, 형식 오류는 한 코드로 나간다 | +| 검증 방법 | parse 단위 테스트 + sample 컨트롤러 테스트 | + +## 4. 31절 시나리오 추적 + +### 4.1 중복·동시 요청 — sample `POST /posters/{id}/imagePublications` 같은 키 재전송 + +```text +브라우저 --Idempotency-Key--> WebMvcRequestIdFilter(요청 ID) -> JsonBodyLimitFilter(multipart라 통과) + -> Spring Security(JWT) -> RequestLoggingFilter -> RateLimitInterceptor(켜졌을 때) + -> PosterImagePublicationController(키 blank·길이 검사) + -> PublishPosterImageUseCase: transactions.inWrite( IdempotencyExecutor.execute(scope, fingerprint, attempt, action) ) + -> 결과: 202 / replay 202 / 409 IN_FLIGHT / 422 MISMATCH / 503 UNAVAILABLE / 500 RECOVERY_REQUIRED +``` + +| 항목 | 기록 | +| --- | --- | +| 입력 신뢰 | 키는 호출자 값. 길이만 본다(02-12). scope는 tenant·principal·키를 digest한 값이라 원문 키는 저장소에 가지 않는다 | +| 인가 | 보안 체인이 인증. 권한은 use case 쪽(sample 정책). principal이 없으면 `IllegalArgumentException` → 400(401이 아님 — 보안 체인이 먼저 막으므로 도달 불가) | +| 규칙 소유 | 같은 요청 판정은 `IdempotencyExecutor`와 use case의 fingerprint(`PosterImagePublicationFingerprint`) | +| 트랜잭션 | `execute`가 `inWrite` 안에서 돈다. PostgreSQL 저장소면 claim이 같은 트랜잭션에 묶이고, Redis면 밖에 있다. 두 경우의 동시 요청 동작 차이는 application·persistence 영역(이 리뷰 범위 밖, 미검증) | +| 외부 부작용 | object storage staging은 트랜잭션 뒤(`stageAndPrepare`) | +| 성공의 의미 | 202는 "예약됨". 상태는 `GET .../{operationId}`로 본다 | +| 오류 변환 | carrier 한 분기. in-flight 409의 클라이언트 행동이 정해지지 않았다(02-01). complete 단계의 503은 "action 전"이라는 문서와 다르다(P6-new-2) | +| 진단 | 응답 `meta.requestId`·`traceId`. scope digest는 로그에만 | + +### 4.2 다른 사용자 리소스 접근 — `GET /operations/{id}` + +`DurableOperationController.get`은 principal·tenant를 query에 담아 `GetDurableOperationUseCase`로 넘기고, 없음과 남의 것을 같은 404 `OPERATION_NOT_FOUND`로 답한다(`DurableOperationController.java:106-118`). 판정은 use case와 `DurableOperationAccessPolicy`가 소유한다(I-1a 해결 유지). ID를 바꿔도 존재 여부가 새지 않는다. 남은 점: `OperationErrorCode`가 web 패키지 안의 enum이라 GraphQL·gRPC가 같은 연산을 노출하면 코드가 따로 생긴다(관찰, 발견으로 올리지 않음). + +### 4.3 큰 입력 — JSON 본문, 콜백 본문, 목록 + +JSON은 1 MiB 기본 상한(`WebMvcPlatformSettings`)으로 선언 길이·스트림 계수 두 단계로 막는다(테스트 공백은 02-09). 알림 콜백은 컨트롤러가 `readNBytes(max+1)`로 직접 막는다. fileserver admin의 `limit`·`maxItems`는 HTTP에서 상한 없이 받아 use case로 넘긴다(use case 쪽 상한은 fileserver 영역에서 확인). 페이지 파라미터는 `PageParams`가 막는다. + +### 4.4 적용 제외 + +| 시나리오 | 사유 | +| --- | --- | +| 외부 응답 지연·유실, DB 오류·경쟁, 메시지 중복·역순, 여러 서버 작업 실행 | 이 영역은 변환만 한다. 원인 쪽은 httpclient·persistence·messaging 영역 | +| 신·구 버전 공존 | web-advanced 버전 정책은 운영 소비자 0. 예외 변환 결함만 02-07에 적었다 | +| 세션·토큰 갱신 경쟁 | JWT 기본 모드는 서버 세션이 없다. redis-session 모드는 실행하지 않았다(미검증) | +| 종료·재시작 | `GracefulShutdownProbe`·`TomcatLoadAndShutdownIT`가 있으나 `performanceTest`는 게이트에서 컴파일만 됐다(미검증) | +| 선택 어댑터 제거 | composition 영역 | + +## 5. 41절 설계 선택 검토 + +### 5.1 HTTP 오류를 Envelope 하나로(소유자 결정 2) + +| 질문 | 답 | +| --- | --- | +| 1. 무엇이 필요한가 | 모든 HTTP 오류가 한 모양이고 `error.code`가 안정적이어야 한다. 짝 프론트가 이 모양을 검증한다 | +| 2. 지킬 성질 | 어떤 경로(MVC 예외, 보안 체인, 인터셉터, fileserver)에서도 같은 키 집합·같은 문구 표·같은 코드 규칙 | +| 3. 현재 보장 | `ErrorResponseFactory`가 본문을 만들고 `ClientErrorMessages`가 문구를 정한다. problem+json 누수는 막혔다(I-3a). 보장하지 않는 것: null 필드 존재(02-02), 직접 쓰는 writer의 문자셋(02-04), 라이브러리 예외의 코드(02-07) | +| 4. 대안 | 현상 유지 / RFC 9457 problem+json / Envelope + wire 계약 문서 | +| 5. 득실 | problem+json은 표준 도구와 맞지만 결정 2를 뒤집는다. Envelope 유지는 비용이 작고, 대신 wire 규칙을 문서·테스트로 고정해야 한다 | +| 6. 왜 이 선택 | 결정 2를 유지한다. 부족한 것은 선택이 아니라 "키 집합을 단언하는 테스트와 소비자용 문서"다 | +| 7. 재검토 조건 | 외부 공개 API로 쓰여 표준 도구 연동이 요구되면 problem+json을 다시 비교한다 | + +### 5.2 멱등성 in-flight는 기다리지 않고 409, retryable=false + +| 질문 | 답 | +| --- | --- | +| 1. 필요 | 결과 불명 쓰기를 같은 키로 안전하게 다시 보낼 수 있어야 한다 | +| 2. 성질 | 같은 키는 한 번만 실행. 처리 중인 동안 다른 시도는 실행하지 않는다. 클라이언트는 "새 키로 다시"를 하지 않는다 | +| 3. 현재 보장 | 앞 두 성질은 executor가 보장한다. 세 번째는 응답이 오히려 반대로 말한다(02-01) | +| 4. 대안 | 409 + retryable=true + `Retry-After` / 서버 대기 후 replay / 키 조회 엔드포인트 / 202 + 상태 URL | +| 5. 득실 | 02-01 표 참고. 202 + 상태 URL은 모든 KEYED 엔드포인트를 비동기 모양으로 바꿔야 해 비용이 크다 | +| 6. 선택 | 기다리지 않는 409는 스레드를 잡지 않아 유지할 가치가 있다. retryable 값과 문서를 고친다 | +| 7. 재검토 | 처리 시간이 대부분 lease보다 짧다는 측정이 나오면 짧은 대기 + replay가 더 단순할 수 있다 | + +### 5.3 rate limit·인증 거부는 컨버터 밖에서 본문을 직접 쓴다 + +| 질문 | 답 | +| --- | --- | +| 1. 필요 | 컨트롤러 전에 거부한 요청도 Envelope로 답한다 | +| 2. 성질 | 본문·문자셋·헤더가 컨트롤러 응답과 같다 | +| 3. 현재 보장 | 세 writer(`AuthErrorResponseWriter`, `RateLimitInterceptor.reject`, GraphQL body limit)가 각자 `setContentType`·`writeValue`를 한다. 하나가 문자셋을 빠뜨렸다(02-04) | +| 4. 대안 | 현상 유지 / 공용 `EnvelopeResponseWriter` / 인터셉터가 예외를 던져 `GlobalExceptionHandler`가 쓰게 함 | +| 5. 득실 | 공용 writer는 파일 하나로 세 경로가 같아진다. 예외 방식은 보안 체인 안에서는 쓸 수 없다(MVC 밖) | +| 6. 선택 | 공용 writer(리팩토링 R-1) | +| 7. 재검토 | 보안 체인 거부를 MVC로 넘기는 구조로 바뀌면 예외 방식으로 합칠 수 있다 | + +## 6. 리팩토링 후보 + +| ID | 무엇을 | 왜 | 보존 조건 | +| --- | --- | --- | --- | +| R-1 | `AuthErrorResponseWriter`·`RateLimitInterceptor.reject`의 본문 쓰기를 web의 `EnvelopeResponseWriter` 하나로 | 문자셋·content type·`Retry-After` 규칙이 한 곳에 있게(02-04) | 401의 `WWW-Authenticate`, 429의 `X-RateLimit-*`, 문구는 `ClientErrorMessages` | +| R-2 | web-advanced 예외 10종 → `ApiErrorCarrier` + `WebAdvancedError` enum | 변환이 `handleCarrier` 한 분기로(02-07) | 예외 타입 이름(공개 API surface), 메시지의 서버 전용 정보는 본문에 안 나감 | +| R-3 | profile-name record 5개 → `ProfileName` 하나(S5-#12) | 같은 정규식 다섯 벌 | 각 타입이 서로 대입되지 않게 하려면 래퍼 타입은 유지하고 검증만 공용 | +| R-4 | `GlobalExceptionHandler` 등록 경로 하나로(02-10) | 스위치 의미가 코드와 같게 | 사용자가 같은 타입 bean을 주면 그것이 쓰인다 | +| R-5 | `FileserverRequestContextFactory.java:63` 주석 "set by the request-logging filter" → `WebMvcRequestIdFilter` | 주석이 옛 구조를 말함 | 없음 | +| R-6 | web `build.gradle`의 `testImplementation project(':adapter:inbound:web-fileserver')` | 부모 leaf 테스트가 자식 leaf를 안다(방향 역전, 테스트 범위). `PresentationWebConfigTest`의 예시를 web 안 fixture로 바꾸면 끊을 수 있다 | prefix가 절대 경로 컨트롤러를 건드리지 않는다는 단언 | + +## 7. 기능 개발 패턴과 판단 지점 + +### 7.1 템플릿이 주는 틀 + +- 새 HTTP 엔드포인트: 컨트롤러는 DTO를 반환하고 `EnvelopeBodyAdvice`가 감싼다. 예시는 sample-portfolio 컨트롤러와 `DurableOperationController`. +- 도메인 오류: `ApiErrorCarrier` + 자기 `ApiErrorCode` enum이면 `GlobalExceptionHandler`가 한 분기로 처리한다(`OperationErrorCode`가 예). +- 인가: use case의 `@RequiresPermission` + 소유자·tenant 검사는 use case 안. 관리 경로는 `RestrictedPathRule` bean으로 보안 체인에서 한 번 더. +- 입력: `PageParams`·`SortParam`, `ETags`·`PreconditionFailedException`. +- 테스트: `WebContractAssertions`, `ContractFixtureApplication`, `WebArchitectureRules`(ArchUnit), 장애 fixture(`IdempotencyResponseLossContract`, `CommitThenConnectionResetIT`). + +### 7.2 빠진 것 + +- 소비자용 HTTP 계약 문서(Envelope 키 규칙, 상태·코드·retryable·헤더·클라이언트 행동 표). 지금은 README 예외 표가 유일하다(02-01, 02-02). +- `Idempotency-Key` 공용 parse(02-12). +- CORS 노출 헤더 기본값(02-05). +- `String` 반환 금지 규칙(02-06). +- web-fileserver·web-notification README(S5-#14c). + +### 7.3 개발자가 내려야 하는 판단(매뉴얼 재료) + +1. **응답 모양**: DTO를 반환할지 `Envelope`를 직접 만들지. `String`은 반환하지 않는다. 202·Location이 필요하면 `ResponseEntity>`. +2. **오류 코드 설계**: 새 실패마다 status·category·retryable을 정한다. retryable은 "같은 요청을 그대로 다시 보내면 성공할 수 있는가"로 판단한다(02-01이 이 기준을 어긴 예). +3. **404와 403**: 남의 리소스는 "없음"과 같은 404로 답할지(operation이 이 방식), 403으로 답할지. +4. **KEYED 여부**: 중복 실행이 피해인지. 그렇다면 키를 필수로 받고, fingerprint에 넣을 필드를 use case에서 정하고, in-flight·mismatch 응답을 클라이언트에 어떻게 설명할지. +5. **입력 상한**: JSON 1 MiB 밖의 media type을 받으면 자체 상한을 둔다. +6. **공개 경로·관리 경로**: `public-paths`에 넣을지, `RestrictedPathRule`로 막을지. +7. **브라우저 노출 헤더**: 클라이언트가 읽어야 하는 응답 헤더면 CORS 노출 목록에 넣는다. + +## 8. 28개 관점 판정표 + +| # | 관점 | 판정 | 이유 | +| --- | --- | --- | --- | +| 1 | 코드 성숙도 | P | 대부분 명확하다. 문자셋 누락(02-04), String 함정(02-06) | +| 2 | 구조적 성숙도 | O | leaf 분리와 의존 방향이 registry대로. 인가·멱등 판정이 use case에 있다 | +| 3 | 변경 용이성 | P | 오류 코드 추가는 enum 한 곳. 멱등 키 처리는 엔드포인트마다(02-12) | +| 4 | 인지 부하 | P | 등록 경로 이중(02-10), in-flight 의미를 다섯 곳에서 맞춰 읽어야 함(02-01) | +| 5 | 위험 가시성 | X | audience 기본 off(02-03), String 함정(02-06), null 필드(02-02)가 코드에 드러나지 않음 | +| 6 | 실패 성숙도 | P | 실패 변환은 한 분기. 503→500, 라이브러리 예외 500(02-07, 02-08) | +| 7 | 운영 성숙도 | P | 런북 있음. in-flight 런북 문장이 틀림(02-01) | +| 8 | 디버깅 가능성 | O | 요청·trace ID가 보안 체인 앞에서 한 번 발급되고 모든 응답 `meta`에 실림. correlation ID 규칙만 다름(02-11) | +| 9 | 유지보수 성숙도 | P | 남은 Nit(S5-#12, I-7), 낡은 주석(R-5) | +| 10 | 테스트 성숙도 | P | 테스트 600건 13초대. 그러나 `doesNotExist`가 null을 못 가림(02-02), 본문 상한 변이 2건 생존(02-09), 문구 미단언(02-04) | +| 11 | 데이터 성숙도 | - | 이 영역은 저장하지 않는다 | +| 12 | 동시성 성숙도 | P | in-flight 판정은 저장소가 함. HTTP 계약이 클라이언트 행동을 틀리게 말함(02-01) | +| 13 | 확장성 | ? | 부하를 걸지 않았다 | +| 14 | 성능 성숙도 | ? | 필터 4개·HMAC 한 번 정도로 요청당 비용은 작다고 추정. 측정 안 함. 비JSON 본문 상한 없음(02-09) | +| 15 | 보안 성숙도 | X | audience·role 범위(02-03). 그 밖의 경계(XFF 불신, 요청 ID 불신, 중복 키 JSON 거부, 콜백 별도 체인)는 좋음 | +| 16 | 의존성 성숙도 | O | 방향 위반 없음. 테스트 범위 역방향 하나(R-6) | +| 17 | API / Contract 성숙도 | X | 짝 계약과 3곳 불일치(02-01, 02-02, 02-11), 소비자용 계약 문서 없음 | +| 18 | 배포 성숙도 | > | 13 build/CI 영역 | +| 19 | 설정 성숙도 | P | 대부분 fail-closed. audience만 fail-open(02-03), CORS 노출 설정 없음(02-05) | +| 20 | 개발자 경험 | P | 예시·testkit은 충분. 함정 2개(02-06, 02-12) | +| 21 | Guardrail 성숙도 | P | ArchUnit 규칙 있음. String 반환·audience는 막지 않음 | +| 22 | 추상화 성숙도 | O | `ApiErrorCarrier` 한 분기, `RestrictedPathRule` 기여 방식이 적절. web-advanced 예외만 빠짐(02-07) | +| 23 | 일관성 | P | 같은 위반이 경로에 따라 다른 코드(02-08), writer 문자셋(02-04) | +| 24 | 네이밍 / 의미 성숙도 | P | `retryable=false`가 실제 권장 행동과 반대(02-01), 스위치 이름과 동작 불일치(02-10) | +| 25 | 조직 확장성 | P | KEYED 엔드포인트가 늘면 키 처리 갈라짐(02-12) | +| 26 | Ownership 성숙도 | P | web-fileserver·web-notification에 README·CLAUDE.md 없음(S5-#14c) | +| 27 | 삭제 가능성 | O | web-notification·web-fileserver·web-advanced가 한 줄로 빠진다. 스위치 의미만 02-10 | +| 28 | 회복 가능성 | P | 결과 불명 쓰기의 복구 경로(같은 키 재전송)가 문서에 없다(02-01, P6-new-2) | diff --git a/docs/reviews/2026-11-01-maturity-review/03-inbound-realtime-graphql-grpc.md b/docs/reviews/2026-11-01-maturity-review/03-inbound-realtime-graphql-grpc.md new file mode 100644 index 00000000..930bb383 --- /dev/null +++ b/docs/reviews/2026-11-01-maturity-review/03-inbound-realtime-graphql-grpc.md @@ -0,0 +1,434 @@ +# 03 — inbound 실시간·GraphQL·gRPC (websocket · graphql · grpc 어댑터, vendored `grpc:*`·`grpc-advanced:*`) + +2026-11-01 백엔드 성숙도 리뷰, 영역 03. 기준 커밋 `01a8a2a70`(main). + +## 1. 범위 (36.1) + +| 항목 | 기록 | +| --- | --- | +| 대상 | `src/adapter/inbound/websocket`, `src/adapter/inbound/graphql`, `src/adapter/inbound/grpc`, `src/grpc/*`(registry의 `optional-grpc` leaf 7개), `src/grpc-advanced/*`(2개), `src/optional-platforms` | +| 커밋·시점 | `main` @ `01a8a2a70`, 2026-11-01 | +| 목적·실행 구성 | 템플릿. 세 어댑터 모두 기본 bootJar에 없고 `runtimeOnly` 한 줄로 고르는 opt-in. gRPC 플랫폼은 별도 Gradle build(`-p optional-platforms`)이고 어떤 composition도 쓰지 않는다. qualification 이미지(`COMPOSITION=qualification`)만 세 어댑터를 모두 싣는다 | +| 규모·운영 목표 | 문서에 없음. "대규모 운영 준비" 판정은 하지 않는다 | +| 읽은 코드 | 세 어댑터 main 전부(websocket 1,557줄, grpc 어댑터 약 900줄), graphql은 `cost/`·`runtime/`·`dataloader/`·`policy/`·`autoconfigure/`·`context/`·`execution/` 전부와 나머지 목록, gRPC 플랫폼은 `grpc-core-api/ledger`·`grpc-runtime/idempotency`·`grpc-spring-boot-starter` 전부·`grpc-operation-ledger-jpa` 전부·`grpc-testkit/netty/GrpcNettyTestServer`, advanced는 지난 발견 재확인 범위만. 각 leaf `CLAUDE.md`·`README.md`, `src/grpc/CLAUDE.md`, `src/grpc-advanced/CLAUDE.md`, `.github/workflows/{integration-main,ci-quality-gates,release,pr-adapters}.yml`. Spring 소스 `spring-messaging-7.0.9` `SimpleBrokerMessageHandler` | +| 실행한 명령 | 아래 표 | +| 확인 못 한 것 | `-p optional-platforms ci`(grpc-runtime·testkit·advanced 단위 테스트, Netty·fault lane) 이번 커밋에서 미실행. `websocketNginxTest`는 오늘 미실행(결과 파일이 2026-09-28). 실부하·다중 노드·실 TLS 없음. GitHub Actions에서 `grpc-optional-platform-integration` job이 실제로 green인지는 확인하지 않음(외부 조회 금지) | +| 이전 리뷰와 비교 | `docs/reviews/2026-09-18-techlead-review/{03,04,11}-*.md`, `docs/reviews/2026-09-25-review-followup-status.md`의 J·K·N·S5·S6·S7·NEW·P*-new 행, `docs/reviews/2026-08-14-graphql-module-code-review.md` | + +실행 기록(모두 scratchpad worktree `wt-03`, `flock heavy.lock`으로 감쌈, 끝나고 worktree 제거): + +| 명령 | 부하(uptime) | 결과 | +| --- | --- | --- | +| 오케스트레이터 게이트 `ci` | 9.15 | rc=0(7분 9초). 세 어댑터 `check`(test·spotless·checkstyle·Error Prone·API surface) 통과 | +| 오케스트레이터 게이트 `mainCheck` | 20.68 | rc=1. 실패는 objectstorage MinIO 이미지 pull 404 두 건뿐. 이 영역의 `systemTest`(websocket·graphql), `websocketJettyTest`, `*TransportQualificationTest` 3개, `graphqlStableTest`, `conditionalTransportQualification`은 실행됐고 실패 없음 | +| `:adapter:inbound:graphql:test --tests '*Review03ComplexityProbeTest'` (리뷰용 임시 테스트) | 8.65 | 통과 = 결함 재현. `REVIEW03 explicit20=410 omitted=40 nested4=100 variableDefault100000=40` (03-01) | +| `:adapter:inbound:websocket:test --tests '*Review03WebSocketProbeTest'` (임시) | 8.65 | 통과 = 결함 재현. `leakedGlobalBytes=500`(03-07), `openAfterStop=1 running=false`(03-08) | +| `-p optional-platforms :grpc:grpc-operation-ledger-jpa:integrationTest` | 7.89 | 통과. `GrpcOperationLedgerPostgresIT` 2건 + `JpaGrpcOperationLedgerContractIT` 16건, skip 0, `postgres:16-alpine`, V001 SQL을 그대로 적용. 벽시계 77초(잠금 대기 포함) | +| 변이 1: `GraphQlCostBudgetHandler`의 `structuralLimits.verify(shape)` 무력화 → `:adapter:inbound:graphql:systemTest` | 6.13 | 잡힘. 25건 중 2건 실패(`aDocumentDeeperThanTheStructuralLimit…`, `anAliasBomb…`) | +| 변이 2: STOMP SUBSCRIBE destination 검사 무력화 → `:adapter:inbound:websocket:test` | 6.13 | 잡힘. `WebSocketInboundAuthorizationInterceptorTest.permitsAuthenticatedSubscribeOnlyToConfiguredTopic` 실패 | + +임시 테스트 원본은 scratchpad `src03/Review03*.java`에 남겼다. 메인 repo에는 이 문서 말고 바꾼 파일이 없다. + +## 2. 지난 발견 재확인 + +상태: 해결 / 남음 / 바뀜. followup-status에서 이미 `완료`이고 이번에 다시 볼 이유가 없던 행은 생략했다. 아래는 남음·보류였거나 이번 주제(연결 상한·깊이·N+1·deadline·ledger)에 걸린 행이다. + +| ID | 상태 | 근거 | +| --- | --- | --- | +| J-3b (Javadoc "detail은 로그에") | 해결 | `graphql/.../error/GraphQlWireErrorMapper.java:35`가 실제로 로그하는 `GraphQlExceptionResolver`를 가리킨다(J-3a에서 ERROR 로그 추가) | +| J-4c (DataLoader 실패 테스트가 `isNotEmpty()`만) | 남음 | `graphql/src/test/.../runtime/GraphQlBatchLoaderRegistrationTest.java:133,146,162,198` | +| J-9b (chunked 본문 경로 테스트 없음) | 해결 | `graphql/src/systemTest/.../runtime/GraphQlPlatformExecutionPathTest.java:263` `aChunkedBodyOverTheRawCapIsRefusedWith413` | +| J-11b (README가 없는 resolver 설명) | 해결 | `graphql/README.md`에 `GraphqlExceptionResolver` 0건 | +| J-12 / X2-P2-6b | 보류(소유자 결정 35) | 결정대로 유지. 다시 열지 않음 | +| S5-#7c (autoconfig 주석이 사실과 다름) | 남음 | `graphql/.../autoconfigure/GraphQlRootAutoConfiguration.java:39` "component scan excludes by regex" 문장이 아직 있다 | +| S5-#14d (graphql 주석 과다·"design §") | 남음 | graphql main에 `design §` 46곳 | +| S5-#14e (interceptor 생성자 인자 과다) | 남음 | `graphql/.../runtime/GraphQlPlatformWebInterceptor.java:70-80` 인자 10개(9 → 10) | +| K-5b (종료 IT가 context를 안 닫음) | 해결 | `websocket/src/systemTest/.../runtime/TomcatWebSocketShutdownIT.java:29-58`이 context를 닫고 1001을 단언. 단 `TomcatWebSocketAbuseIT.java:69`는 여전히 `handler.stop()` 직접 호출(중복 테스트) | +| P25-new-1 (shutdown 테스트 시간 경계 flaky) | 남음 | `TomcatWebSocketAbuseIT.java:73-77` `took < 20s`와 `await(20s)`가 같은 경계 | +| K-12c (CLAUDE.md "Boot 4.0.0") | 남음 | `adapter/inbound/grpc/CLAUDE.md:8`, `adapter/inbound/graphql/CLAUDE.md:8` | +| techlead 03-H3 (`CONNECTION_MUST_CLOSE` 무시) | 해결 | `websocket/.../servlet/PlatformWebSocketHandler.java:176-180` 1013으로 닫음 | +| techlead 03-H7 (gRPC loopback 전용) | 남음(의도·문서화) | `adapter/inbound/grpc/CLAUDE.md` "Current transport limit". TLS는 P2로 미룸 | +| techlead 03-M4 (글로벌 예산을 poll 때 반납) | 해결 | `OutboundQueue.java:119-124` `releaseInFlight`가 write 뒤 반납. 다만 close 경합은 새 결함 03-07 | +| techlead 03-M5 (모든 `BindableService` 노출) | 해결 | `GrpcServerConfig` `@GrpcExposedService` 한정 | +| techlead 04-M5 (parser 한계 미설치) | 바뀜 | parse 전 `maxDocumentBytes` 16 KiB 검사(`GraphQlPlatformWebInterceptor.java:125-133`) + graphql-java 기본 parser 한계. 별도 설치는 여전히 없음 | +| techlead 04-L2 (전역 `Clock` 빈) | 해결 | `GraphQlRequestContextConfiguration.java:35-37` `@ConditionalOnMissingBean(Clock.class)` | +| techlead 11-C1 / N-1 / N-11a (ledger claim 원자성) | 해결 | `JpaGrpcOperationLedger.java:39-65`(native `INSERT … ON CONFLICT DO NOTHING`), 이번 PG lane 18건 통과 | +| techlead 11-H1 (startup validator 미호출) | 해결 | `GrpcPlatformAutoConfiguration` `grpcPlatformStartupCheck`(`SmartInitializingSingleton`) | +| techlead 11-M9 (starter가 JPA를 끌어옴) | 해결 | starter `build.gradle`에 ledger 의존 없음, `src/grpc/CLAUDE.md` "Durable operation ledger adoption" | +| N-12a (`GrpcClientMessageDeduplicator` "constant space") | 남음 | `grpc-advanced/.../streaming/GrpcClientMessageDeduplicator.java:13,112` | +| N-12b (`ReactiveGrpcClient.serverStream`) | 남음 | `grpc-advanced-compat/.../reactor/ReactiveGrpcClient.java:50` | +| P5-new-1 (Envoy `VirtualHost.cors` deprecated) | 남음 | `grpc-advanced-compat/src/test/resources/envoy/envoy.yaml:37` | +| P15-new-4 (status description 변경 이행 안내) | 바뀜(부분) | `adapter/inbound/grpc/README.md:79-81`에 trailer 안내 추가. 그러나 `:87`은 여전히 "code 문자열만 status description/trailer로 노출"이라 적어 설명이 엇갈린다 | +| S7-lead-2 (root family 표에 gRPC 행 없음) | 남음 | root `CLAUDE.md` 「Module families」 표에 `messaging:*` 행만 있고 `grpc:*`·`grpc-advanced:*` 행이 없다 | + +이번 커밋에서 남은 High/P1은 지난 발견 쪽에는 없다. High는 아래 새 발견 두 건이다. + +## 3. 새 발견 + +심각도별: High 2 · Medium 7 · Low 3. 우선순위별: P1 2 · P2 7 · P3 3. Critical·P0 없음. + +### 03-01 GraphQL 복잡도 점수가 목록 크기를 놓친다 — 페이지 인자 생략·변수 기본값·일반 list 필드 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 1, 5, 6, 10, 13, 14, 15, 17 | +| 근거 | `graphql/.../cost/GraphQlDocumentComplexityScorer.java:217-222` — `first`/`last` 인자가 **값으로 읽힐 때만** `connectionCost`(자식 비용 × 페이지 크기)를 쓰고, 아니면 `fieldCost`(자식 비용 × 1). `:242-249` 변수 참조는 요청 `variables` 맵에 없으면 `null`. `GraphQlCostBudgetHandler.java:78`이 넘기는 맵은 클라이언트가 보낸 원본이라 연산의 변수 기본값(`$n: Int = 100000`)이 없다. `:206` `unwrap`이 `GraphQLList`를 벗겨 버려 일반 list 필드의 개수 정보가 사라진다. 반면 `GraphQlComplexityCalculator.java:9-11` Javadoc은 "first를 생략하면 기본 페이지로 계산해야 한다, 1로 계산하면 예산 우회"라고 적고 있다. 페이지 상한 검사(`GraphQlComplexityCalculator.java:51`)도 `connectionCost`에만 있다. 임시 테스트 결과: `items(first: 20){name}` = 410, `items{name}` = 40, `items{children{children{children{name}}}}` = 100(4단 중첩 list가 선형 합), `query($n:Int=100000){items(first:$n){name}}` = 40으로 통과(같은 값을 리터럴로 쓰면 `GraphQlComplexityRejectedException`) | +| 발생 조건 | adopter 스키마에 list 반환 필드가 있으면 항상. 공격자는 `first`를 빼거나, 변수 기본값으로 숨기거나, 변수를 아예 안 보낸다 | +| 영향 | 복잡도 예산(기본 10,000)과 페이지 상한(기본 100)이 사실상 꺼진다. 중첩 list는 실제 작업이 곱으로 늘어나는데 점수는 합으로만 는다. resolver가 플랫폼 밖 라이브러리 `GraphQlConnectionPolicy`를 직접 부르지 않으면 `first: 100000`이 그대로 DB까지 간다 | +| 심각도·우선순위 | High · P1. GraphQL은 opt-in이지만 이 플랫폼이 판매하는 핵심 보호(`CLAUDE.md` 등급표 "depth/complexity 제한 `wired`")가 list 필드가 생기는 순간 무력하다. 템플릿을 복사한 서비스로 그대로 퍼진다 | +| 확실성 | 직접 확인(E2 임시 테스트). systemTest 스키마(`src/systemTest/resources/graphql-platform/platform.graphqls`)에 list·connection 필드가 하나도 없어서 기존 테스트가 이 경로를 밟지 않는다. `GraphQlDocumentComplexityScorer` 전용 단위 테스트도 없다 | +| 통제 수준 | 깊이·필드·alias 상한은 M3(변이 1로 확인). 목록 크기 반영은 M0 | +| 결정의 근거 | 적용 제외 — 문서화된 계약(Javadoc)과 코드가 어긋난 단순 결함 | +| 최소 개선 방향 | (1) 필드 정의가 list(또는 connection 규약 타입)면 `first`/`last`가 없거나 `null`일 때 `defaultPageSize`를 곱한다. (2) 변수 값은 `ExecutionInput`이 아니라 graphql-java가 기본값을 적용한 `CoercedVariables`(`ValuesResolver.coerceVariableValues`)로 읽는다. (3) 페이지 인자가 없는 일반 list는 기본 배수(`defaultPageSize`)로 곱하고, adopter가 `GraphQlFieldCostDescriptor`로 필드별 배수를 줄 수 있게 한다. 버린 대안: graphql-java 기본 `MaxQueryComplexityInstrumentation` 도입 — 이 역시 list 배수를 모르는 필드 개수 합이라 같은 구멍이 남고, 플랫폼 점수와 두 벌이 된다 | +| 완료 기준 | 위 네 쿼리의 점수가 각각 페이지 크기만큼 곱해지고, 변수 기본값 100000은 `page size exceeds maximum`으로 거부된다 | +| 검증 방법 | `cost/`에 scorer 단위 테스트(위 네 케이스) + systemTest 스키마에 list 필드 하나와 "first 생략 + 중첩" 거부 케이스 | + +### 03-02 GraphQL 요청 deadline(10초)이 실행 중에는 강제되지 않는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(문서와 동작 불일치) + 구조적 위험 | +| 관련 관점 | 5, 6, 9, 14, 22 | +| 근거 | `policy/GraphQlClientPolicy.java:90` `maxExecutionTime` 10초 → `GraphQlPlatformWebInterceptor.java:147` deadline 생성. 읽는 곳은 `GraphQlCostBudgetHandler.java:62`(실행 **전** 한 번)과 `dataloader/GraphQlBatchExecutor.java:110`(platform registrar로 등록한 batch만)뿐. resolver 실행 자체를 끊는 장치(Spring GraphQL `TimeoutWebGraphQlInterceptor`, `DataFetcher` timeout)는 없다. `execution/GraphQlTimeoutPolicy.java`는 main 호출자 0(테스트만). `context/GraphQlDeadline.java:9-12` Javadoc은 "resolver, DataLoader batch, JPA/Mongo/HTTP client deadline으로 같은 budget을 내려준다"고 적는다 | +| 발생 조건 | 느린 resolver·외부 호출이 있는 adopter 쿼리 | +| 영향 | 요청이 10초 뒤에도 servlet 스레드를 잡고 계속 돈다. 클라이언트는 이미 끊었는데 DB 커넥션·스레드가 묶인다. 운영자는 설정만 보고 10초 상한이 있다고 믿는다 | +| 심각도·우선순위 | Medium · P2. 기본 composition에 없고 피해는 자원 점유로 제한된다 | +| 통제 수준 | M1(설정·Javadoc만), 실행 강제 M0 | +| 결정의 근거 | 적용 제외 — 이미 정한 계약(`maxExecutionTime`)을 실행에 연결하는 문제 | +| 최소 개선 방향 | 고른 방법: Spring GraphQL의 `TimeoutWebGraphQlInterceptor`(또는 같은 일을 하는 interceptor)를 `maxExecutionTime`으로 auto-config에 넣고, 시간 초과를 `REQUEST_TIMEOUT`으로 매핑한다. 쓰지 않는 `GraphQlTimeoutPolicy`는 지우거나 하위 호출이 쓰도록 연결한다. 버린 대안: resolver마다 deadline을 검사 — adopter가 기억해야 하는 숨은 규칙이 된다 | +| 완료 기준 | 11초 걸리는 resolver를 가진 systemTest 쿼리가 10초 근처에서 `REQUEST_TIMEOUT`으로 끝난다 | +| 검증 방법 | systemTest에 느린 resolver 케이스 하나(주입 시계 대신 짧은 `maxExecutionTime` 설정) | + +### 03-03 N+1을 막는 길이 adopter 기억에만 있다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 4, 5, 14, 20, 21 | +| 근거 | 플랫폼 batch 보호(chunk·deadline·tenant scope)는 `runtime/GraphQlBatchLoaderRegistrar.java:58-82`로 **명시 등록한** loader에만 붙는다. Spring 표준 `@BatchMapping`이나 per-parent `@SchemaMapping`은 이 경로를 거치지 않는다. 템플릿에는 feature GraphQL 예시가 없고(`graphql/README.md` 「아직 구현하지 않은 범위」), README는 registrar 사용법을 한 줄도 적지 않는다. 비용 카탈로그는 기본이 비어 있어(`GraphQlExecutionChainConfiguration` `GraphQlCostCatalog.of()`) 모든 필드가 같은 가중치 10이다. `EXTERNAL_PER_OBJECT(20)`과 `BATCHED_RELATION(3)` 구분은 adopter가 등록해야만 의미가 있다 | +| 발생 조건 | adopter가 list 부모 아래 자식 필드를 일반 `@SchemaMapping`으로 구현 | +| 영향 | 부모 N개마다 하위 호출 N번. 03-01과 겹치면 점수도 낮게 나와 거부되지 않는다 | +| 심각도·우선순위 | Medium · P2 | +| 통제 수준 | M2(registrar 경로는 `GraphQlBatchLoaderRegistrationTest`로 50 parent → 3 호출 확인), 그 밖 경로 M0 | +| 결정의 근거 | 현재 선택: 플랫폼은 feature-agnostic이고 resolver를 모른다(사실, `CLAUDE.md`). 대안 (a) 문서·예시만 추가, (b) graphql-java instrumentation으로 같은 필드의 per-parent fetch 횟수를 세어 임계값 넘으면 WARN/metric, (c) 카탈로그 미등록 list 자식 필드를 기동 때 경고. 고른 방향: (a)+(b). (c)는 스키마 전체를 adopter가 등록해야 해서 비용 대비 효과가 작다. 재검토 조건: sample에 GraphQL feature가 들어오면 그 예시가 (a)를 대신한다 | +| 최소 개선 방향 | README에 "자식 필드는 `GraphQlBatchLoaderRegistrar.register`로" 조립 예와 `@BatchMapping`과의 차이(플랫폼 budget 미적용)를 적고, 요청당 같은 좌표 fetch 횟수 metric을 추가 | +| 완료 기준 | README 예시가 컴파일되는 테스트로 고정되고, per-parent fetch가 임계값을 넘는 systemTest에서 WARN/metric이 관찰된다 | +| 검증 방법 | systemTest에 list 부모 + 일반 `@SchemaMapping` 자식 쿼리 하나 | + +### 03-04 `GraphQlDataLoaderRequestRegistry`는 도달 불가인데 README가 요청 스코프 장치로 설명한다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(갈라진 중복 복사본) | +| 관련 관점 | 4, 9, 22, 27 | +| 근거 | `dataloader/GraphQlDataLoaderFactory.java:37` `newRequestRegistry()`의 호출자는 테스트 하나(`GraphQlDataLoaderRequestRegistryTest.java:84`)뿐. 실제 요청 스코프는 Spring이 실행마다 새로 만드는 `DataLoaderRegistry`다(`GraphQlBatchLoaderRegistrar.java:19-23,48-50` Javadoc이 스스로 "아무것도 연결하지 않던 registry"라고 적음). 그런데 `graphql/README.md:204-208`은 이 registry가 요청마다 새로 만들어져 tenant 누출을 막는다고 설명한다 | +| 영향 | 읽는 사람이 죽은 타입을 보호 장치로 믿는다. public 타입이라 API surface에도 남는다 | +| 심각도·우선순위 | Low · P3 | +| 결정의 근거 | 적용 제외 — 두 번째 경로가 이미 대체된 상태라 비교할 선택이 없다 | +| 단순화의 보존 조건 | `GraphQlBatchLoaderRegistrar`의 요청 스코프(실행마다 새 `DataLoaderRegistry`)와 `GraphQlBatchContext.cacheScope()` 지문 동작은 유지 | +| 최소 개선 방향 | `GraphQlDataLoaderRequestRegistry`와 `newRequestRegistry()` 삭제, API surface 재승인, README 절을 registrar 기준으로 다시 쓴다 | +| 완료 기준 | main·test grep 0건, `verifyGraphQlApiSurface` 통과 | +| 검증 방법 | `:adapter:inbound:graphql:check` | + +### 03-05 batch loader가 플랫폼 context 없이 불리면 `REQUEST_TIMEOUT`으로 나간다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 6, 8, 17 | +| 근거 | `runtime/GraphQlBatchLoaderRegistrar.java:73-76` context가 없으면 `GraphQlBatchTimeoutException` → mapper가 `REQUEST_TIMEOUT`/TIMEOUT(J-4a 매핑). 원인은 interceptor 미배선 같은 조립 오류인데 클라이언트·운영자는 시간 초과로 본다. 같은 조립 오류를 instrumentation은 WARN과 `PLATFORM_CONTEXT`로 따로 다룬다(P8-new-2) | +| 영향 | 잘못 조립된 배포가 "느리다"로 오진된다. retryable 시간 초과로 보이면 클라이언트가 재시도한다 | +| 심각도·우선순위 | Low · P3 | +| 결정의 근거 | 적용 제외 — 이미 있는 `PLATFORM_CONTEXT` 처리와 맞추는 일 | +| 최소 개선 방향 | 전용 플랫폼 거부(예: `GraphQlPlatformContextMissingException`, INTERNAL + WARN 한 번)로 바꾼다 | +| 완료 기준·검증 | context 없는 batch 호출 테스트가 `INTERNAL_ERROR`와 WARN 한 줄을 단언 | + +### 03-06 WebSocket 연결 수·구독 수·연결 수명 상한이 없고, STOMP 전송 한도가 코드에 드러나지 않는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 5, 6, 13, 14, 15, 19 | +| 근거 | (1) STOMP: `stomp/WebSocketConfig.java:62-68`은 `configureWebSocketTransport`를 두지 않아 메시지 크기 64 KiB·send buffer 512 KiB·send time 10초·첫 메시지 60초가 Spring 기본값으로만 정해진다. 노드·principal당 연결 수 상한이 없다. (2) 구독 수: `WebSocketInboundAuthorizationInterceptor.java:34-36`은 destination만 보고 개수를 세지 않는다. Spring `SimpleBrokerMessageHandler`(7.0.9 소스 `:397-402`)는 세션 하나의 subscription id마다 메시지를 한 번씩 보낸다. 같은 `/topic/events`를 id만 바꿔 N번 SUBSCRIBE하면 broadcast 한 건이 그 세션에 N번 나가고, 구독 registry가 N만큼 커진다. (3) 라이브러리 handler: `servlet/PlatformWebSocketHandler.java:110` `openConnections()`는 세기만 하고 거부하지 않는다. `README.md` 「서비스가 챙길 것」은 인증·origin·크기·idle만 적고 연결 수는 적지 않는다. (4) 연결 수명: 인증은 handshake 한 번이고 토큰 만료·폐기 뒤에도 연결이 유지된다. 이 한계도 문서에 없다 | +| 발생 조건 | 인증된 사용자 한 명(또는 탈취된 토큰)이 연결을 많이 열거나 SUBSCRIBE를 반복 | +| 영향 | 노드 메모리·broker 채널 큐(기본 10,000)를 한 사용자가 채운다. broker 큐가 차면 다른 사용자의 live event가 drop된다(R1 best-effort라 오류 없이) | +| 심각도·우선순위 | Medium · P2. opt-in이고 인증된 사용자만 가능 | +| 통제 수준 | destination allowlist M3(변이 2로 확인). 연결·구독 수 M0 | +| 결정의 근거 | 현재: 노드 내 simple broker, 연결 관리는 컨테이너·프록시 몫(README). 대안 (a) 문서로만 "프록시에서 연결 수 제한", (b) STOMP inbound interceptor에서 세션당 구독 수 1개(이 채널은 destination이 하나뿐)와 노드 연결 수 상한을 설정 키로, (c) principal별 연결 수 제한(분산 카운터 필요). 고른 방향: (b) — destination이 하나뿐이라 "세션당 구독 1"은 비용이 거의 없고, 노드 상한은 지역 카운터로 충분. (c)는 다중 노드에서 Redis가 필요해 이 leaf 범위를 넘으므로 문서로 남긴다. 재검토 조건: broker relay·다중 노드 전달을 도입할 때 | +| 최소 개선 방향 | `configureWebSocketTransport`로 Spring 기본값을 명시 설정 키로 꺼내고, 세션당 중복 SUBSCRIBE 거부, 노드 연결 상한(`app.websocket.max-connections`) 추가. 라이브러리 handler는 생성자에 연결 상한을 받거나 README에 필수 항목으로 적는다 | +| 완료 기준 | 같은 세션의 두 번째 SUBSCRIBE가 ERROR 프레임으로 거부되고, 상한+1번째 연결이 거부되는 systemTest | +| 검증 방법 | `WebSocketBoundaryQualificationTest`에 두 케이스 | + +### 03-07 `SerializedOutboundWriter`의 offer와 close가 겹치면 노드 버퍼 예산이 영구히 샌다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 1, 6, 12, 14 | +| 근거 | `outbound/SerializedOutboundWriter.java:86`에서 `closed`를 본 뒤 `:93` queue lock을 잡기 전에 `close()`(`:179-192`)가 끼어들면, close가 빈 큐를 비운 다음 offer가 메시지를 넣고 `GlobalBufferBudget`에 바이트를 예약한다. 이어지는 `drain()`(`:112`)은 `closed`라 아무것도 쓰지 않는다. writer는 handler map에서 이미 빠졌으므로 그 예약을 돌려줄 주체가 없다. 임시 테스트(queue lock을 잡고 producer를 그 앞에 세운 뒤 close)로 `leakedGlobalBytes=500` 재현 | +| 발생 조건 | 응답 enqueue(`PlatformWebSocketHandler.writeReply`)와 연결 종료(`afterConnectionClosed`·`stop`)가 다른 스레드에서 동시에. 연결이 많고 끊김이 잦을수록 누적 | +| 영향 | 노드 예산이 조금씩 줄어 결국 모든 연결의 GUARANTEED 응답이 1013으로 닫힌다. 코드 주석(`PlatformWebSocketHandler.java:94-96`)이 막는다고 적은 바로 그 누수다. 재시작 전까지 회복되지 않는다 | +| 심각도·우선순위 | Medium · P2. 라이브러리형이라 조립한 서비스에만 해당 | +| 통제 수준 | M2(정상 경로), 경합 경로 M0 | +| 결정의 근거 | 적용 제외 — 동시성 결함 수정 | +| 최소 개선 방향 | `queue.offer`를 queue lock 안에서 `closed`를 다시 확인한 뒤에만 하고, 닫힌 뒤면 `CONNECTION_MUST_CLOSE` 반환. 또는 `close()`의 `discardAll`을 offer와 같은 lock 아래 마지막 단계로 두고 offer도 lock 안에서 closed를 본다 | +| 완료 기준 | 위 경합 테스트에서 `global.buffered() == 0` | +| 검증 방법 | 결정적 경합 테스트를 `SerializedOutboundWriterTest`에 추가(테스트용 hook 대신 queue를 감싼 latch fake로) | + +### 03-08 `PlatformWebSocketHandler.stop()` 뒤에 들어온 연결은 1001을 받지 못한다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 6, 7, 18, 28 | +| 근거 | `servlet/PlatformWebSocketHandler.java:63-71` `afterConnectionEstablished`가 `running`을 보지 않는다. `stop()`(`:133-148`)은 그 시점의 세션만 닫는다. handler 단계(`DEFAULT_PHASE`)와 web server graceful 단계(`DEFAULT_PHASE - 1024`) 사이에 서버는 아직 upgrade를 받는다. 임시 테스트: `stop()` 뒤 연결 → `openAfterStop=1`, `close` 호출 0회 | +| 발생 조건 | 롤링 재시작. 1001을 받은 클라이언트가 바로 재접속하고, 로드밸런서 endpoint 제거가 늦어 같은 pod로 다시 붙는 경우 | +| 영향 | 그 연결은 서버 종료 때 1006으로 끊긴다. stop()이 막으려던 "공격적 재접속"이 바로 그 창에서 생긴다 | +| 심각도·우선순위 | Medium · P2 | +| 결정의 근거 | 적용 제외 — 이미 정한 종료 계약(1001)의 빈틈 | +| 최소 개선 방향 | `afterConnectionEstablished`에서 `!running`이면 즉시 1001(또는 1012)로 닫는다 | +| 완료 기준 | stop 뒤 연결이 즉시 1001로 닫히는 단위 테스트, `TomcatWebSocketShutdownIT`에 "stop 직후 재접속" 케이스 | +| 검증 방법 | `PlatformWebSocketHandlerTest`, systemTest | + +### 03-09 gRPC 어댑터 서버가 io.grpc 기본값으로 뜬다 — deadline·동시 호출·executor·메시지 크기 상한이 없고, 플랫폼 한도는 testkit 서버에만 적용된다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 5, 6, 13, 14, 19, 23 | +| 근거 | `adapter/inbound/grpc/.../GrpcServerRunner.java:75` `NettyServerBuilder.forAddress(...)`에 `maxInboundMessageSize`, `maxConcurrentCallsPerConnection`, `executor`, keepalive·`maxConnectionAge` 설정이 없다. io.grpc 기본은 메시지 4 MiB, 연결당 동시 호출 무제한, 스레드 수 제한 없는 cached executor다. 서버 쪽 기본 deadline(클라이언트가 deadline 없이 부른 호출을 끊는 장치)도 없다. 플랫폼은 `GrpcTransportLimits`(1 MiB/8 KiB), `GrpcServerProfile`, `GrpcAdmissionController`를 갖지만 이를 `NettyServerBuilder`에 적용하는 코드는 `grpc-testkit/.../netty/GrpcNettyTestServer.java:69-70` 하나뿐이고, starter(`GrpcPlatformAutoConfiguration`)는 profile bean만 만들고 서버를 만들지 않는다. 종료는 `stop()`(`:112-130`)이 health를 NOT_SERVING으로 바꾸자마자 `shutdown()`해 LB가 상태를 볼 시간이 없다 | +| 발생 조건 | adopter가 어댑터로 feature 서비스를 노출하고 호출이 몰릴 때. 현재 P1은 loopback 전용이라 같은 Pod sidecar 정도만 해당 | +| 영향 | 느린 handler가 스레드를 무한정 늘린다. Netty lane이 인증한 한도(1 MiB 등)는 실제 production 서버와 다른 서버에 대한 증거다 | +| 심각도·우선순위 | Medium · P2. loopback 제한이 노출을 줄인다. TLS·외부 bind(P2)를 열기 전에는 해결해야 한다 | +| 통제 수준 | 어댑터 M0, 플랫폼 M2(testkit 한정) | +| 결정의 근거 | 현재: 두 스택 공존은 X1-#10·techlead 11-K6에서 의도로 수용됐다(다시 열지 않는다). 대안 (a) 어댑터가 `GrpcTransportLimits`와 같은 값을 자기 `GrpcServerSettings`로 노출해 builder에 설정, (b) 어댑터가 플랫폼 `GrpcServerProfile`을 받는다(registry edge 추가 = "배선은 별도 결정"), (c) 현상 유지 + README에 기본값 명시. 고른 방향: (a). 두 스택 분리 결정을 건드리지 않고 기본값을 코드에 드러낸다. (b)는 소유자가 플랫폼 배선을 결정할 때 다시 본다 | +| 최소 개선 방향 | `GrpcServerSettings`에 `maxInboundMessageBytes`(1 MiB), `maxConcurrentCallsPerConnection`, bounded executor 크기, 기본 deadline을 두고 builder에 적용. stop에 짧은 drain 대기(`shutdownGraceSeconds` 안에서) | +| 완료 기준 | `GrpcP1BoundaryWireTest`에 1 MiB 초과 메시지 `RESOURCE_EXHAUSTED`, deadline 없는 느린 호출이 기본 deadline에 `DEADLINE_EXCEEDED` 케이스 | +| 검증 방법 | `:adapter:inbound:grpc:grpcTransportQualificationTest` | + +### 03-10 operation ledger의 `IN_PROGRESS` claim에 만료·회수가 없다 — 소유자가 죽으면 그 key는 영구히 막힌다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 1, 6, 11, 12, 28 | +| 근거 | `grpc-runtime/.../idempotency/GrpcIdempotencyInterceptor.java:118-121`: claim이 `IN_PROGRESS`면 `waitAndPoll` 또는 `rejectInProgress`. 만료 판단이 없다. `GrpcOperationLedger` port와 `JpaGrpcOperationLedger`에 stale claim 회수 메서드가 없다. `V001__create_grpc_operation_ledger.sql:35-37`은 "owner가 죽은 IN_PROGRESS 행을 찾아 release하기 위한 인덱스"라고 적지만 그 회수 코드는 main 어디에도 없다. COMMITTED 행 보존 기간·정리도 없다 | +| 발생 조건 | claim 뒤 commit/fail 전에 프로세스가 죽거나 트랜잭션 밖에서 claim이 커밋된 경우(`tryInsertClaim`은 `@Transactional`이라 호출자 트랜잭션이 없으면 즉시 커밋) | +| 영향 | 같은 key의 재시도가 영원히 대기하거나 거부된다. 클라이언트가 key를 바꾸면 중복 실행 방지가 깨진다. 테이블은 끝없이 자란다 | +| 심각도·우선순위 | High · P1(ledger 채택 전 차단). 현재는 어떤 서버 경로도 이 판단 함수를 쓰지 않아(03-11) 노출은 없다. 채택하는 순간 pod 재시작 한 번으로 발생하는 일반 장애다 | +| 확실성 | E1(코드 경로 확인). PG lane 18건은 claim 원자성만 다루고 stale claim 케이스는 없다 | +| 통제 수준 | claim 유일성 M4(DB 제약 + PG lane E3). stale 회수 M0 | +| 결정의 근거 | 현재: claim이 소유를 정하는 lease 없는 lock이다. 대안 (a) `claimed_at` + TTL로 stale `IN_PROGRESS`를 조건부 UPDATE로 재claim(`tryReclaimStale`, 기존 `tryReclaimFailed`와 같은 모양), (b) owner token + heartbeat lease(outbox lease와 같은 방식), (c) stale 행을 지우는 sweeper job. 고른 방향: (a). 인덱스가 이미 있고 SQL 한 문장으로 끝나며 회수 시 "결과 불명"을 `GrpcCompletionReconciler`로 넘길 수 있다. (b)는 장시간 작업에만 필요하다. 재검토 조건: 처리 시간이 TTL보다 길 수 있는 method가 생기면 (b) | +| 최소 개선 방향 | port에 `reclaimStale(identity, fingerprint, olderThan, now)` 추가, JPA는 `UPDATE … WHERE state='IN_PROGRESS' AND claimed_at < :cutoff`, interceptor가 stale이면 재claim. 보존 기간 정리 쿼리와 문서 | +| 완료 기준 | 계약 테스트 `GrpcOperationLedgerContract`에 "TTL이 지난 IN_PROGRESS는 같은 요청이 한 번만 재claim" 추가, fake와 JPA(PG lane) 모두 통과 | +| 검증 방법 | `-p optional-platforms :grpc:grpc-operation-ledger-jpa:integrationTest`, `grpc-core-api:test` | + +### 03-11 `app.grpc.platform.operation-ledger-enabled`는 검증만 통과시키고 실제로 key를 처리하는 코드가 없다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(설정 키가 하지 않는 일을 약속) | +| 관련 관점 | 5, 17, 19, 21 | +| 근거 | `grpc-spring-boot-starter/.../GrpcPlatformProperties.java:53` 플래그, `GrpcPlatformStartupValidator.java:149-155` "key would be accepted and never honoured"를 막는 검사. 하지만 starter(`GrpcPlatformAutoConfiguration`)는 ledger bean도 `GrpcIdempotencyInterceptor`도 만들지 않고, `GrpcIdempotencyInterceptor`의 호출자는 테스트(`GrpcIdempotencyInterceptorTest`)뿐이다. 플래그를 `true`로 두면 검증은 통과하고 key는 여전히 처리되지 않는다. `adapter/inbound/websocket/CLAUDE.md` 「Forbidden」의 "하지 않는 동작에 대한 설정 키 금지"와 같은 원칙을 이 family는 어긴다 | +| 영향 | 운영자가 멱등 처리가 켜졌다고 믿는다 | +| 심각도·우선순위 | Medium · P2(optional build, 채택 시 문제) | +| 결정의 근거 | 대안 (a) 플래그를 지우고 validator는 `GrpcOperationLedger` bean 존재로 판단, (b) 플래그가 true면 ledger bean + 서버 interceptor를 조립. 고른 방향: (a). 서버 interceptor 조립은 "플랫폼 배선은 별도 결정"(`src/grpc/CLAUDE.md`)에 속하므로, 그 전까지는 거짓 약속만 없앤다 | +| 완료 기준 | 플래그 삭제, ledger bean이 없으면 `IDEMPOTENCY_KEY_REQUIRED` method가 기동 거부되는 context test | +| 검증 방법 | `GrpcPlatformAutoConfigurationContextTest` | + +### 03-12 ledger PG lane은 main push·nightly에서만 돌고 PR·릴리스 게이트에 없다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험(게이트 범위) | +| 관련 관점 | 10, 18, 21 | +| 근거 | `.github/workflows/integration-main.yml:329-345` job `grpc-optional-platform-integration`이 `-p optional-platforms integrationCheck`를 push(main)와 nightly cron에 실행한다. PR 게이트(`ci-quality-gates.yml:66-73`)는 `-p optional-platforms ci`만, 릴리스(`release.yml:128-147` `grpc-stable-release-gate`)는 testkit lane 3개만 부른다. integration-main은 머지 뒤 알리는 단계라 tag 릴리스가 이 lane 결과를 보지 않는다. 오늘 로컬 실행은 18건 통과 | +| 영향 | ledger SQL을 깨는 변경이 PR에서 통과하고, main이 빨간 상태로 tag가 나갈 수 있다 | +| 심각도·우선순위 | Low · P3. 플랫폼이 아직 채택되지 않았고, 다음 main push에서 드러난다 | +| 결정의 근거 | 적용 제외 — 기존 단계 설계(container lane은 stage 2) 안에서 릴리스 needs 한 줄 문제 | +| 최소 개선 방향 | `release.yml` gRPC gate에 `-p optional-platforms integrationCheck` 추가(PR 예산은 그대로) | +| 완료 기준·검증 | `release.yml` needs와 실행 목록에 포함, 릴리스 dry-run에서 lane 실행 확인 | + +## 4. 31절 시나리오 추적 + +### 4.1 큰 입력·목록 조회 — GraphQL `POST /graphql` + +```text +HTTP body ─> GraphQlRequestBodyLimitFilter(raw cap, 413) + ─> Spring GraphQL decode ─> GraphQlPlatformWebInterceptor + ├─ document bytes ≤ 16 KiB, variables bytes ≤ 64 KiB, JSON 구조·extension allowlist + ├─ principal resolver → GraphQlRequestContext(deadline = now + 10s) + ─> parse/validate(BoundedPreparsedDocumentProvider 캐시) + ─> GraphQlPlatformInstrumentation → GraphQlExecutionChain + ├─ OperationSelection(named 필요 여부) + ├─ DocumentAuthorization(좌표 규칙, fragment 1회 전개) + └─ CostBudget: deadline 1회 확인 → 깊이·필드·alias·fragment 상한 → 복잡도 점수 + ─> resolver 실행 (시간 상한 없음) + ─> 오류는 GraphQlWireErrorMapper 하나 +``` + +| 항목 | 결과 | +| --- | --- | +| 입력 신뢰 수준 | 신뢰하지 않음. 바이트·구조 상한은 parse 전에 걸린다(M3) | +| 인가 위치 | 문서 단위 좌표 인가는 실행 전(`GraphQlDocumentAuthorizationHandler`). 객체 단위 인가는 `modelled`(요청 경로 없음) — adopter resolver 책임 | +| 규칙 소유 | 상한 값은 `GraphQlClientPolicy` 하나 | +| 트랜잭션 | 이 leaf는 열지 않는다. use case 몫 | +| 외부 부작용 | 없음(health 표면만) | +| 성공의 의미 | 상한·인가·예산을 통과하고 resolver가 응답 | +| 오류 변환 | 플랫폼 거부 → `ApiErrorCarrier` → 등록 매핑 → `IllegalArgumentException`=`BAD_PARAMETER` → 나머지 `INTERNAL_ERROR` + ERROR 로그(executionId) | +| 진단 정보 | executionId, MDC requestId, operation name은 allowlist일 때만 metric label | +| 판정 | 깊이·alias·문서 크기는 막힌다(변이 1). **목록 크기는 막히지 않는다(03-01). 실행 시간도 막히지 않는다(03-02)** | + +### 4.2 종료·재시작 — WebSocket + +| 경로 | 결과 | +| --- | --- | +| STOMP 채널 | Spring `SubProtocolWebSocketHandler`의 lifecycle stop이 세션을 GOING_AWAY로 닫는다(Spring 동작, 이 leaf 테스트 없음). broker 큐에 남은 live event는 버려진다(R1 문서화) | +| 라이브러리 handler | context close → `stop()`(DEFAULT_PHASE)이 열린 연결에 1001 → web server graceful 종료. `TomcatWebSocketShutdownIT`로 E2. stop 뒤 새 연결은 빠진다(03-08) | +| gRPC 어댑터 | `GrpcServerRunner.stop()`이 health terminal → `shutdown()` → `shutdownGraceSeconds`(5초) 대기 → `shutdownNow()`. drain 대기 없음(03-09) | + +### 4.3 중복·동시 요청 — gRPC operation ledger + +| 항목 | 결과 | +| --- | --- | +| 요청 식별 | `GrpcOperationIdentity`(caller 지문, method, key 해시). 컬럼 폭 검증(N-11b) | +| DB 제약 | PK `storage_key` + UNIQUE(caller, method, key hash). `INSERT … ON CONFLICT DO NOTHING`의 affected row로 승자 결정. PG lane `concurrentClaimsHaveExactlyOneOwner` 통과(E3, 로컬) | +| 실패 뒤 재시도 | FAILED_TERMINAL은 같은 fingerprint 한 번만 재claim(`tryReclaimFailed`) | +| 결과 불명 | 소유자가 죽은 IN_PROGRESS는 회수 경로가 없다(03-10) | +| 실제 요청 경로 | 없음. 판단 함수만 있고 서버 interceptor가 없다(03-11) | + +### 4.4 외부 응답 지연 — gRPC deadline + +| 항목 | 결과 | +| --- | --- | +| 플랫폼 | `GrpcDeadlineBudget`이 단조 시계 절대 deadline으로 바뀜(N-2 해결). 하위 호출 budget 계산 라이브러리 | +| 어댑터 | 클라이언트 deadline은 io.grpc가 취소로 전달하지만, deadline 없는 호출에 서버 기본값이 없고 executor도 무제한(03-09) | + +### 적용 제외 + +| 시나리오 | 사유 | +| --- | --- | +| 정상 쓰기 요청 | 세 어댑터 모두 feature mutation이 없다(health 표면만) | +| DB 오류·경쟁 | ledger 외 DB 접근 없음. ledger는 4.3에서 다룸 | +| 메시지 중복·역순 | 영역 10(messaging) | +| 신·구 버전 공존 | gRPC proto 호환은 Buf breaking(CI job `grpc-proto-buf`)이 맡는다. 이번에 미실행 — 다른 영역(13 빌드·CI)과 겹침 | +| 여러 서버의 작업 실행 | 이 영역에 scheduler 없음 | +| 세션·토큰 갱신 경쟁 | 인증은 HTTP 계층·adopter resolver 몫. WebSocket 연결 수명 동안 토큰 재확인이 없다는 점만 03-06에 기록 | +| 다른 사용자 리소스 접근 | GraphQL 객체 인가는 `modelled`(요청 경로 없음), 결정 35로 보류. feature resolver가 없어 따라갈 요청이 없다 | +| 선택 어댑터 제거 | `conditionalTransportQualification`·`conditionalTransportBuildContractTest`가 mainCheck에서 통과(오늘). 영역 12(bootstrap)와 겹쳐 상세는 생략 | + +## 5. 41절 설계 선택 검토 + +### 5.1 GraphQL 비용 제한을 플랫폼 자체 scorer로 둔 것 + +1. **필요한 것**: 실행 전에 비싼 문서를 거절. 대상은 adopter가 나중에 붙일 임의 스키마. +2. **지킬 성질**: 거절 판단이 실제 작업량의 상한이어야 한다. 특히 list 크기에 비례해야 한다. +3. **현재 보장**: 깊이·필드·alias·fragment 상한은 지켜진다(변이 1). 복잡도는 페이지 인자가 값으로 보일 때만 곱한다. list 기본 배수·변수 기본값은 반영하지 않는다(03-01, E2). +4. **대안**: (a) graphql-java `MaxQueryComplexityInstrumentation` + `FieldComplexityCalculator`, (b) 현재 scorer를 고친다, (c) 깊이·필드 상한만 남기고 복잡도는 버린다. +5. **얻고 지불하는 것**: (a)는 graphql-java가 coerced 변수·기본값을 계산해 준다. 대신 플랫폼의 페이지 상한 거부·카탈로그 가중치를 calculator로 다시 써야 하고, 테스트가 바뀐다. (b)는 코드 변경이 작지만 변수 coercion을 직접 맞춰야 한다. (c)는 가장 단순하지만 `first: 100`을 12단 중첩하는 문서를 막지 못한다. +6. **현재 조건의 선택**: (b). 기존 카탈로그·거부 코드와 테스트를 유지하면서 구멍만 막는다. 변수는 graphql-java `ValuesResolver`로 coercion하면 (a)의 장점을 가져온다. +7. **바뀌는 조건**: adopter가 federation·persisted query처럼 graphql-java 표준 계측을 함께 쓰게 되면 (a)로 옮기는 편이 두 벌 유지를 줄인다. + +### 5.2 gRPC를 두 스택(어댑터 서버 + vendored 플랫폼)으로 둔 것 + +1. **필요한 것**: 지금은 loopback unary 하나. 나중에 TLS·streaming·멱등성이 필요할 수 있다. +2. **지킬 성질**: production 서버가 문서가 말하는 한도로 동작한다. +3. **현재 보장**: 어댑터 서버는 io.grpc 기본값. 플랫폼 한도는 testkit 서버에만 적용(03-09). 멱등성은 판단 함수와 ledger만 있고 서버 경로가 없다(03-11). +4. **대안**: (a) 현상 유지 + 어댑터에 한도 명시, (b) 어댑터가 플랫폼 `grpc-runtime`을 받는다(registry edge 추가), (c) 플랫폼을 템플릿에서 빼고 필요할 때 가져온다. +5. **얻고 지불하는 것**: (a)는 작고 두 스택 결정을 건드리지 않는다. 같은 한도 값을 두 곳이 갖는 중복은 남는다. (b)는 증거(Netty lane)가 production 서버를 가리키게 되지만 플랫폼 143개 파일이 어댑터 의존에 들어온다. (c)는 유지비를 없애지만 소유자가 만든 플랫폼을 버린다. +6. **선택**: 소유자 결정(X1-#10 수용, "배선은 별도 결정")을 존중해 (a). 중복 값은 `GrpcTransportLimits` 값을 어댑터 문서에 인용해 두 곳이 같다는 사실을 테스트로 고정한다. +7. **바뀌는 조건**: TLS·외부 bind(P2)를 열거나 streaming이 필요해지면 (b)를 다시 본다. 그때 03-10·03-11이 먼저 닫혀야 한다. + +### 5.3 WebSocket live push를 simple broker + best-effort로 둔 것 + +1. **필요한 것**: 단일 노드에서 도메인 이벤트 알림. +2. **지킬 성질**: 발행 스레드를 느리게 하지 않는다. 한 사용자가 다른 사용자의 수신을 막지 않는다. +3. **현재 보장**: broker 채널 bounded executor(K-11b, 테스트 있음), 꽉 차면 drop. 구독·연결 수 상한이 없어 한 사용자가 큐를 채울 수 있다(03-06). +4. **대안**: (a) 현상 + 세션당 구독 1·연결 상한, (b) broker relay(RabbitMQ·ActiveMQ), (c) SSE로 전환. +5. **비용**: (a)는 interceptor 몇 줄. (b)는 운영 인프라 추가. (c)는 STOMP 클라이언트 계약을 깨고 servlet 스레드 점유 모델이 다르다. +6. **선택**: (a). README가 이미 단일 노드 best-effort라고 선언했고, 그 범위 안에서 공정성만 막으면 된다. +7. **바뀌는 조건**: 다중 노드 전달이나 재전송이 요구되면 (b). + +## 6. 리팩토링 후보 + +| 대상 | 무엇을 왜 | 보존 조건 | +| --- | --- | --- | +| `GraphQlDataLoaderRequestRegistry` + `GraphQlDataLoaderFactory.newRequestRegistry()` | 도달 불가 중복 경로 삭제(03-04) | registrar 요청 스코프, `cacheScope()` 지문, API surface 재승인 | +| `GraphQlTimeoutPolicy` | main 호출자 0. 03-02에서 쓰거나 삭제 | `REQUEST_TIMEOUT` wire code 유지 | +| `GraphQlPlatformWebInterceptor` 생성자 10개 | anonymous 3값을 record 하나로(S5-#14e) | 거부 순서·오류 코드·`GraphQlRequestStageErrorMappingTest` | +| `TomcatWebSocketAbuseIT.shutdownClosesLiveConnections` | `TomcatWebSocketShutdownIT`와 중복, 시간 경계 flaky(P25-new-1). 삭제하거나 "close code만" 단언으로 축소 | 1001 단언은 ShutdownIT가 계속 가진다 | +| `TomcatWebSocketAbuseIT` inline FQN 9곳 | import로 | 없음(형식만) | +| `GrpcClientMessageDeduplicator` | 세션별 map으로 나눠 `endSession` O(1)(N-12a) | 중복 판정 결과, 세션 종료 후 outcome 미보존 | +| gRPC 어댑터 `GrpcServerSettings` | 한도 값을 `GrpcTransportLimits`와 같은 이름·값으로(03-09) | `ignoreUnknownFields=false` 바인딩, loopback 강제 | + +## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료) + +### 7.1 템플릿이 주는 틀 + +| 기능 | 주는 것 | 빠진 것 | +| --- | --- | --- | +| GraphQL 필드 추가 | `classpath:graphql/*.graphqls` 병합, `@Controller` 자동 바인딩, 플랫폼 상한·인가·비용·오류 매핑, `GraphQlBatchLoaderRegistrar`, 전송 경계 ArchUnit | feature 예시(sample에 GraphQL 없음), 목록 필드 비용 규약(03-01), DataLoader 조립 예(03-03), 실행 시간 상한(03-02) | +| WebSocket 서버 push | `LiveEventProjector` 하나 등록하면 broadcast, bounded 채널 | projector 예시(sample 0), 연결·구독 상한(03-06) | +| WebSocket 요청/응답 | `PlatformWebSocketHandler` + budget, README 조립 예 | 연결 수 상한, stop 뒤 연결 처리(03-08) | +| gRPC 서비스 | `@GrpcExposedService` + `GrpcAuthenticationPolicy` 하나, 오류 매핑, health | `.proto` 예시, 서버 한도(03-09), TLS(P2) | +| gRPC 멱등 mutation | ledger 테이블·JPA 어댑터·판단 함수 | 서버 interceptor, stale claim 회수(03-10·03-11) | + +### 7.2 개발자가 내려야 하는 판단 + +1. **어느 전송인가.** 요청/응답이면 web. 서버가 먼저 알려야 하면 STOMP 채널. 연결 하나에서 명령을 주고받으면 라이브러리 handler. 내부 서비스 간이면 gRPC(지금은 같은 Pod만). +2. **GraphQL list 필드를 만들 때.** connection(`first`/`last`)으로 둘지 일반 list로 둘지 정한다. 지금 scorer는 인자가 값으로 보일 때만 곱한다. 03-01 수정 전까지는 모든 list에 `first` 인자를 필수(non-null)로 두는 것이 안전하다. +3. **자식 필드를 어떻게 가져오나.** 부모가 list면 `GraphQlBatchLoaderRegistrar.register`로 batch loader를 쓴다. `@BatchMapping`은 플랫폼 chunk·deadline이 붙지 않는다. +4. **비용 가중치.** 외부 호출이 있는 필드는 `GraphQlCostCatalog`에 `EXTERNAL_PER_OBJECT`로 등록한다. 등록하지 않으면 모두 10이다. +5. **오류 코드.** product 오류는 `ApiErrorCode`를 가진 예외(`ApiErrorCarrier`)로 던진다. GraphQL 전용 코드는 `GraphQlErrorCode.platform`에 `GRAPHQL_` 접두로만. +6. **WebSocket 연결 상한.** 프록시(Nginx `limit_conn`)에서 둘지 앱에서 둘지 정한다. 지금 앱에는 없다. +7. **gRPC 멱등성.** `IDEMPOTENCY_KEY_REQUIRED` method는 03-10·03-11이 닫히기 전에는 application `IdempotencyExecutor`를 use case 안에서 쓰는 쪽이 안전하다(websocket `CLAUDE.md`와 같은 권고). +8. **opt-in 절차.** `runtimeOnly` 한 줄 + registry edge + env key 등록 + `conditionalTransportQualification` 실행. 세 leaf `CLAUDE.md` 「Adopting」 절이 순서를 준다. + +## 8. 28개 관점 판정표 + +기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역. + +| # | 관점 | 판정 | 이유 | +| --- | --- | --- | --- | +| 1 | 코드 성숙도 | P | 대부분 정돈. 동시성 누수(03-07)·비용 계산 구멍(03-01) | +| 2 | 구조적 성숙도 | P | inbound→outbound 금지·전송 경계 ArchUnit은 M3. gRPC 두 스택이 같은 한도를 따로 가진다(03-09) | +| 3 | 변경 용이성 | P | GraphQL auto-config가 기능별 8개로 나뉨(S5-#7a). 비용 규칙을 바꾸려면 scorer·calculator·policy 세 곳을 같이 봐야 한다 | +| 4 | 인지 부하 | P | 등급표·README가 잘 돼 있음. 죽은 registry를 장치로 설명(03-04), graphql 주석 32% | +| 5 | 위험 가시성 | X | 실행 시간 상한(03-02)·ledger 플래그(03-11)·STOMP 전송 한도(03-06)가 코드에 없거나 약속과 다르다 | +| 6 | 실패 성숙도 | P | 오류 매핑 단일화·마스킹+로그는 O. stale claim·종료 창·deadline 미강제 | +| 7 | 운영 성숙도 | P | 1001 종료·health terminal 있음. gRPC drain 대기 없음 | +| 8 | 디버깅 가능성 | P | executionId·requestId 연결 O. batch context 누락이 timeout으로 보임(03-05) | +| 9 | 유지보수 성숙도 | P | 남은 W5 nit 다수(S5-#14d·#14e, K-12c, N-12) | +| 10 | 테스트 성숙도 | P | 변이 2개 모두 잡힘. list 필드·scorer 단위 테스트 없음(03-01). shutdown 테스트 시간 경계 flaky(P25-new-1) | +| 11 | 데이터 성숙도 | P | ledger DB 제약·마이그레이션 PG 검증 O. 보존·정리 없음(03-10) | +| 12 | 동시성 성숙도 | P | claim 원자성 E3, gRPC admission·rotation 경합 수정(N-5). writer close 경합(03-07) | +| 13 | 확장성 | X | 연결·구독 수 상한 없음(03-06), gRPC executor 무제한(03-09) | +| 14 | 성능 성숙도 | P | 문서 캐시·bounded 채널 O. 비용 점수가 실제 작업과 비례하지 않음(03-01). 실부하 증거 없음 | +| 15 | 보안 성숙도 | P | handshake principal·origin allowlist·introspection off·좌표 인가 O. 목록 크기 DoS(03-01), 구독 증폭(03-06) | +| 16 | 의존성 성숙도 | O | grpc BOM·lockfile, 플랫폼 별도 build, registry edge 최소 | +| 17 | API / Contract 성숙도 | P | wire 오류 코드 카탈로그·API surface 스냅샷 O. 설정 키가 약속만 함(03-11), README 설명 엇갈림(P15-new-4) | +| 18 | 배포 성숙도 | P | build-time opt-in 명확. ledger lane이 릴리스 게이트 밖(03-12) | +| 19 | 설정 성숙도 | P | `ignoreUnknownFields=false`, `@Validated`, 필수 deployment-mode O. 숨은 기본값(STOMP·gRPC) | +| 20 | 개발자 경험 | P | 「Adopting」 절차 O. GraphQL·WebSocket feature 예시 없음 | +| 21 | Guardrail 성숙도 | P | strict lane(no-skip)·전송 경계 ArchUnit·production 인가 정책 강제 O. 비용·deadline 가드 부재 | +| 22 | 추상화 성숙도 | P | 판단 함수 + port 구조는 적절. 쓰이지 않는 `GraphQlTimeoutPolicy`·registry | +| 23 | 일관성 | P | 오류 문구 shared 표 통일 O. 같은 한도가 두 gRPC 스택에 따로 | +| 24 | 네이밍 / 의미 성숙도 | P | 대체로 명확. `operation-ledger-enabled`가 실제 의미와 다름 | +| 25 | 조직 확장성 | - | 이 영역 단독으로 판단할 근거 없음(팀·소유 정보 없음) | +| 26 | Ownership 성숙도 | P | leaf별 `CLAUDE.md`가 소유 규칙을 가짐. root family 표에 gRPC 행 없음(S7-lead-2) | +| 27 | 삭제 가능성 | O | 세 어댑터 모두 한 줄 제거로 빠지고 `conditionalTransportQualification`이 확인(오늘 통과) | +| 28 | 회복 가능성 | X | stale `IN_PROGRESS` 회수 불가(03-10), 예산 누수는 재시작 전 회복 불가(03-07) | + +### 성능·테스트 시간 메모 + +오늘 게이트의 테스트 결과 XML(testsuite time 합, JVM·Spring 기동 시간 제외): + +| lane | 건수 | 시간 | +| --- | --- | --- | +| websocket `test` / `systemTest` / `websocketJettyTest` / `websocketTransportQualificationTest` | 74 / 18 / 8 / 5 | 3.6초 / 1.8초 / 0.9초 / 1.9초 | +| graphql `test` / `systemTest` / `graphqlStableTest` / `graphqlTransportQualificationTest` | 377 / 25 / 4 / 8 | 9.7초 / 2.1초 / 0.3초 / 1.9초 | +| grpc 어댑터 `test` / `grpcTransportQualificationTest` | 48 / 20 | 2.7초 / 2.3초 | +| ledger `integrationTest`(로컬) | 18 | 0.55초(+ container 기동) | + +실행 시간은 과하지 않다. 비용은 기동 쪽에 있다(graphql systemTest가 random-port 서버를 띄움). 요청당 복잡도 계산 비용은 측정하지 않았다(scorer 방문 노드 상한 200,000이 상한). diff --git a/docs/reviews/2026-11-01-maturity-review/04-persistence.md b/docs/reviews/2026-11-01-maturity-review/04-persistence.md new file mode 100644 index 00000000..08f1af24 --- /dev/null +++ b/docs/reviews/2026-11-01-maturity-review/04-persistence.md @@ -0,0 +1,480 @@ +# 04 Persistence — 성숙도 리뷰 (2026-11-01) + +영역: `adapter:outbound:persistence-jpa`, `adapter:outbound:persistence-mongo`, +`adapter:outbound:persistence-fileserver`, `adapter:outbound:persistence-notification`, Flyway 마이그레이션과 스키마. + +## 1. 범위 + +| 항목 | 기록 | +| --- | --- | +| 대상 | `clean-architecture-backend-template`, Gradle 루트 `src/` | +| 커밋 | `main` @ `01a8a2a70` (리뷰 후속 Wave 1–3 머지 직후). 작업 트리 깨끗함 | +| 목적·지원 구성 | 템플릿(reference implementation). 파생 서비스가 복사해 쓴다. JPA·Mongo는 `runtimeOnly` 한 줄로 켜는 capability다. 다중 인스턴스를 전제로 한 장치(outbox lease fencing, `FOR UPDATE SKIP LOCKED` claim)가 있으므로 다중 인스턴스를 지원 구성으로 본다 | +| 규모·운영 목표 | 문서에 합의된 수치 없음. 그래서 "대규모 운영 준비" 판정은 하지 않는다 | +| 읽은 코드 | 네 leaf의 `src/main`(JPA 193개·Mongo 278개·notification 48개·fileserver 27개 파일)의 트랜잭션·예외 변환·엔티티·쿼리·claim 경로, `src/test`·`postgresqlIntegrationTest`·`testFixtures`의 관련 부분, 각 `build.gradle`, 루트 `src/build.gradle` lifecycle, `.github/workflows/*.yml`, `config/module-defaults/persistence-jpa.yml`, 마이그레이션 디렉터리 9곳, `docs/jpa/*.md`, ADR-JPA-003. sample의 WorkLog 영속 경로(참조 패턴으로서) | +| 위임 조사 | Mongo leaf, notification·fileserver leaf는 읽기 전용 하위 조사로 나눠 읽었다. High로 올린 항목과 핵심 근거는 내가 코드를 다시 열어 확인했다 | +| 실행한 명령 | 아래 표 | +| 확인 못 한 것 | Mongo 컨테이너 lane(현재 커밋 미실행. 결과 XML은 09-28 것), JPA platform 태그 lane(`jpaPlatformContractTest` 등, 현재 커밋 미실행), 04-05의 실제 중복 처리 재현, 04-11의 실제 WriteConflict 재현, 쿼리 수 실측(04-09는 계산값) | +| 이전 리뷰와 비교 | techlead `05`·`06`, followup-status E·F·S2 행과 persistence 관련 TEST·X1·S6·S7·P*·ORCH 행 | + +실행한 명령 (모두 scratchpad worktree `wt-04`에서, `flock heavy.lock` 안에서 실행. 끝난 뒤 worktree 삭제): + +| 명령 | 부하(uptime 1분) | 결과 | +| --- | --- | --- | +| `./gradlew :adapter:outbound:persistence-jpa:test` (+ 실험 테스트 1개 파일 추가) | 26.38 | 통과. 503개, 테스트 시간 합 8.6초, wall 2분 29초(컴파일 포함, 고부하) | +| `./gradlew :adapter:outbound:persistence-jpa:postgresql{FileserverMetadata,FileserverReclamation,Idempotency,Migration}IntegrationTest --continue` | 14.03 | 4개 lane 모두 통과. 16/15/8/5개, 테스트 시간 4.9/0.6/4.5/8.1초, Gradle 56초(lock 대기 포함 wall 181초) | +| `./gradlew :adapter:outbound:persistence-jpa:test --tests '*ScratchReview*'` | 7.92 | 실험 3개 통과(04-01·04-02·04-03 근거) | + +게이트 결과(오케스트레이터 실행, `scratchpad/gates`): `ci rc=0`(434초). `mainCheck rc=1` — 원인은 objectstorage MinIO 이미지 pull 실패 2건이고 이 영역과 무관하다. 이 영역에서 `ci`가 돌린 것은 `persistence-jpa:test`(502개, 16.6초), `persistence-notification:test`(19개, 1.1초), `persistence-mongo:test`(79개, 6.1초)·`mongoStableContractTest`(465개, 6.1초)다. `persistence-fileserver:test`는 `NO-SOURCE`다. `mainCheck`에서 이 영역이 실제로 돌린 테스트는 `mongoDocumentContractTest`(2개)뿐이다. 실 DB lane은 두 게이트 어디에도 없다. + +### 0.1 전제 + +| 전제 | 기록 | +| --- | --- | +| 사용 목적 | 사내 서비스 시작점 템플릿. 파생 서비스(tech-log-backend 등)가 복사한다 | +| 지원 실행 형태 | 다중 인스턴스 서버(근거: outbox·durable operation·recipient lease의 fencing 설계) | +| 데이터와 권한 | 알림 수신 거부·연락처(개인정보 해시), 파일 메타데이터·쿼터, 멱등성 기록 | +| 의존 시스템 | PostgreSQL(주), H2(로컬 전용), MongoDB(선택, 소비자 0) | +| 운영 목표 | 미정. 허용 지연·데이터 손실·복구 시간 수치 없음 | +| 지원·비지원 | JPA: PostgreSQL만 운영 대상. Mongo: imperative만, outbox·멱등성·lock 미지원 | + +## 2. 지난 발견 재확인 + +경로 약어: `PJ` = `src/adapter/outbound/persistence-jpa`, `PM` = `src/adapter/outbound/persistence-mongo`, `PN` = `src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform`, `PF` = `src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver`. + +| ID | 상태 | 근거 | +| --- | --- | --- | +| E-3c canonical append ownership 테스트 | 해결 | 테스트가 `PJ/src/test/.../outbox/jpa/JpaOutboxStoreTest.java:157-174`(append·claim·mark의 트랜잭션 없는 호출 거부)로 옮겨졌다 | +| E-4c inbox 테스트가 운영 쿼리 복사본 실행 | 바뀜 | 이제 `@Query` 어노테이션에서 SQL을 읽어 실행한다(`PJ/src/postgresqlIntegrationTest/.../PostgreSqlInboxCutoffIntegrationTest.java:122-147`). 아직 adapter(`JpaNotificationInbox.markAllRead`)를 거치지 않는다. `'UNREAD'`는 fixture INSERT(`:165`)에만 남았다 | +| E-5c README "aggregate당 최대 한 row" | 남음 | `PJ/README.md:255` 문장 그대로 | +| E-6a tenant 규칙이 필드 이름 `tenantId`로만 판정 | 남음 | `PJ/src/testFixtures/.../testkit/arch/TenantScopedRepositoryPredicate.java:19,49-51` | +| E-12 CLAUDE.md 벤더 표에 `55P03` 누락 | 남음 | `PJ/CLAUDE.md:273-279`에 없음. 코드는 `PJ/src/main/.../postgresql/PostgreSqlSqlStateErrorMapping.java:20`에서 매핑 | +| F-1d security lane "injection" 과장 | 바뀜 | 단위 테스트에 `$ne`·`$gt` 거부가 생겼다(`PM/src/test/.../query/PolicyAwareMongoQueryBuilderTest.java:121-161`). lane 설명(`PM/build.gradle:209`)은 여전히 injection을 주장하지만 lane 테스트(`MongoSecurityIntegrationLaneTest.java:93-165`)에는 없다 | +| F-5d CSFLE 테스트·호출자 없음 | 바뀜 | 테스트 5개 추가(`MongoCsfleClientFactoryTest.java:59-124`). leaf 밖 호출자는 0. README "테스트 없는 진입점"(`PM/README.md:165-167`)에 5개가 남음 | +| F-9a inline FQN | 남음 | `PM/src/main/.../autoconfigure/MongoPlatformAutoConfiguration.java` 37줄(:62, :69, :129-166 외). 규칙 `PM/CLAUDE.md:70` | +| S2-#8b "두 조립 루트가 adapter를 스캔" 서술 | 남음 | `PJ/src/test/.../CandidateAdapterCompositionTest.java:6-14`, `PJ/src/main/.../idempotency/postgresql/PostgreSqlIdempotencyStore.java:52` | +| S2-#12 이력 서술 Javadoc | 남음 | 네 문구("used to" 등) JPA main 16줄, Mongo main 41개 파일 51회 | +| S2-#14a JPA CLAUDE.md의 "NoSQL은 미래 모듈"·MapStruct 절 | 남음 | `PJ/CLAUDE.md:17-19, 317-340` | +| S2-#14b API surface에 옮겨간 타입 | 해결 | `docs/architecture/jpa-adopter-api-surface.txt`에 `FileserverSchemaActivation` 없음 | +| S2-lead-2 / X1-#3b 멱등성 공통 계약 | 남음 | testFixtures 어디에도 `IdempotencyStoreContract` 없음 | +| TEST-F-2a claim 순서 단언 없음 | 남음 | `PJ/src/postgresqlIntegrationTest/.../platform/PostgreSqlWorkClaimContractTest.java:78-86` `isNotEmpty()`만 | +| TEST-FAKE-DeliveryProjectionStorePort | 남음 | fake 3개, 공통 계약 없음 | +| S7-lead-4 / X1-#6d recipient lease 공통 fencing 계약 | 남음 | PG IT 하나뿐(`PostgreSqlRecipientLeaseFencingIntegrationTest`) | +| ORCH-new-2 `NotificationPayloadAtRestContractTest` inputs 미선언 | 남음 | `src/adapter/outbound/notification/src/test/.../NotificationPayloadAtRestContractTest.java:155-163`가 다른 leaf의 V10 SQL을 읽는데 `notification/build.gradle`에 `inputs` 없음 | +| P4-new-1 fileserver migration 불변성 테스트 없음 | 해결 | `PJ/src/test/.../migration/AppliedMigrationImmutabilityTest.java:39-43`이 notification·fileserver 디렉터리도 검사. inputs 선언 `PJ/build.gradle:267-271` | +| P20-new-5 / 결정 36 JPA 설정 prefix | 남음 | 플랫폼 키가 아직 `app.persistence.vendor`, `app.runtime.migration-on-startup`에 있다(`PJ/src/main/resources/config/module-defaults/persistence-jpa.yml:160-164`, `PostgreSqlIdempotencyStoreConfig.java:38`). 결정 36은 이것을 `app.persistence-jpa.*`로 모으라고 했다(Wave 4 P33 예정) | +| S6-#16c hikari 이력 주석 | 남음 | `persistence-jpa.yml:33-37` | +| S6-#16e OSIV 예외 메시지의 문서 ID | 남음 | `PJ/src/main/.../startup/OpenInViewSafetyValidator.java:29` | + +남은 High/P1급 지난 발견: 없음. 남은 항목은 모두 W4(테스트)·W5(문서) 성격이다. + +## 3. 새 발견 + +심각도 순. 단순 결함은 설계 선택 필드를 `적용 제외`로 둔다. + +### 04-01 커밋 중 연결이 끊기면 "재시도 가능(DB_UNAVAILABLE)"으로 답한다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 6 실패, 12 동시성, 17 계약, 11 데이터, 5 위험 가시성 | +| 근거 | `PJ/src/main/.../failure/PersistenceExceptionTranslator.java:24,97` — SQLState가 `08`로 시작하면 무조건 `DB_UNAVAILABLE`. `OperationalError.DB_UNAVAILABLE`은 `retryable=true`(`src/shared-contract/.../OperationalError.java:54`). `SpringTransaction.execute`(`PJ/src/main/.../transaction/SpringTransaction.java:98-105`)는 커밋 실패도 같은 번역기로 보낸다. `TransactionCompletionUnknownException`은 main 어디에서도 생성되지 않는다(생성자 호출 0건). 실험: `TransactionSystemException(SQLException "08006")`을 커밋에서 던지는 `PlatformTransactionManager`로 `inWrite`를 호출 → `DB_UNAVAILABLE retryable=true`(E2). web은 retryable 코드에 `Retry-After`를 붙인다(`src/adapter/inbound/web/.../observability/RetryAfterAdvisor.java:29`) | +| 발생 조건 | 커밋 요청을 보낸 뒤 응답 전에 DB 연결이 끊김(장애 조치, 네트워크 단절, `pg_terminate_backend`) | +| 영향 | 서버는 커밋했을 수 있다. 클라이언트는 "일시 장애, 다시 시도"를 받고 같은 쓰기를 다시 보낸다. 멱등성 키가 없는 쓰기는 중복된다. ADR-JPA-003("completion unknown은 자동이든 아니든 재시도하지 않는다")과 반대다 | +| 심각도·우선순위 | High / P1. 데이터 중복으로 이어지는 도달 가능한 경로이고, 기본 조립의 모든 쓰기 유스케이스가 지난다. 템플릿을 복사하면 그대로 퍼진다 | +| 확실성 | 분류 결과는 실험으로 확인. 실제 PG에서 같은 SQLState가 나오는지는 `PostgreSqlTransactionIntegrationTest:147-197`이 연결 종료를 재현하지만 결과 코드를 단언하지 않아 미확인 | +| 결정의 근거 | 적용 제외 — 기대 계약(ADR-JPA-003)이 이미 정해져 있다 | +| 이해 비용 | 쓰기 유스케이스 작성자는 "503+Retry-After면 재시도해도 안전한가"를 코드에서 알 수 없다 | +| 최소 개선 방향 | `SpringTransaction`이 커밋 단계에서 난 예외를 따로 잡는다. `TransactionTemplate.execute` 대신 `getTransaction`/`commit`을 직접 부르거나, 액션 완료 여부를 플래그로 기록한다. 액션이 끝난 뒤 난 `08*`·`40003`·전송 단절은 `DB_COMPLETION_UNKNOWN`(retryable=false)로 바꾼다 | +| 완료 기준 | 커밋 중 연결 종료 시 호출자가 `DB_COMPLETION_UNKNOWN`을 받는다. 커밋 전 연결 실패는 여전히 `DB_UNAVAILABLE`이다 | +| 검증 방법 | `PostgreSqlTransactionIntegrationTest#connectionLossDuringCommit…`에 결과 코드·retryable 단언 추가. 커밋 전 실패와 구분하는 단위 테스트 1개 | + +### 04-02 다중 인스턴스에서 알림 정산 job이 중복 처리된다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(정적). 중복 처리의 업무 영향 범위는 일부 미확인 | +| 관련 관점 | 12 동시성, 13 확장성, 6 실패, 5 위험 가시성 | +| 근거 | `PN/JdbcReconciliationJobStore.java:43-52` claim은 `SELECT … FOR UPDATE SKIP LOCKED`다. `:117-123`은 이것을 트랜잭션 없이 `JdbcOperations.query`로 실행한다. 호출자 `src/adapter/outbound/notification/.../dispatch/ReconciliationJobWorker.java:81`과 스케줄러 `NotificationBackgroundWorkers.java:79-104`에도 트랜잭션이 없다. autocommit이라 행 잠금은 SELECT가 끝나는 순간 풀린다. lease·owner 컬럼도 없다. 같은 leaf의 다른 쓰기는 모두 `CallerTransaction.require`를 부르는데 이 store의 네 메서드(`:93-143`)만 부르지 않는다 | +| 발생 조건 | 인스턴스 2개 이상, 정산 대기 job이 있을 때 | +| 영향 | 같은 job을 여러 인스턴스가 동시에 가져간다. 공급자 상태 조회가 중복되고 `attempts`가 두 번 오른다(최대 시도 도달이 빨라짐). 결과 기록이 두 번 일어날 때의 업무 영향은 reconciler 구현의 멱등성에 달려 있고 확인하지 않았다 | +| 심각도·우선순위 | High / P1. 코드가 "잠근다"는 의도를 보이지만 실제로 잠그지 않는다. 다중 서버 업무 중복 실행에 해당한다 | +| 결정의 근거 | 적용 제외 — 같은 leaf의 recipient claim(`RecipientClaimSql`)이 이미 lease+fence 방식을 쓴다. 그 방식을 따르면 된다 | +| 최소 개선 방향 | claim을 `UPDATE … SET claimed_by, claimed_until … WHERE id IN (SELECT … FOR UPDATE SKIP LOCKED) RETURNING`으로 바꾸고, reschedule·complete는 owner+token 조건 UPDATE로 바꾼다. 마이그레이션으로 컬럼 추가 | +| 완료 기준 | 두 연결에서 동시에 claim하면 겹치는 job이 0개. lease가 지난 job만 다른 인스턴스가 가져간다 | +| 검증 방법 | 실 PG 동시 claim 테스트(두 스레드, 교집합 0 단언). 가능하면 X1-#6d의 범용 `ClaimFencingContract`를 상속 | + +### 04-03 JPA 연관관계 원칙(양방향 금지)을 막는 장치가 없고, 템플릿 문서와 fixture는 반대로 가르친다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 5 위험 가시성, 21 guardrail, 20 개발자 경험, 23 일관성, 4 인지 부하 | +| 근거 | 전수 확인 결과 production 엔티티 28개(JPA 4, notification 12, fileserver 6, sample 5, gRPC ledger 1)에 `@ManyToOne`·`@OneToMany`·`@OneToOne`·`@ManyToMany`가 하나도 없다. 모두 UUID 컬럼으로 서로를 가리킨다. sample `WorkLogEntity.java:52-58`만 `@ElementCollection`(LAZY) 2개. 그러나 (1) ArchUnit 규칙 묶음 `JpaArchitectureRules`(`PJ/src/testFixtures/.../testkit/arch/JpaArchitectureRules.java:34-102`)와 `JpaProductionArchitectureTest`(`src/app-bootstrap/src/architectureTest/.../JpaProductionArchitectureTest.java`)에 연관관계 규칙이 없다. (2) `docs/jpa/entity-mapping-guide.md:50-57`은 "inverse collection + 양쪽을 맞추는 association helper"를 권장한다. (3) testFixtures `PagedParent.java:41-46`·`LifecycleParent.java:46-51`이 `@OneToMany(mappedBy, cascade=ALL, orphanRemoval)` + `@ManyToOne` 양방향 예시다. (4) sample 엔티티는 `JpaProductionArchitectureTest`의 import 대상이 아니다(app-bootstrap이 sample에 의존하지 않음) | +| 발생 조건 | 파생 서비스 개발자가 가이드나 fixture를 따라 첫 연관관계를 만들 때 | +| 영향 | 양방향 매핑이 아무 경고 없이 들어온다. 그러면 한쪽만 바꿔 FK가 비는 실수, `cascade=ALL`이 다른 aggregate 행을 지우는 실수, 직렬화·toString 순환, 컬렉션 로딩 N+1이 개발자 기억에 맡겨진다. 사용자가 정한 "위험은 코드에 드러나야 한다" 원칙과 반대다 | +| 심각도·우선순위 | Medium / P1. 지금 production에 위반은 없다. 그러나 템플릿이 반대 패턴을 문서와 예제로 배포하므로 복제 범위가 크다 | +| 결정의 근거 | 확인한 사실: 현재 코드는 이미 "ID 참조만" 방식으로 일관된다. 기록된 의도: 가이드는 양방향 helper를 권장한다. 둘이 어긋난다. 추론: 현재 코드의 일관성은 의도된 규칙이 아니라 결과일 가능성이 있다 | +| 최소 개선 방향 | `JpaArchitectureRules`에 "필드에 `@OneToMany(mappedBy=…)`가 있으면 위반"(또는 "`@OneToMany`·`@ManyToMany` 금지, `@ManyToOne`은 LAZY 필수") 규칙을 추가하고 `JpaProductionArchitectureTest`와 sample 아키텍처 테스트에서 호출한다. 가이드 50-57행을 "aggregate 사이는 ID 참조, aggregate 안 자식은 단방향 `@ManyToOne` 또는 `@ElementCollection`"으로 바꾼다. fixture는 단방향으로 바꾸거나 "규칙의 위반 예시"로 이름과 위치를 옮긴다 | +| 대안 비교 | (a) 문서만 고침: 비용 최소, 강제 없음(M1). (b) ArchUnit 규칙(선택): 빌드에서 막힘(M3), 규칙 1개·테스트 1개. (c) 컴파일 단계 annotation processor: 강제 강도는 같고 비용 큼. (d) 현상 유지: 원칙과 문서가 계속 충돌. (b)를 고른다. (c)는 얻는 것 대비 비용이 크다 | +| 단순화의 보존 조건 | pagination·lifecycle 계약 테스트가 쓰는 fixture 동작(LAZY 컬렉션 페이지 경고, orphan 삭제)은 단방향 매핑이나 별도 위반 fixture로 유지해야 한다 | +| 재검토 조건 | aggregate 안 자식 컬렉션을 엔티티로 다뤄야 하는 실제 요구(예: 자식 단독 조회·수정)가 생기면 `@OneToMany` 단방향(+`@JoinColumn`) 허용 범위를 다시 정한다 | +| 완료 기준 | 양방향 fixture를 production 패키지에 넣으면 `architectureCheck`가 실패한다. 가이드와 fixture가 원칙과 같은 말을 한다 | +| 검증 방법 | 위반 fixture로 규칙이 실패하는지 보는 red/green 테스트 | + +### 04-04 실 PostgreSQL lane 9개(57개 테스트)가 어떤 게이트·workflow에서도 돌지 않는다. persistence-fileserver는 자기 테스트가 0개다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(게이트 누락) | +| 관련 관점 | 10 테스트, 21 guardrail, 26 ownership, 18 배포 | +| 근거 | readiness lane 16개(`PJ/build.gradle:166-183`) 중 workflow가 이름으로 부르는 것은 5개뿐이다(`.github/workflows/integration-main.yml:305-317`). `postgresql{Lifecycle,SecurityBaseline,Migration,Aggregate,Query,Idempotency,FileserverMigration,FileserverMetadata,FileserverReclamation}IntegrationTest`는 workflow·`release-registry.json` 어디에도 없다. 이 클래스들에는 `@Tag`가 없어 태그 lane(`jpaPlatformContractTest` 등)에도 안 잡힌다. 루트 `integrationCheck`(`src/build.gradle:100-105`)가 유일한 집계인데 `ci`·`mainCheck`에 들어 있지 않고, workflow는 `--dry-run`만 한다(`integration-main.yml:96-99`). 게이트 로그: `persistence-fileserver:test NO-SOURCE`, `mainCheck`는 JPA 실 DB lane을 하나도 실행하지 않음. 실행 확인: 4개 lane을 직접 돌려 44개 모두 통과(E2) — 지금은 깨져 있지 않다 | +| 발생 조건 | fileserver·멱등성·마이그레이션 영속 코드를 바꾸는 PR | +| 영향 | 파일 메타데이터·쿼터 회수·멱등성 저장소의 실제 SQL 동작이 바뀌어도 아무 게이트가 실패하지 않는다. `PJ/CLAUDE.md:97`("Contracts run against real PostgreSQL")과 `:119-121`("fail closed")의 주장이 실행으로 뒷받침되지 않는다 | +| 심각도·우선순위 | Medium / P1. 결함 자체가 아니라 검출 공백이지만, persistence-fileserver는 다른 검증 경로가 없다 | +| 결정의 근거 | 적용 제외 — 원하는 계약(실 DB 계약 실행)이 이미 문서에 있다 | +| 최소 개선 방향 | `integration-main.yml`에 `./gradlew :adapter:outbound:persistence-jpa:integrationTestLaneCheck` 한 step을 추가하거나, fileserver·idempotency lane을 `fileserver-pr.yml`·`pr-adapters.yml`의 해당 path filter job에 넣는다. 장기적으로는 fileserver IT를 `persistence-fileserver` leaf로 옮긴다(04-13 참고) | +| 완료 기준 | 16개 readiness lane이 모두 하나 이상의 workflow에서 실행된다. lane 목록과 workflow를 대조하는 테스트가 있으면 더 좋다 | +| 검증 방법 | workflow 실행 기록, 또는 lane 이름 ↔ workflow 텍스트 대조 테스트 | + +### 04-05 `@Version` 충돌이 변환되지 않고 500 INTERNAL_ERROR로 나간다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 6 실패, 17 계약, 12 동시성, 8 디버깅 | +| 근거 | `SpringTransaction`의 번역기는 SQLState만 본다(`PersistenceExceptionTranslator.java:73-84`). `ObjectOptimisticLockingFailureException`은 SQLException이 없어 `Optional.empty()` → `.orElse(failure)`(`SpringTransaction.java:105`)로 원래 예외가 나간다. web은 이것을 `INTERNAL_ERROR` 500으로 답한다(`src/adapter/inbound/web/.../error/GlobalExceptionHandler.java:189-196`). 실험으로 확인(E2). `DB_OPTIMISTIC_CONFLICT`(409)는 정의돼 있고 `LockFailureClassificationContractTest`가 enum 값만 확인한다(`src/app-bootstrap/src/test/.../LockFailureClassificationContractTest.java:38-60`). 이 코드를 만드는 곳은 라이브러리 API인 `PostgreSqlExceptionTranslator`뿐이고, 기본 조립은 이것을 쓰지 않는다 | +| 발생 조건 | 같은 aggregate를 두 요청이 동시에 수정. sample `UpdateWorkLogUseCase.java:32-73`은 읽은 뒤 버전을 비교하지만, 비교와 커밋 사이 경쟁은 커밋 시점 `@Version` 충돌로만 잡힌다 | +| 영향 | 클라이언트는 "다시 읽고 고쳐라"(409) 대신 "서버 오류"(500)를 받는다. 운영 로그에는 정상 경쟁이 error로 남는다 | +| 심각도·우선순위 | Medium / P2 | +| 결정의 근거 | 적용 제외 — 기대 코드(`DB_OPTIMISTIC_CONFLICT`)가 이미 정해져 있다 | +| 최소 개선 방향 | `SpringTransaction.execute`(또는 `PersistenceExceptionTranslator`)에서 Spring `OptimisticLockingFailureException`을 `DB_OPTIMISTIC_CONFLICT`로 바꾼다. 04-06의 표 통합과 같이 하면 한 곳만 고친다 | +| 완료 기준 | 커밋 시점 버전 충돌 시 호출자가 `PersistenceFailureException(DB_OPTIMISTIC_CONFLICT)`를 받고 web은 409를 답한다 | +| 검증 방법 | 단위 테스트(실험과 같은 형태) + 실 PG 두 트랜잭션 경쟁 테스트 1개 | + +### 04-06 SQLState 분류표가 두 벌이고 이미 갈라졌다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(갈라진 중복) | +| 관련 관점 | 23 일관성, 9 유지보수, 17 계약, 22 추상화 | +| 근거 | 표 1: `failure/StandardSqlStateErrorMapping` + `postgresql/PostgreSqlSqlStateErrorMapping.java:17-23`(SQLState → `OperationalError`). `TransactionPort` 경로가 쓴다. 표 2: `postgresql/error/PostgreSqlFailureClassifier.java:50-61`(SQLState → `FailureCategory`) + `api/error/JpaPersistenceException.java:59-75`(`FailureCategory` → `OperationalError`). 라이브러리 API 경로가 쓴다. 실험: `25P03`이 표 1에서는 `DB_IDLE_IN_TX_TIMEOUT`(retryable=true), 표 2에서는 `TRANSACTION_TIMEOUT` → `DB_QUERY_CANCELED`(retryable=false)(E2). `40003`은 표 2에만 있다(completion unknown). `@Version` 충돌은 표 2에만 있다(04-05) | +| 발생 조건 | 같은 DB 오류가 어느 경로로 올라오느냐에 따라 | +| 영향 | 같은 장애에 클라이언트가 받는 retryable 값이 경로마다 다르다. SQLState를 하나 추가할 때 두 곳을 고쳐야 하고, 하나만 고쳐도 아무 테스트가 실패하지 않는다 | +| 심각도·우선순위 | Medium / P2 | +| 결정의 근거 | 확인한 사실: 두 표 모두 `PersistenceFailureException`을 만든다(`JpaPersistenceException extends PersistenceFailureException`). 기록된 의도: 표 2 Javadoc은 "세 갈래 병렬 분류 대신 같은 코드"를 말한다(`JpaPersistenceException.java:19`). 의도는 하나로 모으는 것이었고 끝나지 않았다 | +| 최소 개선 방향 | 표 2(`PostgreSqlFailureClassifier` → `FailureCategory`)를 정본으로 하고, `PostgreSqlSqlStateErrorMapping`은 그 결과로부터 파생한다. 또는 반대로 표 1에 `FailureCategory`를 얹는다 | +| 대안 비교 | (a) 표 2 정본(선택): 범주가 더 풍부(completion unknown, optimistic, schema mismatch). 표 1의 SPI(`SqlStateErrorMapping`)는 vendor 확장점이라 어댑터 하나로 남긴다. (b) 표 1 정본: 기본 경로라 영향 범위 작음, 그러나 completion-unknown·optimistic 표현이 없다. (c) 두 표 유지 + 일치 테스트: 가장 싸지만 중복이 남는다. (a)를 고르고, 이행 중에는 (c)의 일치 테스트로 보호한다 | +| 단순화의 보존 조건 | `SqlStateErrorMapping` SPI(H2 행 기여)와 중복 SQLState 기여 시 기동 실패(`PersistenceExceptionTranslator.java:43-56`)는 유지 | +| 재검토 조건 | 두 번째 RDBMS 벤더가 운영 대상이 되면 vendor별 표 구조를 다시 정한다 | +| 완료 기준 | 모든 SQLState에 대해 두 경로의 결과 코드가 같다(또는 표가 하나다) | +| 검증 방법 | `PostgreSqlState` 전 값에 대한 parameterized 일치 테스트 | + +### 04-07 bulk UPDATE가 `@Version`을 올리지 않는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 12 동시성, 11 데이터, 21 guardrail | +| 근거 | `PN/inbox/InboxItemJpaRepository.java:82-108` `markAllRead`는 `state`·`read_at`을 바꾸지만 `version`을 올리지 않고 `clearAutomatically`도 없다. 엔티티는 `@Version`(`PN/inbox/InboxItemEntity.java:72-74`). `PN/RecipientClaimSql.java:53-64` `EXPIRE_OVERDUE`도 같다. 같은 leaf의 claim SQL은 이미 version을 올린다(`RecipientClaimSql.java:42-46`). `JpaAuditMechanismRule.bulkUpdatesOfAuditedEntitiesStampAudit`는 audit 컬럼만 본다 | +| 발생 조건 | 같은 트랜잭션이나 다른 요청이 그 전에 읽은 엔티티를 수정·flush | +| 영향 | 낙관적 락이 충돌을 못 잡고 `read_at`이나 EXPIRED 상태를 되돌린다(lost update) | +| 심각도·우선순위 | Medium / P2 | +| 결정의 근거 | 적용 제외 | +| 최소 개선 방향 | 두 쿼리에 `version = version + 1`, `@Modifying(clearAutomatically = true, flushAutomatically = true)`. 그리고 audit 규칙과 같은 방식으로 "`@Version` 엔티티 테이블을 바꾸는 native/JPQL UPDATE는 version을 올린다" ArchUnit/문자열 규칙을 추가 | +| 완료 기준 | 두 쿼리 뒤에 이전 버전으로 flush하면 낙관적 락 충돌이 난다 | +| 검증 방법 | 실 PG 테스트 1개(읽기 → bulk → 이전 엔티티 수정 → 충돌 단언) | + +### 04-08 upsert가 "찾고 없으면 넣기"라 동시 요청에서 깨진다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 12 동시성, 11 데이터, 6 실패 | +| 근거 | 수신 거부: `PN/JpaSuppressionStore.java:47-64` find → save. DDL에 unique 제약이 없고 일반 인덱스뿐이다(`persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V2__notification_platform_contact_template_policy.sql:77-93`). finder는 단건 `Optional`(`PN/SuppressionJpaRepository.java:33`). 선호 설정: `PN/JpaPolicyStores.java:50-72` 같은 구조, 제약 `uk_notification_preference`는 있음(V2:102) | +| 발생 조건 | 같은 대상의 bounce webhook 두 개가 동시에 도착, 또는 첫 선호 저장이 동시에 두 번 | +| 영향 | 수신 거부: 행이 2개 생기고, 그 뒤 같은 키의 upsert는 매번 `IncorrectResultSizeDataAccessException`(500)으로 실패한다. 수동 정리 전까지 회복되지 않는다. 선호 설정: 한쪽이 `DB_UNIQUE_VIOLATION`(409)을 받는다. 멱등해야 할 동작이 충돌 오류가 된다 | +| 심각도·우선순위 | Medium / P2 | +| 결정의 근거 | 적용 제외 — 같은 클래스의 dedup 경로가 이미 `ON CONFLICT`로 고쳐져 있다 | +| 최소 개선 방향 | 새 마이그레이션 `UNIQUE (tenant_id, normalized_target_hmac, reason)`(기존 중복 정리 포함), 두 store를 `INSERT … ON CONFLICT … DO UPDATE` native upsert로 | +| 완료 기준 | 동시 upsert 두 개 후 행 1개, 두 호출 모두 성공 | +| 검증 방법 | 실 PG 동시 upsert 테스트 | + +### 04-09 sample 목록 조회가 N+1이다(페이지당 최대 202쿼리) + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(정적 계산, 실측 안 함) | +| 관련 관점 | 14 성능, 10 테스트, 20 개발자 경험, 21 guardrail. sample 영역과 겹침(>) | +| 근거 | `WorkLogEntity.java:52-58` LAZY `@ElementCollection` 2개. `WorkLogRepositoryAdapter.java:77-80` `findAll(pageRequest)` 뒤 행마다 `toDomain` → `WorkLog.rehydrate`가 `List.copyOf(techStack)`, `List.copyOf(links)`(`domain/worklog/WorkLog.java:51-52`)로 두 컬렉션을 초기화. `default_batch_fetch_size` 기본 0(`persistence-jpa.yml:150`). 페이지 크기 상한 100(`PageParams.java:20`). 쿼리 수 = 1(page) + 1(count) + 2×N → N=20이면 42, N=100이면 202. testkit에 `JpaQueryAssertions`(`PJ/src/testFixtures/.../testkit/query/`)가 있지만 sample은 persistence-jpa testFixtures를 쓰지 않는다 | +| 발생 조건 | `GET` 목록 요청마다 | +| 영향 | 요청당 DB 왕복이 행 수에 비례한다. 템플릿의 "참조 구현"이 N+1을 보여 주므로 파생 서비스가 그대로 복사한다 | +| 심각도·우선순위 | Medium / P2 | +| 결정의 근거 | 대안: (a) `default_batch_fetch_size`를 100 정도로 기본 설정(선택: 한 줄, 모든 LAZY 컬렉션에 효과, 쿼리 수 4로 고정). (b) 목록은 이미 있는 `WorkLogSummaryQueryPort`(컬렉션 없는 projection)로 돌림: 목록 화면 요구가 요약뿐이면 가장 싸다. (c) `@EntityGraph` fetch join: 컬렉션 2개 동시 join은 카테시안 곱과 페이지 메모리 처리 경고를 만든다 → 기각 | +| 최소 개선 방향 | (a)와 함께, sample 목록 테스트에 `JpaQueryAssertions`로 "쿼리 수 ≤ 4" 단언을 넣는다 | +| 완료 기준 | 목록 요청의 쿼리 수가 N과 무관하다 | +| 검증 방법 | statement 수 단언 테스트(실 PG lane) | + +### 04-10 기본 쓰기·읽기 트랜잭션에 시간 제한이 없다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 6 실패, 7 운영, 14 성능 | +| 근거 | `SpringTransaction.java:58`은 `inNew`에만 30초를 건다. `inWrite`·`inRootWrite`·`inRead`는 timeout 없음. `statement_timeout`·`lock_timeout`·`idle_in_transaction_session_timeout`을 설정하는 코드·설정이 없다(`set_config`는 COPY loader·실험 패키지에만). Hikari `leak-detection-threshold: 30000`(`persistence-jpa.yml`)은 경고만 한다 | +| 발생 조건 | 느린 쿼리, 행 잠금 대기, 트랜잭션 안의 외부 호출 | +| 영향 | 커넥션 10개(기본 pool) 풀이 오래 붙잡혀 다른 요청이 `connection-timeout` 5초 뒤 실패한다. 원인 쿼리는 끝나지 않는다 | +| 심각도·우선순위 | Medium / P2 | +| 결정의 근거 | 대안: (a) `TransactionTemplate.setTimeout`을 모드별로(선택: JPA query hint로 전파, 코드 한 곳). (b) DB role 수준 `ALTER ROLE … SET statement_timeout`: 앱 밖이라 템플릿이 보장 못 함, runbook에 병기. (c) 매 트랜잭션 `set_config('statement_timeout', …, true)`: 왕복 1회 추가 → (a)로 충분할 때 기각 | +| 최소 개선 방향 | `app.persistence-jpa.transaction.write-timeout`/`read-timeout` 설정(기본 예: 10초/5초)을 두고 템플릿에 적용 | +| 완료 기준 | 기본 설정에서 `pg_sleep(실제보다 긴 값)`이 든 `inWrite`가 정해진 시간 안에 실패한다 | +| 검증 방법 | 실 PG 테스트 1개 | + +### 04-11 Mongo 트랜잭션 본문의 일시 오류가 재시도되지 않는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(정적, 실 서버 미재현) | +| 관련 관점 | 6 실패, 12 동시성, 10 테스트 | +| 근거 | 본문에 넘기는 것은 `template.withSession(session)`(`PM/src/main/.../transaction/SpringMongoTransactionSessionFactory.java:92`)이다. `MongoTemplate`은 드라이버 예외를 Spring `DataAccessException`으로 바꿔 던진다. 그런데 `runBody`는 `MongoException`만 잡는다(`:141-142`). 그래서 WriteConflict(TransientTransactionError)는 `MongoTransactionTransientException`이 되지 않고, `MongoTransactionRetryCoordinator.execute`(`retry/MongoTransactionRetryCoordinator.java:85-92`)의 본문 재시도 분기에 걸리지 않는다. coordinator를 실 서버에서 검증하는 테스트는 없다 | +| 영향 | `PM/CLAUDE.md:137-139`가 보장하는 "본문 재시도"가 템플릿 경로에서는 동작하지 않는다. 쓰기 경쟁이 그대로 실패로 나간다. 소비자가 0이라 현재 피해는 없다 | +| 심각도·우선순위 | Medium / P2 | +| 결정의 근거 | 적용 제외 | +| 최소 개선 방향 | `runBody`에서 `DataAccessException`의 cause 사슬에서 `MongoException`을 찾아 분류한다 | +| 완료 기준 | replica set lane에서 강제 WriteConflict 후 본문이 한 번 더 실행되고 성공한다 | +| 검증 방법 | `mongoReplicaSetTest`에 테스트 추가 | + +같은 파일의 관련 소항목(Low): commit 재시도 대기 중 인터럽트가 `IllegalStateException`으로 바뀌어 "commit 결과 모름" 표시가 사라진다(`MongoTransactionRetryCoordinator.java:150,186`). `MongoTransactionCommitUnknownException`으로 감싸야 한다. + +### 04-12 Mongo 기본 경로(URI만 준 배포)에 timeout·pool 제한이 없다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 19 설정, 6 실패, 7 운영 | +| 근거 | typed profile이 없으면 설정 적용을 건너뛴다(`PM/src/main/.../client/MongoProfileClientSettingsAutoConfiguration.java:82-83`). 그러면 드라이버 기본값(pool 100, server selection 30초, socket timeout 무제한)을 쓴다. `PM/src/main/resources/config/mongo.yml:11` 주석은 "active-profile이 비면 안 된다"고 하지만 `MongoPlatformSettings.java:84-86`은 profile이 있을 때만 검사한다 | +| 심각도·우선순위 | Medium / P2 | +| 최소 개선 방향 | `mongo.yml`에 `spring.mongodb` timeout·pool 기본값을 두거나, 주석을 실제 동작에 맞춘다 | +| 결정의 근거 | 적용 제외 — 문서와 코드 불일치 정리 | +| 완료 기준·검증 | URI만 준 기동에서 `MongoClientSettings`의 socket·selection timeout이 유한값임을 단위 테스트로 확인 | + +### 04-13 persistence adapter가 정책을 소유하고, claim 토큰을 프로세스 메모리에 둔다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 2 구조, 5 위험 가시성, 12 동시성, 22 추상화 | +| 근거 | `PF/JpaCleanupQueue.java:36` `MAXIMUM_ATTEMPTS = 8`, `:151-160` 소진 시 ABANDONED 판정, `:67` lease 10분 상수. `:100-116` claim은 행마다 UPDATE를 따로 보내고 `SKIP LOCKED`가 없다. claim 토큰은 `heldClaims` 맵(`:77`)에 두고 `CleanupItem`으로 돌려주지 않는다. 다른 인스턴스가 reclaim하거나 트랜잭션이 롤백되면 항목이 남는다. inbox 상태 전이(seen/read/archive 단조성)는 엔티티 메서드에 있다(`PN/inbox/InboxItemEntity.java:106-151`) | +| 영향 | 재시도 한도·lease 길이를 바꾸려면 persistence 코드를 고쳐야 한다(HARD-STOP 4 "비즈니스 규칙이 mapper·설정으로 이동"과 같은 방향의 위험). 토큰이 프로세스에 있어 fencing 정보가 포트 계약에 드러나지 않는다 | +| 심각도·우선순위 | Medium / P2 | +| 결정의 근거 | 기록된 의도: 주석(`:110-113`)은 "재시작하면 토큰을 잃는 것이 목적"이라 한다. 그 목적은 토큰을 `CleanupItem`에 실어 호출자가 들고 있어도 똑같이 지켜진다 | +| 최소 개선 방향 | 토큰과 시도 횟수를 `CleanupItem`에 싣고, `markFailed`의 소진 판정은 application(`application-fileserver`)으로, 한도·lease는 포트 인자나 설정으로. claim은 notification의 CTE + `SKIP LOCKED` + `RETURNING` 한 문장 패턴으로 | +| 대안 비교 | (a) 현상 유지 + 문서화: 비용 0, 숨은 위험 유지. (b) 위 방향(선택). (c) 범용 lease 모듈로 통합(X1-#6): 범위가 커서 이번 항목과 분리 | +| 단순화의 보존 조건 | "늦게 깬 worker의 완료는 적용되지 않는다"(토큰 불일치 시 0행)는 유지 | +| 완료 기준 | adapter에 정책 상수 없음, claim 한 문장, 토큰이 포트 타입에 있음 | +| 검증 방법 | `PostgreSqlFileserverReclamationIntegrationTest` 확장 | + +### 04-14 notification·fileserver 영속 leaf가 테스트 규칙(공유 계약)을 따르지 않는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(규칙 위반) | +| 관련 관점 | 10 테스트, 26 ownership, 23 일관성 | +| 근거 | `application-notification`, `application-fileserver`에 `testFixtures` source set이 없다. fileserver fake는 `application-fileserver/src/test/.../testkit/InMemory*.java`에 있고, `MetadataPortContractTest`는 abstract가 아니다. PG IT는 fake와 별개로 작성됐다. AGENTS.md 테스트 규칙 6("fake와 adapter가 같은 추상 계약을 통과")과 capability 완료 기준 5 위반. fileserver IT 37개는 `persistence-jpa`의 source set에 있다(`PJ/build.gradle:102-115`) | +| 영향 | fake로 통과한 유스케이스 테스트가 실제 저장소 동작과 다를 수 있다. leaf 소유자와 테스트 소유자가 다르다 | +| 심각도·우선순위 | Medium / P2 (지난 W4 항목 TEST-FAKE-*·X1-#3b·S7-lead-4와 같은 묶음) | +| 결정의 근거 | 적용 제외 — 규칙이 이미 정해져 있다 | +| 최소 개선 방향 | 포트별 abstract `XxxContract`를 각 application leaf testFixtures로, fake 테스트와 PG IT가 상속. fileserver IT는 `persistence-fileserver`의 integration lane으로 이동 | +| 완료 기준·검증 | 포트마다 계약 1개, 구현 2개 이상이 상속. `persistence-fileserver:test`가 NO-SOURCE가 아님 | + +### 04-15 Mongo 라이브러리를 파생 서비스가 쓸 경로와 예시가 없다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 / 개선 제안 | +| 관련 관점 | 20 개발자 경험, 22 추상화, 27 삭제 가능성, 13 확장성 | +| 근거 | 레지스트리에서 mongo leaf에 의존할 수 있는 모듈은 `app-bootstrap`뿐이고 그 줄도 주석이다(`src/app-bootstrap/build.gradle:164`). README는 "서비스 어댑터 leaf가 `implementation`으로 받는다"(`PM/README.md:140-142`)고 하지만 등록 절차 안내가 없다. `@Document`·`MongoRepository` 예시가 0개. main 278개 파일·18,939줄, 공개 타입 271개(`docs/architecture/mongo-api-surface.txt`), leaf 밖 production 소비자 0 | +| 영향 | 파생 서비스는 레지스트리 edge, 예외 변환(`MongoDuplicateKeyException` 등), 정책 적용 범위(repository 직접 사용 시 `MongoQueryPolicy` 우회)를 추측해야 한다 | +| 심각도·우선순위 | Medium / P2 | +| 결정의 근거 | 사용자 원칙상 소비자 없는 코드는 확장 지점이지 죽은 코드가 아니다. 다만 확장 지점이면 "어떻게 꽂는지"가 있어야 한다. 그 부분이 빠졌다 | +| 최소 개선 방향 | testFixtures에 document·repository·mapper·port 구현 예시 한 벌, `docs/mongodb`에 "소비 leaf 등록" 절차(레지스트리 edge 추가 예) | +| 대안 비교 | (a) 예시+절차(선택). (b) advanced 패키지를 별도 leaf로 분리해 표면 축소: 효과 크지만 이동 범위 큼(CLAUDE.md가 이미 별도 커밋으로 미룸). (c) 소비자 생길 때까지 삭제: 소유자 결정(capability 유지)과 충돌 → 기각 | +| 완료 기준·검증 | 예시가 `mongoStableContractTest`에서 컴파일·실행된다 | + +### 04-16 notification·fileserver leaf에 가까운 안내 문서가 없고 패키지가 평평하다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 개선 제안 | +| 관련 관점 | 4 인지 부하, 9 유지보수, 26 ownership | +| 근거 | 두 leaf에 `CLAUDE.md`·`README.md`가 없다(루트 CLAUDE.md는 "nearest guidance가 local rules를 소유"한다고 말한다). notification은 엔티티·repository·adapter·SQL 상수 약 37개가 `platform` 한 패키지에 있고 하위는 `inbox`뿐. fileserver는 `entity/`·`repository/`로 나눴고 adapter는 루트에 있어 두 leaf 규칙이 다르다 | +| 심각도·우선순위 | Low / P3 | +| 최소 개선 방향 | 두 leaf에 짧은 CLAUDE.md(테스트 위치, 트랜잭션 guard 규칙, 마이그레이션 위치·불변성 테스트). notification을 기능별 하위 패키지로 | +| 결정의 근거·완료 기준 | 적용 제외 — 문서·배치 정리. 완료: 두 leaf에 안내 문서, 같은 패키지 규칙 | + +### 04-17 미리 정한 UUID + primitive `long` version이라 `save()`가 merge로 동작한다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(작음) | +| 관련 관점 | 14 성능, 11 데이터 | +| 근거 | `PF/entity/FileEntity.java:78` 외 fileserver 엔티티의 `@Version long`. Spring Data는 primitive version이면 id null 여부로 새 엔티티를 판단하는데 id가 미리 정해져 있어 merge가 된다. `save` 호출: `PF/JpaFileMetadata.java:76`, `JpaFileQuota.java:50`, `JpaUploadSession.java:58` 등 | +| 영향 | insert마다 SELECT 1회 추가. id가 겹치면 unique 오류 대신 낙관적 락 오류나 덮어쓰기 | +| 심각도·우선순위 | Low / P3 | +| 최소 개선 방향 | `Persistable` 구현 또는 `Long version`(null = 새 엔티티) | +| 결정의 근거·검증 | 적용 제외. 검증: statement 수 단언 테스트 | + +## 4. 31절 시나리오 추적 + +### 선택 1 — DB 오류·경쟁: sample WorkLog 동시 수정 + +``` +WorkLog 수정 요청 (expectedVersion 선택) + → WorkLogController (입력 검증, inbound DTO → command) + → UpdateWorkLogUseCase.handle ── tx.inWrite 시작 (REQUIRED, READ_COMMITTED, timeout 없음) + → repository.findById → 버전 비교(있으면) → 도메인 메서드로 규칙 적용 + → WorkLogRepositoryAdapter.save → findById(audit created_* 이월) → jpa.save = merge + ── 커밋: flush 시 UPDATE … WHERE version=? + → 응답 +``` + +| 항목 | 결과 | +| --- | --- | +| 입력 신뢰 수준 | 인증된 사용자 입력. 크기·형식은 web에서 검증 | +| 권한 판단 위치 | 이 영역 밖(> 인증 영역). 영속 계층은 소유자 조건 없이 id로만 조회한다 | +| 규칙 소유 객체 | `WorkLog` 도메인(상태 전이). 버전 비교는 유스케이스. audit 스탬프는 adapter(`WorkLogRepositoryAdapter.java:42-56`) — 인프라 관심사라 적절 | +| 트랜잭션 | 유스케이스가 `TransactionPort.inWrite`로 연다. adapter는 열지 않는다. 시간 제한 없음(04-10) | +| 외부 부작용 | 없음(outbox 미사용 경로) | +| 성공의 의미 | 커밋 후 반환. `@Version`이 경쟁을 막는다 | +| 오류 변환 | 버전 비교 실패 → `WorkLogVersionMismatchException`(sample 핸들러가 409). 비교 통과 후 커밋 경쟁 → `ObjectOptimisticLockingFailureException` 원본 → 500(04-05). 커밋 중 연결 끊김 → `DB_UNAVAILABLE` retryable(04-01) | +| 진단 정보 | 500 경로는 스택 포함 error 로그. persistence carrier는 SQLState만 로그(파라미터 없음) — 민감정보 보호는 지켜진다 | + +### 선택 2 — 여러 서버의 작업 실행: 알림 정산 job + +`NotificationBackgroundWorkers`(인스턴스마다 스케줄러 1개) → `ReconciliationJobWorker.reconcileOnce` → `JdbcReconciliationJobStore.claimDue`(autocommit `FOR UPDATE SKIP LOCKED`) → 공급자 조회 → `reschedule`/`complete`. 소유권 표시가 없어 중복 실행된다(04-02). 같은 leaf의 recipient claim, JPA outbox claim은 owner+token fencing으로 올바르게 처리한다(`PJ/README.md` outbox 절, V17). + +### 선택 3 — 큰 입력·목록 조회 + +web `PageParams.MAX_SIZE=100` → 유스케이스 → adapter `PageRequest`. 크기 상한은 web에만 있고 adapter는 `size<=0`만 보정한다(`WorkLogRepositoryAdapter.java:69`). 쿼리 수는 N에 비례(04-09). 라이브러리 keyset은 상한 500(`api/query/KeysetPageRequest.java:19`), Mongo keyset 1,000·skip 상한 있음. notification의 limit 없는 List 조회 4곳(`ConsentJpaRepository.java:23`, `ProviderEventJpaRepository.java:32`, `RecipientDeliveryJpaRepository.java:28`, `SuppressionJpaRepository.java:24`)은 누적 데이터에 비례해 커진다(Low, 04-14 작업 때 같이). + +### 적용 제외 + +| 시나리오 | 사유 | +| --- | --- | +| 정상 쓰기 요청 | 선택 1이 같은 경로를 포함 | +| 중복·동시 요청 | 멱등성 executor는 composition·application 영역. 영속 측 공통 계약 부재는 S2-lead-2로 재확인 | +| 외부 응답 지연·유실 | 영속 영역에 외부 호출 없음 | +| 메시지 중복·역순 | outbox 발행·소비는 messaging 영역. 영속 측 fencing은 V17·`OutboxLeaseFencingContract`로 확인 | +| 신·구 버전 공존 | 마이그레이션 불변성 테스트(해시 고정)로 적용된 파일 변경은 막힌다. expand/contract 지침은 `docs/jpa/migration-guide.md`. 실제 무중단 전환 실험은 범위 밖 | +| 세션·토큰 갱신 경쟁, 다른 사용자 리소스 접근 | 인증·인가 영역 | +| 종료·재시작 | 스케줄러 종료는 notification adapter 영역 | +| 선택 어댑터 제거 | `JpaActivationEnvironmentPostProcessor`(enabled=false → Boot 자동설정 제외)와 Mongo `MongoCapabilityActivationTest`가 다룬다. composition 영역에서 확인 | + +## 5. 41절 설계 선택 검토 + +### 5.1 엔티티 사이를 연관관계 없이 ID로만 잇는다(현재 코드의 선택) + +1. 필요한 것: aggregate 경계 유지, 의도치 않은 로딩·cascade 방지, 사용자 원칙(양방향 금지). +2. 지킬 성질: 한 aggregate의 저장이 다른 aggregate 행을 바꾸지 않는다. 로딩 범위가 쿼리에서 보인다. +3. 현재 보장: production 엔티티 전부가 UUID 컬럼으로 참조한다(전수 확인). 강제 장치는 없다(M2, 04-03). +4. 대안: (a) 단방향 `@ManyToOne` LAZY 허용, (b) 가이드대로 양방향 + helper, (c) ID 참조만. +5. 대가: (a) 조인 쿼리 작성이 편하다. 프록시·LAZY 예외를 알아야 한다. (b) 양쪽 동기화를 기억해야 한다. cascade 오용 위험이 크다. (c) 조인이 필요하면 JPQL/projection을 직접 쓴다. 로딩이 늘 명시적이다. +6. 현재 조건에서의 선택: (c)가 원칙과 aggregate 경계에 맞는다. aggregate 안 자식은 `@ElementCollection` 또는 단방향 `@ManyToOne`까지 허용하는 것이 현실적이다. +7. 바뀌는 조건: aggregate 안 자식을 독립 엔티티로 조회·수정해야 하는 요구가 생기면 단방향 `@OneToMany(@JoinColumn)` 허용 여부를 다시 본다. + +판정: 선택은 타당하지만 코드에 강제되지 않고 문서가 반대로 말한다. 그래서 설명 검증은 "부분 통과"다. + +### 5.2 예외 변환을 TransactionPort 경계에서 SQLState로 한 번만 한다 + +1. 필요한 것: DB 세부(SQL, 제약 이름)가 클라이언트로 새지 않게, 그리고 재시도 가능 여부를 정확히 알린다. +2. 지킬 성질: 결과 불명은 재시도 불가로, 경쟁은 409로, 장애는 503으로. +3. 현재 보장: 누출 방지는 지켜진다(carrier는 코드만, 로그도 코드만). 재시도 판단은 두 곳에서 틀린다(04-01 커밋 단계 구분 없음, 04-05 SQLState 없는 Spring 예외 미처리). 분류표가 두 벌이다(04-06). +4. 대안: (a) adapter마다 변환, (b) 경계에서 한 번(현재), (c) 경계에서 한 번 + 단계(액션/커밋) 인지 + Spring 예외 타입 인지. +5. 대가: (a) 누락이 쉽고 중복된다. (b) 단순하지만 단계 정보를 잃는다. (c) `SpringTransaction`에 수십 줄 추가. +6. 선택: (b)의 위치는 맞다. (c)로 보강해야 ADR-JPA-003을 지킨다. +7. 바뀌는 조건: 트랜잭션 엔진이 둘이 되거나 reactive 트랜잭션이 들어오면 다시 본다. + +### 5.3 실 PostgreSQL 계약 lane을 `ci`·`mainCheck` 밖에 둔다 + +1. 필요한 것: PR이 빨라야 하고(ci 7분), 실 DB 동작은 검증돼야 한다. +2. 지킬 성질: 실 DB lane마다 적어도 한 workflow가 실행한다. +3. 현재 보장: 태그 lane 5개와 readiness 5개는 workflow가 돈다. readiness 9개는 아무도 돌리지 않는다(04-04). +4. 대안: (a) 전부 `mainCheck`로, (b) path filter workflow로(현재 일부), (c) `integrationCheck`를 nightly에 통째로. +5. 대가: (a) main 단계가 수 분 늘어난다(이번 측정: 4개 lane Gradle 56초). (b) 필터 누락이 생긴다(지금 상태). (c) 반나절 늦게 발견. +6. 선택: (c)를 기본 안전망으로 두고 (b)를 유지하는 것이 비용 대비 낫다. 지금은 안전망이 없다. +7. 바뀌는 조건: lane 수가 늘어 nightly 시간이 문제가 되면 matrix로 나눈다. + +## 6. 리팩토링 후보 + +| 무엇 | 왜 | 보존할 동작·타입·실패 계약 | +| --- | --- | --- | +| SQLState 분류표 두 벌 → 한 벌(04-06) | 갈라진 중복, retryable 값 불일치 | `SqlStateErrorMapping` SPI, 중복 기여 시 기동 실패, `PersistenceFailureException` 타입과 web의 carrier 처리, 로그에 SQL 미포함 | +| `SpringTransaction.execute`에 커밋 단계 구분(04-01·04-05) | ADR-JPA-003 준수, 409 정상화 | 모드별 propagation·isolation·readOnly 표(`PJ/CLAUDE.md:221-226`), `inRootWrite`의 중첩 거부, 재시도 0회 | +| `JpaCleanupQueue` 정책·토큰 이동(04-13) | 정책이 adapter에, 토큰이 메모리에 | 토큰 불일치 시 완료 무시, lease 만료 후 reaper 인수 | +| notification `platform` 패키지 분할(04-16) | 37개 파일 평면 | 공개 타입 이름, Spring bean 이름(조립 코드가 참조) | +| Mongo `internal` 패키지 이동(CLAUDE.md 보류 항목) | 공개 타입 271개 | `verifyMongoApiSurface` 스냅샷이 줄어드는 것으로 증명, Stable 패키지가 advanced를 참조하지 않는 규칙 | + +## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료) + +새 aggregate 하나를 JPA로 저장할 때 템플릿이 주는 것: + +- 따라 할 예시: sample `WorkLogEntity`·`WorkLogPersistenceMapper`·`WorkLogRepositoryAdapter`·`WorkLogJpaRepository`, 계약 테스트 `WorkLogRepositoryContract`(fake와 adapter 공용). +- 기반: `AuditableEntity`(audit 컬럼), `AuditContextPort`, `TransactionPort`, `CallerTransaction.require`(adapter가 호출자 트랜잭션을 요구), `PersistenceExceptionTranslator`. +- 검사: `JpaProductionArchitectureTest`(엔티티 노출·final·generic repository·audit·tenant), `AppliedMigrationImmutabilityTest`(마이그레이션 해시 고정). +- 문서: `docs/jpa/entity-mapping-guide.md`, `query-fetch-guide.md`, `migration-guide.md`, `transaction-guide.md`. + +빠진 것: + +- 연관관계 규칙과 그 검사(04-03). 지금 가이드는 원칙과 반대다. +- 목록 조회의 쿼리 수 검사 예시(04-09). testkit 도구는 있는데 sample이 쓰지 않는다. +- 낙관적 락 충돌의 표준 처리(04-05). +- notification·fileserver처럼 "application leaf가 따로 있는 capability"의 영속 leaf 템플릿: testFixtures 계약, 테스트 위치, CLAUDE.md(04-14, 04-16). +- Mongo로 aggregate를 저장하는 예시 한 벌(04-15). + +개발자가 여기서 내려야 하는 판단: + +1. 이 데이터는 독립 aggregate인가, 다른 aggregate의 자식인가. → 독립이면 ID 컬럼, 자식이면 `@ElementCollection` 또는 단방향 `@ManyToOne`(LAZY). 양방향은 쓰지 않는다. +2. 같은 행을 동시에 바꿀 수 있는가. → 그렇다면 `@Version`(wrapper `Long`, null = 새 행)을 둔다. bulk UPDATE를 쓰면 version도 올린다. +3. "같은 것이 두 번 생기면 안 되는가". → 애플리케이션 조회가 아니라 DB unique 제약으로 막고, upsert는 `ON CONFLICT`로 쓴다. +4. 여러 인스턴스가 같은 행을 처리하는가(큐·스케줄러). → claim은 `UPDATE … WHERE id IN (SELECT … FOR UPDATE SKIP LOCKED) RETURNING`, 완료는 owner+token 조건 UPDATE. autocommit SELECT FOR UPDATE는 잠그지 않는다. +5. 트랜잭션은 누가 여는가. → 유스케이스가 `TransactionPort`로 연다. adapter는 `CallerTransaction.require`만 부른다. 예외는 포트 자체가 원자 단위인 저장 프로토콜뿐이다. +6. 목록 조회는 몇 번 쿼리하는가. → 컬렉션을 가진 엔티티를 페이지로 읽으면 N+1이다. projection 포트나 batch fetch를 쓰고 쿼리 수를 테스트로 고정한다. +7. 스키마 변경은 새 파일인가. → 적용된 `V*` 파일은 고치지 않는다. 새 버전을 추가하고 `applied-migrations.sha256`에 해시를 추가한다. +8. 오류를 클라이언트에 어떻게 알리는가. → adapter에서 잡지 말고 `TransactionPort` 경계 변환에 맡긴다. 업무 의미가 있는 충돌(버전 불일치 등)만 유스케이스가 자기 예외로 바꾼다. + +## 8. 28개 관점 판정표 + +기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역. + +| 번호 | 관점 | 판정 | 한 줄 이유 | +| --- | --- | --- | --- | +| 1 | 코드 성숙도 | P | 트랜잭션·fencing 코드는 의도가 드러난다. 갈라진 분류표(04-06)와 adapter 안 정책(04-13)이 남음 | +| 2 | 구조적 성숙도 | P | leaf 방향은 레지스트리로 강제됨. adapter가 정책을 소유(04-13), JPA leaf가 플랫폼 라이브러리와 capability 저장소를 함께 가짐 | +| 3 | 변경 용이성 | P | SQLState 하나 추가에 두 표 수정(04-06). 마이그레이션은 해시 고정으로 안전 | +| 4 | 인지 부하 | P | JPA CLAUDE.md는 상세하나 길고 일부 낡음(S2-#14a). 분리 leaf 2개에 안내 없음(04-16) | +| 5 | 위험 가시성 | X | 양방향 금지·bulk version·claim 잠금이 모두 개발자 기억에 의존(04-02·04-03·04-07) | +| 6 | 실패 성숙도 | X | 커밋 결과 불명이 재시도 가능으로 나감(04-01), 버전 충돌 500(04-05), 시간 제한 없음(04-10) | +| 7 | 운영 성숙도 | P | Hikari·OSIV·DDL·Flyway 위험 설정을 기동 시 거부. timeout 기본값 없음(04-10, 04-12) | +| 8 | 디버깅 가능성 | P | 오류 로그에 SQL·파라미터 없음(보호 O). 정상 경쟁이 error 로그(04-05) | +| 9 | 유지보수 성숙도 | P | 이력 서술 Javadoc(S2-#12), 중복 표(04-06) | +| 10 | 테스트 성숙도 | P | unit 503개·실 PG lane 다수, 그러나 9개 lane 미실행(04-04), 공유 계약 부재(04-14), 쿼리 수 검사 미사용(04-09) | +| 11 | 데이터 성숙도 | P | 마이그레이션 불변성 O, unique 제약 누락(04-08), bulk version 누락(04-07) | +| 12 | 동시성 성숙도 | P | outbox·recipient·durable operation fencing O. 정산 job 무잠금(04-02), upsert 경합(04-08) | +| 13 | 확장성 | P | 다중 인스턴스 claim 패턴 존재, 한 곳 누락(04-02). Mongo 소비 경로 없음(04-15) | +| 14 | 성능 성숙도 | P | keyset·상한 제공. sample N+1(04-09), merge 추가 SELECT(04-17). 실측은 안 함 | +| 15 | 보안 성숙도 | O | SQL·파라미터 비노출, runtime role 권한 lane, RLS `set_config(…, true)`(트랜잭션 범위), schema provider는 반환 시 search_path 초기화·실패 시 abort | +| 16 | 의존성 성숙도 | O | vendor 드라이버 격리 ArchUnit, Mongo 레지스트리 parity 테스트 | +| 17 | API / Contract | P | `DB_*` 코드 표 존재. 실제 도달 코드가 계약과 다름(04-01, 04-05) | +| 18 | 배포 성숙도 | ? | 마이그레이션 기동 순서·readiness 연계는 코드로 확인. 실제 무중단 배포 실험 없음 | +| 19 | 설정 성숙도 | P | 위험 값 기동 거부 O. prefix 분산(P20-new-5 남음), Mongo 주석·코드 불일치(04-12) | +| 20 | 개발자 경험 | P | 예시·testkit 풍부. 원칙과 반대인 가이드(04-03), Mongo 예시 없음(04-15) | +| 21 | Guardrail | P | 엔티티·노출·audit·마이그레이션 규칙 M3. 연관관계·bulk version 규칙 없음 | +| 22 | 추상화 성숙도 | P | `TransactionPort`·`CallerTransaction`은 적절. Mongo 공개 타입 271개 대비 소비자 0 | +| 23 | 일관성 | P | 두 분류표(04-06), 두 분리 leaf의 패키지 규칙 상이(04-16), claim 패턴 3종 | +| 24 | 네이밍 / 의미 | P | `claimDue`가 잠그지 않음(04-02), `QUOTA_EXCEEDED`를 상태 충돌에 사용(`PF/JpaFileQuota.java:94-96`) | +| 25 | 조직 확장성 | P | fileserver 테스트가 JPA leaf에 있어 소유가 섞임(04-14) | +| 26 | Ownership | P | 분리 leaf 2개 안내 문서 없음(04-16) | +| 27 | 삭제 가능성 | O | `enabled=false`가 Boot 자동설정까지 제외, runtimeOnly 한 줄로 제거 | +| 28 | 회복 가능성 | P | completion-unknown 회복 경로가 커밋 단계에서 끊김(04-01). 수신 거부 중복은 수동 정리 필요(04-08) | + +미검증: 18(무중단 배포), 04-02의 업무 중복 효과, 04-11 실 서버 재현, 04-09 실측, JPA 태그 lane과 Mongo 컨테이너 lane의 현재 커밋 실행 결과. diff --git a/docs/reviews/2026-11-01-maturity-review/05-outbound-capabilities.md b/docs/reviews/2026-11-01-maturity-review/05-outbound-capabilities.md new file mode 100644 index 00000000..5d35c39e --- /dev/null +++ b/docs/reviews/2026-11-01-maturity-review/05-outbound-capabilities.md @@ -0,0 +1,566 @@ +# 05. Outbound capability 영역 성숙도 리뷰 + +대상 leaf: `adapter:outbound:redis-runtime`, `redis-sdk`, `cache-redis`, `httpclient`, `objectstorage`, +`notification`, `fileserver`, `identifier`, `support`, `application-notification`, `application-fileserver`, +`application-objectstorage`, `composition:fileserver-platform`, `composition:notification-platform`. + +경로는 `src/`를 생략한다. 패키지 앞부분이 긴 경로는 파일 이름만 적고, 처음 나올 때 leaf를 밝힌다. + +## 1. 범위 + +| 항목 | 기록 | +| --- | --- | +| 대상 | `clean-architecture-backend-template`, 브랜치 `main`, 커밋 `01a8a2a70` | +| 확인 시점 | 2026-11-01 | +| 목적과 실행 구성 | 템플릿(파생 서비스의 시작점). 기본 조립은 web·support·identifier뿐이고, 이 영역의 나머지는 `app-bootstrap/build.gradle`에 `runtimeOnly` 한 줄로 켜는 선택 모듈이다(`app-bootstrap/build.gradle:162-171`). 다중 인스턴스 배포를 전제로 한 설정(lease, `FOR UPDATE SKIP LOCKED`, Redis 공유 상태)이 있다. | +| 규모·운영 목표 | 합의된 SLO·처리량 없음. 그래서 "운영 준비 완료" 판정은 하지 않는다. | +| 읽은 범위 | 14개 leaf의 main 코드(약 9.5만 줄) 중 위험 경로: 알림 제출·dispatch·recovery·SES/SMTP·SNS 콜백, 파일 업로드(tus)·복사·다운로드·권한·쿼터, 객체 저장소 S3/local-dev 오류 분류, Redis 캐시·멱등성·rate-limit Lua·연결 lane, HTTP client retry·deadline·circuit breaker·SSRF, support의 module-defaults 로더, identifier. 각 leaf의 README·CLAUDE.md·`config/module-defaults/*.yml`, `AutoConfiguration.imports`, `app-bootstrap`의 관련 설정. 하위 조사 4개(알림, 파일·객체 저장소, Redis, HTTP client·support·identifier)가 코드를 읽었고, High 판정 항목은 리뷰어가 해당 줄을 직접 다시 읽어 확인했다. | +| 실행한 것 | ① 오케스트레이터 게이트 결과 읽기: `ci` rc=0(이 영역 14개 leaf `test` 전부 실행·통과), `mainCheck` rc=1(objectstorage MinIO lane 2개 실패, 원인은 이미지 pull 404). ② 변이 실험 2회(별도 worktree, `flock` 잠금): 아래 표. ③ 현재 `build/test-results` XML 집계(ci가 11-01 20:38~20:40에 만든 결과). | +| 확인 못 한 것 | Redis 실제 서버 lane(`ca.redis-topology-lane`, explicit-only라 게이트에 없음), HTTP client Toxiproxy lane(`httpClientFailureInjectionTest`, `integrationCheck`에만 있음), MinIO lane(이미지 소멸로 실행 불가), SES/SMTP 실제 발송, 다중 인스턴스 경쟁 실험, 부하 측정. 지난 리뷰의 실행 결과는 증거로 쓰지 않았다. | +| 비교 가능한 범위 | techlead 07·08·09, followup-status B·C·D·G·H·S3·S4 그룹과 후속 발견(P·ORCH), 2026-08-14 notification 모듈 리뷰. | + +변이 실험(worktree `wt-05`, 실행 후 원복·삭제): + +| # | 바꾼 코드 | 돌린 테스트 | 결과 | +| --- | --- | --- | --- | +| M1 | `AppendUploadApplicationUseCase.java:165` 클라이언트 offset 불일치 검사 무력화 | `:application-fileserver:test` (부하 15.7) | 잡힘 — `ResumableUploadUseCasesTest.anOffsetTheClientGuessedWrongIsRejectedWithoutWriting` 실패 | +| M2 | `CopyFileApplicationUseCase.java:70-71`, `PrepareDownloadApplicationUseCase.java:53-54`에서 권한 검사에 넘기는 descriptor를 `Optional.empty()`로 (소유자 검사가 사라짐) | `:application-fileserver:test`, `:composition:fileserver-platform:test`, `:adapter:inbound:web-fileserver:test` (부하 8.0) | **살아남음** — 442개 전부 통과 (05-08) | + +테스트 실행 시간(현재 결과, ci 실행분): 14개 leaf 합계 테스트 약 1,790개, 클래스 시간 합 약 63초. 가장 긴 것은 objectstorage 19.4초(`ObjectStorageArchitectureTest`가 대부분), cache-redis 6.5초, httpclient 8.3초. 과하지 않다. + +## 2. 지난 발견 재확인 + +상태: 해결 / 남음 / 바뀜(형태가 달라짐) / 일부. + +| ID | 상태 | 근거 | +| --- | --- | --- | +| B-7d tenant 거부를 SUPPRESS로 보고 | 해결 | `AdminAuthorizationGuard.java:41-49`가 호출 연산의 authority를 인자로 받음 | +| B-10a 알림 README·CLAUDE.md "R0 legacy" | 남음 | `adapter/outbound/notification/README.md:1,3`, `CLAUDE.md:15,23` | +| B-10b application-notification CLAUDE.md 없음 | 남음 | `application-notification/`에 `build.gradle`·`src`만 | +| B-10c / C-12c / D-11c / G-12b CLAUDE.md "Boot 4.0.0" | 남음 | notification `CLAUDE.md:8`, fileserver `CLAUDE.md:8`, objectstorage `CLAUDE.md:8`, cache-redis `CLAUDE.md:8`, identifier `CLAUDE.md:8`(새로 확인) | +| B-10d / S1-#19 / S3-#11 / S4-#16a·b inline FQN·이력 주석 | 남음(줄어듦) | notification main FQN 약 93줄, objectstorage 약 60줄, httpclient 약 59줄. 예: `LeaseRecoveryService.java:103-104`, `RedisCacheRegionAdapter.java:262-266` | +| S1-#20 notification `dispatch/` 46파일 | 남음 | 제출·템플릿·ContactPoint·reconciliation이 한 패키지 | +| S4-#3a 미조립 provider 5종 삭제 | 일부 | adapter는 삭제(`ProviderType`은 SES·SMTP만). `ApnsDeviceToken`, `FcmInstallationId`, `WebPushContent` 같은 contact/content 타입은 남음 | +| S4-#3b SES projector 연결 | 해결 | `NotificationPlatformRegistriesConfig.java:39` `StandardDeliveryProjector` | +| S4-#17b `*ProviderProperties` 이름 | 남음 | `SesProviderProperties`·`SmtpProviderProperties`는 바인딩 대상이 아닌 record | +| SesSuppressionUpdater dead code | 해결(삭제) | suppression은 `ProviderEventProjectionService.java:84-88` | +| ORCH-new-2 알림 계약 테스트 inputs 미선언 | 남음(범위 넓어짐) | `NotificationPayloadAtRestContractTest`와 ReleaseGate·LegacyNamespaceRetirement·ModeSsot 테스트가 저장소 파일을 읽지만 `notification/build.gradle`에 `inputs` 없음 | +| 결정 13 category 생략 → 400 | 해결(위치 다름) | 유스케이스가 아니라 `AcceptNotificationCommand.java:71-72`에서 거부 | +| 결정 21 provider profile 소실 → 일반 재시도 후 FAILED | 해결 | `NotificationDispatchService.java:170-176, 249-286` | +| C-10 / S2-#11 fileserver 경쟁 SQL leaf 테스트 0 | 바뀜 | leaf 안에는 여전히 없음. 실제 SQL은 `persistence-jpa`의 `PostgreSqlFileserverMetadataStoreIntegrationTest:107,258,283,313`(Testcontainers)이 검증 | +| C-12b composition 주석 drift | 남음 | `composition/fileserver-platform/build.gradle:8-10` | +| C-12c fileserver "default off" | 남음 | `adapter/outbound/fileserver/CLAUDE.md:19`, `README.md:17` vs `fileserver.yml`의 `enabled: true` | +| D-4 staged kernel·handoff 동작 테스트 | 대부분 해결 | `StagedObjectPublicationLifecycleTest`(666줄), `ObjectPublicationHandoffRaceTest`. `StagedObjectPublicationKernelTest`는 이름과 달리 verdict policy만 봄 | +| D-7a direct·multipart 업로드 코드 | 해결(삭제) | 해당 클래스 없음 | +| D-11a~e objectstorage 문서 drift | 남음 | `objectstorage/CLAUDE.md:8,19,21`, `README.md:18-19`, `LocalDevObjectDataStore.java:77` | +| P4-new-1 fileserver migration 불변성 테스트 | 해결 | `AppliedMigrationImmutabilityTest.java:43-45` manifest에 V1~V5 | +| P14-new-5 application-objectstorage testFixtures 없음 | 남음 | testFixtures 디렉터리 없음, `PosterImagePublicationWorkflowTest.java:253` 자체 fake | +| P30-new-3 local-dev create-only가 JVM 단위 | 일부 | `LocalObjectPathGuard.java:37-39,157-170`에 범위가 적힘. 동시 생성 테스트 없음 | +| S5-#14c web-fileserver README·CLAUDE.md 없음 | 남음 | 디렉터리에 `*.md` 0개 | +| S3AsyncResponseBodyBridgeTest 간헐 실패 | 개선, 위험 남음 | sleep 제거·1분 상한. `:40-41` await 없는 `shutdownNow`, `:84` 비동기화 `ByteArrayOutputStream` | +| G-2b fake가 rate-limit HDEL/PEXPIRE 미흉내 | 일부 | 고정 필드 구조로 HDEL 불필요, 실제 Redis 필드 수 단언 추가(`LiveRedisSemanticPortsTest.java:242-255`). fake는 여전히 PEXPIRE 무시(`InMemorySemanticRedisCommands.java:395-475`) | +| G-4j env-keys "Replaced by"가 없는 키 | 남음 | `docs/registries/env-keys.yaml:1428, 1460` | +| G-5b redis-runtime README·CLAUDE.md 없음 | 남음 | 디렉터리에 `build.gradle`·`src`만 | +| G-12c `src/README.md` orphan Redis 키 | 남음 | `src/README.md:312-320`(`external` client-mode는 존재하지 않음) | +| G-12d cache-redis README 테스트 명령 | 해결 | `cache-redis/README.md:230-234` | +| G-12e runtime 키의 owner_module | 일부 | runtime이 바인딩하는 22개 키의 owner가 아직 cache-redis | +| S1-#3b lease 호출자 0 / 결정 8 공통 계약 | 일부 | `DistributedLeaseContract`(testFixtures)를 in-memory·Redis·live Redis가 상속. lock+lease 공통 계약은 없음 | +| S2-lead-2 멱등성 공통 계약 테스트 | 남음 | `application-core/src/testFixtures/.../idempotency/testkit/`에 `InMemoryIdempotencyStore`뿐 | +| S3-#12a `CacheKeys` 가변 generation, `KeyDigest` 위치 | 남음 | `RedisCacheRegionAdapter.java:352-354`, `capability/RedisKeys.java` | +| S3-#12b CLAUDE.md "legacy cache router" | 남음 | `cache-redis/CLAUDE.md:22` | +| S3-#13c Redis health indicator 중복 | 남음 | `RedisRuntimeAutoConfiguration.java:276-288`, `:308-331` | +| ORCH-new-4 redis-sdk 테스트 경로·inputs | 일부 | 경로 수정됨(`RedisSdkModuleBoundaryTest:181`). `inputs` 미선언, `RedisSupportMatrixTest`에 document-contract 태그 없음 | +| P13-new-2 local-redis lane 기동 WARN | 남음 | `RedisRuntimeSettings.java:207,215` WARN 2줄과 `run-compose-runtime-smoke.sh:520-522` 무음 검사 충돌 | +| P20-new-3 sample 죽은 키 | 남음 | `sample-portfolio/src/main/resources/application.yml:254-273`(`app.cache.redis.*`), `:286-287`(`app.outbound.http.*`) | +| H-3d `DefaultDynamicTargetGateway.exchange` 테스트 0 | 해결, 공백 남음 | `DefaultDynamicTargetGatewayTest` exchange 7건. 사설 IP로 resolve되는 hop 거부는 exchange 경로로 미검증 | +| H-10a / P20-new-4 README httpclient 절 | 남음 | `src/README.md:337-365`가 `app.capabilities.http-client`·`bindLegacy`를 설명(코드에 0건) | +| S3-#1 / H-5 / H-7 reactive 스택 (결정 9) | 해결 | src·build.gradle·lockfile에 webflux·reactor 0건 | +| S3-#13a Jackson 2 사용 | 남음 | `RemoteProblemDecoder.java:3-4`, `httpclient/build.gradle:56,64` | +| P11-new-2 `verify-httpclient-docs.py` 경로 | 남음 | `scripts/verify-httpclient-docs.py:22,64`. `.github/workflows/release.yml:188`에서 실행되므로 release 작업이 실패한다 | +| P11-new-3 FailureInjection lane이 docker-proxy에 의존 | 수정됨, 미실행 | `FailureInjectionContractTest.java:53-68` 루프백 거부 방식. 이번 게이트에 이 lane 없음 | +| S3-#6 `HttpClientTagPolicy` | 해결 | `HttpClientTagPolicy.java:32` | + +지난 발견 중 남은 High/P1은 없다. 남은 것은 대부분 W5(문서·Nit)와 W4(테스트 규칙)다. 다만 W4 중 "공통 포트 계약 테스트 없음"(S2-lead-2, P14-new-5)은 이번 새 발견 05-02·05-16과 직접 연결된다. + +## 3. 새 발견 + +심각도 분포는 문서 끝 「발견 요약」에 있다. High는 전체 양식으로, Medium·Low는 필요한 필드만 쓴다. 설계 선택이 아닌 단순 결함은 "대안 비교: 적용 제외 — 이유"로 둔다. + +### 05-01 알림 attempt를 "요청 시작 안 함(확정)"으로 저장한 채 provider를 호출한다 — 워커가 발송 중 죽으면 같은 알림이 다시 나간다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 1, 5, 6, 10, 11, 12, 28 | +| 근거 | ① `application-notification/.../dispatch/DeliveryAttemptFactory.java:54-56` — attempt 행을 처음 만들 때 `ProviderExecutionEvidence.notStarted()`(값 false, 확실성 PROVEN). ② `NotificationDispatchService.java:189-199` 이 행을 insert하고, `:201` lease 확인 뒤 `:215` `submitOutsideTransaction`이 provider를 부른다. 그 사이에 evidence를 바꾸는 쓰기가 없다(`requestStarted`를 쓰는 곳은 insert `JpaDeliveryAttemptStore.java:80-83`과 완료 기록 `:288-291`뿐). ③ `LeaseRecoveryService.java:101-106` `provablyNeverStarted`가 PROVEN+false면 true, `:134-136`이 그 경우 reconcile 없이 `READY_TO_DISPATCH`로 되돌린다. 리뷰어가 세 곳 모두 직접 읽었다. | +| 발생 조건 | SES/SMTP 호출 중 pod가 SIGKILL·OOM으로 죽는다. 또는 shutdown-grace(20s)를 넘긴다. 또는 워커가 lease 만료(`lease-duration` 2m, `NotificationDeliveryConfiguration.java:131`에서 staleAfter로도 쓰임)를 넘겨 멈춘다. | +| 영향 | recovery가 그 수신자를 다시 큐에 넣고 다른 워커가 같은 메일을 다시 보낸다. 늦게 깨어난 첫 워커의 결과 기록은 fence로 버려진다. 이 경로는 `LeaseRecoveryService` 주석과 `allow-ambiguous-fallback: false` 설정이 막겠다고 한 바로 그 경우다. | +| 심각도·우선순위 | High / P1. 가이드 35.2의 "결과 불명 작업의 무방비 재실행"에 해당한다. 기본 구성(SERVING, 다중 인스턴스)에서 프로세스 중단만으로 도달한다. 금전 피해는 아니므로 Critical은 아니다. 템플릿 기본값이라 파생 서비스로 그대로 복제된다. | +| 확실성 | 코드 경로는 확인(E1). 실제 crash 재현은 하지 않았다. | +| 테스트가 못 잡는 이유 | `LeaseRecoveryServiceTest.java:241-247`과 `PostgreSqlNotificationBackgroundPassIntegrationTest.java:370`이 attempt를 factory가 아니라 직접 만들어 넣는다. factory → crash → recovery를 잇는 테스트가 없다. | +| 결정의 근거 | 코드 주석은 "호출 전에는 아무것도 시작 안 됨이 증명된 사실"이라고 적는다. 행을 insert한 순간에는 맞지만, 그 행이 호출이 끝날 때까지 그대로 남는다는 점이 빠졌다. "증명"은 insert 시점에만 참이다. | +| 최소 개선 방향 | factory가 `requestStarted = UNKNOWN`으로 행을 만든다. "확정 미시작"은 `closedBeforeSubmission`(`:205-211`)이나 adapter가 돌려준 `ProviderCallNotStartedException` 결과로만 기록한다. | +| 대안 비교 | (a) 위 방법: 쓰기 추가 없음, crash 시 항상 reconcile. SMTP처럼 상태 조회가 없는 provider는 운영자 대기로 간다. (b) insert는 미시작 확정으로 두고 호출 직전에 UNKNOWN으로 갱신하는 쓰기를 추가: 트랜잭션 한 번 더, insert~갱신 사이 crash만 안전 requeue. (c) 현상 유지: 중복 발송 허용. (a)를 고른다. (b)가 얻는 것은 "insert 직후 crash" 한 구간의 requeue뿐이고 쓰기가 늘어난다. | +| 단순화의 보존 조건 | 행이 없을 때의 requeue(`:117-122`)와 완료된 attempt의 requeue(`:124-133`)는 유지한다. | +| 완료 기준 | factory로 만든 attempt를 recovery에 넣으면 reconcile 경로를 탄다. | +| 검증 방법 | `LeaseRecoveryServiceTest`에 `DeliveryAttemptFactory.create(...)`로 만든 미완료 attempt → `recoverOnce()` → `reconciled`에 포함, `transitions` 비어 있음. Postgres lane에서 같은 흐름 1건. | + +### 05-02 Redis 멱등성 `renew()`가 처리 lease를 연장하지 못한다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(현재 호출자 없음 — 잠복) | +| 관련 관점 | 1, 10, 12, 17 | +| 근거 | `cache-redis/.../idempotency/RedisIdempotencyStoreAdapter.java:183-190` renew를 `Transition("EXECUTING", "EXECUTING", …, leaseMillis, …)`로 보낸다. `IdempotencyScripts.java:101-108`은 revision·from 상태를 보기 전에 `state == ARGV[5]`(목표 상태)면 `ALREADY`를 반환한다. 현재 상태가 EXECUTING이면 renew는 항상 이 분기에 걸리고 `leaseUntil` 갱신(`:122-126`)에 닿지 않는다. fake도 같은 순서라 버그를 따라 한다(`InMemorySemanticRedisCommands.java:258-263`). main 코드에 `renew(` 호출자는 없다(grep). 리뷰어가 Lua를 직접 읽었다. | +| 발생 조건 | 파생 서비스가 30초(기본 processing lease)보다 긴 작업에서 renew로 lease를 늘린다. | +| 영향 | renew는 `ALREADY_RENEWED_SAME_OPERATION`(성공처럼 보이는 값)을 돌려주고 lease는 그대로 만료된다. 다른 요청이 `TAKEN_OVER`로 가져가 같은 부작용을 두 번 실행한다. | +| 심각도·우선순위 | High / P1. 공개 포트의 계약이 조용히 깨져 있고 성공 값으로 숨는다. 템플릿 안에 호출자가 없어 지금 피해는 없지만, 쓰는 순간 중복 실행이다. | +| 결정의 근거 | 적용 제외 — "같은 상태로의 전이"를 재시도 응답으로 해석한 Lua 분기 순서의 단순 결함이다. | +| 최소 개선 방향 | Lua에서 `ARGV[4] ~= ARGV[5]`일 때만 ALREADY 분기를 탄다. fake도 같이 고친다. | +| 완료 기준 | renew 후 lease가 연장되고, 다른 owner의 claim이 `IN_PROGRESS`를 받는다. | +| 검증 방법 | application-core testFixtures에 멱등성 공통 계약(`IdempotencyStoreContract`)을 만들고 in-memory·Redis fake·live Redis·PostgreSQL store가 상속한다(S2-lead-2와 같은 작업). renew 정상 경로 케이스를 넣는다. | + +### 05-03 캐시 `ONLY_IF_SOURCE_REVISION_NEWER`가 조건 없이 덮어쓴다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 1, 5, 11, 17 | +| 근거 | `application-core/.../cache/CacheRecordIntent.java:8`이 이 intent를 공개한다. `cache-redis/.../cache/RedisCacheRegionAdapter.java:238-253`은 `ONLY_IF_OBSERVED`만 Lua CAS로 보내고, 나머지는 `presenceOf`(`:262-266`)로 보낸다. `presenceOf`는 `ONLY_IF_ABSENT`가 아니면 `ALWAYS`다. `sourceRevision`은 envelope에 저장만 하고(`:229`) 비교하지 않는다. 이 intent를 쓰는 테스트는 없다. 리뷰어가 직접 읽었다. | +| 발생 조건 | 호출자가 "원본 revision이 더 새로울 때만 기록"을 요청했는데, 늦게 끝난 loader가 옛 revision으로 기록한다. | +| 영향 | 새 값이 옛 값으로 덮인다. 결과는 `RECORDED`라 호출자는 조건이 지켜졌다고 믿는다. hard TTL(5분) 동안 옛 값을 읽는다. | +| 심각도·우선순위 | High / P1. 호출자가 명시한 일관성 조건을 성공 응답으로 무시한다. 지원하지 않으면 거부해야 할 계약이다. | +| 결정의 근거 | 적용 제외 — enum 값 하나의 구현 누락이다. | +| 최소 개선 방향 | `ONLY_IF_OBSERVED`처럼 Lua로 envelope의 revision을 비교하고 교체한다. 당장 구현하지 않으면 이 intent에 `NOT_RECORDED_CONDITION`이 아니라 명시적 미지원 예외를 던진다. | +| 완료 기준 | 더 작은 revision의 기록은 `NOT_RECORDED_CONDITION`, 큰 revision은 `RECORDED`. | +| 검증 방법 | application-core testFixtures에 `CacheRegionContract`를 만들고 fake와 Redis adapter가 같은 표를 통과한다. | + +### 05-04 캐시 무효화와 느린 loader의 경합, stampede 보호 없음, 문서는 jitter를 주장 + +- 성격: 구조적 위험(경합 결과는 추론). 관점 1, 5, 12, 14. +- 근거: Miss는 항상 `CacheWriteCondition.unavailable()`을 돌려준다(`RedisCacheRegionAdapter.java:135,169,173`). `invalidate`는 `GETDEL` 하나다(`:277`). single-flight, early refresh, TTL jitter 구현은 없다(grep 0건). 그런데 `cache-redis/CLAUDE.md:17-18`은 "deterministic bounded jitter"를 구현했다고 적는다. region 무효화 반영은 generation 재확인 주기가 softTtl(30s)과 같아 인스턴스 간에 최대 30초 늦는다(`:316`, 테스트가 이 지연을 고정: `RedisCacheRegionAdapterTest.java:237-240`). +- 발생 조건: 미스 → 원본에서 옛 값 로드 중 → 다른 요청이 invalidate → `UPSERT`/`ONLY_IF_ABSENT`로 옛 값 재기록. 인기 키 만료 순간 동시 미스. +- 영향: 무효화 직후 옛 값이 최대 hard TTL(5분) 남는다. 동시 미스가 모두 원본을 친다. +- 심각도·우선순위: Medium / P2. 캐시 사용처가 템플릿에 없고, 05-03을 고치면 revision 비교로 첫 시나리오를 막을 수단이 생긴다. +- 최소 개선 방향: 고른 방법 — invalidate를 key 단위 tombstone(짧은 TTL, 이전 revision 기록 거부)으로 바꾸고 Miss에도 observation token을 돌려준다. 버린 대안 — 분산 lock 기반 single-flight: Redis 왕복과 lock 만료 처리가 늘고, 대부분의 캐시에는 tombstone+CAS로 충분하다. stampede는 문서에 "보호 없음, 호출자가 single-flight 책임"을 적거나 로컬 single-flight를 붙인다. CLAUDE.md의 jitter 문장은 지운다. +- 완료 기준: "invalidate 후 옛 loader의 기록이 거부된다" 계약 케이스 통과. + +### 05-05 HTTP client: 4xx 응답이 circuit breaker 실패로 집계된다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 6, 7, 17, 19 | +| 근거 | `httpclient/.../restclient/BlockingResponseMapper.java:72-76` THROW_ON_ERROR(기본)에서 2xx가 아니면 `HttpRemoteErrorException`. `BlockingAttemptExecutor.java:95-100`이 이를 `REMOTE_STATUS`로 만들고, `:111-114`가 REMOTE_STATUS면 breaker에 실패로 넘긴다. `resilience/AttemptResiliencePipeline.java:104-106` `circuitBreaker.onError`. breaker는 `ResilienceRegistry.java:37-41` `CircuitBreakerRegistry.ofDefaults()`라 모든 예외를 실패로 센다. breaker 임계값·창·대기 시간을 바꾸는 설정 키는 없다. 리뷰어가 직접 읽었다. | +| 발생 조건 | 조회 API가 정상적으로 404/409/422를 많이 돌려준다(라이브러리 기본: 최소 100회 중 50% 실패). | +| 영향 | breaker가 열리고 그 profile의 모든 호출이 기본 60초 동안 `HttpCircuitOpenException`으로 거부된다. 상대 서버는 건강하다. | +| 심각도·우선순위 | High / P1. 상대가 정상인데 기능 전체가 멈춘다. 프로젝트가 고칠 설정 키도 없다. | +| 결정의 근거 | 적용 제외 — 실패 분류 기준의 누락이다. 업계 관행(5xx·timeout만 실패)과 다를 이유가 코드·문서에 없다. | +| 최소 개선 방향 | 5xx·408·429와 전송 실패만 `onError`, 그 밖의 4xx는 `onSuccess`(또는 ignore)로 기록한다. profile별 breaker 설정(임계값·최소 호출 수·대기 시간)을 `app.httpclient.clients[n].circuit-breaker.*`로 노출한다. | +| 완료 기준 | 404 응답 200회 뒤에도 breaker가 CLOSED. | +| 검증 방법 | `AttemptResiliencePipeline` 단위 테스트에 상태 코드 표(`@ParameterizedTest`). | + +### 05-06 HTTP client: 전체 시간 예산이 진행 중인 attempt를 끊지 못한다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 6, 7, 14, 17 | +| 근거 | transport timeout은 profile 고정값(connect 0.5s, 응답 헤더 2s, read idle 3s)이고 남은 deadline으로 줄이지 않는다(`apache/ApacheClientFactory.java:74,79-80,129`). main에 `cancel(`/`abort(` 호출이 없다. deadline 검사는 attempt 시작 전에만 있다(`DefaultGenericHttpGateway.java` `attempt()`). JDK transport는 read idle을 쓰지 않는다(`jdk/JdkBlockingTransportProvider.java:66`). README는 "One effective deadline covers … read"라고 적는다. | +| 발생 조건 | 상대가 바이트를 3초보다 짧은 간격으로 조금씩 보낸다(slow drip). 또는 JDK transport로 body가 멈춘다. | +| 영향 | `totalCall` 4초를 무제한 넘긴다. 호출 스레드(virtual thread)와 pool 연결(기본 50)이 묶인다. 호출자의 요청 deadline이 깨진다. | +| 심각도·우선순위 | High / P1. 31절 "외부 응답 지연" 시나리오의 핵심 계약(대기 제한)이 문서와 다르다. | +| 결정의 근거 | 적용 제외 — 문서가 약속한 성질의 구현 누락. | +| 최소 개선 방향 | attempt마다 `min(stage timeout, 남은 deadline)`으로 RequestConfig를 만들고, 남은 시간이 끝나면 요청을 취소(Apache `cancel`, JDK `CompletableFuture` timeout)한다. | +| 완료 기준 | slow-drip 서버에 대해 호출이 `totalCall + 작은 오차` 안에 끝난다. | +| 검증 방법 | Toxiproxy `slicer`/`latency` toxic으로 `httpClientFailureInjectionTest`에 케이스 추가, 이 lane을 `mainCheck`에 포함(05-16). | + +### 05-07 파일 서버: copy가 디스크 수위 검사를 우회하고, 쿼터는 기록만 한다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 6, 13, 14, 15, 28 | +| 근거 | `application-fileserver/.../lifecycle/CopyFileApplicationUseCase.java:66-103`에 admission(디스크 high-water)도 quota도 없다. 대상 namespace는 요청 본문에서 온다(`web-fileserver/.../FileLifecycleController.java:88,109`). 업로드 쪽 쿼터도 상한을 비교하지 않는다(`persistence-fileserver/.../JpaFileQuota.java:21-30`), 범위는 namespace 단위(`CreateUploadApplicationUseCase.java:100-102`)이고 commit은 예약보다 큰 값을 받는다(`JpaQuotaCommit.java:37-52`). 리뷰어가 copy 경로를 직접 읽었다. | +| 발생 조건 | `file:copy` 권한을 가진 사용자가 큰 파일을 반복 복사한다. | +| 영향 | 업로드는 high-water(0.85)에서 멈추지만 copy는 그 선을 넘어 볼륨을 끝까지 채운다. 그 뒤 모든 사용자의 업로드·복사가 실패한다. 같은 볼륨을 쓰는 다른 프로세스도 영향을 받을 수 있다. | +| 심각도·우선순위 | High / P1. 인증된 사용자 하나로 서비스 전체 쓰기가 멈춘다. 기본 역할 `ROLE_FILE_WRITE`가 `file:copy`를 포함한다(`app-bootstrap/.../config/security.yml:58`). | +| 결정의 근거 | 사용자별 쿼터를 둘지는 서비스 정책이다(0.2절). 하지만 "디스크를 다 채우지 않는다"는 템플릿이 지켜야 할 안전한 기본값이고, 업로드 경로는 이미 지킨다. copy만 빠졌다. | +| 최소 개선 방향 | copy에 `admissionController.acquireUpload`와 `quotaService.reserve`를 넣는다. 대상 namespace는 policy 허용 목록으로 제한한다. 쿼터 상한 강제(principal/tenant 범위)는 별도 결정으로 분리한다. | +| 대안 비교 | (a) copy에 admission만 추가: 볼륨 고갈은 막고 사용자 간 공정성은 남는다. (b) (a) + 쿼터 상한: 공정성까지, 쿼터 정책 결정 필요. (c) copy 기능을 서버 측 링크(참조 카운트)로: 바이트가 늘지 않지만 삭제·정리 모델이 바뀐다. 최소 변경은 (a), 템플릿 기본값으로는 (b)를 권장. | +| 완료 기준 | high-water 이상에서 copy가 거절된다. | +| 검증 방법 | `FileLifecycleUseCasesTest`에 수위 초과 fake admission으로 copy 거절 케이스. | + +### 05-08 파일 서버: 소유자 검사를 지워도 테스트가 하나도 실패하지 않는다 + +- 성격: 확인된 결함(테스트 공백). 관점 10, 15, 21. +- 근거: 변이 M2. `CopyFileApplicationUseCase.java:70-71`과 `PrepareDownloadApplicationUseCase.java:53-54`에서 descriptor를 `Optional.empty()`로 바꾸면 `RoleBasedFileAccessPolicy.java:65`(`descriptor.isPresent() && …`)가 소유자 검사를 건너뛴다. application-fileserver·composition·web-fileserver 테스트 442개가 모두 통과했다(E2). 원인은 `application-fileserver/src/test/.../testkit/FakeFileAccessPolicy.java:22-28`이 descriptor를 무시하고 연산만 기록하는 것이다. 소유자·tenant 판정은 `RoleBasedFileAccessPolicyTest:133,164,187`에만 있다. +- 발생 조건: 누군가 use case를 고치다 descriptor를 빼먹는다. `DownloadDescriptor`는 public record라 새 inbound 경로가 권한 검사 없이 `OpenDownloadContent`를 부를 수도 있다(`OpenDownloadContentApplicationUseCase.java:38-40`). +- 영향: 다른 사용자의 파일 다운로드(31절 "다른 사용자 리소스 접근")가 회귀해도 게이트가 통과한다. +- 심각도·우선순위: Medium / P1. 지금 코드는 안전하지만 인가 회귀를 막는 장치가 없다. +- 최소 개선 방향: fake가 받은 descriptor를 기록하고, use case 테스트마다 "descriptor.owner == record owner"를 단언한다. COPY·MOVE·READ_METADATA 거부 테스트를 추가한다. +- 완료 기준: M2 변이가 죽는다. + +### 05-09 객체 저장소: MinIO 이미지 공급원이 사라져 mainCheck가 빨갛다 + +- 성격: 확인된 결함(외부 공급원 의존). 관점 7, 10, 16, 18, 28. +- 근거: `mainCheck` rc=1. `objectStorageMinioContractTest`, `objectStorageMinioFaultTest`가 `ContainerFetchException`(pull 404, "repository does not exist"). 같은 머신에서 `alpine:3`은 받아졌다(오케스트레이터 확인). 이미지 고정이 네 곳에 복사돼 있다: `MinioManagedObjectContractTest.java:52`, `MinioManagedObjectFaultTest.java:37-39`, `minio-provider-evidence.json:5`(test·integrationTest 두 벌, 내용 동일), 그리고 compose가 다른 태그를 쓴다(`docker-compose.infra.yml:183,425` `minio/minio:RELEASE.2024-09-13…`). 고정된 버전(2024-01-16)의 evidence는 `status: UNSUPPORTED`이고 create-only 계열 5개 프로필을 제외한다(`minio-provider-evidence.json`의 `excludedProfiles`, `limitations`). lane은 `rejectSkipped = true`로 fail-closed다(`objectstorage/build.gradle:85-103`), `mainCheck`가 둘 다 요구한다(`:123-125`). +- 발생 조건: Docker Hub 저장소 삭제·비공개 전환·rate limit. 이번이 실제 사례다. +- 영향: main 브랜치 게이트가 코드와 무관하게 실패한다. 이 영역의 유일한 실제 S3 벤더 증거(완료 기준 5)가 사라진다. local compose 개발 환경도 같은 공급원을 쓴다. +- 심각도·우선순위: Medium / P1. 데이터 피해는 없지만 main 게이트가 막혀 있어 다른 회귀를 가린다. +- 게이트가 어떻게 반응해야 하는가: 지금처럼 skip하지 않고 실패하는 것은 맞다(조용히 skip하면 벤더 증거가 없는데 초록이 된다). 부족한 것은 두 가지다. ① 실패 이유가 "코드 결함"인지 "공급원 소멸"인지 메시지로 구분되지 않는다. lane 시작 전에 이미지 pull을 별도 단계로 두고, 실패하면 "pinned image unavailable: "로 실패시킨다. ② 공급원이 사라졌을 때 바꿀 곳이 네 군데다. 이미지 참조를 `minio-provider-evidence.json` 하나에서 읽게 하고 compose도 같은 값을 쓰게 한다. +- 대안 비교: + +| 후보 | 얻는 것 | 비용·위험 | 판단 | +| --- | --- | --- | --- | +| (a) 같은 digest를 조직 레지스트리(GHCR/ECR)에 미러하고 거기서 받기 | 공급원 소멸에 영향받지 않음, digest 그대로라 evidence 유효 | 미러 운영(최초 push, 보존 정책), 원본 digest를 아직 가진 곳이 있어야 함(로컬 캐시·CI 캐시) | 1순위. 원본 digest를 확보할 수 있으면 증거 연속성을 지킨다 | +| (b) 같은 제작사의 다른 레지스트리(예: `quay.io/minio/minio`) | 코드 변경 최소 | 그 레지스트리도 같은 이유로 사라질 수 있음. digest가 같은지 확인 필요. 이번 리뷰에서 가용성 미확인 | (a)가 불가능할 때 임시 | +| (c) 커뮤니티 fork·재배포 이미지(예: Chainguard 등) | 계속 유지되는 공급원 | 다른 빌드라 evidence 재작성 필요, S3 조건부 쓰기 동작이 다를 수 있음 | evidence 재측정을 감수할 때 | +| (d) 다른 S3 호환 구현(SeaweedFS, Garage, LocalStack S3, Ceph RGW) | MinIO 의존 제거 | `If-None-Match`·`If-Match` 의미가 구현마다 다름. 계약 lane의 판정 기준(create-only 지원 여부)을 다시 정해야 함 | 장기 선택지. 단기 복구 수단은 아님 | +| (e) lane을 explicit-only로 내리고 mainCheck에서 빼기 | 게이트 즉시 초록 | 실제 벤더 증거 0개가 됨(기준 5 위반) | 기각 | + + 후보의 현재 가용성은 외부 접속 금지 규칙 때문에 확인하지 않았다. +- 완료 기준: 이미지 참조 한 곳, 미러 또는 대체 공급원에서 두 lane 통과, 공급원 실패 시 이유가 구분되는 메시지. + +### 05-10 알림: collapse 미지원 예외가 try 밖에서 터져 끝없이 재시도된다 + +- 성격: 확인된 결함. 관점 6, 7, 11. +- 근거: `NotificationDispatchService.java:331` `requireCollapseSupported`가 `new ProviderSubmission(...)` 인자를 만드는 중에 실행되고, `try`(`:334`)보다 앞이다. 던진 `ProviderCallNotStartedException`(`:355-359`)이 dispatch 밖으로 나가고 attempt는 DISPATCHING으로 남는다. 05-01 때문에 recovery가 이 행을 "확정 미시작"으로 보고 다시 큐에 넣는다. collapse는 HTTP 요청으로 들어온다(`web-notification/.../SubmitNotificationHttpRequest.java`). 템플릿의 provider(SES·SMTP)는 둘 다 collapse를 지원하지 않는다. +- 영향: collapse를 지정한 요청은 약 lease 주기마다 같은 실패를 반복한다. attempt 행이 계속 늘고 재시도 한도도, FAILED 종료도 없다. +- 심각도·우선순위: Medium / P2. 발송은 일어나지 않는다. 대신 독이 든 요청 하나가 영구히 워커를 쓴다. +- 최소 개선 방향: collapse 확인을 attempt insert 전, `failBeforeAttempt` 경로(`:167-187`)로 옮긴다. 05-01을 고치면 루프는 reconcile로 바뀌지만 원인은 여기서 고쳐야 한다. + +### 05-11 알림: SMTP 실패가 전부 "결과 불명"이 되어 재시도 없이 운영자 대기로 멈춘다 + +- 성격: 확인된 결함. 관점 6, 7, 8. +- 근거: `adapter/outbound/notification/.../provider/smtp/JavaMailSenderSmtpDispatch.java:44-52`가 모든 `MailException`을 `replyCode=empty, dataCommitted=true`로 감싼다. 그래서 `SmtpFailureClassifier.java:49-75`의 4xx/550 분기는 운영 경로에서 실행되지 않는다. SMTP는 상태 조회가 없어 reconcile은 `Unsupported` → `RECONCILIATION_REQUIRED`(`ReconciliationService.java:122-127,148-159`). +- 영향: 릴레이 다운·인증 실패·잘못된 수신자처럼 "보내지 않은 것이 확실한" 실패도 재시도되지 않고 운영자가 하나씩 처리해야 한다. +- 심각도·우선순위: Medium / P2. +- 최소 개선 방향: nested `SMTPSendFailedException`·`SMTPAddressFailedException`의 return code를 꺼낸다. `MailAuthenticationException`과 connect 실패는 `dataCommitted=false`. 같은 성격으로 SES 사전 오류(`SesNotificationProviderAdapter.java:107-138`, `SesRequestMapper.java:99`)를 `ProviderCallNotStartedException`으로 감싼다. +- 검증: 실제 `JavaMailSender` 예외를 넣는 분류 테스트, GreenMail 같은 실제 SMTP 컨테이너 테스트 1건(기준 5). + +### 05-12 파일 서버: tus PATCH가 쓰기를 커밋한 뒤 `file:read`를 요구한다 + +- 성격: 확인된 결함. 관점 1, 15, 17. +- 근거: `web-fileserver/.../TusController.java:171-181` append(`file:upload`) 커밋 후 `:183` `status.handle(...)` 호출. `GetUploadStatusApplicationUseCase.java:28` `@RequiresPermission("file:read")`. 기본 역할은 상속하지 않는다(`security.yml:51-59`, "a writer that also reads holds both roles"). 리뷰어가 직접 읽었다. +- 영향: write 역할만 가진 클라이언트는 바이트·offset이 커밋됐는데 403을 받는다. 자동 finalize(`:184-191`)가 실행되지 않고 HEAD로 이어받기도 못 한다. +- 심각도·우선순위: Medium / P2. 두 역할을 함께 주면 피할 수 있지만 문서가 권하는 최소 권한 구성에서 깨진다. +- 최소 개선 방향: `AppendUploadResult`에 `expectedLength`·`expiresAt`을 실어 status 재조회를 없앤다. 버린 대안 — `ROLE_FILE_WRITE`에 `file:read`를 더함: 최소 권한 원칙과 security.yml의 의도에 어긋난다. + +### 05-13 파일 서버: 정리 worker가 기본으로 꺼져 있다 + +- 성격: 확인된 결함(위험한 기본값). 관점 7, 19, 28. +- 근거: `composition/fileserver-platform/.../config/module-defaults/fileserver.yml:79` `admin.enabled: false`, `:82` `cleanup.enabled: false`. `FileserverCleanupConfiguration.java:24-28`은 true일 때만 켜진다. 만료 세션을 정리 작업으로 바꾸는 곳은 `DefaultCleanupService.java:126`뿐이다. 기동 검증에 cleanup 관련 검사가 없다. +- 영향: 기본 구성에서 staging `.part`, 거절·삭제된 콘텐츠가 쌓여 결국 high-water에 걸린다. 05-07과 합쳐지면 디스크 문제가 더 빨리 온다. +- 심각도·우선순위: Medium / P2. +- 최소 개선 방향: cleanup을 기본 on으로 한다. 끄려면 운영 프로필에서 명시적 이유 키를 요구하거나 기동 경고를 낸다. + +### 05-14 HTTP client: 기본 설정에서 결과 불명 분류가 틀린 경로로 나간다 + +- 성격: 확인된 결함. 관점 6, 8, 17. +- 근거: ① `resilience/DefaultRetryEligibilityEngine.java:19-21`의 maxAttempts 거부가 `:47-49`의 ambiguity 판정보다 먼저다. 기본 maxAttempts=1이면 SENT_NO_RESPONSE인 비멱등 요청이 `HttpAmbiguousExecutionException`이 아니라 일반 timeout 예외로 나간다. README는 ambiguous 예외를 약속한다. ② `restclient/BlockingAttemptExecutor.java:222-234`가 transport 호출 전에 단계를 REQUEST_BODY로 올려, `ApacheFailureClassifier`의 "보내기 전 실패" 분기가 실행될 수 없다. TLS handshake timeout이 SENT_NO_RESPONSE가 된다. ③ `:136`에서 계산한 evidence를 `StableBlockingExceptionMapper.java:26-27`이 덮어써 HTTP/2 REFUSED_STREAM → NOT_SENT 보정이 사라진다. +- 영향: 호출자가 "보냈는지 모름"과 "안 보냄"을 구분하지 못한다. POST를 정산해야 할 때 일반 실패로 보고 다시 보내거나, 안 보낸 요청을 운영자 대기로 보낸다. +- 심각도·우선순위: Medium / P2. retry는 idempotency 선언으로 막혀 있어(`RetryContext.java:71-75`) 클라이언트 자체가 중복 POST를 만들지는 않는다. 오류 계약이 틀린 것이다. +- 최소 개선 방향: ambiguity 판정을 먼저 한다. 단계는 연결 이벤트나 엔진 예외 타입으로 정한다. evidence는 더 구체적인 쪽을 유지한다. gateway 수준의 ambiguous 테스트를 추가한다. + +### 05-15 HTTP client: 바인딩되지만 동작하지 않는 설정 키, 0 timeout 허용 + +- 성격: 확인된 결함. 관점 5, 19, 21. capability 기준 3 위반. +- 근거: `timeout.request-write-idle`, `timeout.proxy-connect`, `proxy.connect-timeout`, `pool.eviction-interval`, `pool.shutdown-timeout`, `observability.operation-name-required` 6개는 profile factory 밖 소비처가 0이다. `profile/ClientProfileValidator.java:94-107`은 비슷한 미지원 키를 거부하면서 이 6개는 받는다. `:109-118`은 totalCall만 0을 거부한다(Apache에서 0은 무한). maxAttempts 상한이 없고, budget 이름이 없으면 retry budget이 무제한이다(`RestClientRuntimeFactory.java:90`). +- 영향: 운영자가 timeout을 설정했다고 믿지만 적용되지 않는다. 0을 넣으면 무한 대기. +- 심각도·우선순위: Medium / P2. +- 최소 개선 방향: 6개 키를 지우거나 `*_UNSUPPORTED` 위반으로 거부한다. 모든 timeout에 `> 0`, maxAttempts에 상한. + +### 05-16 capability 완료 기준 5가 영역 전체에서 지켜지지 않는다 + +- 성격: 확인된 결함(규칙과 구조의 불일치). 관점 10, 21, 23, 27. +- 근거: + - 포트 계약 테스트가 포트 소유 모듈 testFixtures가 아니라 adapter의 `src/test`에 있다: `notification/.../testkit/ProviderAdapterContract.java`, `CallbackContract.java`, `fileserver/.../testkit/ContentStoreContract.java`, `objectstorage/.../contract/ObjectStorageProviderContract.java`. `application-notification`, `application-fileserver`, `application-objectstorage`에는 testFixtures 디렉터리가 없다. + - cache·idempotency·rate-limit 포트에는 공통 계약이 없다. testFixtures에 있는 것은 `DistributedLeaseContract`, `DurableOperationStoreContract`, `OutboxLeaseFencingContract`뿐이다(`application-core/src/testFixtures`). 그래서 05-02·05-03이 fake와 adapter 양쪽에서 같은 버그로 숨었다. + - `ObjectStorageProviderContract`는 local-dev provider만 상속하고 MinIO 테스트는 상속하지 않는다. + - 실제 벤더 테스트: Redis는 Testcontainers가 아니라 외부 topology lane이고 `-Predis.topology.mode` 없이는 explicit-only다. HTTP client Toxiproxy lane은 `integrationCheck`에만 있다. 알림 SES/SMTP 실제 테스트는 없다(`ProviderSandboxSmokeTest`는 env로만 켜짐). 이번 게이트에서 돈 실제 벤더 lane은 MinIO 2개뿐이었고 둘 다 실패했다(05-09). +- 영향: 파생 서비스가 새 adapter(예: 다른 캐시, 다른 메일 provider)를 만들 때 상속할 계약이 없다. AGENTS.md 규칙 6과 기준 5가 문서에만 있다. +- 심각도·우선순위: Medium / P2. +- 최소 개선 방향: 포트 소유 leaf에 `java-test-fixtures`를 붙이고 계약 클래스를 옮긴다. cache·idempotency 계약을 새로 만든다(05-02·05-03의 검증 수단). Redis·HTTP client 실제 lane 하나씩을 `mainCheck`에 넣는다. +- 버린 대안: 기준 5를 완화해 "adapter test에 계약이 있으면 충분"으로 바꾸기 — 파생 서비스가 계약을 재사용할 수 없어 기준의 목적(갈아끼울 수 있는 포트)이 사라진다. + +### 05-17 Redis: 연결 실패를 "결과 불명"으로 보고하고, 시간 초과된 연결을 pool에 돌려준다 + +- 성격: 확인된 결함. 관점 6, 12, 14. +- 근거: `redis-runtime/.../RedisRuntimeOwner.java:201` `openLane` 예외가 `RedisLaneUnavailableException`이 아니어서 `SemanticRedisCall`(`:73,109-111`)이 unknown으로 분류한다. Redis가 완전히 내려가면 멱등성 claim은 `Indeterminate`(→ reconcile 경로), rate-limit은 `NO_MUTATION_CONFIRMED`가 된다. 명령은 하나도 보내지 않았다. 또 `SemanticRedisCall`은 실패·시간 초과 뒤 `invalidate()`를 부르지 않는다(`:98-112`). 로컬 await 200ms, Lettuce timeout 2초(`RedisTopologyClientFactory.java:295`)라 큐에 명령이 남은 연결이 다음 사용자에게 간다. 최악 지연: lane 대기 2s + 연결 2s + 명령 0.2s ≈ 4.2s, health probe는 두 lane에서 약 9.5s(`RedisHealthContributor.java:86-104`). +- 영향: Redis 장애 때 "안 보냈음"이 확실한 경우도 reconcile·불명 처리로 간다. 시간 초과 직후 다음 명령이 앞 명령의 응답을 기다린다. +- 심각도·우선순위: Medium / P2. 결정 24(포화 시 UNAVAILABLE)는 lane 포화 경우만 충족한다. +- 최소 개선 방향: 연결 열기 실패를 lane unavailable로 분류한다. 실패·시간 초과 lease는 invalidate한다. rate-limit은 남은 caller deadline을 borrow·connect에도 적용한다. + +### 05-18 설정 prefix·바인딩 방식이 capability 기준 4와 다르다 + +- 성격: 확인된 결함(규칙 불일치). 관점 19, 23. +- 근거: redis-runtime은 `@ConfigurationProperties("app.redis")`(`RedisRuntimeAutoConfiguration.java:85`)와 setter+`validate()` 방식이다. cache-redis는 `app.capabilities.*`와 `app.rate-limit.*`를 쓴다. 알림은 `@Value` 두 곳에 기본값을 중복한다(`NotificationCallbackMvcController.java:58`, `NotificationSubmissionConfiguration.java:91`). 같은 auto-configuration이 R0 legacy prefix(`app.notification.slack-webhook`, `google-email`)를 함께 import한다(`NotificationPlatformAutoConfiguration.java:29-31`). +- 영향: 모르는 키 거부(StrictSettingsBinder)가 일부 모듈에서 동작하지 않는다. 운영자가 한 모듈의 설정을 여러 트리에서 찾아야 한다. +- 심각도·우선순위: Low / P3. 결정 36처럼 예외로 인정할지 정하고, 인정하면 AGENTS.md 규칙 4에 적는다. + +### 05-19 bootstrap이 알림·파일 서버 권한 이름을 안다 + +- 성격: 확인된 결함(기준 7). 관점 3, 27. +- 근거: `app-bootstrap/src/main/resources/config/security.yml:40-45`(notification 권한 2개), `:50-59`(`ROLE_FILE_*` → `file:*`). 모듈을 빼도 이 매핑이 남고, 모듈을 넣는 서비스는 bootstrap 파일을 알아야 한다. +- 심각도·우선순위: Low / P3. 남은 매핑은 동작하지 않는 문자열일 뿐이다. +- 최소 개선 방향: 각 composition 모듈의 `module-defaults/*.yml`이 `app.security.authz.role-permissions.` 항목을 싣는다. Spring Binder는 여러 property source의 Map 항목을 합치므로 bootstrap은 이 줄들을 지울 수 있다. 버린 대안 — 모듈별 `RolePermissionContributor` bean: 코드가 늘고 설정 한 곳에서 보이지 않는다. +- 완료 기준: 모듈 한 줄을 지우면 security 설정에서 해당 권한이 사라진다. + +### 05-20 SES 콜백: replay 창 5분이 장애 뒤 SNS 재전송을 버린다 + +- 성격: 구조적 위험(SNS 재전송 시 Timestamp가 유지된다는 점은 AWS 동작에 대한 추론). 관점 6, 11, 28. +- 근거: `SesCallbackAdapter.java:79-81,101-111`이 메시지 `Timestamp`와 수신 시각 차이가 5분(`notification.yml` replay-skew)을 넘으면 거부한다. 중복 방지는 이미 ledger unique 제약이 한다(`persistence-notification` `V1__…sql:174-178`). 또 `SnsSignatureVerifier.java:80`은 cert fetch 실패(`IllegalStateException`, `NotificationCallbackProviderConfig.java:74-86`)를 잡지 않아 500이 된다. +- 영향: 서버가 5분 넘게 내려가 있었다면 그동안의 bounce·complaint가 영구 손실되고 suppression이 누락된다. 반송 주소로 계속 보내 발신 평판이 떨어질 수 있다. +- 심각도·우선순위: Medium / P2. +- 최소 개선 방향: 중복은 unique 제약에 맡기고 창을 SNS 재시도 기간에 맞춰 늘린다(설정 키는 이미 있다 — 기본값 변경). cert fetch 실패는 일시 장애(503)로 명시 매핑한다. + +### 05-21 identifier leaf: 이름·문서가 내용과 맞지 않는다 + +- 성격: 개선 제안. 관점 4, 24, 26. +- 근거: main 코드는 `HmacUserPrincipalPseudonymizer` 한 클래스(53줄)다. README·CLAUDE.md·`package-info.java`는 "식별자 생성/인코딩(UUIDv7), clock, crypto/random"을 말한다. README `:3`의 패키지 루트(`dev.caskeleton.adapter.identifier`)는 실제(`…adapter.outbound.identifier`)와 다르다. README는 `app-bootstrap`이 조립한다고 적지만 실제는 `composition/service-runtime/.../PseudonymizationConfig.java:26`이다. `composition:fileserver-platform`의 registry edge(`adapter-outbound-identifier`)는 build.gradle에서 쓰이지 않는다. 테스트에 알려진 정답 벡터(RFC 4231)가 없어 charset·알고리즘을 바꾸는 변이가 살아남을 수 있다(추론). +- 심각도·우선순위: Low / P3. +- 최소 개선 방향: leaf 이름은 유지하고(소비자 영향) 문서를 실제 내용으로 고친다. 정답 벡터 테스트 1건. 쓰지 않는 registry edge 삭제. + +### 05-22 파일 서버: finalize가 writer lease 없이 돈다 + +- 성격: 구조적 위험(결과는 추론). 관점 12. +- 근거: `FinalizeUploadApplicationUseCase.java:118-148`은 lease를 잡지 않는다. `AtomicMoveContentPublisher.java:32-39`는 hash 계산과 move 사이에 틈이 있다. `LocalUploadContent.java:83-105`의 lease 해제는 노드 단위 `instanceId`가 같으면 해제한다. +- 영향: 길이를 미루는 Draft-12 업로드에서 append와 finalize가 겹치면 INTEGRITY_MISMATCH 후 고아 파일, 레코드는 VERIFYING에 멈춘다. +- 심각도·우선순위: Low / P3(Draft-12 경로에서만 도달, 켜면 Medium). +- 최소 개선 방향: finalize도 lease·fence로 감싸고 해제는 lease token 기준으로. + +### 05-23 작은 결함 묶음 (각각 독립, Low / P3) + +| ID | 내용 | 근거 | +| --- | --- | --- | +| 05-23a | 0바이트로 선언한 업로드에 1바이트를 쓸 수 있고, 그 세션은 만료까지 finalize 불가 | `UploadSessions.java:67`, `LocalUploadContent.java:108` `Math.max(expected, 1)` | +| 05-23b | S3 mutation의 500/503을 "확정 미반영"으로 분류. 요청 본문 bridge가 재구독 불가라 `maxAttempts>1`이어도 PUT 재시도는 항상 실패 | `S3ProviderErrorMapper.java:45,63`, `S3AsyncRequestBodyBridge.java:60-63`, `S3AsyncClientFactory.java:28-32`. kernel이 다음 시도에서 `resolveCreate`로 확인해 손상은 없음 | +| 05-23c | 알림 dedup DROP 결과를 저장하지 않아 같은 idempotency key의 응답이 시간에 따라 바뀜 | `NotificationSubmissionService.java:135-138` | +| 05-23d | module-defaults 파일 간 같은 키·같은 파일명을 검출하지 않음(지금 7개 파일 사이 충돌 0건) | `support/.../ModuleDefaultsEnvironmentPostProcessor.java:43-49` | +| 05-23e | Redis `DEGRADED` 상태가 health status order에 없음 — 전체 health가 DOWN 대신 DEGRADED로 보일 수 있음(추론, 미검증) | `RedisRuntimeAutoConfiguration.java:70-71`, yml에 `status.order` 없음 | +| 05-23f | rate-limit dedup 정책이 기본으로 켜져 있지만 adapter·Lua 어디서도 쓰지 않음. `evaluationId`도 무시 → INDETERMINATE 뒤 재시도가 두 번 차감 | `RateLimitPolicy.java:36`, `EdgeRateLimitTransportBridge.java:69` | +| 05-23g | HTTP client 401마다 retry 가능 여부와 상관없이 토큰을 다시 받음 | `DefaultGenericHttpGateway.java:194` | + +다른 영역으로 넘기는 것(>): `AuthenticationMode.REDIS_SESSION`이 요구하는 `redisVersionedSessionRepository` bean을 main 코드 어디서도 만들지 않는다(`app-bootstrap/.../AuthenticationModeSettings.java:50-53`) — 인증 영역. + +## 4. 31절 시나리오 추적 + +### 4.1 외부 응답 지연·유실 — 알림 1건 발송 (적용) + +`POST /v1/notifications` → 제출 → dispatch → SES 호출을 따라갔다. + +```text +HTTP 요청 → web-notification 컨트롤러(DTO 검증, @RequiresPermission notification:submit) + → NotificationSubmissionService: tx { (tenant, idempotency_key) UNIQUE insert, 지문 비교 } + → (스케줄러) RecipientClaimSql: FOR UPDATE SKIP LOCKED, lease 2m + → tx { attempt insert (evidence = 미시작 확정) } ← 05-01 + → lease 재확인 → [tx 밖] SES 호출 (connect 2s, apiCallTimeout 10s, SDK 재시도 꺼짐) + → tx { recorder.record (owner + fence 조건) } → retryPolicy → lease 해제 +``` + +| 항목 | 결과 | +| --- | --- | +| 입력 신뢰 수준 | HTTP 본문은 비신뢰. DTO 검증 후 `AcceptNotificationCommand` 생성자가 category를 강제(`:71-72`) | +| 인가 위치 | use case 메서드의 `@RequiresPermission`, 관리자 연산은 `AdminAuthorizationGuard` | +| 규칙 소유 객체 | 중복 제출: DB unique 제약 + 지문. 발송 상태: `RecipientDeliveryRecord`, 재시도: `RetryPolicy` | +| 트랜잭션 | insert·claim·attempt insert·결과 기록이 각각 짧은 트랜잭션. provider 호출은 트랜잭션 밖(`NotificationDispatchService.java:215`) — 맞다 | +| 외부 부작용 | SES·SMTP 발송. provider 쪽 idempotency key는 없다(SES API가 지원하지 않음) | +| 성공의 의미 | 제출 응답은 "접수", 발송 성공은 provider 수락(`SubmissionOutcome`)과 콜백 기반 delivery 결과가 따로다 | +| 오류 변환 | timeout → AMBIGUOUS → reconcile(SES), SMTP는 전부 AMBIGUOUS(05-11) | +| 진단 정보 | attempt 행에 evidence·failure code, health endpoint의 backlog·stuck lease 임계값 | +| 결론 | 정상 경로와 timeout 분류는 계약대로다. 프로세스 중단 시 결과 불명이 "확정 미시작"으로 바뀌는 구멍(05-01)과 독 요청 루프(05-10)가 남는다. | + +### 4.2 큰 입력 — tus 업로드 (적용) + +`POST /v1/uploads`(Upload-Length) → `PATCH`(Upload-Offset, body) → finalize. + +| 항목 | 결과 | +| --- | --- | +| 입력 신뢰 | `Upload-Length` 상한(`TusRequestParser.java:75`)과 policy 상한(`CreateUploadApplicationUseCase.java:171-177`). PATCH body는 쓰기 전 상한 검사(`LocalAppendEngine.java:221`), 선언 초과 거절(`:249-268`), 실패 시 truncate(`:82-101`), 고정 버퍼 스트리밍 | +| 경로 | 서버가 만든 키만 경로가 된다. normalize 후 `startsWith` 검사(`DefaultPhysicalPathResolver.java:26-27,115-133`), NOFOLLOW로 한 단계씩 내려감. 클라이언트 파일명은 경로에 쓰이지 않는다 | +| 콘텐츠 타입 | magic byte 판별 6종 또는 octet-stream(`MediaTypeVerifier.java:23-30`), 다운로드에 `nosniff`, 기본 `attachment`(`HttpContentDispositionFactory.java:41-86`) | +| 인가 | 역할(`@RequiresPermission file:*`) + `FileAccessPolicyPort`(소유자·tenant) 둘 다(결정 32 반영). 테스트 공백은 05-08 | +| 동시성 | offset·lease·terminal 전이가 조건부 UPDATE(`UploadLeaseRepository.java:26-148`). offset 검사는 변이 M1로 테스트가 잡음을 확인 | +| 결론 | 크기·경로·타입 방어는 잘 돼 있다. 남은 것은 디스크 상한(05-07), 권한 조합(05-12), 정리 기본값(05-13) | + +### 4.3 다른 사용자 리소스 접근 — 파일 다운로드 (적용) + +`GET /v1/files/{id}/content` → `PrepareDownloadApplicationUseCase`가 `authorize(DOWNLOAD, subject, descriptor)` → `RoleBasedFileAccessPolicy`가 소유자·tenant 비교. 현재 코드는 다른 사용자의 id로 요청하면 거부한다. 하지만 이 검사를 지워도 게이트가 통과한다(변이 M2, 05-08). 콘텐츠를 여는 use case는 descriptor를 그대로 신뢰한다(`OpenDownloadContentApplicationUseCase.java:38-40`). + +### 4.4 중복·동시 요청 — 멱등성 claim (부분 적용) + +Redis 멱등성 store는 Lua 단일 키 원자 실행과 Redis `TIME`을 쓴다. 같은 owner의 재시도는 `ALREADY`로 처리한다. renew가 그 분기에 먹혀 lease를 늘리지 못한다(05-02). executor 조립은 `composition:idempotency`(다른 영역)다. + +### 4.5 선택 어댑터 제거 (적용) + +`app-bootstrap/build.gradle:162-171`에서 이 영역의 선택 모듈은 모두 주석 처리돼 있고 기본 조립은 support·identifier만 `implementation`으로 받는다(`:211-212`). `ci`의 `:app-bootstrap` 테스트가 이 기본 조립으로 통과했다. 모듈을 빼도 남는 흔적은 `security.yml`의 권한 매핑(05-19)과 Redis readiness 관련 주석·session bean 이름(`observability.yml:51-77`, `AuthenticationModeSettings.java`)이다. 각 모듈 기준 충족 여부는 7절 표에 있다. + +### 4.6 적용 제외 + +| 시나리오 | 사유 | +| --- | --- | +| 정상 쓰기 요청(일반 도메인) | 이 영역은 도메인 쓰기가 아니라 capability. 4.1·4.2가 같은 경계를 다룬다 | +| DB 오류·경쟁 | 영역의 SQL은 persistence leaf(다른 영역). 조건부 UPDATE 사용만 확인 | +| 메시지 중복·역순 | messaging은 다른 영역. SNS 콜백 중복은 ledger unique로 처리됨을 확인(05-20) | +| 신·구 버전 공존 | 캐시 envelope schema version(`CacheEnvelope.CURRENT_SCHEMA_VERSION`)만 확인, 실험 안 함 | +| 여러 서버의 작업 실행 | 4.1의 lease·SKIP LOCKED로 대신함. 다중 인스턴스 실험은 미실행 | +| 세션·토큰 갱신 경쟁 | HTTP client 토큰 single-flight(`SingleFlightTokenLoaderTest`)만 확인. 세션은 인증 영역 | +| 종료·재시작 | 알림 shutdown-grace 20s 설정 확인. 05-01이 이 시나리오의 결함이다. 실제 종료 실험은 안 함 | + +## 5. 41절 설계 선택 검토 + +### 5.1 알림 attempt의 "요청 시작 증거"로 recovery 경로를 고르는 설계 + +1. 필요한 것: 워커가 죽은 뒤 남은 DISPATCHING 건을 처리해야 한다. 상태 조회가 없는 provider(SMTP)도 있다. +2. 지킬 성질: provider가 받았을 수 있는 요청은 다시 보내지 않는다. 확실히 안 보낸 것만 다시 큐에 넣는다. +3. 현재 보장: `provablyNeverStarted`가 PROVEN+false만 requeue한다(`LeaseRecoveryService.java:101-106`). 규칙 자체는 맞다. 하지만 그 증거를 insert 시점에 "확정"으로 쓰고 갱신하지 않아 보장이 깨진다(05-01). +4. 대안: (a) 모든 미완료 attempt를 reconcile(이전 방식). (b) 증거 기반 분기 + insert는 UNKNOWN. (c) 호출 직전 증거 갱신 쓰기 추가. +5. 비용: (a) 단순하지만 상태 조회 없는 provider는 전부 운영자 대기. (b) 쓰기 추가 없음, "확정 미시작"이 생기는 곳이 명확(adapter 결과·lease 상실 종료). (c) 쓰기 1회 추가로 insert 직후 crash만 자동 requeue. +6. 선택: (b). 현재 설계의 의도(증거로 분기)를 유지하면서 증거가 참인 시점에만 기록한다. +7. 다시 볼 조건: 상태 조회를 지원하는 provider가 대부분이 되면 (a)로 단순화할 수 있다. insert 직후 crash 비율이 측정상 의미 있으면 (c). + +### 5.2 캐시 무효화 모델: region generation + 키 GETDEL + +1. 필요한 것: 키 단위·region 단위 무효화, Redis 장애 시 원본으로 우회. +2. 지킬 성질: 무효화 뒤 옛 값이 다시 보이지 않는다(적어도 정해진 시간 안에). +3. 현재 보장: region은 generation 카운터, 인스턴스는 softTtl(30s)마다 재확인. 키는 `GETDEL`. 느린 loader가 무효화 뒤 옛 값을 다시 쓰는 것은 막지 못한다(05-04). revision 조건은 구현되지 않았다(05-03). +4. 대안: (a) 현상 유지 + 문서에 "최대 hard TTL 동안 옛 값 가능" 명시. (b) 키 tombstone + revision CAS. (c) pub/sub로 무효화 전파(로컬 캐시가 있을 때만 의미). (d) 분산 lock single-flight. +5. 비용: (a) 0, 일관성 약함. (b) Lua 하나, tombstone TTL 관리. (c) pub/sub 전송이 아직 없다(G-4i). (d) 왕복 증가, lock 만료 처리. +6. 선택: (b). 이미 `ONLY_IF_OBSERVED`용 Lua CAS가 있어 같은 모양으로 확장된다. +7. 다시 볼 조건: 로컬(L1) 캐시를 추가하면 (c)가 필요하다. 쓰기 빈도가 높아 CAS 충돌이 측정되면 재검토. + +### 5.3 MinIO 하나에 기대는 실제 S3 벤더 증거 + +1. 필요한 것: S3 호환 저장소에서 adapter 계약이 맞다는 실행 증거(기준 5). +2. 지킬 성질: 게이트가 초록이면 실제 벤더로 계약을 확인했다는 뜻이어야 한다. +3. 현재 보장: digest 고정 + `rejectSkipped`로 fail-closed. 공급원이 사라지자 실패했다 — 성질은 지켰다. 대신 복구 수단이 없고, 고정 버전 자체도 create-only를 지원하지 않는다(`UNSUPPORTED`). +4~6. 대안과 선택은 05-09 표. 조직 레지스트리 미러를 고른다. +7. 다시 볼 조건: 운영 대상이 AWS S3로 정해지면 `objectStorageAwsQualificationTest`(현재 explicit-only)를 정기 실행하고 MinIO는 보조로 내린다. + +## 6. 리팩토링 후보 + +| 대상 | 무엇을, 왜 | 보존 조건 | +| --- | --- | --- | +| notification `dispatch/` 46파일 | `submission/`, `dispatch/`, `reconciliation/`, `contact/`로 나눈다. 한 패키지에 기능 4개 | public 타입 이름·api surface 스냅샷(`docs/notification/api-surface-snapshot.txt`) 갱신, 테스트 패키지 동기 이동 | +| notification adapter의 R0 legacy(`core/`, `slack/`, `email/google/`) | platform과 한 auto-config에 있음. 별도 leaf로 떼거나 삭제 결정 | `app.notification.slack-webhook`·`google-email` 키 동작, 해당 env 키 | +| 포트 계약 테스트 위치 | adapter `src/test` → 포트 소유 leaf testFixtures(05-16) | 상속하는 구현 목록이 줄지 않을 것 | +| `RedisCacheRegionAdapter`의 `CacheKeys` 가변 generation | `RegionGeneration` 객체로 분리(S3-#12a) | softTtl 재확인 주기, generation 0 처리 | +| Redis health indicator 2개 | 상태 값만 인자로 받는 하나로(S3-#13c) | readiness 그룹 멤버 이름 `redisRequired`/`redisOptional` | +| httpclient 단계 추적 | 연결 이벤트로 단계를 올리게(05-14) | `ExecutionEvidence` 값의 의미, 기존 분류 테스트 | +| support의 `messaging/` encoder | support는 module-defaults·startup 규칙이 책임. messaging encoder는 messaging bridge 쪽이 맞다 | `IntegrationEventEncoderAutoConfiguration` bean 이름, 조립 순서 | +| `NotificationPlatformSettings.ProviderProfile` | provider마다 전용 필드(`Ses ses`)를 추가하는 구조 → provider별 설정 record를 sealed 하위 타입으로 | 기존 키 경로 `…profiles[n].ses.*`, 검증 메시지 | + +## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료) + +### 7.1 capability 모듈별 완료 기준 현황 + +| 기준 | redis(runtime+cache) | httpclient | objectstorage | notification | fileserver | +| --- | --- | --- | --- | --- | --- | +| 1 포트만 호출 | O | X — 호출 surface가 모듈 타입(`GenericHttpGateway`, `@HttpClientProfile`). 라이브러리형이라 `implementation`이 필요한데 README는 runtimeOnly 한 줄이라고만 함 | O | O | O | +| 2 imports·enabled·순서 | O | O(순서 의존 없음) | O | P — adapter 쪽 순서 지정 없음 | P — `beforeName`만 | +| 3 동작하지 않는 키 없음 | P — sample 죽은 키(P20-new-3) | X — 05-15 | O | P — R0 키 동거 | O | +| 4 prefix 하나·StrictSettingsBinder | X — 05-18 | O | O | X — `@Value` 중복 | O | +| 5 계약 테스트·실제 벤더 | P — lease만, 실제 lane은 explicit-only | P — 계약 위치, 실제 lane은 integrationCheck만 | P — 계약 위치, MinIO 실패(05-09) | X — testFixtures 없음, 실제 벤더 없음 | P — 계약 위치, Postgres는 다른 leaf | +| 6 README 3가지 | P — redis-runtime README 없음 | O | O | O(composition README) | P — web-fileserver README 없음 | +| 7 모듈만 안다 | O(주석 외) | O | O | P — security.yml | P — security.yml | + +### 7.2 새 기능을 추가할 때 개발자가 내려야 하는 판단 + +**외부 API client 추가 (httpclient)** +1. profile 설정(`APP_HTTPCLIENT_CLIENTS_N_*`): base-url, allowed-hosts·ports, body 상한, prod TLS profile. +2. `@HttpExchange` 인터페이스 + 메서드마다 `@HttpOperationPolicy(name, idempotency)`. +3. application-core에 포트를 정의하고 adapter leaf가 httpclient를 `implementation`으로 받는다. +- 판단 지점: 이 연산은 멱등한가(아니면 idempotency key를 보낼 수 있는가)? 결과 불명(`SENT_NO_RESPONSE`)을 어떻게 정산하는가? 4xx 중 무엇이 업무상 정상인가(05-05가 고쳐지기 전에는 breaker에 주의)? 전체 deadline이 transport timeout 합보다 큰가(05-06)? + +**알림 provider·채널 추가** +1. `ProviderType`, adapter·failure classifier, `ProviderRuntimeAssembler`, `NotificationProviderConfig`, `ProviderProfile` 필드, `NotificationSecretRequirements`, `notification.yml`, api surface 스냅샷·evidence manifest. +2. 채널이면 `Channel`, sealed `NotificationContent`, `ContactPointType`, renderer·slot policy, persistence 매핑, web DTO까지. +- 판단 지점: provider가 상태 조회를 지원하는가(없으면 결과 불명이 전부 운영자 대기)? 어떤 예외가 "확실히 안 보냄"인가? 콜백 서명 방식과 replay 창은? collapse·priority 같은 선택 기능을 지원하는가? + +**파일 연산 추가** +1. `FileOperation` 값과 `RoleBasedFileAccessPolicy.tierOf` 매핑, `@RequiresPermission`, security 매핑. +2. use case 안에서 `authorize(op, subject, Optional.of(record.toDescriptor()))` — descriptor를 빠뜨리면 소유자 검사가 조용히 꺼진다(05-08). +3. 바이트를 새로 만드는 연산이면 admission·quota(05-07). 실패 시 cleanup·recovery 큐에 넣을 것. +- 판단 지점: 이 연산은 디스크를 늘리는가? 대상 namespace를 누가 정하는가? 중간 실패 시 고아 파일을 누가 회수하는가? + +**캐시 region·rate-limit 정책 추가** +1. cache region은 지금 `CacheRegionPort` bean 하나(`RedisCacheConfig.java:281`). 새 region은 cache-redis 안에 bean 추가가 필요하다 — 템플릿이 확장 지점을 주지 않는다. +2. rate-limit 정책은 `app.capabilities.rate-limit.policies.` yml 블록. 라우트별 정책은 inbound 코드를 고쳐야 한다. +- 판단 지점: 키에 tenant·사용자 범위를 넣었는가(호출자 책임)? 무효화 뒤 옛 값이 얼마나 허용되는가(05-04)? Redis 장애 시 원본으로 갈 것인가 거부할 것인가? rate-limit revision을 바꾸면 카운터가 초기화된다. + +### 7.3 템플릿이 주는 틀과 빠진 것 + +- 주는 것: capability별 auto-configuration·module-defaults·README 모양, StrictSettingsBinder, lease 공통 계약, 알림·파일 서버의 완성된 참조 구현. +- 빠진 것: 포트별 공통 계약 테스트(cache·idempotency·rate-limit·알림 provider·파일 콘텐츠 store)를 testFixtures에서 상속하는 틀, 새 cache region을 서비스가 선언하는 확장 지점, httpclient를 포트 뒤로 숨기는 예제 adapter, application-* leaf의 CLAUDE.md(B-10b와 같은 성격, fileserver·objectstorage도 없음). + +### 7.4 폴더 구조 + +- 찾기 쉬운 것: composition 모듈이 조립을, application-* 가 유스케이스를, adapter가 벤더 코드를 갖는 3단 구조는 알림·파일 서버에서 일관된다. +- 찾기 어려운 것: Redis는 runtime·sdk·cache 세 leaf인데 runtime에 README가 없고 규칙이 cache-redis CLAUDE.md에 섞여 있다(G-5b). `redis-sdk`(main 24,506줄)는 소비자가 0인 라이브러리형 모듈이다 — 사용자 원칙상 확장 지점이지만, 무엇을 위해 남기는지 README에 소비 예제가 없다. identifier leaf는 이름과 내용이 다르다(05-21). 알림 adapter는 R0 legacy와 platform이 한 leaf에 있다. + +### 7.5 성능 (코드에서 읽은 값, 측정 아님) + +| 항목 | 값 | +| --- | --- | +| Redis lane 연결 수 | REGULAR 64, SCRIPT 8(rate-limit·멱등성·lease 공유) — `RedisRuntimeSettings.java:457-458` | +| Redis 대기·timeout | lane 대기 2s, connect 2s, 명령 500ms/1s/2s, capability 명령 200ms. 최악 약 4.2s(05-17) | +| SCRIPT lane 처리량(추정) | 왕복 1ms면 pod당 약 8k ops/s, Redis가 200ms로 느려지면 약 40 ops/s | +| HTTP client pool | 전체 50, route당 25, pending 100(200ms 대기) | +| HTTP client timeout | connect 0.5s, TLS 1s, 응답 헤더 2s, read idle 3s, 전체 4s | +| HTTP 응답 버퍼링 | 응답 전체를 메모리에, profile당 최악 50 × 5MB = 250MB | +| 알림 dispatch | claim 50건, 동시 64(virtual thread + semaphore), lease 2m, poll 1s | +| 캐시 TTL | soft 30s, hard 5m, negative 10s | +| 테스트 시간 | 14 leaf 합 약 63s, 1,790개 | + +## 8. 28개 관점 판정표 + +기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역. + +| # | 관점 | 판정 | 한 줄 이유 | +| --- | --- | --- | --- | +| 1 | 코드 성숙도 | P | 경로·크기 방어는 견고하나 공개 계약이 조용히 깨진 곳이 있다(05-02, 05-03) | +| 2 | 구조적 성숙도 | O | application-*/adapter/composition 분리와 registry edge가 지켜진다. ci의 architectureCheck 통과 | +| 3 | 변경 용이성 | P | provider 추가 시 일반 profile record 수정 필요, bootstrap security.yml 수정 필요(05-19) | +| 4 | 인지 부하 | P | 알림·파일 서버는 개념이 많고 문서 drift(W5 항목 다수)가 읽는 비용을 올린다 | +| 5 | 위험 가시성 | P | 결과 불명·lease 의도가 주석에 잘 드러나지만, 그 주석이 틀린 곳(05-01)과 문서가 jitter를 주장하는 곳(05-04)이 있다 | +| 6 | 실패 성숙도 | P | 결과 불명 분류 체계는 있으나 SMTP·HTTP 기본 경로·Redis 연결 실패에서 분류가 틀린다(05-11, 05-14, 05-17) | +| 7 | 운영 성숙도 | P | health·backlog 임계값은 있음. 정리 worker 기본 꺼짐(05-13), breaker 설정 키 없음(05-05) | +| 8 | 디버깅 가능성 | P | attempt evidence·failure code가 남는다. MinIO 실패가 공급원 문제로 구분되지 않는다(05-09) | +| 9 | 유지보수 성숙도 | P | 이력 주석·FQN·CLAUDE.md 버전 drift가 남아 있음(2절) | +| 10 | 테스트 성숙도 | P | offset 검사는 테스트가 잡음(M1). 소유자 검사 제거는 못 잡음(M2), fake가 adapter 버그를 따라 함(05-02) | +| 11 | 데이터 성숙도 | P | 제출 중복은 DB unique로 강제. 재발송(05-01), 캐시 옛 값(05-03), bounce 손실(05-20) | +| 12 | 동시성 성숙도 | P | SKIP LOCKED·fence·조건부 UPDATE는 좋다. lease 만료 후 재발송, finalize lease 없음(05-22) | +| 13 | 확장성 | ? | 다중 인스턴스·부하 실험 없음. SCRIPT lane 8개가 병목 후보(추정) | +| 14 | 성능 성숙도 | P | 상한(pool·body·lane)은 정해져 있음. deadline이 진행 중 요청을 끊지 못함(05-06) | +| 15 | 보안 성숙도 | P | 경로 탐색·SSRF·SNS 서명·nosniff 방어 확인. copy로 디스크 고갈(05-07), 인가 회귀 미검출(05-08) | +| 16 | 의존성 성숙도 | P | reactive 스택 제거(결정 9), SES는 AWS SDK. MinIO 공급원 소멸(05-09), Jackson 2 잔존(S3-#13a) | +| 17 | API / Contract 성숙도 | P | 포트 계약이 공개돼 있으나 구현이 일부 intent·renew를 지키지 않는다 | +| 18 | 배포 성숙도 | > | 배포 파이프라인은 다른 영역. 이 영역은 release 스크립트 경로 오류(P11-new-2)만 기록 | +| 19 | 설정 성숙도 | P | module-defaults 구조는 일관. 동작 안 하는 키·0 timeout 허용(05-15), prefix 여러 개(05-18) | +| 20 | 개발자 경험 | P | 모듈 한 줄로 켜지는 경험은 좋다. 새 adapter가 상속할 계약·확장 지점이 없다(7.3) | +| 21 | Guardrail 성숙도 | P | StrictSettingsBinder, fail-closed lane. 기준 5를 강제하는 장치는 없다(05-16) | +| 22 | 추상화 성숙도 | P | 포트 경계는 적절. httpclient는 포트 없이 모듈 타입을 노출(7.1 기준 1) | +| 23 | 일관성 | P | 계약 테스트 위치·설정 바인딩 방식이 모듈마다 다르다 | +| 24 | 네이밍 / 의미 성숙도 | P | identifier leaf 이름 불일치(05-21), `*ProviderProperties`(S4-#17b) | +| 25 | 조직 확장성 | ? | 담당자·소유 표기 없음. 판단할 자료 없음 | +| 26 | Ownership 성숙도 | P | env-keys owner_module 오기(G-12e), application-* CLAUDE.md 없음 | +| 27 | 삭제 가능성 | P | 한 줄 제거로 대부분 사라짐(`ci`의 기본 조립 통과). security.yml 잔여(05-19) | +| 28 | 회복 가능성 | P | reconcile·recovery 경로가 있다. 증거 오기로 회복이 재발송이 됨(05-01), 정리 기본 꺼짐(05-13) | + +## 발견 요약 + +| 심각도 | 개수 | ID | +| --- | --- | --- | +| Critical | 0 | | +| High | 6 | 05-01, 05-02, 05-03, 05-05, 05-06, 05-07 | +| Medium | 12 | 05-04, 05-08, 05-09, 05-10, 05-11, 05-12, 05-13, 05-14, 05-15, 05-16, 05-17, 05-20 | +| Low | 11 | 05-18, 05-19, 05-21, 05-22, 05-23a~g | + +| 우선순위 | 개수 | ID | +| --- | --- | --- | +| P1 | 8 | 05-01, 05-02, 05-03, 05-05, 05-06, 05-07, 05-08, 05-09 | +| P2 | 10 | 05-04, 05-10, 05-11, 05-12, 05-13, 05-14, 05-15, 05-16, 05-17, 05-20 | +| P3 | 11 | 05-18, 05-19, 05-21, 05-22, 05-23a~g | + +사용 결정: **조건부 사용 가능.** 파일 서버의 크기·경로·타입 방어와 알림의 제출 중복 방지는 그대로 써도 된다. 알림 발송(05-01), Redis 멱등성 renew·캐시 revision 조건(05-02, 05-03), HTTP client(05-05, 05-06), 파일 copy(05-07)는 고치기 전에는 파생 서비스에서 쓰지 않거나 우회 조건을 문서로 정해야 한다. diff --git a/docs/reviews/2026-11-01-maturity-review/06-messaging.md b/docs/reviews/2026-11-01-maturity-review/06-messaging.md new file mode 100644 index 00000000..e9557756 --- /dev/null +++ b/docs/reviews/2026-11-01-maturity-review/06-messaging.md @@ -0,0 +1,495 @@ +# 06 — messaging 영역 성숙도 리뷰 + +- 대상: vendored `messaging:*`(`src/messaging`), `adapter:outbound:messaging`(anti-corruption bridge), + `adapter:outbound:messaging-kafka`, `composition:outbox-relay` +- 기준 커밋: `main` `01a8a2a70` +- 작성일: 2026-11-01 +- 소유자 결정 유지: vendored 플랫폼은 Clean Architecture 레이어가 아니다(MSG-023 §6.2). messaging outbox도 + 유지한다(followup `X1-지도-Outbox`). 이 문서는 그 결정을 뒤집지 않고 그 안의 품질과 결정의 반영 상태를 본다. + +## 1. 범위 + +| 항목 | 기록 | +| --- | --- | +| 대상 저장소 | `clean-architecture-backend-template`, Gradle 루트 `src/` | +| 커밋·확인 시점 | `01a8a2a70`, 2026-11-01 20:30–21:10 KST | +| 목적과 지원 실행 구성 | 서비스 시작점 템플릿. 다중 인스턴스 배포를 전제한다(relay가 `SKIP LOCKED` + lease fencing을 쓴다). broker는 Kafka 하나 | +| 규모·운영 목표 | 합의된 수치 없음. 그래서 처리량·복구 시간은 "현재 기본값으로 계산한 값"으로만 적는다 | +| 읽은 코드 | `composition/outbox-relay/src/main/**` 전부, `adapter/outbound/messaging/src/main/**` 전부, `adapter/outbound/messaging-kafka`(코드 없음, `module-defaults/messaging.yml`), `application-core/.../application/outbox/**`(relay 동작 확인용), `persistence-jpa/.../outbox/**`(claim SQL·완료 확인용), `messaging-runtime-core` `DefaultMessagePublisher`, `messaging-transport-spi` `DefaultMessagingRuntimeRegistry`, `messaging-policy` `MessagingAdmissionController`, `messaging-kafka` `KafkaMessagingTransport`·`KafkaPublishFailureClassifier`, starter의 `MessagingShutdownLifecycle`·`MessagingOutboxRelayLifecycle`·`MessagingReliabilityAutoConfiguration`·`MessagingConsumeConfiguration`·`MessagingPublishConfiguration`, starter-kafka `KafkaMessagingAutoConfiguration`·`KafkaDeadLetterQuarantine`, sample `PortfolioEventOutbox`, `SubmitDurableOperationUseCase`, runbook `outbox-dead-letter`·`outbox-publish-failed`, `docs/messaging/*`. Spring Framework 7.0.9 소스(`ExecutorConfigurationSupport`, `ScheduledAnnotationBeanPostProcessor`)로 종료 순서 확인 | +| 읽지 않은 코드 | vendored admin·claim-check·cloudevents·schema-avro/protobuf·observability 내부, `KafkaConsumerRegistrar` 786줄 중 settlement 세부 | +| 수행한 테스트·실험 | 아래 "실행" 참고 | +| 확인 못 한 것 | 실제 Kafka·PostgreSQL로 앱 relay를 끝까지 돌리는 실험(그런 테스트가 저장소에 없고 이번에 만들지도 않음), 실제 SIGTERM 종료 순서 실측, 처리량 실측 | +| 이전 리뷰와 비교 범위 | techlead `10-messaging.md`, followup-status M·H 그룹, 모듈 리뷰 `2026-08-14-messaging-module-code-review.md`(MSG-015·MSG-023) | + +### 실행 + +| 명령 | 결과 | +| --- | --- | +| 오케스트레이터 `ci` 게이트 로그(`gates/ci.log`) | rc=0. 이 영역 leaf의 `test` 전부 통과 | +| 오케스트레이터 `mainCheck` 게이트 로그 | rc=1. 원인은 `objectstorage`의 MinIO 이미지 pull 404(이 영역 밖). 이 영역의 broker 실연 lane(`integrationTest`)은 `mainCheck`에 들어 있지 않아 컴파일만 됐다 | +| 실험 1 (worktree `wt-06`, 부하 load avg 13.3): `./gradlew :messaging:messaging-runtime-core:test --tests '*DefaultMessagePublisherTest.reviewExperiment*' :adapter:outbound:messaging:test --tests '*PlatformIntegrationEventPublishAdapterTest.reviewExperiment*'` | 통과. 출력: `completion=REJECTED transmission=NOT_TRANSMITTED code=SHUTTING_DOWN retryable=true`, 이어서 bridge `outcome=REJECTED_BEFORE_SEND retryable=false`. 06-01 근거 | +| 실험 2 (변이, worktree, load avg 7.6): `OutboxRelayScheduler`에서 `metrics.recordRelayResult`·`metrics.refresh` 호출을 사실상 제거하고 `./gradlew :composition:outbox-relay:test` | 18개 전부 통과(변이 생존). 06-05 근거 | +| 테스트 시간(`build/test-results` XML 합계) | `adapter:outbound:messaging` 36개 2.8s, `messaging-kafka` adapter 4개 3.5s, `composition:outbox-relay` 18개 2.2s, `messaging-spring-boot-starter` 72개 4.9s, 나머지 messaging leaf는 각 1.5s 이하. 실행 시간은 문제 아님 | + +실험용 테스트 편집은 worktree에만 했고 끝나고 worktree를 지웠다. + +## 2. 지난 발견 재확인 + +| ID | 지난 내용(요약) | 상태 | 근거 | +| --- | --- | --- | --- | +| techlead H10 | 자동조립 publisher가 관측을 기록하지 않음 | 해결 | `messaging-spring-boot-starter/.../MessagingPublishConfiguration.java:224-231` observation 주입 | +| techlead H3 | consumer가 배선되지 않음 | 바뀜 | starter-kafka가 `MessageHandler` bean마다 consumer를 연다(`MessagingConsumeConfiguration.java:60-68`). 다만 application leaf 쪽 경로가 없다 → 06-08 | +| techlead M4 | 실행 경로에 스키마 호환성 검사 없음 | 바뀜 | 문서가 "선언만 하고 강제하지 않음"으로 표시(`docs/messaging/configuration-reference.md:123`). 앱 payload 버전에는 여전히 없음 → NN-10 | +| techlead M5 | outbox 두 개 공존 | 남음(소유자 결정으로 유지) | vendored `MessagingReliabilityAutoConfiguration`·`JdbcOutboxRepository`가 runtime classpath에 있음. 문서·종료 순서 비용 → 06-02, NN-11 | +| techlead M7 / H-1b | producer-id 키 부재, 빈 값 통과 | 해결 | `messaging-kafka/src/main/resources/config/module-defaults/messaging.yml` `producer-id`, `MessagingBridgeRootAutoConfiguration.java:77-87` | +| H-1a | bridge 조건이 platform보다 먼저 평가 | 해결 | `MessagingBridgeRootAutoConfiguration.java:32-33` `afterName` | +| H-8 | bridge `prepare`가 모든 예외를 REJECTED로 | 해결 | `PlatformIntegrationEventPublishAdapter.java:59-67`, 테스트 `aFailureOtherThanAnIncompatibleValueIsNotTurnedIntoARefusal` | +| H-9, H-10b, H-10c | `KafkaSender` seam 관련 | 해당 없음(코드 삭제) | `adapter/outbound/messaging-kafka/src/main` 아래 Java 없음 | +| M-1 | 이미 인코딩된 payload 재인코딩 | 해결 | `DefaultMessagePublisher.java:314-322` | +| M-2a~f | Kafka 보안 설정 미적용 | 해결 | `KafkaMessagingAutoConfiguration.java:154-209`, followup의 테스트 존재 확인 | +| M-3, M-7 | handler timeout 중복, poison 무한 재시도 | 해결 | `KafkaConsumerRegistrarTest.java:160,191,219` | +| M-4a | admission 거부를 동기 예외로 던짐 | 해결 | `DefaultMessagePublisher.java:228-233` (결과로 반환). 단, 그 결과의 의미가 bridge에서 뒤집힌다 → 06-01 | +| M-4b, M-4c, M-6, M-11 | vendored relay·cleanup | 해결 | `OutboxRelayTest.java:90`, `MessagingOutboxRelayLifecycleTest.java:77`, `OutboxOperationsTest.java:114`, `OutboxPostgresIT.java:226`. 이 relay는 앱이 쓰지 않는다 | +| M-5a | publish가 최대 65초 막힘 | 해결 | `KafkaMessagingAutoConfiguration.java:203-206` `max.block.ms` = 5s | +| M-8a | 옛 prefix `backend.messaging` fixture yml 2개 | 남음 | `messaging-spring-boot-starter/src/test/resources/application-valid.yml:2-3`, `application-invalid-ordering.yml`. 참조 0건 | +| TEST-FAKE-MessagePublisher | fake와 `DefaultMessagePublisher`의 공통 계약 없음 | 남음 | `messaging-core-api`에 `testFixtures` 없음. `implements EncodedMessagePublisher`는 test fake 3곳과 본체뿐 | +| A-2 그룹 밖(followup:173) | `MessagingAdminDurabilityValidator`의 profile 대소문자 판정 | 남음 | `MessagingAdminDurabilityValidator.java:25,53-54` `Set.of("prod","production")::contains`. `Prod`면 검사를 건너뛴다 | + +남은 High/P1 지난 항목은 없다. 남은 것은 Low/Nit(M-8a, admin profile 판정)와 테스트 계약(TEST-FAKE)이다. + +## 3. 새 발견 + +심각도별: High 2 · Medium 10 · Low 2. 우선순위별: P1 2 · P2 8 · P3 4. + +### 06-01 — 다시 시도하면 될 거부를 relay가 즉시 DEAD로 보낸다 + +- 성격: 확인된 결함 +- 관련 관점: 6, 1, 17, 28, 5 +- 근거 + - platform은 일시적 거부를 `REJECTED` + `retryable=true`로 돌려준다. + - 종료 중 admission 거부: `MessagingAdmissionController`가 `MessageBackpressureException("SHUTTING_DOWN")`(category `TRANSIENT_INFRASTRUCTURE`, retryable true)을 던지고 `DefaultMessagePublisher.java:228-233`이 `PublishResult.rejected`로 바꾼다. + - permit 대기 초과: 같은 경로. 기존 테스트 `DefaultMessagePublisherTest.aSaturatedPermitPoolRejectsAsRetryableWithinTheCallersDeadline`이 `(REJECTED, retryable=true)`를 단언한다. + - runtime 없음(종료 후 registry close): `DefaultMessagingRuntimeRegistry.java:86-90` → `DefaultMessagePublisher.java:261-267` `PUBLISH_RUNTIME_UNAVAILABLE` REJECTED. + - transport 닫힘: `KafkaMessagingTransport.java:121-123` `KAFKA_TRANSPORT_CLOSED` REJECTED. + - Kafka 인증·인가 오류: `KafkaPublishFailureClassifier.java:51-58`가 `AuthenticationException`·`AuthorizationException`을 확정 거부로 본다. credential 교체 중 실패나 ACL 배포 순서 문제도 여기로 온다. + - bridge는 `retryable`을 보지 않는다. `PlatformIntegrationEventPublishAdapter.java:140-151`은 completion과 transmission만 보고 `REJECTED_BEFORE_SEND`/`REJECTED_AFTER_BROKER`를 만든다. + - relay는 그 둘을 "같은 payload는 또 거부된다"로 보고 시도 예산을 쓰지 않고 바로 DEAD로 보낸다(`PublishPendingOutboxEventsUseCase.java:149-153`, `OutboxPublishOutcome.java` `retryable()`은 `AMBIGUOUS`만 true). + - DEAD row는 같은 aggregate의 뒤 row를 모두 막는다(`PostgreSqlOutboxClaimRepository.java:27-36`, `p.status <> 'PUBLISHED'`). + - 실험 1: `SHUTTING_DOWN` 거부가 `REJECTED/NOT_TRANSMITTED/retryable=true`로 나오고, 같은 모양의 결과를 bridge가 `REJECTED_BEFORE_SEND`(retryable false)로 바꾸는 것을 실행으로 확인했다. 마지막 고리(`REJECTED_BEFORE_SEND` → DEAD)는 기존 `OutcomeAwareRelayTest.aRefusalBeforeTransmissionIsDeadLettered`가 단언한다. + - platform 문서도 "REJECTED는 포기해도 안전"이라고 적는다(`docs/messaging/delivery-guarantees.md:21-22`). 같은 platform이 retryable REJECTED를 만든다. +- 발생 조건: 배포 종료 중 relay가 돌고 있을 때(06-02), 다른 publisher와 permit을 다툴 때, Kafka 인증 정보 교체·ACL 변경 순간. +- 영향: 이미 커밋된 비즈니스 이벤트가 DEAD가 되고 그 aggregate의 이후 이벤트가 전부 멈춘다. 자동 복구가 없다. runbook의 수동 SQL이 필요하다. +- 심각도·우선순위: High / P1. 배포는 정상 운영 동작이다. 결과가 영구 정지라서 출시 전 차단 항목으로 본다. +- 확실성: 각 고리는 코드와 테스트로 확인했다(E2). 실제 종료에서 몇 건이 걸리는지는 미측정이다. +- 결정의 근거: 적용 제외 — 두 계약(platform `retryable`, application "확정 거부") 사이의 번역 누락이다. 선택 비교가 아니라 번역을 맞추는 문제다. +- 통제 수준: M0(retryable 거부를 retryable로 다루는 수단 없음). 증거 E2. +- 최소 개선 방향: bridge `mapOutcome`에서 `result.failure().retryable()`이 true인 REJECTED는 "다시 시도 가능, 전송 안 됨"으로 번역한다. application 어휘에 그 값이 없으므로 `OutboxPublishOutcome`에 `DEFERRED_NOT_SENT`(가칭) 하나를 추가하고, relay는 이 값에서 `markFailed`를 하되 시도 횟수를 늘리지 않는 쪽을 고른다. Kafka 인증·인가 오류는 classifier에서 retryable 거부로 분류한다. + - 버린 대안 1: `AMBIGUOUS`로 번역. 동작은 비슷하지만 "전송됐을 수 있음"이라는 거짓 정보를 남기고 중복 경고를 오염시킨다. + - 버린 대안 2: relay가 platform `FailureDescriptor`를 직접 본다. application-core가 platform 타입을 알게 돼 bridge의 존재 이유가 사라진다. +- 완료 기준: retryable REJECTED가 relay에서 FAILED가 되고 DEAD가 되지 않는다. 인증 오류가 retryable로 분류된다. +- 검증 방법: bridge 테스트에 retryable REJECTED → 새 값 케이스, relay 테스트에 새 값 → FAILED(시도 미소비) 케이스. 실험 1의 두 테스트를 정식 테스트로 옮긴다. + +### 06-02 — platform 종료 순서가 앱 relay를 모른다 + +- 성격: 확인된 결함(정적) +- 관련 관점: 6, 7, 12, 28, 23 +- 근거 + - 앱이 실제로 쓰는 relay는 `@Scheduled` 메서드다(`OutboxRelayScheduler.java:36`). SmartLifecycle이 아니다. + - platform 종료 순서는 vendored relay(`MessagingOutboxRelayLifecycle`, phase `Integer.MAX_VALUE`)를 먼저 멈추고 그다음 admission을 닫도록 설계됐다(`MessagingShutdownLifecycle.java:109-123`, phase `MAX_VALUE - 1024`). 앱은 vendored relay를 만들지 않는다(`OutboxRepository` bean을 만드는 production 코드 없음). + - Spring 7.0.9에서 `@Scheduled` 작업은 `ContextClosedEvent`에 `cancel(false)`로 취소된다(`ScheduledAnnotationBeanPostProcessor` 597·613행). 실행 중인 relay 회차는 계속 돈다. scheduler executor의 lifecycle phase는 `Integer.MAX_VALUE / 2`다(`ExecutorConfigurationSupport` 75행). + - 그래서 종료 순서는 "admission 닫기(MAX-1024) → scheduler가 실행 중 회차를 기다림(MAX/2) → bean destroy(registry·transport close)"다. 실행 중 회차의 남은 row는 `SHUTTING_DOWN`, `RUNTIME_NOT_INSTALLED`, `KAFKA_TRANSPORT_CLOSED` 순으로 거부된다. 06-01 때문에 모두 DEAD가 된다. + - `MessagingShutdownLifecycle` 주석은 이 상황을 "row가 ambiguous가 된다"고 설명한다(`:113-116`). 앱 경로에서는 DEAD가 된다. 주석과 실제가 다르다. +- 발생 조건: SIGTERM 순간 relay 회차가 진행 중. 적체가 있거나 broker가 느리면 회차가 길어 확률이 커진다(배치 20 × publish 최대 약 10초). +- 영향: 06-01이 있는 지금은 배포마다 일부 row가 DEAD가 될 수 있다. 06-01을 고쳐도 시도 예산을 쓰고 FAILED 경고를 남긴다. +- 심각도·우선순위: Medium / P1. 단독 영향은 중간이지만 06-01과 같이 고쳐야 배포 경로가 안전해진다. +- 확실성: 순서는 Spring 소스와 phase 값으로 확인했다(E1). 실제 종료 실측은 하지 않았다. +- 결정의 근거: 확인된 사실은 위와 같다. 기록된 의도는 "relay가 먼저 멈춘다"(`MessagingOutboxRelayLifecycle.java:55-68`)이다. 리뷰어 추론: vendored relay를 기준으로 설계한 뒤 앱 relay가 composition으로 옮겨지면서(2026-09-28) 이 순서에 들어가지 않았다. +- 이해 비용: 운영자가 배포 후 DEAD를 보면 원인을 broker에서 찾게 된다. 종료 순서를 알아야 원인을 찾는다. +- 최소 개선 방향: `OutboxRelayScheduler`를 SmartLifecycle로 바꾸고 phase를 `MessagingShutdownLifecycle`보다 높게 둔다. stop에서 진행 중 회차를 끝내고 새 회차를 막는다. 남은 claim은 lease를 놓아(release) 다른 인스턴스가 바로 가져가게 한다. + - 대안 비교: (a) 현상 유지 + 06-01만 수정 — 비용 최소, 배포마다 FAILED 잡음과 시도 소비가 남는다. (b) scheduler executor phase를 올리기 — 전역 설정이라 다른 `@Scheduled` 작업까지 바뀐다. (c) relay 전용 SmartLifecycle — 범위가 relay에 한정된다. (c)를 고른다. +- 비용·부작용: relay 루프를 직접 소유하게 된다. `@Scheduled` 의존이 사라지므로 `@EnableScheduling` 결정(L-1)도 함께 다시 본다. +- 재검토 조건: relay를 별도 프로세스(worker 배포 단위)로 분리하면 이 순서 문제는 그 프로세스의 종료 절차로 옮겨 간다. +- 완료 기준: 종료 중에 claim된 row가 DEAD가 되지 않고, PUBLISHED 또는 lease 해제 상태로 남는다. +- 검증 방법: 컨텍스트 테스트에서 relay 회차를 막아 둔 채 `context.close()`를 호출하고 row 상태를 단언한다. + +### 06-03 — broker가 몇 분만 멈춰도 row가 대량으로 DEAD가 되고 복구는 수작업이다 + +- 성격: 구조적 위험 +- 관련 관점: 28, 6, 7, 19, 14 +- 근거 + - 시도 예산은 고정 3회, 기본 지연 30초다(`OutboxBackoffPolicy.java:24,27`). 실패 지연은 1회차 30–60초, 2회차 60–90초다. + - 지연의 기준 시각은 회차 시작 시각이다(`PublishPendingOutboxEventsUseCase.java:99`의 `now`를 `:176`에서 사용). broker가 멈추면 publish 하나가 약 5초(`max.block.ms` 5s 또는 publish deadline 5s) 걸린다. 배치 20개면 회차 하나가 약 100초다. 그래서 뒤쪽 row는 FAILED로 표시되는 순간 이미 재시도 시각이 지나 있다. 다음 회차에 바로 다시 시도된다. + - 계산(추론): 전면 장애에서 row 하나가 DEAD까지 가는 데 약 3회차, 대략 5분이다. 5분 넘는 broker 장애는 그동안 claim된 모든 head row를 DEAD로 만든다. + - `AMBIGUOUS`(전송됐을 수 있음)도 시도를 쓴다(`:143-147`). 장애 동안 실제로는 저장된 메시지도 DEAD가 될 수 있다. 코드 주석은 "parking it loses a message that was delivered"라며 이 결과를 피하려 하지만 3회 뒤에는 결국 parking한다. + - 복구 절차는 row마다 `UPDATE`다(`docs/runbooks/outbox-dead-letter.md:39-41`). runbook의 차단 범위 조회(`:27`)는 `aggregate_id`·`occurred_at` 기준이라 현재 FIFO 키 `(tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index)`와 다르다. + - 상수를 바꾸면 registry와 runbook을 같이 바꿔야 한다는 결정(I10)이 있다(`application-core/README.md` OutboxBackoffPolicy 절). +- 발생 조건: Kafka 장애·네트워크 단절이 약 5분 이상. +- 영향: 장애가 끝나도 이벤트 발행이 자동으로 재개되지 않는다. 장애 동안 이벤트를 만든 모든 aggregate가 운영자 개입 전까지 멈춘다. +- 심각도·우선순위: High / P2. 지원 장애 조건에서 중요한 기능이 멈춘다. 데이터는 남아 있고 경보(`outcome=DEAD`)와 수동 절차가 있어 P2로 둔다. +- 통제 수준: M1(runbook·경보 문서), 자동 복구 M0. 증거 E1 + 계산. +- 결정의 근거: 기록된 의도는 "상수를 runbook과 맞춘다"이다. 장애 길이와 예산의 관계는 기록되어 있지 않다. +- 최소 개선 방향 + - (a) 재시도 시각을 실패 시점 `clock.instant()`로 계산한다. 비용이 가장 작고 예산이 의도한 시간만큼 유지된다. + - (b) `AMBIGUOUS`와 broker 도달 불가류 실패는 시도 예산을 쓰지 않고 상한 있는 지연(예: 최대 5분)으로 계속 재시도한다. 예산은 payload 자체의 거부에만 쓴다. + - (c) DEAD 일괄 재구동 절차(조건별 `UPDATE`와 차단 범위 조회)를 runbook에 현재 FIFO 키로 고친다. + - 버린 대안: `MAX_ATTEMPTS`만 늘리기. 장애 길이에 비례해 숫자를 계속 키워야 하고, 진짜 poison row가 늦게 격리된다. +- 재검토 조건: relay가 per-row 지연 대신 broker 상태(circuit)를 보고 회차를 건너뛰게 되면 (b)는 불필요할 수 있다. +- 완료 기준: broker가 10분 멈췄다가 돌아오면 운영자 개입 없이 PENDING/FAILED가 PUBLISHED로 간다. +- 검증 방법: 시계를 주입한 relay 테스트로 장애 10분을 흉내 낸다. 실제 확인은 Toxiproxy lane(이미 vendored 쪽에 있다)에 앱 relay를 올려서 한다(06-09). + +### 06-04 — aggregate 하나의 발행 속도가 poll 주기당 1건으로 묶인다 + +- 성격: 구조적 위험(성능) +- 관련 관점: 14, 13, 5 +- 근거 + - claim은 aggregate마다 가장 앞 row 하나만 고른다(`PostgreSqlOutboxClaimRepository.java:27-36`). + - relay는 tick마다 한 번만 claim한다. 배치가 꽉 차도 바로 다음 claim을 하지 않는다(`OutboxRelayScheduler.java:36-39`, fixed-delay `PT5S`). + - 그래서 e1이 이번 회차에 발행돼도 e2는 다음 tick까지 기다린다. + - 계산(추론): aggregate 하나는 최대 0.2건/초다. 인스턴스 하나는 최대 20건/5초 ≈ 4건/초다. aggregate 하나에 이벤트 100건이 쌓이면 비우는 데 약 8분 이상 걸린다. + - 한 회차의 DB 왕복은 claim 1 + row마다 UPDATE(claim flush) + row마다 완료 트랜잭션 1 + 지표 GROUP BY 2다. 배치 20이면 약 43문장이다. +- 발생 조건: 한 aggregate가 초당 0.2건 넘게 이벤트를 만들거나, 백로그가 인스턴스당 초당 4건을 넘는다. +- 영향: `outbox.publisher.lag`가 계속 늘어난다. 하류 소비가 분 단위로 늦어진다. +- 심각도·우선순위: Medium / P2. 업무 부하에 따라 달라진다. 템플릿 기본값이 그대로 복제된다. +- 통제 수준: 처리량 상한을 알리는 문서·검사 없음(M0). 증거 E1 + 계산. 실측 안 함. +- 최소 개선 방향: 배치가 꽉 찼으면 다음 tick을 기다리지 않고 곧바로 다시 claim한다(상한 있는 반복). aggregate 안 처리량이 필요하면 claim에서 aggregate별로 "앞 row가 같은 lease에 잡힌 경우" 다음 row까지 함께 가져오는 방법을 비교한다. + - 버린 대안: poll 주기만 줄이기. 빈 tick마다 DB 질의와 지표 질의가 늘어난다. +- 재검토 조건: 목표 처리량을 합의하면 그 수치로 다시 판단한다. +- 완료 기준: 백로그 상태에서 인스턴스 처리량이 poll 주기에 묶이지 않는다. 처리량 상한을 README에 숫자로 적는다. +- 검증 방법: PostgreSQL 통합 테스트에서 같은 aggregate 이벤트 N건이 몇 번의 relay 호출로 비워지는지 센다. + +### 06-05 — relay가 꺼져 있거나 실패하는 동안 outbox 지표가 갱신되지 않는다 + +- 성격: 확인된 결함 +- 관련 관점: 7, 8, 10, 5 +- 근거 + - relay 기본값은 꺼짐이다(`persistence-jpa.yml:190` `${APP_OUTBOX_RELAY_ENABLED:false}`, `OutboxSettings.java:39-43`). + - `outbox.pending.size`·`outbox.publisher.lag` 갱신은 relay scheduler 안에서만 일어난다(`OutboxRelayScheduler.java:48-49`가 유일한 호출자). + - relay 회차가 예외로 끝나면 catch로 가서 지표 갱신을 건너뛴다(`:39-58`). DB 장애 동안 게이지가 마지막 값에 멈춘다. + - 실험 2: 지표 호출 두 줄을 막아도 `composition:outbox-relay` 테스트 18개가 모두 통과했다. `OutboxMetrics` 단위 테스트가 없다. + - 대비: vendored relay는 "relay를 잊으면 조용히 실패한다"를 문제로 적고 lifecycle로 강제한다(`MessagingOutboxRelayLifecycle.java:11-13`). +- 발생 조건: messaging을 고르고 `APP_OUTBOX_RELAY_ENABLED`를 빠뜨린 배포. 또는 relay가 매 회차 예외를 던지는 장애. +- 영향: row가 쌓여도 `outbox_publisher_lag` 경보가 울리지 않는다. runbook의 감지 조건(`outbox-publish-failed.md:21-23`)이 성립하지 않는다. +- 심각도·우선순위: Medium / P2. +- 통제 수준: M0(감지 경로가 relay 실행에 종속). 증거 E2(변이 실험). +- 결정의 근거: 적용 제외 — 지표 수집 위치를 relay에서 떼어 내는 단순 결함이다. +- 최소 개선 방향: 게이지 갱신을 relay와 독립된 주기 작업(또는 Micrometer gauge의 지연 조회)으로 옮긴다. relay가 꺼져 있고 발행 포트가 있으면 기동 시 WARN 한 줄을 남긴다. `OutboxMetrics` 테스트를 추가한다. +- 완료 기준: relay가 꺼진 상태에서도 `outbox.pending.size{status=PENDING}`가 실제 행 수를 보여 준다. +- 검증 방법: relay를 끈 컨텍스트 테스트에서 PENDING row를 넣고 게이지 값을 단언한다. 실험 2 변이가 죽는지 확인한다. + +### 06-06 — application EventId 문법과 platform MessageId(UUID)가 다르다 + +- 성격: 확인된 결함(잠재) +- 관련 관점: 17, 1, 5, 22 +- 근거 + - application은 `[A-Za-z0-9][A-Za-z0-9._:-]*` 1–96자를 받는다(`EventId.java:6-12`). + - bridge는 `UUID.fromString`으로 바꾼다. UUID가 아니면 `IllegalArgumentException` → `REJECTED_BEFORE_SEND` → DEAD다(`PlatformIntegrationEventPublishAdapter.java:62-67,132-134`). 기존 테스트도 `"event-1"`이 REJECTED가 됨을 단언한다. + - `SubmitDurableOperationUseCase.canonicalIdentity`는 UUID가 아닌 operation id를 `"operation-" + sha256`으로 바꾼다(`SubmitDurableOperationUseCase.java:167-173`). 이 값은 UUID가 아니므로 이 경로로 들어온 이벤트는 항상 DEAD다. 지금은 HTTP adapter가 UUID만 만들어 도달하지 않는다(`DurableOperationController.java:86`). +- 발생 조건: UUID가 아닌 operation id(새 inbound adapter, 클라이언트 지정 id) 또는 UUID가 아닌 event id를 만드는 use case. +- 영향: append는 성공하고 비즈니스 트랜잭션은 커밋된다. 실패는 나중에 relay에서 DEAD로 나타나고 aggregate를 막는다. 원인이 호출 지점과 멀다. +- 심각도·우선순위: Medium / P2. +- 통제 수준: M0. 증거 E1(+ 기존 bridge 테스트). +- 최소 개선 방향: 둘 중 하나로 계약을 맞춘다. (a) application `EventId`를 UUID로 좁힌다. 비용이 작고 실패가 append 시점으로 당겨진다. (b) bridge가 비 UUID id를 결정적 UUIDv5로 바꾼다. 소비자가 보는 id가 원래 값과 달라진다. 소비자 중복 제거 키가 event id라는 계약(`application-core/README.md`)을 지키려면 (a)가 낫다. `canonicalIdentity`의 digest 경로는 (a)에 맞춰 UUIDv5로 바꾼다. +- 완료 기준: bridge가 거부할 id는 `IntegrationEventDraft` 생성 또는 encode 단계에서 거부된다. +- 검증 방법: 비 UUID event id로 encode를 호출하면 예외가 나는 테스트. + +### 06-07 — 샘플이 aggregate 순서 번호를 벽시계로 만든다 + +- 성격: 구조적 위험 +- 관련 관점: 12, 1, 11, 20 +- 근거 + - `PortfolioEventOutbox.java:92,98-105`가 `AggregateOrder(sequenceOf(occurredAt), 0)`으로 순서를 만든다. 값은 epoch 마이크로초다. + - FIFO gate는 이 번호로 앞뒤를 정한다(`PostgreSqlOutboxClaimRepository.java:33-35`). + - `(tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index)`에 유일 제약이 없다(V3·V13·V18·V19 확인, PK는 `event_id`뿐). + - 설계 문서는 "strict aggregate ordering은 timestamp가 아니라 explicit aggregate sequence를 요구한다"고 적는다(`docs/superpowers/specs/2026-07-28-messaging-production-capability-design.md:595`). +- 발생 조건: 같은 aggregate를 두 인스턴스가 연달아 바꾸고 두 서버 시계가 어긋남. 또는 NTP가 시계를 되돌림. 또는 같은 마이크로초에 두 이벤트. +- 영향: 나중에 커밋된 변경의 이벤트가 먼저 나간다. 같은 번호 두 개는 서로를 막지 않아 순서가 정해지지 않는다. 소비자의 "마지막 상태" 판단이 틀린다. +- 심각도·우선순위: Medium / P2. 샘플은 새 기능의 복사 원본이다. +- 통제 수준: M1(설계 문서), 코드 M0. 증거 E1. +- 최소 개선 방향: 샘플에서 aggregate의 버전(낙관적 락 version) 또는 DB 시퀀스를 순서 번호로 쓴다. outbox에 순서 키 유일 제약을 추가해 중복 번호를 append 시점에 거부한다. + - 버린 대안: 순서를 `occurred_at`으로만 두기. 지금 바로 이 문제다. +- 완료 기준: 샘플의 순서 번호가 aggregate 쓰기와 같은 트랜잭션에서 단조 증가한다. 같은 번호 두 번 append는 실패한다. +- 검증 방법: 같은 aggregate에 같은 순서 번호 두 건 append → 제약 위반 테스트. 샘플 use case 테스트에서 연속 변경의 번호가 증가하는지 단언. +- 비고: 소유 leaf는 `sample-portfolio`·`persistence-jpa`다. 계약은 이 영역의 FIFO 의미라서 여기 적는다. + +### 06-08 — 소비(consume)를 지원한다는 결정이 application 쪽 경로로 이어지지 않는다 + +- 성격: 구조적 위험(기능 개발 경로 공백) +- 관련 관점: 2, 20, 25, 17 +- 근거 + - 소유자 결정 10: "Kafka 소비 지원. `MessageHandler` 하나 + starter-kafka가 consumer 조립"(followup-status:38). + - inbox 중복 제거는 `IdempotentConsumer` bean이 있어야 한다(`MessagingConsumeConfiguration.java:137-144`, 문서 `docs/messaging/outbox-inbox.md:115-119`). 이 타입은 `messaging-reliability`에 있다. + - registry에서 `messaging-reliability`·`messaging-reliability-jdbc-postgresql`로 가는 application leaf 간선이 없다. bridge leaf는 `messaging-core-api`만 볼 수 있다(`modules.json` `:adapter:outbound:messaging`). `adapter:inbound:*`에 messaging leaf가 없다. + - 저장소 전체에서 application 쪽 `MessageHandler` 구현·예제가 0건이다. + - 소비자 중복 제거 의무는 문서에만 있다(`adapter/outbound/messaging/README.md` "중복 가능 구간", runbook `outbox-dead-letter.md:40`). +- 발생 조건: 파생 서비스가 이벤트 소비 기능을 처음 만든다. +- 영향: 어디에 handler를 둘지, inbox를 어떻게 조립할지 템플릿이 답하지 않는다. 각 팀이 registry 간선을 임의로 늘리거나 중복 제거 없이 소비한다. +- 심각도·우선순위: Medium / P2. +- 통제 수준: M1(문서). 증거 E1. +- 결정의 근거: 기록된 의도는 "지원"이다. 현재 코드는 platform 안에서만 지원한다. 리뷰어 추론: consumer 조립은 platform 조립 경계(starter)에서 끝났고 application 경계 설계가 남았다. +- 최소 개선 방향: `adapter:inbound:messaging`(가칭) leaf를 registry에 추가하고 `messaging-core-api`와 inbox 조립용 edge를 준다. 그 leaf가 application 포트(예: `IntegrationEventHandlerPort`)를 platform `MessageHandler`로 감싸는 bridge를 소유한다. 예제 handler 하나와 INBOX_TRANSACTIONAL destination 예시를 둔다. + - 버린 대안: app-bootstrap에서 직접 handler bean 등록. composition root에 업무 handler가 들어가 HARD-STOP 4에 가까워진다. +- 완료 기준: 샘플 이벤트 하나를 소비하는 handler가 inbox로 중복을 거르고, registry gate를 통과한다. +- 검증 방법: Kafka+PostgreSQL 통합 테스트로 같은 메시지 두 번 전달 시 부작용 1회. + +### 06-09 — 실제로 쓰는 발행 경로에는 broker 실연 테스트가 없고, broker 실연 lane은 어떤 기본 게이트에도 없다 + +- 성격: 확인된 결함(검증 공백) +- 관련 관점: 10, 21, 18 +- 근거 + - 앱 경로 `PublishPendingOutboxEventsUseCase → OutboxMessagePublishAdapter → PlatformIntegrationEventPublishAdapter → DefaultMessagePublisher → Kafka`를 한 번에 도는 테스트가 없다. `PublishPendingOutboxEventsUseCase`를 쓰는 통합 테스트는 PostgreSQL + fake publisher뿐이다(`persistence-jpa/src/postgresqlIntegrationTest/.../readiness/*`). 앱 leaf 쪽 Kafka Testcontainers 사용은 0건이다. + - Kafka 실연 테스트(`KafkaBrokerIT`, `KafkaAmbiguityChaosIT`, `MessagingLiveRoundTripQualificationTest` 등)는 vendored relay나 publisher 직접 호출을 검증한다. 앱은 vendored relay를 쓰지 않는다. + - 이 lane들은 `integrationCheck`에만 묶인다(`src/build.gradle:100-105`). `mainCheck` 로그에서 messaging `integrationTest`는 컴파일만 됐다(`mainCheck.log:246-292`). + - 06-01은 각 고리의 단위 테스트가 서로 다른 가정(retryable REJECTED / REJECTED=확정)을 단언하면서 통과해서 숨어 있었다. +- 영향: 앱 경로의 실패 분류·종료·재시도가 실제 broker와 맞는지 아무 게이트도 확인하지 않는다. +- 심각도·우선순위: Medium / P2. +- 통제 수준: M0(앱 경로). 증거 E1. +- 최소 개선 방향: `adapter:outbound:messaging-kafka`에 Kafka+PostgreSQL 통합 lane 하나를 두고 앱 relay를 실제로 돌린다: 정상 발행, broker 정지 후 재개(06-03), 종료 중 회차(06-02). lane은 CI 방향 결정에 따라 `mainCheck` 단계에 지정한다. + - 버린 대안: vendored relay 테스트를 앱 증거로 인용하기. 다른 코드다. +- 완료 기준: 앱 relay가 실제 Kafka로 발행한 레코드를 테스트가 읽어 envelope 바이트를 비교한다. 이 lane이 이름 있는 게이트에 들어 있다. +- 검증 방법: 그 lane의 실행 로그. + +### NN-10 — 이벤트 payload 버전을 올리는 방법과 호환성 검사가 없다 + +- 성격: 구조적 위험 +- 관련 관점: 17, 11, 20 +- 근거 + - encoder catalog는 `(contractId, payloadVersion)`을 키로 여러 버전을 함께 둘 수 있다(`JsonIntegrationEventEncoder.java:98,157-161`). + - 버전 사이 호환성 검사가 없다. 기동 시 검사는 선언 hash와 classpath schema 파일의 일치뿐이다(`src/messaging/CLAUDE.md` "IntegrationEventEncoderPort" 절). + - platform의 `schema.compatibility`는 선언만 한다(`docs/messaging/configuration-reference.md:123`). + - payload v2를 추가하는 절차 문서가 없다. `payloadVersion`을 설명하는 문서는 `application-core/README.md:28` 한 줄이다. + - outbox에 이미 쌓인 v1 row는 저장된 바이트 그대로 나간다(`JpaOutboxStore.java:197-235`). 이 점은 옳다. 다만 소비자가 v1·v2를 함께 받는 기간이 생긴다는 사실이 적혀 있지 않다. +- 발생 조건: 기존 이벤트에 필드를 바꾸거나 지우는 변경. +- 영향: 깨지는 schema 변경이 게이트를 통과한다. 소비자가 배포 순서에 따라 실패한다. +- 심각도·우선순위: Medium / P2. +- 통제 수준: M0. 증거 E1. +- 최소 개선 방향: 같은 contract의 직전 버전 schema와 새 schema를 비교하는 테스트 fixture를 `shared-contract` 또는 `adapter:outbound:support` testFixtures에 두고, contract를 추가할 때 그 테스트를 함께 만들게 한다. 버전 올리기 절차(새 버전 추가 → 소비자 배포 → 생산자 전환 → 옛 버전 제거)를 README에 적는다. + - 버린 대안: 외부 schema registry 도입. 이 템플릿 범위에 비해 운영 비용이 크다. +- 완료 기준: 필드 삭제 같은 깨지는 변경이 테스트에서 실패한다. +- 검증 방법: 샘플 contract에 깨지는 v2를 넣는 변이 실험. + +### NN-11 — outbox가 둘인데 문서와 주석은 하나처럼 말한다 + +- 성격: 개선 제안(이해 비용) +- 관련 관점: 4, 5, 23, 24 +- 근거 + - `docs/messaging/configuration-reference.md:28-33`: "outbox는 canonical 하나다". + - 같은 폴더 `docs/messaging/outbox-inbox.md:28-60`은 vendored `messaging_outbox`와 그 relay(`REJECTED → markFailed`, 종단)를 "Outbox"로 설명한다. 앱이 쓰는 `outbox_event`·`composition:outbox-relay`는 `docs/messaging`에 언급이 없다. + - 두 모델은 같은 이름의 상태가 반대 뜻이다. `OutboxPublishOutcome.java` javadoc이 "naming trap between the two outbox models is real"이라고 직접 경고한다. + - vendored relay·lifecycle·cleanup bean 정의와 DDL은 runtime classpath에 있다(`messaging-spring-boot-starter/build.gradle:41-42` `implementation`). 조건이 맞지 않아 bean은 안 생긴다. + - `MessagingShutdownLifecycle.java:113-116`은 존재하지 않는 relay를 전제로 순서를 설명한다(06-02). +- 영향: 새 개발자가 `docs/messaging`을 읽고 앱 outbox의 동작을 잘못 예측한다. DEAD/FAILED 의미를 반대로 읽는다. +- 심각도·우선순위: Medium / P3. +- 통제 수준: M1(경고 주석 한 곳). 증거 E1. +- 결정의 근거: 소유자 결정은 "messaging outbox 유지"다. 이 항목은 유지 자체가 아니라 두 모델의 경계 표시를 다룬다. +- 최소 개선 방향: `docs/messaging/outbox-inbox.md` 맨 앞에 "이 문서는 vendored platform outbox다. 이 템플릿의 application은 `outbox_event`와 `composition:outbox-relay`를 쓴다"를 적고 앱 outbox 문서로 연결한다. 두 상태 이름 대응표를 한 곳에 둔다. `configuration-reference.md`의 "하나다"를 "application 경로는 하나다"로 고친다. +- 완료 기준: `docs/messaging`에서 앱 outbox 문서로 가는 링크가 있고, 상태 대응표가 하나 있다. +- 검증 방법: 문서 리뷰. + +### NN-12 — 배치 크기와 lease 시간의 관계를 검사하지 않는다 + +- 성격: 구조적 위험 +- 관련 관점: 12, 19, 21 +- 근거 + - 회차 하나의 최악 시간은 배치 크기 × (송신 전 대기 5s + 응답 대기 5s)다(`KafkaMessagingAutoConfiguration.java:203-206`, `PublishOptions` 기본 5s). 기본값 20이면 약 200초다. + - lease는 `in-flight-timeout` 기본 5분이다(`persistence-jpa.yml:196`). 지금은 여유가 있다. + - `OutboxSettings`는 각 값을 따로 검사한다(`OutboxSettings.java:35-53`). `batch-size: 40`이면 최악 약 400초로 lease를 넘는다. 그러면 다른 인스턴스가 row를 다시 claim해 같은 이벤트를 또 보낸다. 늦은 쪽은 STALE이 된다(fencing은 상태 덮어쓰기만 막는다). +- 영향: 설정 하나로 다중 인스턴스 중복 발행이 정상 운영 중에 생긴다. +- 심각도·우선순위: Medium / P3. 기본값에서는 발생하지 않는다. +- 통제 수준: M0. 증거 E1 + 계산. +- 최소 개선 방향: 기동 시 `batchSize × 2 × publishDeadline < inFlightTimeout`을 검사하고 어기면 기동을 거부한다. 또는 relay가 회차 중 남은 lease를 보고 남은 row를 놓는다. +- 완료 기준: lease를 넘을 수 있는 설정 조합이 기동에서 거부된다. +- 검증 방법: `OutboxSettings` 바인딩 테스트에 경계 조합 추가. + +### NN-13 — 이 영역 문서·주석의 낡은 설명 + +- 성격: 개선 제안 +- 관련 관점: 24, 9, 26 +- 근거 + - `OutboxRelayScheduler.java:15` "Registered by `OutboxConfig`"(실제 `OutboxRelayAutoConfiguration`). + - `PublishPendingOutboxEventsUseCase.java:27` "Wired manually by `app-bootstrap`"(실제 `composition:outbox-relay`). + - `adapter/outbound/messaging/README.md:73-77` 검증이 "build-tools로 옮겼다", `VerifyMessagingEvidenceTask`(둘 다 없음. 실제는 루트 `src/build.gradle:140` `verifyMessagingContracts`). + - `adapter/outbound/messaging/CLAUDE.md:8` "Spring Boot 4.0.0"(실제 4.0.8). + - `docs/runbooks/outbox-dead-letter.md:27` 차단 범위 조회가 옛 FIFO 키 사용(06-03). + - `OutboxLeaderElectionToken.java:4-5` "presence satisfies the multi-instance coordination requirement". 이 bean을 요구하는 검사가 없다. 리더 선출도 하지 않는다(row 단위 claim이다). + - `composition:outbox-relay`, `adapter:outbound:messaging-kafka`에 `CLAUDE.md`가 없다(README만 있음). +- 심각도·우선순위: Low / P3. +- 최소 개선 방향: 위 문장을 현재 위치로 고친다. `OutboxLeaderElectionToken`은 지우거나 이름을 `OutboxClaimStrategy`처럼 실제 동작으로 바꾼다. +- 완료 기준: 위 위치의 설명이 코드와 맞는다. +- 검증 방법: 문서 리뷰. + +### NN-14 — DLQ 격리 레코드가 모든 원인을 `POISON_MESSAGE`로 적는다 + +- 성격: 개선 제안 +- 관련 관점: 8, 28 +- 근거: `KafkaDeadLetterQuarantine.java:41-47`. 복원 불가 레코드와 "시도 예산 소진"(일시 장애로 handler가 계속 실패한 경우)을 같은 category로 적는다. +- 영향: redrive 판단 때 원인을 구분하지 못한다. 일시 장애로 격리된 메시지를 poison으로 오해한다. +- 심각도·우선순위: Low / P3. +- 최소 개선 방향: 호출자가 사유 category를 넘기게 한다(`UNDECODABLE` / `ATTEMPTS_EXHAUSTED`). +- 완료 기준: 두 경로가 다른 header 값을 남긴다. +- 검증 방법: `KafkaConsumerRegistrarTest`에 header 단언 추가. + +## 4. 31절 시나리오 추적 + +### 4.1 정상 쓰기 → 발행 (`POST` durable operation) + +| 항목 | 내용 | +| --- | --- | +| 입력 신뢰 수준 | HTTP 본문은 외부 입력이다. operation id는 서버가 UUID로 만든다(`DurableOperationController.java:86`) | +| 인가 위치 | web adapter(이 영역 밖). relay는 `@RequiresPermission("outbox:relay")`가 붙어 있지만 bean이 아니라 관례로만 지킨다 | +| 규칙 소유 객체 | 이벤트 생성 규칙: `SubmitDurableOperationUseCase`. 봉투 규칙: `JsonIntegrationEventEncoder`. 순서 규칙: FIFO gate(SQL) | +| 트랜잭션 | `transactions.inWrite` 하나 안에서 operation 저장과 `outbox.append`(`SubmitDurableOperationUseCase.java:106-140`). append는 caller 트랜잭션이 없으면 거부한다(`JpaOutboxStore.java:61`) | +| 외부 부작용 | 요청 안에서는 없다. relay가 커밋 뒤 비동기로 Kafka에 보낸다 | +| 성공의 의미 | 202 응답은 "operation과 발행 의도가 함께 커밋됨"이다. 발행 완료가 아니다 | +| 오류 변환 | 발행 실패는 요청에 영향이 없다. relay에서 FAILED/DEAD로 남고 `Slf4jOutboxRelayFailureReportAdapter`가 ERROR 한 줄을 남긴다 | +| 진단 정보 | `correlation_id`(= operation id), `event_id`, `outbox.*` 지표. 단 relay가 꺼져 있으면 지표가 안 움직인다(06-05) | + +원자성 판정: outbox 기록과 비즈니스 쓰기는 같은 JPA 트랜잭션에서 커밋된다. `CallerTransaction.require`가 경계에서 강제한다(M4, 이 경로 한정). 비즈니스 저장소가 JPA가 아닌 경우(Mongo 등)의 원자성은 다른 영역에서 확인해야 한다(>). + +### 4.2 메시지 중복·역순 + +- 중복: lease 만료 재claim, `markPublished` 실패, AMBIGUOUS 재시도에서 같은 event id로 다시 나간다. 소비자 중복 제거가 필요하지만 application 쪽 소비 경로가 없다(06-08). +- 역순: FIFO gate는 aggregate마다 head 하나만 내보낸다. relay는 응답을 기다린 뒤 다음 row로 간다(`OutboxMessagePublishAdapter.java:43` `join`). Kafka producer는 idempotence를 켠다(`KafkaMessagingAutoConfiguration.java:184-190`). 그래서 순서 번호가 맞으면 역순은 없다. 순서 번호 자체가 벽시계면 역순이 생긴다(06-07). + +### 4.3 여러 서버의 relay 실행 + +- claim은 `FOR UPDATE SKIP LOCKED`, 인스턴스마다 UUID owner, row마다 token 증가(`JpaOutboxStore.java:105-127`). +- 완료는 owner·token이 맞을 때만 적용된다. 아니면 STALE(`:136-162`). `PostgreSqlOutboxConcurrentRelayIntegrationTest`가 있다. +- 같은 aggregate의 두 row는 두 인스턴스가 동시에 가져갈 수 없다. 앞 row가 PUBLISHED가 아니면 뒤 row는 gate에 걸린다. +- 남은 위험: 배치 시간이 lease를 넘는 설정(NN-12). + +### 4.4 외부 응답 지연·유실 (Kafka 느림·정지) + +- 송신 전 대기 5s(`max.block.ms`), 응답 대기 5s(publish deadline)로 묶인다. relay thread가 무한정 막히지 않는다. +- deadline 초과는 AMBIGUOUS로 분류된다(`DefaultMessagePublisher.java:244-256`). 결과 불명을 "전송됐을 수 있음"으로 남기는 것은 옳다. +- 장애가 약 5분을 넘으면 DEAD가 대량으로 생긴다(06-03). + +### 4.5 종료·재시작 + +- 진행 중 relay 회차는 끝까지 돈다. 그러나 platform admission이 먼저 닫혀 남은 row가 DEAD가 된다(06-01, 06-02). +- 프로세스가 강제 종료되면 IN_FLIGHT row는 5분 뒤 다른 인스턴스가 가져간다. 이 경로는 설계대로다. +- consumer 쪽은 drain 마감 30s 뒤 미정산 메시지를 broker 재전달에 맡긴다(`MessagingShutdownLifecycle.java:21-28`). 앱 handler가 없어 앱 경로로는 확인 대상이 없다. + +### 4.6 신·구 버전 공존 + +- outbox row는 append 때의 바이트를 그대로 내보낸다. 배포가 바뀌어도 옛 row의 봉투는 변하지 않는다. +- destination 선언이 새 배포에서 빠지면 옛 row는 `PUBLISH_PREPARATION_FAILED` REJECTED → DEAD가 된다. 이것은 설정 오류라 확정 거부로 보는 것이 맞다. +- payload 버전 호환성 검사와 절차가 없다(NN-10). + +### 4.7 선택 어댑터 제거 + +- `app-bootstrap/build.gradle`에서 `messaging-kafka` 줄을 지우면 bridge·platform·Kafka client·기본 설정이 함께 빠진다(README 서술, `KafkaCapabilityActivationTest`). +- 발행 포트가 없으면 relay scheduler가 생기지 않고 PENDING row가 그대로 남는다(`OutboxRelayAutoConfiguration.java:62-64`). 대역 publisher가 row를 DEAD로 소진하지 않는다. 설계대로다. +- 이때 지표도 갱신되지 않아 적체가 보이지 않는다(06-05). + +### 4.8 적용 제외 + +| 시나리오 | 사유 | +| --- | --- | +| 세션·토큰 갱신 경쟁 | 이 영역에 사용자 세션이 없다 | +| 다른 사용자 리소스 접근 | 사용자 요청 경로가 없다. tenant는 봉투 필드로만 옮긴다 | +| 큰 입력·목록 조회 | payload 상한은 platform이 검사한다(`KafkaMessagingTransport.java:124-130`, admission). 목록 조회 API는 없다 | +| DB 오류·경쟁 | `markPublished` 실패 경로만 해당하며 4.3·README에 설명된 대로 IN_FLIGHT로 남아 재claim된다. 별도 추적 생략 | + +## 5. 41절 설계 선택 검토 + +### 5.1 application outcome 어휘: "REJECTED = 확정 거부 → 즉시 DEAD" + +1. 필요한 것: relay가 재시도할 실패와 재시도해도 소용없는 실패를 구분해야 한다. +2. 지킬 성질: 다시 보내면 성공할 수 있는 이벤트는 DEAD가 되면 안 된다. 다시 보내도 실패할 이벤트는 예산을 낭비하지 않는다. +3. 현재 보장: 4값 enum(`OutboxPublishOutcome`)과 bridge 번역. platform의 `retryable` 정보는 번역에서 버려진다. 성질 1을 지키지 못한다(06-01). +4. 대안: (a) 현상 유지, (b) 5번째 값 "전송 안 됨 + 재시도 가능", (c) REJECTED는 전부 retryable로 보고 예산으로 제한, (d) relay가 platform 타입을 직접 본다. +5. 비용: (a) 배포·장애마다 영구 정지 위험. (b) enum 값 하나와 relay 분기 하나. (c) 진짜 poison row가 3회 동안 aggregate를 막고 예산을 쓴다. (d) 경계가 깨진다. +6. 선택: (b). 의미를 잃지 않는 가장 작은 변경이다. +7. 재검토 조건: platform이 retryable REJECTED를 없애고 그 경우를 AMBIGUOUS가 아닌 별도 completion으로 바꾸면 (a)로 돌아가도 된다. + +### 5.2 relay 실행 방식: `@Scheduled` fixed-delay, tick당 claim 1회, aggregate당 head 1건 + +1. 필요한 것: 커밋된 이벤트를 순서대로, 다중 인스턴스에서 겹치지 않게 내보낸다. +2. 지킬 성질: aggregate 안 순서, 같은 row 동시 발행 금지, 종료 시 진행 중 row를 망가뜨리지 않음. +3. 현재 보장: 순서와 동시성은 SQL gate와 fencing으로 M4에 가깝게 지킨다. 종료 조율은 없다(06-02). 처리량은 poll 주기에 묶인다(06-04). +4. 대안: (a) 현상 유지, (b) relay 전용 SmartLifecycle 루프(배치가 차면 바로 다시 claim, stop에서 drain), (c) vendored `OutboxRelayWorker`로 교체, (d) CDC(Debezium). +5. 비용: (a) 0, 종료·처리량 문제 유지. (b) 루프 코드 소유, 테스트 필요. (c) outbox 모델·DDL·상태 의미 전환이 필요하고 소유자 결정 7(앱 outbox 하나)과 충돌한다. (d) 운영 인프라 추가, 2026-09-25에 삭제한 방향. +6. 선택: (b). 지금 결정과 충돌하지 않고 두 문제를 같이 줄인다. +7. 재검토 조건: relay를 별도 worker 배포 단위로 떼면 lifecycle 대신 그 프로세스의 종료 절차로 판단한다. 목표 처리량이 수백 건/초를 넘으면 (d)를 다시 비교한다. + +### 5.3 outbox 두 개 유지(소유자 결정) + +1. 필요한 것: application은 검증된 봉투를 같은 트랜잭션에 기록하는 outbox가 필요하다. platform은 제품으로서 자기 outbox를 가진다. +2. 지킬 성질: 개발자가 어느 outbox가 동작 중인지 헷갈리지 않는다. platform의 종료·지표 설계가 앱 경로에도 맞는다. +3. 현재 보장: bean 조건으로 vendored relay가 앱에서 생기지 않는다. 문서·종료 순서는 vendored relay 기준이다(06-02, NN-11). +4. 대안: (a) 결정 유지 + 경계 표시 보강, (b) vendored outbox를 starter `implementation`에서 빼서 opt-in 의존으로, (c) 하나로 합치기. +5. 비용: (a) 문서·주석 수정. (b) starter 의존 정리와 vendored 테스트 classpath 조정. (c) 결정 번복. +6. 선택: (a)를 먼저, (b)는 다음 단계 후보. 결정은 유지한다. +7. 재검토 조건: 앱이 vendored relay의 기능(claim-check, ordering key 등)을 필요로 하면 다시 비교한다. + +## 6. 리팩토링 후보 + +| 대상 | 무엇을 왜 | 단순화의 보존 조건 | +| --- | --- | --- | +| `OutboxRelayScheduler` + `OutboxRelayAutoConfiguration` | `@Scheduled`를 relay 전용 lifecycle 루프로 바꾼다(06-02, 06-04) | 발행 포트가 없으면 relay가 없다. `relay-enabled=false`면 relay가 없다. 예상 못 한 예외에도 루프가 산다. 같은 ERROR 필드(`retry.disposition=next-tick`)를 남긴다. 회차가 겹치지 않는다 | +| `OutboxMetrics` | relay에서 떼어 내 독립 갱신(06-05) | PUBLISHED는 세지 않는다. `MeterRegistry`가 없으면 no-op. event type이 사라지면 series를 덮어쓴다 | +| `OutboxLeaderElectionToken` | 소비자 없는 marker. 지우거나 실제 동작 이름으로 | `BootstrapCapabilityReachabilitySystemTest.java:30`의 단언을 함께 고친다 | +| `PlatformIntegrationEventPublishAdapter.mapOutcome` | retryable 정보를 보존하는 번역(06-01) | CONFIRMED·AMBIGUOUS 번역은 그대로. transmission 근거로 before/after를 나누는 규칙 유지. 문자열 비교 금지(MSG-022) | +| starter 테스트 리소스 2개 | 참조 없는 옛 prefix fixture 삭제(M-8a) | 없음 | + +## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료) + +### 템플릿이 주는 틀 + +- 새 이벤트 발행: `IntegrationEventContractContribution` bean 등록 → use case에서 `IntegrationEventDraft` 생성 → `IntegrationEventEncoderPort.encode` → 같은 `inWrite` 안에서 `OutboxAppendPort.append`. 예시는 `SubmitDurableOperationUseCase`(단건 aggregate)와 sample `PortfolioEventOutbox`(여러 이벤트). +- destination 선언: `app.messaging.destinations.`(`docs/messaging/configuration-reference.md`). +- 발행 켜기: `runtimeOnly project(':adapter:outbound:messaging-kafka')`, `APP_MESSAGING_PRODUCER_ID`, `APP_MESSAGING_KAFKA_BROKERS`, `APP_OUTBOX_ENABLED=true`, `APP_OUTBOX_RELAY_ENABLED=true`. +- fake: application-core testFixtures `InMemoryOutboxStore`, 계약 `OutboxLeaseFencingContract`. + +### 빠진 것 + +- 이벤트 소비(handler 위치, inbox 조립) 예제와 leaf(06-08). +- aggregate 순서 번호를 만드는 올바른 예(06-07). +- payload 버전 올리기 절차와 호환성 테스트(NN-10). +- 앱 relay를 실제 Kafka로 돌리는 테스트 틀(06-09). +- `MessagePublisher` fake와 본체의 공통 계약(TEST-FAKE-MessagePublisher). + +### 개발자가 내려야 하는 판단 + +1. 이 이벤트의 aggregate는 무엇이고 순서 번호는 어디서 오는가? 벽시계가 아니라 aggregate version이나 DB 시퀀스를 쓴다. +2. event id는 무엇으로 만드는가? 소비자 중복 제거 키가 되므로 재시도해도 같은 값이 나와야 한다. 지금 bridge는 UUID만 받는다(06-06). +3. 이 이벤트는 발행 완료를 기다려야 하는 요청인가? 아니라면 202 + outbox. 기다려야 하면 outbox만으로는 요구를 못 채운다(가이드 41.6). +4. payload를 바꾸는가? 바꾸면 새 `payloadVersion`을 추가하고 소비자가 먼저 두 버전을 읽게 한다. +5. 이 destination의 소비자는 부작용이 있는가? 있으면 INBOX_TRANSACTIONAL을 쓴다. +6. 한 aggregate가 초당 몇 건을 만드는가? 0.2건/초를 넘으면 현재 relay 기본값으로는 지연이 쌓인다(06-04). +7. relay를 몇 개 인스턴스에서 켤 것인가? batch-size를 올리면 lease 시간과 함께 계산한다(NN-12). + +## 8. 28개 관점 판정표 + +기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역. + +| 번호 | 관점 | 판정 | 한 줄 이유 | +| --- | --- | --- | --- | +| 1 | 코드 성숙도 | P | 실패 경로를 의식한 코드가 많다. platform과 application 사이 실패 의미 번역에 결함(06-01, 06-06) | +| 2 | 구조적 성숙도 | P | 발행 경로는 port → bridge → platform으로 깨끗하다. 소비 경로에 application leaf가 없다(06-08) | +| 3 | 변경 용이성 | P | 새 이벤트 추가 경로는 짧다. payload 버전 변경 경로가 없다(NN-10) | +| 4 | 인지 부하 | P | 두 outbox 모델과 반대 뜻의 상태 이름(NN-11) | +| 5 | 위험 가시성 | P | 중복 가능 구간은 README에 있다. "REJECTED = 영구"라는 가정이 코드에서 보이지 않는다(06-01) | +| 6 | 실패 성숙도 | X | 일시 거부·종료·짧은 장애가 영구 DEAD로 이어진다(06-01, 06-02, 06-03) | +| 7 | 운영 성숙도 | P | runbook·경보·구조화 ERROR가 있다. relay 꺼짐·실패 중 지표 정지(06-05), runbook 조회가 옛 키 | +| 8 | 디버깅 가능성 | P | failure report에 event·aggregate·correlation id가 있다. DLQ 사유가 한 값(NN-14) | +| 9 | 유지보수 성숙도 | P | 주석·README에 낡은 위치 설명(NN-13) | +| 10 | 테스트 성숙도 | P | 단위 테스트 촘촘하고 빠름(합계 수 초). 앱 경로 실연 테스트 없음(06-09), 지표 변이 생존(06-05) | +| 11 | 데이터 성숙도 | P | 봉투 바이트·hash 보존이 좋다. 순서 키 유일 제약 없음(06-07) | +| 12 | 동시성 성숙도 | P | SKIP LOCKED + fencing은 좋다. 배치·lease 관계 미검사(NN-12), 종료 순서(06-02) | +| 13 | 확장성 | P | 인스턴스 수평 확장은 된다. aggregate당 처리량 상한(06-04) | +| 14 | 성능 성숙도 | ? | 계산만 했다. 실측 없음. 회차당 약 43 DB 문장, 인스턴스당 최대 약 4건/초 | +| 15 | 보안 성숙도 | O | Kafka TLS/SASL·ACL 적용 확인(M-2 해결). 실패 report에 payload를 싣지 못하게 타입으로 막음 | +| 16 | 의존성 성숙도 | P | broker SDK는 선택 줄을 지우면 빠진다. starter가 쓰지 않는 vendored outbox 구현을 `implementation`으로 싣는다 | +| 17 | API / Contract 성숙도 | P | 봉투 v1 schema와 hash 검사가 있다. EventId/MessageId 불일치(06-06), payload 호환성 없음(NN-10) | +| 18 | 배포 성숙도 | X | 배포 종료 중 row가 DEAD가 될 수 있다(06-02). broker 실연 lane이 기본 게이트 밖(06-09) | +| 19 | 설정 성숙도 | P | strict 바인딩, producer-id 필수. relay 기본 꺼짐의 결과가 안 보임(06-05), 값 사이 관계 미검사(NN-12) | +| 20 | 개발자 경험 | P | 발행 한 줄 켜기가 쉽다. 소비·버전·순서 번호 안내가 없다(06-07, 06-08, NN-10) | +| 21 | Guardrail 성숙도 | P | caller 트랜잭션 강제, 대역 publisher 금지, producer-id 필수가 좋다. 이벤트 id·순서 번호·설정 조합 가드 없음 | +| 22 | 추상화 성숙도 | P | bridge는 필요한 만큼만 안다. outcome 어휘가 platform 의미 하나를 담지 못한다(06-01) | +| 23 | 일관성 | P | platform 종료 설계와 앱 relay 방식이 다르다(06-02, NN-11) | +| 24 | 네이밍 / 의미 성숙도 | P | `OutboxLeaderElectionToken`이 하지 않는 일을 이름으로 말한다. 두 outbox의 FAILED 의미 반대 | +| 25 | 조직 확장성 | P | 발행은 팀별로 독립 추가 가능. 소비는 registry 간선을 각자 만들게 된다(06-08) | +| 26 | Ownership 성숙도 | P | leaf README가 근거를 잘 남긴다. composition·messaging-kafka에 `CLAUDE.md` 없음 | +| 27 | 삭제 가능성 | O | messaging 줄 하나로 bridge·platform·Kafka가 함께 빠지고, relay는 남은 row를 소진하지 않는다 | +| 28 | 회복 가능성 | X | DEAD는 수동 SQL로만 풀리고 짧은 장애에도 대량 발생한다(06-03) | diff --git a/docs/reviews/2026-11-01-maturity-review/07-bootstrap-composition-config.md b/docs/reviews/2026-11-01-maturity-review/07-bootstrap-composition-config.md new file mode 100644 index 00000000..0764e2ef --- /dev/null +++ b/docs/reviews/2026-11-01-maturity-review/07-bootstrap-composition-config.md @@ -0,0 +1,422 @@ +# 07 — 조립 루트·공용 런타임·설정 계약·컨테이너 (bootstrap-composition-config) + +- 기준: 브랜치 `main`, 커밋 `01a8a2a70` +- 맡은 leaf: `app-bootstrap`, `composition:service-runtime`, `composition:idempotency`(조립 쪽), `sample-portfolio` +- 맡은 비-leaf 범위: 설정·환경 계약(`app.*` prefix, env key, `verifyEnvKeys`), `src/Dockerfile`, `src/Dockerfile.sample`, 루트 compose 파일, 보안 기본값 +- 증거 표기: 가이드 35.5 — E1 정적 확인, E2 테스트 실행, E3 실험 확인 + +## 1. 범위 + +| 항목 | 기록 | +| --- | --- | +| 대상 | `clean-architecture-backend-template`, Gradle 루트 `src/` | +| 커밋·시점 | `01a8a2a70`, 2026-11-01 20:30~20:50 KST. 메인 repo 작업 트리는 깨끗한 상태 | +| 목적·실행 구성 | 템플릿. 기본 조합은 web + 관측 + cores + support/identifier. 단일 배포 단위, 다중 인스턴스는 `APP_MULTI_INSTANCE_ENABLED`로 선택 | +| 규모·운영 목표 | 정해진 목표 없음. 그래서 "운영 준비 완료" 판정은 하지 않는다 | +| 읽은 코드·구성 | `app-bootstrap/src/main` 전체(31 java, yml 8, logback), `build.gradle` 전체, `composition/service-runtime`·`composition/idempotency` main 전체, `sample-portfolio`의 조립(`SamplePortfolioApplication`, `bootstrap/**`), `WorkLogController`, WorkLog 유스케이스, `application.yml`, README·CLAUDE.md, `src/Dockerfile`, `src/Dockerfile.sample`, `src/.dockerignore`, `src/.env.example`, 루트 `docker-compose*.yml`, build-logic `ca.config-contract`, support `startup/*`, persistence-jpa `JpaStartupAutoConfiguration`·`MigrationStartupRunner`(타이밍 확인용), web `WebSecurityAutoConfiguration`·`MethodSecurityConfig`·`JwtDecoderConfig`·`SecuritySettings` | +| 게이트(오케스트레이터 실행) | `ci` rc=0(434s, 잠금 대기 포함). `mainCheck` rc=1 — 실패는 `:adapter:outbound:objectstorage:objectStorageMinioContractTest`·`objectStorageMinioFaultTest`의 `ContainerFetchException`(MinIO 이미지 조회 실패, 08 영역). 같은 실행에서 `:app-bootstrap:verifyEnvKeys` OK(346 env keys, 249 APP_ 참조), `:app-bootstrap:systemTest` 4 suite 8 test 통과, `:app-bootstrap:publicPathSnapshotTest`, `:sample-portfolio:webSystemTest` 실행됨 | +| 이 리뷰가 돌린 실험 | (1) worktree `wt-07`에서 `:app-bootstrap:systemTest --tests '*ExperimentProbeTest*'` — BUILD SUCCESSFUL 10s, 부하 7~15. 기본 조합을 실제로 띄워 트레이서·로깅·audience·지연 초기화를 관찰. (2) `Dockerfile.sample`과 `Dockerfile`의 builder 단계 COPY 집합을 그대로 재현한 디렉터리에서 `./gradlew help --offline` — sample 집합 rc=1, main 집합 rc=0. 둘 다 끝난 뒤 worktree·임시 디렉터리 삭제 | +| 확인 못 한 것 | 실제 `docker build`(이미지 빌드·기동). JPA를 켠 조합에서 prod 검증 순서의 실측(PostgreSQL 필요). `:app-bootstrap:integrationTest`는 이번 게이트에 없음(결과 파일이 2026-09-28). sample `systemTest`·`integrationTest`도 이번 게이트에 없음. 부하·메모리 측정 | +| 이전 리뷰와 비교 | techlead `12-bootstrap-sample.md`, followup-status L·S6 행, `2026-09-07-app-bootstrap-module-code-review.md`(BOOT-001~017, 2026-09-19 closure에서 전부 닫힘) | + +## 2. 지난 발견 재확인 + +followup-status에서 `남음`이던 행과 이 영역의 핵심 행만 다시 봤다. BOOT-001~017은 closure 문서 이후 코드가 크게 바뀌어(바인더·startup 어휘가 support로 이동) 표본만 확인했다. + +| ID | 상태 | 근거 | +| --- | --- | --- | +| L-2b runtime.yml multi-instance 주석 | 남음 | `src/app-bootstrap/src/main/resources/config/runtime.yml:11-13`이 여전히 "requires the 5 instance-coordination beans". 실제 검사는 `distributedLockProvider` 하나(`StartupSafetyValidator.java:18-19,48-57`) | +| L-4a sample이 중앙 ArchUnit에서 빠짐 | 해결(바뀜) | `src/app-bootstrap/build.gradle:192` `architectureTestRuntimeOnly project(':sample-portfolio')`. `..application..`·`..domain..` 패턴 규칙이 sample 패키지에도 걸린다(`ApplicationBoundaryArchitectureTest.java:55-59`) | +| L-4b 없는 ArchUnit 규칙 인용 | 남음 | `src/sample-portfolio/CLAUDE.md:43`, `src/app-bootstrap/README.md:478`, `src/domain-core/README.md:27`. 규칙 정의 0건 | +| L-7b `ActuatorSecurityHttpTest`가 도달 불가 200 단언 | 해결 | `ActuatorSecurityHttpTest.java:95-97`이 이제 `loggers`가 404임을 단언 | +| L-10f build.gradle 고아 주석 | 남음 | `src/app-bootstrap/build.gradle:280-281` "Kafka producer ownership…" 주석이 `jakarta.ws.rs-api` 줄 위에 있음 | +| L-11a `ca-skeleton.rate-limit.*` | 해결 | `application-test.yml`·sample `application.yml`에 `ca-skeleton.` 키 0건. sample은 `app.rate-limit`(`sample-portfolio/.../application.yml:189`) | +| L-11b test yml `api-base-path: ""` + `/api/healthcheck` | 남음 | `src/app-bootstrap/src/test/resources/application-test.yml:112,118` | +| L-11c 참조 없는 `broken-readme.md` | 남음 | `src/app-bootstrap/src/test/resources/developer-experience/broken-readme.md` 존재 | +| S6-#2d 멱등성 provider 기본값 | 해결(유지) | `composition/idempotency/.../module-defaults/idempotency.yml:12` `disabled`, `IdempotencySettings.java` `Provider.DISABLED` | +| S6-#4 root 넓은 scan | 해결(유지) | `CaSkeletonApplication.java:19-26` 자기 패키지 scan + bootstrap 4개 패키지 properties scan | +| S6-#7 sample이 bootstrap 인프라 복사 | 해결(유지) | sample이 `composition:service-runtime`·`composition:idempotency`를 `runtimeOnly`로 받음(`sample-portfolio/build.gradle` dependencies) | +| S6-#9 sample yml의 읽는 코드 없는 블록 | 남음(범위 커짐) | `app.capabilities.cache`(`application.yml:150-177`), `app.bootstrap`(`:180-181`), `app.logging`(`:209-225`) 그대로. 추가로 sample이 `WebSecurityAutoConfiguration`을 제외해서 `app.security`·`app.authz`·`app.cors`(`:194-208`)도 읽히지 않는다(07-03) | +| S6-#10e sample CLAUDE.md 경로 | 남음 | `src/sample-portfolio/CLAUDE.md:20-23` `adapter/web`, `adapter/persistence`, `adapter/identifier`(실제는 `adapter/inbound/web`, `adapter/outbound/persistence`, `adapter/outbound/identifier`) | +| S6-#15 bootstrap `:test`의 저장소 governance 테스트 | 남음 | `app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/` 45파일 6,991줄. Wave 4 P33에 배정됨 | +| S6-#16a 이력·리뷰 ID 주석 | 남음 | bootstrap·composition main에서 `BOOT-n`/`Dn`/`DRIFT-` 류 35줄 | +| S6-#16d config yml 같은 3줄 헤더 | 남음 | `config/{server,observability,runtime,security}.yml` 4개가 같은 3줄 | +| S6-#17 `TracingSettings.sampleRate`가 String | 남음(이동) | `composition/service-runtime/.../TracingSettings.java:13,56-63`, `TracingSampleRateResolver.java:18-29`, `TracingSamplingEnvironmentPostProcessor.java:30`에서 세 번 파싱 | +| BOOT-005 startup 순서 | 해결(유지) | `StartupOrder` 상수, `RuntimeEnvironmentProfileValidator.java:90-92`, `TracingSamplingEnvironmentPostProcessor.getOrder()` | +| BOOT-017 bootstrap이 어댑터 구현 소유 | 해결 | bootstrap main에 포트 구현 없음. 단 `DurableOperationConfig`가 유스케이스를 조립한다(07-08) | + +지난 리뷰에서 남은 High/P1은 이 영역에 없다. 위 `남음`은 전부 W4·W5(테스트 규칙·문서)다. + +## 3. 새 발견 + +### 07-01 트레이스가 어디로도 나가지 않는다 — OTLP endpoint를 설정해도 span을 만들지도 보내지도 않는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 7, 8, 5, 16, 19 | +| 근거 | `composition/service-runtime/.../tracing/TracingConfig.java:66-91` — 자체 `Tracer` bean이 `SdkTracerProvider.builder().setSampler(...).build()`로 만든다. span processor·exporter를 붙이는 줄이 없다. `TracingSettings.Exporter.isConfigured()`(`TracingSettings.java:35`)는 호출하는 곳이 없다. `app-bootstrap/gradle.lockfile`의 runtime classpath에 Boot의 tracing 자동 설정 모듈(`spring-boot-micrometer-tracing*`, `spring-boot-opentelemetry`)이 없다. 그래서 `TracingSamplingEnvironmentPostProcessor`가 넣는 `management.tracing.sampling.probability`(`:30-38`)를 읽는 코드도 없다. 문서는 반대로 말한다: `composition/service-runtime/README.md:72-75` "엔드포인트를 설정하면 export 가 시작된다", `config/observability.yml:153-158` | +| 실행 결과 (E3) | 기본 조합을 `OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318`로 띄움 → Tracer bean은 `micrometerTracer` 하나, `SpanExporter` 0개, `SpanProcessor` 0개, `ObservationHandler`는 `defaultMeterObservationHandler` 하나(트레이싱 핸들러 없음). 즉 HTTP 요청 observation이 span을 만들지 않는다 | +| 발생 조건 | 항상. 운영자가 OTLP collector 주소를 넣는 순간 문제가 드러나야 하지만 아무 오류도 경고도 없다 | +| 영향 | "트레이스 기본 제공" 주장이 거짓이다. 로그의 `trace_id`는 web filter가 만든 W3C 값(`WebMvcRequestIdFilter.java:108-118`)이라 로그 상관은 된다. 그러나 서비스 간 span 트리, 지연 분해, 오류 span(`SpanErrorRecorder`)은 없다. 파생 서비스가 그대로 복제한다 | +| 심각도·우선순위 | High / P1. 관측성은 이 템플릿이 기본 조합에 넣었다고 선언한 기능이다. 설정 옵션이 동작하지 않는데 조용하다(AGENTS.md capability 기준 3 "동작하지 않는 옵션은 설정 키 자체를 두지 않는다" 위반) | +| 확실성 | 직접 확인: 빈 목록, lockfile. 추론: Boot 4의 tracing 자동 설정 모듈을 넣으면 `micrometerTracer`의 `@ConditionalOnMissingBean`과 순서 경쟁이 생길 수 있다 — 수정 때 확인할 것 | +| 통제 수준 | M1(문서만 있음). 테스트 `TracingActivationContextTest`는 bean 존재만 본다 | +| 결정의 근거 | 설계 선택 포함. 기록된 의도: "Plan A — seam activated"(`observability.yml:154`). 현재 효과: seam만 있고 출력이 없다 | +| 최소 개선 방향 | 고른 방법: 자체 `Tracer` 조립을 지우고 Boot 4의 tracing 모듈(`spring-boot-micrometer-tracing-opentelemetry` 계열 starter)과 OTLP export 설정 키 하나로 바꾼다. `app.tracing.sample-rate`의 profile 기본값(prod 0.01)은 EPP로 Boot 키에 넣는 현재 방식을 유지한다. 버린 대안 1: 자체 `SdkTracerProvider`에 `BatchSpanProcessor`+`OtlpHttpSpanExporter`를 직접 붙인다 — observation→span 연결(`TracingObservationHandler`, propagator)까지 손으로 만들어야 해서 Boot가 이미 주는 것을 다시 짠다. 버린 대안 2: tracing 의존성과 설정을 지우고 "로그 상관만 제공"으로 범위를 줄인다 — 가능하지만 owner가 관측 기본 제공을 정했으므로 소유자 결정이 필요하다 | +| 단순화의 보존 조건 | `app.tracing.enabled=false`면 Tracer 없음. `SpanErrorRecorder`는 Tracer가 없어도 NOOP bean으로 남음. prod 기본 sample rate 0.01, 그 밖 1.0. 응답 `meta.traceId`와 로그 `trace_id`가 같은 값 | +| 완료 기준 | endpoint를 넣으면 span exporter bean이 생기고, 넣지 않으면 exporter가 없거나 비활성이다. HTTP 요청 하나가 span 하나를 만든다 | +| 검증 방법 | systemTest에 in-memory span exporter를 주입해 HTTP 요청 1건 → span 1건, `trace_id`가 응답 meta·MDC와 같음을 단언 | + +### 07-02 prod 기동 검사가 DB 연결과 Flyway 마이그레이션이 끝난 뒤에 돈다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험(실측은 미실행) | +| 관련 관점 | 6, 15, 11, 5, 21 | +| 근거 | 모든 `StartupRule`은 `StartupRuleRunner.afterSingletonsInstantiated()`(`adapter/outbound/support/.../startup/StartupRuleRunner.java:35`)에서 한 번에 돈다. 이 콜백은 모든 싱글턴이 만들어진 뒤에 불린다. JPA 모듈을 켜면 그 전에 이미 (a) `FlywayMigrationInitializer`가 `MigrationStartupRunner.migrate()`로 마이그레이션을 실행하고, (b) `jpaResolvedDataSourceCheck`(`JpaStartupAutoConfiguration.java:101-107`, `InitializingBean`)가 DB 연결을 연다. 그런데 prod를 지키는 `PostgreSqlTransportSecurityValidator`(sslmode=verify-full), `FlywayProdSafetyValidator`(baseline-on-migrate·out-of-order·clean), `RequiredEnvironmentValidator`는 모두 `StartupRule`이다. 주석은 반대로 적었다: `JpaStartupAutoConfiguration.java:59` "datasource connection env present **before migration runs**" | +| 발생 조건 | JPA 모듈 선택 + prod + 금지 값 하나(예: `sslmode=disable`, `APP_…`로 `spring.flyway.out-of-order=true`) | +| 영향 | 기동은 결국 실패한다. 그러나 실패 전에 (1) 평문 연결로 DB 비밀번호가 나간다, (2) out-of-order·baseline 옵션으로 마이그레이션이 이미 적용된다. (2)는 되돌릴 수 없는 스키마 변경이다. 검증기의 존재 이유가 "운영 DB에 위험한 옵션이 닿기 전에 막기"인데 순서가 그 뒤다 | +| 심각도·우선순위 | High / P1. prod 안전 검사의 약속 자체가 순서 때문에 깨진다. 기본 조합에는 JPA가 없어서 P0은 아니다 | +| 확실성 | 직접 확인: runner 호출 시점(Spring 계약), JPA 쪽 bean 종류. 실측하지 않음: PostgreSQL이 필요해 이 리뷰에서 재현하지 않았다. `lazy-initialization=true`에서도 `SmartInitializingSingleton` 기반 검사는 돈다는 것은 실험으로 확인했다(E3: `lazy-prod-no-salt => FAILED`, `lazy-prod-include-stacktrace => FAILED`). 단 `InitializingBean` 기반 JPA 검사(`jpaPlatformStartupCheck`, `jpaResolvedDataSourceCheck`)는 지연 초기화에서 건너뛸 수 있다 — 05 영역 확인 필요 | +| 통제 수준 | M2(검사는 구현돼 있음), 순서는 M0 | +| 결정의 근거 | 41절 D2 참조. 단일 runner로 모은 결정은 옳았다. 문제는 실행 시점이 phase 이름(`PROFILE_CHECK`, `ENV_VALIDATION`)과 맞지 않는 것이다 | +| 최소 개선 방향 | 고른 방법: 환경만 읽는 rule(`violations(Environment)`만 쓰는 것 — 현재 전부 해당)은 `EnvironmentPostProcessor`나 `BeanFactoryPostProcessor` 단계에서 돌리는 두 번째 진입점을 support에 둔다. rule 인터페이스와 종료 코드는 그대로 둔다. 버린 대안 1: Flyway 전략(`MigrationStartupRunner`) 안에서 rule을 먼저 부른다 — JPA만 고치고 다른 모듈의 같은 문제를 남긴다. 버린 대안 2: DataSource bean에 `@DependsOn("startupRuleRunner")` — 그래도 runner 자체가 `afterSingletonsInstantiated`라 효과가 없다 | +| 단순화의 보존 조건 | 위반 시 같은 종료 코드(71/72/78), 같은 `startup.phase`·`error.code` 로그 필드, 한 rule의 위반을 한 번에 보고 | +| 완료 기준 | prod + `sslmode=disable`에서 DataSource가 연결을 열기 전에 기동이 실패한다 | +| 검증 방법 | JPA systemTest에 연결 시도를 세는 DataSource 프록시를 두고, 금지 값에서 연결 횟수 0 + 종료 코드 71을 단언 | + +### 07-03 실행 중인 샘플에서는 `@RequiresPermission`이 아무 일도 하지 않는다 — 익명 삭제 가능, 생성은 500 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(정적 확인) | +| 관련 관점 | 15, 5, 20, 21, 10 | +| 근거 | `SamplePortfolioApplication.java:31` `@EnableAutoConfiguration(exclude = WebSecurityAutoConfiguration.class)`. 제외한 클래스가 `MethodSecurityConfig`·`AuthorizationAdapter`·`RolePermissionRegistry`를 들여오는 유일한 곳이다(`adapter/inbound/web/.../WebSecurityAutoConfiguration.java:41-49`). 그 대신 들어오는 `SamplePublicAccessSecurityConfig.java:21-26`은 `/**` 전체 permitAll이고 인증 수단이 없다. 그런데 유스케이스는 권한을 선언한다: `DeleteWorkLogUseCase.java:14` `@RequiresPermission("worklog:close")`(주석 "admin-tier"), `CreateWorkLogUseCase.java:23` `worklog:write`. 컨트롤러는 인증 주체가 없으면 owner를 `null`로 넘기고(`WorkLogController.java:221-229`) 도메인은 `Objects.requireNonNull`로 거부한다(`WorkLogOwner.java`) — NPE라 `GlobalExceptionHandler`의 `Exception` 처리(500)로 간다. 권한 E2E 테스트는 보안 필터와 자동 설정을 끄고 advisor를 직접 넣는다(`WorkLogAuthorizationE2ETest`), 그래서 실행본의 상태를 보지 못한다 | +| 발생 조건 | `:sample-portfolio:bootRun` 또는 sample 이미지로 띄운 앱 | +| 영향 | 누구나 `DELETE /api/worklogs/{id}`로 아무 기록이나 지운다. 생성은 항상 500이다. README의 curl 예시(`sample-portfolio/README.md:33-58`)는 경로(`/work-logs`)도 틀렸다. 더 큰 문제는 복제 범위다. 샘플은 adopter가 가장 먼저 베끼는 코드이고, 여기서 "보안 자동 설정 하나 제외"가 메서드 보안 전체를 조용히 끈다는 사실이 어디에도 드러나지 않는다. `@RequiresPermission`이 붙은 bean이 있는데 advisor가 없으면 실패하는 장치도 없다 | +| 심각도·우선순위 | High / P1. 데모라 데이터 가치는 낮지만, 인가 위치(유스케이스)라는 핵심 규칙이 예시에서 무력화되고 복제된다(35.2 "샘플을 통해 복제되는 범위") | +| 확실성 | 정적 경로는 끝까지 확인했다. HTTP로 실제 삭제를 재현하지는 않았다(PostgreSQL 필요) | +| 통제 수준 | M0(실행본에서). 단위 계층은 M3 | +| 결정의 근거 | 기록된 의도: "IdP 없이 둘러볼 수 있는 공개 데모"(`sample-portfolio/README.md:410-412`). 의도는 URL 공개였지 권한 검사 제거가 아니었다고 읽힌다 — README도 "JWT 필터 체인·메서드 보안·권한 port만 뺀다"고 적어 메서드 보안 제거를 인정하면서 유스케이스 주석은 admin 전용이라고 말한다 | +| 최소 개선 방향 | 고른 방법: `WebSecurityAutoConfiguration`을 제외하지 않고, 샘플은 JWT 대신 고정 데모 주체(예: `X-Demo-Role` 헤더나 local 전용 dev 토큰)를 넣는 인증 필터 하나만 둔다. 그러면 권한 검사는 production과 같은 경로로 돈다. 버린 대안 1: 지금 구조 유지 + README 경고 — 위험이 코드에 드러나지 않는다는 원칙에 어긋난다. 버린 대안 2: 샘플에서 `@RequiresPermission`을 지운다 — 인가 위치를 보여 주는 예시가 사라진다. 함께 할 것: `@RequiresPermission` bean이 있는데 `requiresPermissionAuthorizationAdvisor`가 없으면 기동 실패하는 rule을 web 모듈에 둔다 | +| 완료 기준 | 실행 중인 샘플에서 권한 없는 주체의 DELETE가 403, 권한 있는 주체는 204. 생성은 주체가 있으면 201 | +| 검증 방법 | sample `systemTest`(실제 컨텍스트, 보안 자동 설정 포함)에서 위 세 경우를 HTTP로 단언 | + +### 07-04 `Dockerfile.sample`은 빌드되지 않는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 18, 20, 10 | +| 근거 | `src/Dockerfile.sample:50-53`은 `gradlew`, `gradle/`, `config/`, `settings.gradle build.gradle **/build.gradle **/gradle.lockfile`만 복사한다. `src/Dockerfile:46,53`이 따로 복사하는 `gradle.properties`와 `build-logic/` 전체가 없다. `settings.gradle:1-6`은 `includeBuild('build-logic')`로 convention plugin을 가져오므로 build-logic의 `settings.gradle`(version catalog)과 `src/main/groovy` 플러그인이 없으면 settings 단계에서 실패한다. main Dockerfile 주석(`:49-52`)이 같은 실패를 이미 설명하고 고쳤는데 sample은 따라가지 않았다. 이 파일을 빌드하는 CI lane도 없다(`git grep Dockerfile.sample` → 문서·계획서만) | +| 실행 결과 (E3) | 두 COPY 집합을 그대로 재현한 디렉터리에서 `./gradlew help --offline`. sample 집합: rc=1, `settings.gradle line 9 … A problem occurred evaluating project ':build-logic' … unknown property 'libs'`. main 집합(+`build-logic/`, `gradle.properties`): rc=0. 실제 `docker build`는 하지 않았다 | +| 발생 조건 | 문서대로 `docker build -f src/Dockerfile.sample src/`(`Dockerfile.sample:12`) | +| 영향 | 샘플 이미지를 만들 수 없다. 07-03의 문제를 이미지로 배포하는 경로는 지금은 막혀 있지만, 고치면 그대로 드러난다 | +| 심각도·우선순위 | Medium / P2. 운영 이미지가 아니라 데모 이미지다 | +| 통제 수준 | M0(검증 lane 없음) | +| 결정의 근거 | 적용 제외 — main Dockerfile이 이미 정답을 갖고 있어 선택 비교가 필요 없다 | +| 최소 개선 방향 | builder 단계를 main과 같게 맞춘다. 더 나은 방법: 두 Dockerfile의 builder 단계를 하나로 두고 `ARG` 하나로 `:app-bootstrap`/`:sample-portfolio`를 고른다(main이 이미 `COMPOSITION` 인자로 같은 일을 함). 갈라진 복사본을 없애는 쪽이 원칙에 맞다 | +| 완료 기준 | `docker build -f src/Dockerfile.sample src/` 성공, 이미지 HEALTHCHECK 통과 | +| 검증 방법 | 두 Dockerfile을 모두 빌드하는 CI lane(또는 `DeveloperExperienceContractTest`에 builder COPY 집합 동일성 단언) | + +### 07-05 prod에서 JWT audience를 비워도 기동하고, 경고도 없이 audience 검사를 끈다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 15, 19, 6 | +| 근거 | `.env.example:97` `APP_SECURITY_JWT_AUDIENCE=`(빈 값). `SecuritySettings.java:35-41`은 값이 `null`일 때만 경고하고, 빈 문자열이면 경고 없이 `""`로 둔다. `JwtDecoderConfig.java:80-82`는 audience가 비면 검사기를 붙이지 않는다. prod secret guard(`SecretSourceValidator.REQUIRED_PROD_SECRETS`, `:34-35`)와 그 밖의 prod rule 어디에도 audience가 없다. `.env.example:12-15`는 "issuer와 audience는 기본값이 없다 — 아무도 고르지 않은 대상을 막기 위해"라고 말한다 | +| 실행 결과 (E3) | prod + 빈 audience(두 경로 모두 빈 값)로 기본 조합 기동 → `BOOTED` | +| 발생 조건 | `.env.example`을 복사하고 audience를 채우지 않은 prod 배포 | +| 영향 | 같은 IdP realm에서 다른 클라이언트용으로 발급된 토큰을 이 API가 받는다(토큰 혼용). 문서의 약속과 반대로 동작한다 | +| 심각도·우선순위 | Medium / P2. issuer 검사는 남아 있어 외부 토큰은 막힌다. 피해 범위가 같은 IdP의 다른 client로 제한된다 | +| 통제 수준 | M0(prod 강제 없음) | +| 결정의 근거 | 설계 선택 포함. 기록된 의도는 "blank disables the check"(`application.yml:45`)로, 로컬 편의 때문이다 | +| 최소 개선 방향 | 고른 방법: prod에서 JWT 모드면 audience 필수인 `StartupRule`을 web 모듈에 둔다(local·dev는 지금처럼 허용, 대신 빈 값도 경고). 버린 대안: 모든 profile에서 필수 — 로컬 IdP 없이 띄우는 흐름을 깨고, 이 템플릿의 local 경험을 바꾼다 | +| 완료 기준 | prod + JWT + 빈 audience → 기동 실패(ENV_VALIDATION). local은 경고 1줄 | +| 검증 방법 | `DefaultCompositionBootTest`에 prod 빈 audience 거부 케이스 추가 | + +### 07-06 로그 설정이 두 군데에서 읽힌다 — `LoggingSettings`는 아무도 쓰지 않고, logback은 env 키를 직접 읽는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 19, 5, 8, 22 | +| 근거 | `bootstrap/settings/LoggingSettings.java`는 `app.logging.*`를 바인딩하고 잘못된 값을 "경고 후 기본값"으로 고친다(예: 빈 경로 → `logs/app.json`, `:20-23`). main 코드에 이 record를 쓰는 곳이 없다(사용처는 `LoggingSettingsTest`뿐). 실제 로깅을 정하는 `logback-spring.xml:17-46`은 `springProperty source="APP_LOG_FILE_ENABLED"` 같은 env 키 이름을 직접 읽는다. 그래서 (1) `app.logging.*`를 yml이나 profile 파일로 바꾸면 반영되지 않고, (2) `LoggingSettings`의 경고는 실제로 적용되지 않는 대체값을 알린다(경로 대체값 `logs/app.json` vs logback 기본 `logs/ca-skeleton.json`) | +| 실행 결과 (E3) | `--app.logging.file.enabled=true --app.logging.file.path=…`로 기동 → root appender `[ASYNC_CONSOLE]`만. 파일 appender가 붙지 않는다 | +| 발생 조건 | 운영자가 env 대신 `application-prod.yml`이나 설정 서버로 `app.logging.*`를 바꿀 때 | +| 영향 | 로그 파일·보관 기간이 설정과 다르게 동작한다. 경고 로그가 거짓 정보를 준다 | +| 심각도·우선순위 | Medium / P2 | +| 통제 수준 | M1 | +| 결정의 근거 | 설계 선택 포함. logback은 Spring 바인딩보다 먼저 초기화돼 typed settings를 쓸 수 없다는 제약이 있다(`logback-spring.xml:5` 주석) | +| 최소 개선 방향 | 고른 방법: `LoggingSettings`를 지우고, logback `springProperty`의 `source`를 `app.logging.*` 키로 바꾼다(`springProperty`는 Spring Environment를 읽으므로 env→yml placeholder 경로가 그대로 산다). 값 검증은 logback이 실패할 값(예: maxHistory<=0)만 `StartupRule` 하나로 fail-fast. 버린 대안: `LoggingSettings`를 유지하고 logback을 런타임에 재구성 — 초기 로그와 이후 로그가 다른 설정을 쓰는 구간이 생긴다 | +| 단순화의 보존 조건 | env 키 이름(`APP_LOG_*`)과 기본값, JSON 필드, 마스킹 | +| 완료 기준 | `app.logging.file.enabled=true`(yml)로 파일 appender가 붙는다. 같은 값이 한 곳에서만 정의된다 | +| 검증 방법 | 위 실험을 systemTest로 고정 | + +### 07-07 종료 시간 예산표에 async executor 대기 19초가 빠져 있다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 7, 18, 12, 9 | +| 근거 | 루트 `docker-compose.yml:9-19,88-89`의 예산: 앱 30s(`timeout-per-shutdown-phase`) + preStop 5s + 여유 5s = `stop_grace_period: 40s`. 그런데 `AsyncExecutorConfig.java:27-28,53-54`는 `setWaitForTasksToCompleteOnShutdown(true)` + `awaitTermination 19s`이고 주석은 "container app-shutdown budget (20s)"라고 적는다. Spring은 lifecycle 단계(웹 서버 graceful 30s까지)를 끝낸 뒤 bean destroy에서 executor 대기를 한다. 최악은 30 + 19 = 49s로 40s를 넘는다 | +| 발생 조건 | 종료 시점에 HTTP 요청 처리가 길고, 동시에 async 작업이 큐에 남아 있을 때 | +| 영향 | 컨테이너가 SIGKILL로 끝나 async 작업이 중간에 끊긴다. 종료 로그가 남지 않는다 | +| 심각도·우선순위 | Medium / P2. 최악 경로에서만 일어난다 | +| 확실성 | lifecycle → destroy 순서는 Spring 계약으로 판단했다. 최악 시간은 측정하지 않았다. `AsyncGracefulShutdownBehaviorTest`(2 test, 통과)는 executor만 따로 본다 | +| 통제 수준 | M1(표는 있음, 표가 틀림) | +| 결정의 근거 | 적용 제외 — 숫자 정합성 문제다 | +| 최소 개선 방향 | executor 대기를 `spring.lifecycle.timeout-per-shutdown-phase`에서 계산하거나, 예산표에 executor 대기를 넣어 `stop_grace_period`를 다시 잡는다. 숫자는 한 곳(env-keys)에만 두고 compose·주석은 그것을 가리킨다 | +| 완료 기준 | 예산표의 합 ≤ `stop_grace_period`, 코드 상수와 주석이 같은 값 | +| 검증 방법 | 종료 순서를 기록하는 systemTest(웹 요청 1개 + async 작업 1개를 걸고 close 시간 측정) | + +### 07-08 기본 조립 루트가 아직 선택 capability를 안다 (capability 기준 7 위반) + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 2, 27, 26, 23, 19 | +| 근거 | AGENTS.md capability 기준 7: "이 모듈을 아는 곳은 모듈 자신뿐". 현재 bootstrap·이미지·compose에 남은 것: (1) `config/security.yml:39-59` — notification·durable operation·fileserver 권한 매핑. (2) `src/Dockerfile:158-167` — fileserver 저장 경로 `VOLUME` (기본 이미지는 fileserver가 없다). (3) `docker-compose.yml:70-82,110-113` — `fileserver-data` 볼륨을 무조건 마운트. (4) `application-dev.yml:20-22`, `application-prod.yml:22-28` — persistence-jpa 키(`app.persistence.vendor`, `spring.flyway.enabled`)와 이미 삭제된 `JpaSchemaSafetyValidator` 설명(`application-prod.yml:11`). (5) `bootstrap/autoconfigure/operation/DurableOperationConfig.java:37-74` — 유스케이스 조립이 bootstrap에 남음. 소유자 결정 3은 같은 성격(outbox relay·멱등성 executor)을 `composition:*`으로 옮겼다. 그래서 sample은 이 조립을 재사용할 수 없다. (6) build-logic `ConfigContractPlugin.java` `dependsOn(':adapter:outbound:redis-runtime:compileJava')` — env 계약 태스크가 특정 leaf를 안다 | +| 발생 조건 | capability를 지우거나 새 capability를 더할 때 | +| 영향 | 한 줄 삭제로 기능이 "완전히" 사라지지 않는다. 지운 기능의 권한 문자열·볼륨·설정이 남아, 읽는 사람이 그 기능이 켜져 있다고 오해한다. 새 capability 작성자는 bootstrap 파일을 고쳐야 하는지 판단해야 한다 | +| 심각도·우선순위 | Medium / P2 | +| 통제 수준 | M1. `DefaultCompositionBootTest`는 bean만 보고 설정·이미지 자산은 보지 않는다 | +| 결정의 근거 | 41절 D1 참조 | +| 최소 개선 방향 | 고른 방법: 권한 매핑은 각 capability의 `config/module-defaults/<모듈>.yml`로, durable operation 조립은 `composition:durable-operation`(또는 기존 outbox-relay 모듈)로 옮긴다. fileserver 볼륨은 fileserver README의 "필요한 마운트"로 옮기고 기본 compose에서는 뺀다. 버린 대안: bootstrap에 두고 "선택 시 사용" 주석만 단다 — 기준 7을 문서로 대체하는 것이라 기각 | +| 완료 기준 | bootstrap main·기본 compose·기본 Dockerfile에서 capability 이름(`fileserver`, `notification`, `operation`, `persistence`) grep 0건 | +| 검증 방법 | 위 grep을 `DefaultCompositionBootTest` 옆 계약 테스트로 고정 | + +### 07-09 새 기능을 만들 때 따라 할 예시가 세 갈래다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험(갈라진 복사본) | +| 관련 관점 | 3, 4, 23, 20, 25 | +| 근거 | (1) `sample-portfolio` — 한 Gradle 모듈 안에 `domain/`·`application/<기능>/`·`adapter/`를 두고 기능별 패키지(P30 결정). (2) `app-bootstrap/src/test/java/dev/caskeleton/onboarding/**` — `DomainFeatureOnboardingContractTest`가 쓰는 예시는 종류별 패키지(`application/usecase`, `application/port`, `application/query`, `application/command`). (3) AGENTS.md "기능 개발 프로토콜" — production 기능은 `domain-core` → `application-core` → `adapter:*` leaf로 여러 Gradle 모듈에 나눠 둔다. 셋이 서로 다른 배치를 가르친다. 또 sample의 posterimage 기능은 application 클래스만 45개라, 가장 단순한 WorkLog 흐름보다 먼저 눈에 띈다 | +| 발생 조건 | 처음 기능을 추가하는 개발자·에이전트 | +| 영향 | 어느 예시를 베끼느냐에 따라 패키지 규칙이 달라진다. ArchUnit은 `..application..` 같은 넓은 패턴이라 셋 다 통과시키므로, 일관성이 리뷰에만 의존한다 | +| 심각도·우선순위 | Medium / P2 | +| 통제 수준 | M1 | +| 결정의 근거 | 41절 질문은 7절(매뉴얼 재료)과 함께 적었다 | +| 최소 개선 방향 | 고른 방법: 패키지 규칙 하나를 정하고(P30이 고른 기능별 배치), onboarding fixture를 같은 배치로 바꾼다. AGENTS.md 프로토콜에 "sample은 한 모듈에 모든 계층을 두지만 실제 기능은 leaf별로 나눈다"는 차이를 한 줄로 적는다. sample README 첫 절을 WorkLog 한 흐름(생성 1건)으로 시작한다. 버린 대안: sample을 leaf 여러 개로 쪼갠다 — 템플릿 삭제 용이성(샘플 한 모듈 삭제)을 잃는다 | +| 완료 기준 | 예시 패키지 배치가 하나. ArchUnit에 "application 하위는 기능 패키지" 규칙(선택) | +| 검증 방법 | onboarding fixture와 sample에 같은 규칙 적용 | + +### 07-10 설정 오타·죽은 키가 기동에서도 게이트에서도 안 잡히는 곳이 있다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 19, 21, 23 | +| 근거 | (1) bootstrap 자기 설정은 `@ConfigurationProperties`(관대한 바인딩, 모르는 키 무시): `AsyncExecutorSettings.java:16-17`, `BootstrapSettings`, `RuntimeSafetySettings`, `SecretSourceSettings`, `AuthenticationModeSettings`. 모듈들은 `StrictSettingsBinder`(모르는 키면 실패)를 쓴다. 그래서 `app.async.executor.core-sise` 같은 오타는 조용히 기본값이 된다. (2) `verifyEnvKeys`는 yml·java만 본다(`ConfigContractPlugin.java` file trees). compose 파일·`logback-spring.xml`은 대상이 아니다. 실제로 `docker-compose.prod-smoke.yml:29` `APP_LOG_JSON_ENABLED`는 어디서도 읽지 않는 키다. (3) sample `application.yml`의 죽은 블록(S6-#9, 07-03) | +| 영향 | 운영자가 값을 바꿨다고 믿지만 반영되지 않는다 | +| 심각도·우선순위 | Low / P3. 기본값이 안전한 쪽이라 피해가 작다 | +| 통제 수준 | 모듈 M3, bootstrap M1 | +| 결정의 근거 | 적용 제외에 가깝다 — 기준 4가 이미 strict 바인딩으로 정했다 | +| 최소 개선 방향 | bootstrap 설정 record도 `StrictSettingsBinder`로 묶는다(prefix `app.async`, `app.runtime`, `app.bootstrap`, `app.secret-source`). `verifyEnvKeys` 입력에 루트 compose 파일과 `logback-spring.xml`의 `source="APP_*"`를 넣는다 | +| 완료 기준 | 오타 키로 기동 실패. compose의 미등록 `APP_*` 키로 `verifyEnvKeys` 실패 | +| 검증 방법 | 각각 실패 테스트 1건 | + +### 07-11 주석·문서가 현재 동작과 다르다 (이번에 새로 찾은 것) + +| 필드 | 내용 | +| --- | --- | +| 성격 | 개선 제안(문서 결함) | +| 관련 관점 | 9, 5, 20 | +| 근거 | `application-prod.yml:11` 삭제된 `JpaSchemaSafetyValidator`를 prod 규칙으로 나열. `src/Dockerfile:201-202` "readiness 그룹이 datasource를 포함한다" — 기본 조합의 readiness는 `readinessState`뿐(`config/observability.yml:79-80`), JPA를 켤 때만 `db`가 붙는다. `AsyncExecutorConfig.java:27` "budget (20s)"(07-07). `sample-portfolio/README.md:22-58` 엔드포인트 표·curl이 `/work-logs`, `/work-logs/import` — 실제는 `/worklogs`, `/worklogs:batchCreate`(`WorkLogController.java:89-165`). `SamplePortfolioApplication.java` Javadoc "The one exclusion is the web leaf's security root"는 맞지만 그 결과(메서드 보안 없음)를 말하지 않는다 | +| 심각도·우선순위 | Low / P3 | +| 결정의 근거 | 적용 제외 — 문서 수정 | +| 최소 개선 방향 | 위 줄을 고친다. 샘플 curl은 sample webSystemTest의 실제 요청에서 생성하거나, 테스트가 README 경로를 읽어 대조한다 | +| 완료 기준 | 위 위치가 코드와 같다 | +| 검증 방법 | 리뷰 + README 경로 대조 테스트(선택) | + +### 07-12 virtual thread를 켠 상태에서 `server.tomcat.threads.max`는 동시 처리 상한이 아니다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 미검증(구조적 위험 후보) | +| 관련 관점 | 14, 13, 19 | +| 근거 | `application.yml:54-57` virtual thread 기본 켜짐. `config/server.yml:15-17` `threads.max: 200`, `RuntimeNumericBoundsValidator.java:22`가 이 값을 검증한다. Boot는 virtual thread를 켜면 Tomcat 요청 처리에 virtual thread executor를 쓰고, 이때 `threads.max`는 동시 처리 상한으로 작동하지 않는다(Boot 동작, 이번에 실측 안 함). 실제 상한은 `max-connections: 8192` | +| 영향 | 운영자가 `threads.max`로 부하를 제한한다고 믿으면, JPA를 켠 서비스에서 수천 요청이 커넥션 풀(기본 10)에서 대기한다 | +| 심각도·우선순위 | Low / P3(미검증) | +| 최소 개선 방향 | 설정 주석에 "virtual thread가 켜져 있으면 상한은 max-connections와 하위 자원(풀·rate limit)"이라고 적고, 필요하면 동시 요청 제한(semaphore filter)을 선택 항목으로 둔다 | +| 검증 방법 | 기본 조합에서 지연 엔드포인트에 300 동시 요청 → 동시 처리 수 측정 | + +### 07-13 기본 compose가 관리 포트 9001을 모든 인터페이스에 연다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 개선 제안(보안 기본값) | +| 관련 관점 | 15, 18 | +| 근거 | `docker-compose.yml:52` `"9001:9001"`. 관리 체인은 `health`·`info`·`prometheus`를 인증 없이 허용한다(`ManagementSecurityConfig.java` `permitAll`). `info.env.enabled: true`(`observability.yml:96-97`)라 `info.capabilities.*`와 build revision이 보인다. local override는 DB 포트를 loopback으로만 연다(`docker-compose.local.yml:14-16` 설명)와 대조된다 | +| 영향 | compose로 띄운 개발 장비가 LAN에 메트릭·구성 정보를 노출한다. 운영(k8s)과는 무관하다 | +| 심각도·우선순위 | Low / P3 | +| 최소 개선 방향 | `"127.0.0.1:9001:9001"`. 앱 포트도 같은 원칙을 쓸지 결정 | +| 검증 방법 | `docker compose config` 결과 대조(기존 compose 계약 테스트에 추가) | + +### 07-14 프로필 검증기가 main class 이름을 문자열로 비교한다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 개선 제안 | +| 관련 관점 | 21, 20 | +| 근거 | `RuntimeEnvironmentProfileValidator.java:83-87` `"dev.caskeleton.bootstrap.CaSkeletonApplication".equals(...)`. AGENTS.md 템플릿 재사용 체크리스트 2·3단계가 바로 이 패키지와 클래스 이름을 바꾸라고 한다. 바꾸고 문자열을 놓치면 profile 없는 jar가 기동한다. 다만 `RuntimeEnvironmentProfileValidatorTest`가 class literal로 주입해 검사하므로, 이름만 바꾸면 그 테스트가 실패해 알려 준다(M3) | +| 심각도·우선순위 | Low / P3 | +| 최소 개선 방향 | `CaSkeletonApplication.class.getName()`을 쓴다. 같은 leaf라 의존 문제가 없다 | +| 검증 방법 | 기존 단위 테스트 | + +## 4. 31절 시나리오 추적 + +### 4.1 선택 어댑터 제거 — 기본 조합 기동 (적용) + +- 입력 신뢰: 운영자 env. 필수는 `SPRING_PROFILES_ACTIVE`, `APP_NAME`, `APP_SECURITY_JWT_ISSUER`, `APP_SECURITY_JWT_AUDIENCE`(빈 값 허용 — 07-05), prod는 `APP_PRIVACY_PSEUDONYMIZATION_SALT`. +- 흐름: `RuntimeEnvironmentProfileValidator`(EPP, profile 정확히 1개) → 모듈 기본값 EPP(support) → 컨텍스트 생성 → `SmartInitializingSingleton` 검사들(`SecretSourceValidator`, `StartupSafetyValidator`, `AuthenticationModeCompositionValidator`, `StartupRuleRunner`) → readiness UP. +- 결과(E2): `DefaultCompositionBootTest`가 local·dev·prod에서 capability bean 0개, DataSource·Mongo·Kafka·Redis 연결 bean 0개로 기동함을 단언하고 이번 게이트에서 통과. prod에서 salt 없으면 실패하는 것도 단언. 이번 실험(E3)에서 `lazy-initialization=true`여도 secret·에러상세 검사가 돈다. +- 잘못된 조합: `APP_IDEMPOTENCY_PROVIDER=redis`인데 모듈이 없으면 `IdempotencyAutoConfiguration.java:49-62`이 store 수를 세어 기동 실패. `APP_MULTI_INSTANCE_ENABLED=true`인데 lock provider가 없으면 `StartupSafetyValidator`가 종료 코드 72. 이해 가능한 오류로 거부된다. +- 남는 것: 기본 조합이 선택 capability의 설정·볼륨·권한 문자열을 갖고 있다(07-08). + +### 4.2 정상 쓰기 요청 — sample `POST /api/worklogs` (적용) + +- 입력 신뢰: 외부 JSON. `@Valid` DTO, unknown field 거부(`spring.jackson…fail-on-unknown-properties: true`). +- 인가 위치: 유스케이스 `@RequiresPermission("worklog:write")` — 실행본에서는 advisor가 없어 검사가 없다(07-03). +- 규칙 소유: `WorkLog.create`(도메인), owner 필수는 `WorkLogOwner.of`. +- 트랜잭션: `CreateWorkLogUseCase.handle` 안의 `tx.inWrite` 하나. 저장과 outbox append가 같은 트랜잭션(이중 쓰기 금지 예시로 적절). +- 외부 부작용: 없음(outbox 행만). relay는 sample에서 꺼짐(`application.yml:234-237`). +- 성공의 의미: 201 + ETag. 실행본에서는 주체가 없어 owner `null` → NPE → 500(07-03). +- 오류 변환: 도메인 예외 → `DomainExceptionHandler`, 그 밖은 `GlobalExceptionHandler`. +- 진단: `request_id`·`trace_id` MDC(web filter), JSON 로그(local·dev는 패턴 로그). span 없음(07-01). + +### 4.3 다른 사용자 리소스 접근 — sample `DELETE /api/worklogs/{id}` (적용) + +- 인증 없음 → 메서드 보안 없음 → `DeleteWorkLogUseCase`가 존재만 확인하고 삭제(07-03). 소유자 비교도 없다. 템플릿이 "객체 ID를 바꿔도 거부된다"를 보여 주는 예시는 fileserver(`FileAccessPolicyPort`, 다른 영역)에만 있고 sample에는 없다. 매뉴얼 재료로 7절에 적었다. + +### 4.4 종료·재시작 (적용) + +- 신호: Dockerfile `ENTRYPOINT ["java", …]` exec 형식이라 java가 PID 1로 SIGTERM을 받는다. +- 신규 요청 차단: `server.shutdown: graceful`, `timeout-per-shutdown-phase: 30s`. 게이트 로그(mainCheck.log)에 "Graceful shutdown complete"가 찍힌다. +- 진행 작업: async executor가 최대 19s 더 기다린다 → 예산표와 어긋남(07-07). +- readiness: 종료 중 readiness 전환은 Boot 기본 동작에 맡긴다(별도 확인 안 함). +- 메시지 확인: 기본 조합에 메시지 없음 — 적용 제외(10 영역). + +### 4.5 적용 제외 + +| 시나리오 | 사유 | +| --- | --- | +| 중복·동시 요청 | 멱등성 실행 경로는 web·persistence·Redis 영역. 이 영역은 조립만: provider≠disabled면 store가 정확히 1개여야 기동(`IdempotencyAutoConfiguration.java:49-62`) — 충족 | +| 외부 응답 지연·유실 | 기본 조합에 외부 호출 없음(08 영역) | +| DB 오류·경쟁 | 기본 조합에 DB 없음(05 영역). 단 prod 검사 순서는 07-02 | +| 메시지 중복·역순 | 10 영역 | +| 신·구 버전 공존 | API·스키마는 02·05 영역 | +| 여러 서버의 작업 실행 | 다중 인스턴스 검사는 lock provider 존재만 본다(`StartupSafetyValidator`). 스케줄러 소유권은 05·10 영역 | +| 세션·토큰 갱신 경쟁 | 02 영역(redis-session 모드) | +| 큰 입력·목록 조회 | 02 영역. sample batch 상한 1000은 `@Size`로 강제(`WorkLogController.java:177-183`) | + +## 5. 41절 설계 선택 검토 + +### D1. capability = `runtimeOnly` 한 줄 + 모듈 자체 `AutoConfiguration.imports`, 기본 조합은 web-only + +1. 필요: 파생 서비스가 쓰지 않는 기능(JPA·Redis·Kafka…)의 연결·설정·의존성을 지지 않고 시작해야 한다. +2. 지킬 성질: 줄을 지우면 bean·설정·의존성이 함께 사라진다. 기본 조합은 외부 연결 없이 기동한다. 선택한 기능이 덜 설정되면 기동 실패. +3. 현재 보장: `app-bootstrap/build.gradle:157-171` 주석 처리된 선택 줄, `DefaultCompositionBootTest`(E2, 이번 게이트 통과), `qualificationBootJar`로 전부 켠 조합을 compose lane에서 검증. 보장하지 않는 것: 설정 파일·이미지·compose의 capability 흔적(07-08), 권한 문자열. +4. 대안: (a) 모든 모듈을 `implementation`으로 싣고 `enabled` 스위치로 끄기(이전 방식). (b) Gradle feature variant/플랫폼별 bootJar 여러 개. (c) 현재 방식. +5. 득실: (a)는 끄는 것을 잊으면 연결을 시도하고, 의존성 표면이 크다 — 이전 리뷰가 이 이유로 기각. (b)는 조합 수만큼 산출물이 생겨 검증 비용이 커진다. (c)는 한 줄로 고르지만, "모듈만 자기를 안다"를 지키려면 권한·볼륨·profile 파일까지 모듈로 옮겨야 한다. +6. 왜 이 선택: 소유자 결정(B안·web-only)과 일치하고 검증이 이미 붙어 있다. 확인한 조건에서 타당하다. +7. 다시 볼 조건: 파생 서비스 대부분이 같은 3~4개 capability를 항상 켠다면, "표준 조합" 플랫폼 하나를 두는 편이 싸다. + +### D2. 기동 검증 = `StartupRule` bean + support의 runner 하나 (`afterSingletonsInstantiated`) + +1. 필요: 잘못된 설정을 첫 요청이 아니라 기동에서 막고, 종료 코드·로그 필드를 일정하게 한다. +2. 지킬 성질: 위험한 값이 외부 시스템(DB·브로커)에 닿기 전에 거부한다. 위반은 phase별 종료 코드로 보고한다. +3. 현재 보장: 규칙 어휘와 보고는 하나로 모였다(`StartupRule`, `StartupValidationContext`). 실행 시점은 모든 싱글턴 생성 뒤라, "닿기 전" 성질은 보장하지 않는다(07-02). bootstrap의 다른 검사(`SecretSourceValidator` 등)도 같은 시점이다. +4. 대안: (a) 현재. (b) 환경만 보는 rule을 EPP/BFPP에서 먼저 실행, bean 상태를 보는 rule만 현재 시점. (c) 각 모듈이 자기 연결 bean 생성 직전에 자기 rule을 부른다. +5. 득실: (a) 단순하지만 순서 위험. (b) 진입점이 둘이 되지만 rule 인터페이스는 하나, 현재 rule 전부가 `violations(Environment)`라 이동 비용이 작다. (c) 모듈마다 호출 위치를 기억해야 한다 — 숨은 규칙이 늘어난다. +6. 판단: (b)가 현재 요구에 맞다. (a)를 유지하려면 "PROFILE_CHECK"라는 이름이 약속하는 시점을 문서로 낮춰야 하는데, 그건 위험을 숨기는 쪽이다. +7. 다시 볼 조건: bean 상태가 필요한 rule이 다수가 되면 두 단계 구분을 phase 속성으로 표현한다. + +### D3. 공용 런타임 배선을 `composition:service-runtime`으로 분리하고, sample은 bean 이름으로 actuator chain을 바꾼다 + +1. 필요: bootstrap과 sample이 같은 tracing·metrics·가명화·actuator 보안을 쓰되 복사하지 않는다(S6-#7). +2. 지킬 성질: 두 조립 루트가 같은 구현을 쓴다. sample의 공개 정책이 production 기본을 바꾸지 않는다. +3. 현재 보장: 두 루트가 `runtimeOnly project(':composition:service-runtime')`. sample은 `actuatorSecurityFilterChain` 이름의 bean으로 공용 chain을 밀어낸다(`ManagementSecurityConfig`의 `@ConditionalOnMissingBean(name=…)`). 보장하지 않는 것: 공용 모듈 안의 tracing이 실제로 동작하는지(07-01) — 분리는 결함도 함께 공유한다. +4. 대안: (a) 현재. (b) 공용 배선을 support에 넣기. (c) 각 루트가 복사. +5. 득실: (b)는 support가 Spring Boot actuator·security·OTel에 의존하게 돼 모든 capability가 그 무게를 진다. (c)는 이미 갈라진 전례가 있다(S6-#7). +6. 판단: (a)가 타당하다. bean 이름으로 대체하는 방식은 문자열 계약이라, 이름이 바뀌면 sample이 조용히 공용 chain과 자기 chain을 둘 다 갖게 된다 — 이름을 상수로 공개하는 정도의 보강이 맞다. +7. 다시 볼 조건: 세 번째 조립 루트(예: 배치 전용 앱)가 생기면 web 의존 부분(actuator chain)과 비-web 부분을 나눈다. + +## 6. 리팩토링 후보 + +| 대상 | 무엇을 왜 | 보존 조건 | +| --- | --- | --- | +| `TracingConfig` 자체 Tracer | Boot tracing 모듈로 교체(07-01). 출력 없는 seam 제거 | enabled=false → Tracer 없음, `SpanErrorRecorder` NOOP 대체, prod 0.01 기본 샘플률, `trace_id` 일치 | +| `TracingSettings.sampleRate` String | `Double`(nullable)로 바꿔 파싱 1회(S6-#17) | 빈 값 = profile 기본값, [0,1] 밖이면 ENV_VALIDATION 실패 | +| `LoggingSettings` + logback env 직접 참조 | 한 출처로(07-06) | `APP_LOG_*` 키 이름·기본값, 마스킹, JSON 필드 | +| `StartupRuleRunner` 단일 시점 | 환경 rule은 EPP/BFPP 단계로(07-02) | 종료 코드 71/72/78, `startup.phase`·`error.code` 필드, rule 단위 일괄 보고 | +| `DurableOperationConfig` | `composition:*` 모듈로(07-08) | `@ConditionalOnBean` 3종 조건, 유스케이스가 bean이라 메서드 보안 프록시 적용 | +| bootstrap `security.yml` 권한 매핑 | 각 capability `module-defaults`로(07-08) | 키(역할명)·값(권한) 그대로, bracket 키 표기 | +| `Dockerfile` / `Dockerfile.sample` builder 단계 | 한 파일 + `ARG`(07-04) | 잠금 검증 단계, 레이어 순서, 비루트·읽기전용 루트 | +| bootstrap 설정 record 바인딩 | `StrictSettingsBinder`로(07-10) | 현재 기본값과 오류 메시지의 env 키 이름 | + +## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료) + +### 템플릿이 주는 틀 + +- 조립: capability는 `app-bootstrap/build.gradle`에서 한 줄. 새 capability는 자기 `AutoConfiguration.imports` + `config/module-defaults/<모듈>.yml` + README의 env 키. +- 기동 검사: `StartupRule` bean 하나를 모듈에 둔다. 비밀값은 `RequiredProductionSecrets` bean. +- 공용 런타임: tracing·metrics·가명화·actuator 보안은 `composition:service-runtime`이 준다. 파생 서비스는 손대지 않는다. +- 예시: sample WorkLog(생성·조회·수정·삭제·batch, ETag, outbox). onboarding fixture(테스트 안). +- 검증: `DefaultCompositionBootTest`(기본 조합), `qualificationBootJar`+compose lane(전부 켠 조합), `verifyEnvKeys`. + +### 빠진 것 + +- 실행본에서 인가가 실제로 도는 예시(07-03)와 객체 소유자 검사 예시. +- 트레이스가 실제로 나가는 경로(07-01). +- 예시 배치 규칙 하나(07-09). +- "새 설정 키를 추가할 때 고칠 곳" 목록: settings record, `module-defaults` yml, `docs/registries/env-keys.yaml`, `.env.example`(생성물), 모듈 README. 지금은 `verifyEnvKeys` 실패 메시지로 배운다. + +### 개발자가 여기서 내려야 하는 판단 + +1. 이 기능은 production leaf에 둘 것인가, sample에 둘 것인가? (예시는 sample, 실제 기능은 `domain-core`/`application-core`/`adapter:*`.) +2. 외부 연결이 필요한가? 필요하면 어떤 capability 줄을 켜는가, 그 capability README의 env 키를 채웠는가? +3. 이 설정 값이 틀리면 언제 알아야 하는가? 기동 시점이면 settings record compact constructor 또는 `StartupRule`. prod에서만 금지면 `RuntimeProfileSnapshot.isProduction()` 분기. +4. 그 검사가 외부 시스템에 닿기 전에 도는가? (07-02 — 지금은 개발자가 직접 확인해야 한다.) +5. 이 유스케이스의 권한은 무엇이고, 객체 소유자 검사가 필요한가? 권한 문자열은 어느 설정 파일(모듈 기본값)에 매핑하는가? +6. 응답·로그에 비밀·개인정보가 섞이는가? `user_principal`은 가명화되고, owner 원문은 응답에 넣지 않는다(sample 예시). +7. 종료 중에 진행 작업이 끝나야 하는가? async executor 대기와 컨테이너 grace를 같이 본다(07-07). +8. 기능을 지우면 무엇이 남는가? 권한 매핑·볼륨·compose 항목까지 모듈 안에 있는가(07-08)? + +## 8. 28개 관점 판정표 + +기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역 + +| 번호 | 관점 | 판정 | 한 줄 이유 | +| --- | --- | --- | --- | +| 1 | 코드 성숙도 | P | 조립 코드는 작고 명확(main 31파일 1,505줄). 출력 없는 tracing 조립과 소비자 없는 `LoggingSettings`가 남음 | +| 2 | 구조적 성숙도 | P | composition 모듈 분리·좁은 scan은 좋음. bootstrap이 capability 권한·볼륨·durable operation 조립을 가짐(07-08) | +| 3 | 변경 용이성 | P | capability 추가·삭제는 한 줄. 새 기능 예시가 세 갈래(07-09) | +| 4 | 인지 부하 | P | bootstrap `:test` 저장소 계약 테스트 45파일, sample posterimage 45클래스, 이력 주석 35줄 | +| 5 | 위험 가시성 | X | 동작 안 하는 OTLP 설정(07-01), 실행본에서 꺼진 인가(07-03), 검사 순서(07-02)가 코드에서 안 보임 | +| 6 | 실패 성숙도 | P | profile·secret·에러상세·멱등성 store 수·multi-instance 모두 fail-fast(E2·E3). prod audience 미검사(07-05), 검사 시점(07-02) | +| 7 | 운영 성숙도 | P | health/liveness/readiness 분리, graceful shutdown, 관리 포트 분리. 종료 예산 불일치(07-07), 트레이스 없음 | +| 8 | 디버깅 가능성 | P | `request_id`·`trace_id`·`user_principal` MDC, JSON 로그, 구조화 startup 실패 로그. 분산 span 없음 | +| 9 | 유지보수 성숙도 | P | 주석·README drift 다수(07-11, L-2b, L-4b, S6-#10e) | +| 10 | 테스트 성숙도 | P | 기본 조합 기동 테스트가 실제 위험을 잡음(E2). 트레이스 출력·sample 실행본 인가·Dockerfile.sample은 테스트 없음 | +| 11 | 데이터 성숙도 | > | 05 영역. 단 prod 검사 순서가 마이그레이션 뒤인 문제는 07-02 | +| 12 | 동시성 성숙도 | P | async executor는 큐 상한·거부 정책·MDC 전파가 있음. virtual thread 상한 의미 미검증(07-12) | +| 13 | 확장성 | ? | 부하·다중 인스턴스 실측 없음 | +| 14 | 성능 성숙도 | P | 기본 조합 기동 약 1.3s/회(`DefaultCompositionBootTest` 4회 5.4s, 부하 ~20), bootstrap `test` 321건 합 10.2s, systemTest 8건 14.2s. 메모리 512m·heap 75%. 부하 측정 없음 | +| 15 | 보안 성숙도 | P | prod 에러상세 차단·secret 강제·관리 체인 분리·loggers 비노출. prod 빈 audience(07-05), sample 익명 삭제(07-03), 9001 전체 공개(07-13) | +| 16 | 의존성 성숙도 | P | lockfile strict. `opentelemetry-exporter-otlp`가 실려 있으나 쓰이지 않음(07-01) | +| 17 | API / Contract 성숙도 | > | 02 영역. sample README 엔드포인트 drift만 07-11 | +| 18 | 배포 성숙도 | P | 비루트·읽기전용 루트·레이어 추출·HEALTHCHECK·digest 고정. `Dockerfile.sample` 빌드 불가(07-04) | +| 19 | 설정 성숙도 | P | `app.*` 통일, 모듈 strict 바인딩, `verifyEnvKeys` OK(346 키). bootstrap 관대한 바인딩, 로그 설정 이중 출처, compose 미검사(07-06, 07-10) | +| 20 | 개발자 경험 | P | 한 줄 선택·`bootRunH2`·`.env.example` 생성. sample 이미지·curl 예시가 동작 안 함 | +| 21 | Guardrail 성숙도 | P | ArchUnit에 sample 포함, StartupRule, 방향 게이트. `@RequiresPermission`인데 advisor 없음을 막는 장치 없음 | +| 22 | 추상화 성숙도 | O | `StartupRule`·`RequiredProductionSecrets`·`SecretSourceStrategy` 같은 확장점은 소비자가 있거나 의도된 확장점 | +| 23 | 일관성 | P | durable operation만 bootstrap 조립, bootstrap만 관대한 바인딩, 예시 배치 세 갈래 | +| 24 | 네이밍 / 의미 | P | `*Config`(일반 설정)와 `*AutoConfiguration`(imports 등록)이 섞여 이름으로 등록 방식을 알 수 없음(`DurableOperationConfig`는 imports 등록) | +| 25 | 조직 확장성 | ? | 작성자 외 사용자의 기능 추가 증거 없음 | +| 26 | Ownership 성숙도 | P | 모듈 README가 env 키를 소유. 권한 매핑·볼륨은 bootstrap이 소유(07-08) | +| 27 | 삭제 가능성 | P | capability·sample 삭제 경로는 검증됨. 지운 capability의 설정 흔적이 bootstrap에 남음 | +| 28 | 회복 가능성 | - | 기본 조합에 상태 저장소 없음. 마이그레이션 복구는 05 영역 | diff --git a/docs/reviews/2026-11-01-maturity-review/08-build-ci-test.md b/docs/reviews/2026-11-01-maturity-review/08-build-ci-test.md new file mode 100644 index 00000000..e124a52b --- /dev/null +++ b/docs/reviews/2026-11-01-maturity-review/08-build-ci-test.md @@ -0,0 +1,389 @@ +# 08 빌드 · CI · 테스트 실행 체계 리뷰 + +- 영역: `src/build-logic`, `src/settings.gradle`, `src/build.gradle`, `src/gradle`(카탈로그·wrapper), `src/gradle.properties`, + `src/config/architecture`, `.github/workflows/*`·`.github/actions/*`, `src/optional-platforms`의 빌드 부분, + strict test lane과 보조 test suite, ArchUnit lane, Spotless·Checkstyle·Error Prone·SpotBugs 설정. +- 기준 커밋: `main` `01a8a2a70`. +- 리뷰 날짜: 2026-11-01. + +## 1. 범위 + +| 항목 | 기록 | +| --- | --- | +| 대상 | `clean-architecture-backend-template`, Gradle 루트 `src/` | +| 커밋·작업 상태 | `01a8a2a70`, 작업 트리 깨끗함. 실험은 scratchpad worktree(`wt-08`)에서만 했다 | +| 목적과 지원 실행 구성 | 템플릿. PR 게이트 = `ci-quality-gates.yml`(`:ci :verifyDependencyLocks`, sample, optional-platforms, buf), main 단계 = `integration-main.yml`(`:mainCheck` 외 컨테이너 lane), 태그 = `release.yml` | +| 규모·운영 목표 | 합의된 CI 시간 목표 없음. "PR 게이트는 분 단위"라는 주석만 있다(`integration-main.yml` 주석). 아래 시간은 측정값이지 목표 대비 판정이 아니다 | +| 읽은 코드·구성 | build-logic main 전부(2,854줄), root `build.gradle`·`settings.gradle`·`gradle.properties`, `libs.versions.toml`, 15개 workflow, setup action, leaf `build.gradle` 중 app-bootstrap·web·persistence-jpa·persistence-mongo·sample-portfolio·httpclient·objectstorage·messaging-kafka, `modules.json`, Checkstyle·SpotBugs 설정, 테스트 소스 1,635개 파일(정규식 표본 조사) | +| 실행한 것 | (1) 오케스트레이터 게이트 로그 읽기: `ci` rc=0 434초, `mainCheck` rc=1 162초. (2) worktree에서 `./gradlew ci mainCheck --dry-run`, `./gradlew integrationCheck --dry-run`(둘 다 rc=0, 시작 부하 8.22). (3) build cache 실험(아래 08-02). (4) `StrictTestLanePlugin` 변이 3개 + `StrictTestLaneConventionTest` 실행(부하 7.16, 18초, 18개 중 5개 실패 = 변이 3개 모두 잡힘). (5) ci 실행이 남긴 `build/test-results/**/*.xml` 984개 집계 | +| 확인 못 한 것 | GitHub(이 저장소의 원격은 `git.learn.hyeonworks.com`)에서 workflow가 실제로 도는지. Docker Hub에서 MinIO 이미지가 사라진 시점·대체 이미지. SpotBugs 신뢰도 `HIGH` 제한이 실제로 놓치는 결함 수. 컴파일·정적분석 태스크별 시간(로그에 태스크 시간이 없고 프로파일을 돌리지 않았다) | +| 이전 리뷰와 비교 | 2026-09-18 techlead `13-build-dependency-ci.md`, 2026-09-25 followup-status 「1차 O Build/CI」 「2차 BUILD · TEST」. 그때의 실행 결과는 증거로 쓰지 않고 현재 코드로 다시 확인했다 | + +### 게이트 결과 요약 + +- `ci` rc=0, 434초(잠금 대기 포함). 663 태스크 중 643 실행, 캐시 적중 1(로컬 build cache가 16MB로 거의 비어 있었다). 시작 부하 9.15, 실행 중 20~31까지 올라갔다. +- `mainCheck` rc=1, 162초. 실패는 `:adapter:outbound:objectstorage:objectStorageMinioContractTest`·`objectStorageMinioFaultTest` 두 lane이다. 원인은 `ContainerFetchException` — `minio/minio@sha256:4c4a48…`를 Docker Hub에서 받을 수 없다(오케스트레이터 확인: `alpine:3`은 받아지고 `minio/minio:latest`도 거부됨). 코드 결함이 아니라 고정한 외부 이미지 공급원이 사라진 것이다. 이미지 자체는 05 영역이 다루고, 이 문서는 게이트 반응만 본다(08-04). +- 경고: 두 로그 모두 `--warning-mode=fail`에서 경고 없음. ci에서 건너뛴 테스트 8개는 모두 의도된 skip(`OptionalAdapterConditionalExecutionContractTest` 4, `NfsAmbiguityIntegrationTest` 3, `ProviderSandboxSmokeTest` 1). + +## 2. 지난 발견 재확인 + +| ID | 상태 | 근거 | +| --- | --- | --- | +| O-3d (ignored-source 검사 테스트 0개) | 해결 | `src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/VerifyNoIgnoredSourcePackagesFunctionalTest.java` 존재. ci 로그 `verifyNoIgnoredSourcePackages: OK — 4628 Java sources` | +| O-5a (의존성 checksum 검증 없음) | 보류(결정 19) | `src/gradle/verification-metadata.xml` 없음. 결정대로 | +| O-10a (httpclient sysprop 반복) | 남음 | `src/adapter/outbound/httpclient/build.gradle` 141~222행에 `httpclient.contract.transports`·`httpclient.http3.tests.enabled` 쌍이 6번 반복 | +| O-10b (`user.timezone=UTC` 반복) | 남음 | `git grep -c user.timezone -- '*.gradle'` = 11개 파일 28번. `JavaConventionsPlugin`에 없음 | +| O-11b (카탈로그 주석이 override 위치를 잘못 적음) | 남음 | `src/gradle/libs.versions.toml:27-31`은 `src/build.gradle`에 이유와 함께 있다고 적는다. 실제는 `src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java:135-136`이고 이유 문장이 없다 | +| O-11c (`netty.version` override가 효과 없음) | 남음 | `JavaConventionsPlugin.java:136` = `4.2.17.Final`. Boot 4.0.8 BOM(`spring-boot-dependencies-4.0.8.pom`)의 `netty.version`도 `4.2.17.Final`. `commons-lang3`는 BOM 3.19.0 → 3.20.0이라 효과 있음 | +| O-11d (optional-platforms README 개수) | 해결 | `src/optional-platforms/README.md`에 개수 표기 없음 | +| BUILD-바로할것-1b (runtime-membership 잔재 문구) | 바뀜(1곳 추가) | `.github/workflows/ci-quality-gates.yml:56`, `src/sample-portfolio/build.gradle:202`에 남음. 추가로 `src/config/architecture/README.md:12`가 "runtime membership은 build logic이 runtime classpath에서 도출한다"고 적지만 그 플러그인은 삭제됐다 | +| BUILD-순수성-이름 | 남음 | `ArchitecturePlugin.java:65` 태스크 이름 `verifyApplicationCoreDependencyPurity`, 클래스 `VerifyApplicationCoreDependencyPurityTask`. 실제 대상은 domain-core·shared-contract·application-* | +| BUILD-계획-B4-34 참고(app-bootstrap `check` → systemTest) | 남음 → 08-02로 | `src/app-bootstrap/build.gradle:90-92`. PR `ci`와 `mainCheck` 둘 다 같은 systemTest를 돌린다 | +| BUILD-계획-B3 (변경 모듈만 실행) | 보류(결정 30) | 결정대로 전체 실행 | +| P13-new-1 (plugin classpath 잠금) | 보류(결정 27) | 결정대로 | +| NEW-1b (새 CI 잡이 실제로 돈 증거 없음) | 미검증 | 원격이 GitHub가 아니다(`origin` = `git.learn.hyeonworks.com`). 그 forge의 Actions 실행 기록은 확인하지 못했다 | +| NEW-13e (집계에 묶이지 않은 lane) | 바뀜 | sample `posterImageMigrationTest`는 이제 돈다. 하지만 새로 확인한 미실행 lane 14개가 있다 → 08-01 | +| TEST-F-1 (fake와 adapter 공유 계약 부족) | 남음 | application-*·domain-core main의 `public interface *Port` 83개. fake와 adapter가 같은 추상 계약을 상속하는 것은 `DurableOperationStoreContract`, `GrpcOperationLedgerContract`, `WorkLogRepositoryContract`, `OutboxLeaseFencingContract`, `DistributedLeaseContract` 등 소수 | +| TEST-DisplayName (한국어로, 결정 5) | 남음 | `AGENTS.md:157`은 아직 "영어로 통일". 테스트 소스의 `@DisplayName` 2,444개 중 영어 2,272, 한국어 172. 규칙 문서와 소유자 결정이 서로 다르다 | +| TEST-이행-4 (계층별 모범 모듈) | 남음 | 문장 3개 이상 테스트 3,514개 중 `// when`·`// then` 주석을 가진 것 610개(17%). sample-portfolio만 141/141(100%). `adapter/outbound/redis-sdk` 221개 중 0개(정규식 추정) | + +## 3. 새 발견 + +### 08-01 — CI가 실행하지 않는 strict lane 14개 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 10, 21, 5, 11, 18 | +| 근거 | `ci`·`mainCheck` dry-run 그래프와 15개 workflow의 `./gradlew` 인자를 대조했다. 어느 쪽에도 없는 lane: ① `:adapter:outbound:persistence-jpa`의 readiness lane 11개(`src/adapter/outbound/persistence-jpa/build.gradle:166-183`) — `postgresqlLifecycle`, `SecurityBaseline`, `Migration`, `Transaction`, `Aggregate`, `Query`, `Idempotency`, `FileserverMigration`, `FileserverMetadata`, `FileserverReclamation`, `NotificationSchemaActivation`. 이들은 `integrationCheck`(`src/build.gradle:100`)에만 들어가는데, `integrationCheck`를 실행하는 workflow는 없다(`integration-main.yml:96`은 `--dry-run`으로 저장 가능 여부만 본다). 그중 9개 클래스·57개 테스트에는 다른 lane이 고르는 `@Tag`도 없다. ② `:adapter:inbound:web:performanceTest`, `webJettyPerformanceTest`(`src/adapter/inbound/web/build.gradle:145,152`) — PERFORMANCE 집계는 어디에도 연결되지 않았다. `integration-main.yml:133`의 `web-load-abuse-and-shutdown` 잡은 이름과 달리 `:adapter:inbound:web:test`와 `webJettyCompatTest`만 돌린다. ③ `:sample-portfolio:systemTest`(`src/sample-portfolio/build.gradle:172`) — sample은 `leafPaths`에서 빠져 `systemTestCheck`에 없고, sample `check`(`:199-207`)도 이 lane을 부르지 않는다 | +| 발생 조건 | 위 lane이 지키는 코드(JPA 멱등성 저장소, fileserver metadata·reclamation SQL, Flyway 경로, sample 전체 기동, Tomcat·Jetty 부하·종료)를 바꾸는 모든 PR과 main push | +| 영향 | 실제 PostgreSQL에서만 드러나는 결함이 PR·main·release 어디서도 잡히지 않는다. `config/jpa/readiness-cards.yaml`은 이 lane들을 근거로 카드 상태를 `selected`·`implemented-candidate`로 적고, `src/build-logic/README.md:47`은 "readiness lanes that require every cited scenario and reject skips"가 삭제된 JPA evidence를 대신한다고 적는다. 둘 다 실행되지 않는 lane에 기대는 주장이다. `JpaReadinessRegistryTest`는 카드가 "존재하는 태스크"를 가리키는지만 보고, 그 태스크가 실행되는지는 보지 않는다 | +| 심각도·우선순위 | High · P1. capability 완료 기준 5("실제 벤더로 도는 테스트")의 증거가 이 lane들이다. 같은 종류의 결함(H10, gRPC ledger lane)이 지난 리뷰에서 High였고, 그때 고친 방식(workflow에 이름을 하나씩 적기)이 같은 결함을 다시 만들었다 | +| 확실성 | 직접 확인: dry-run 그래프, workflow 문자열, 클래스 태그. 추론: 이 lane이 지금 통과하는지는 모른다(돌리지 않았다) | +| 결정의 근거 | 현재 선택은 "integration lane은 workflow가 이름으로 부른다"이다(`integration-main.yml:292` 주석: 카드 소속에 기대지 않고 이름으로 부른다). 이름 목록과 lane 목록이 따로 관리되니, 새 lane을 만들 때 workflow 한 줄을 빠뜨리면 아무도 모른다. `integration-main.yml:292` 주석은 "These six"라고 적지만 실제 단계는 5개다 | +| 이해 비용 | lane을 추가하는 사람이 build.gradle·workflow·집계 태스크 세 곳을 알아야 한다. 이 규칙은 어디에도 강제돼 있지 않다 | +| 최소 개선 방향 | (a) `integration-main.yml`에 `./gradlew :integrationCheck`(또는 lane별이 꼭 필요하면 `:adapter:outbound:persistence-jpa:integrationTestLaneCheck`) 한 단계를 둔다. (b) PERFORMANCE lane은 실행할 곳을 정하거나 `explicitOnly("이유")`로 바꿔 "부르지 않는다"를 코드에 드러낸다(gRPC `grpcPerformanceTest`처럼 문서로만 적지 않는다). (c) sample `systemTest`를 sample `check` 또는 `sampleWebContractCheck` 옆 main 단계에 연결한다. (d) 재발 방지: build-logic에 "explicitOnly가 아닌 모든 strict lane은 루트의 `ci`·`mainCheck`·`integrationCheck`·`performanceCheck` 중 하나에 도달한다"는 TestKit 테스트, 그리고 workflow가 그 네 집계를 모두 부른다는 테스트 하나 | +| 대안 비교 | 현상 유지(이름 나열): 새 lane마다 누락 위험이 같다. 카테고리 집계 실행(제안): workflow는 집계 4개만 알면 된다. 단점은 한 잡이 길어지는 것 — lane별 단계가 필요하면 집계를 쪼개 부르되 "모든 lane이 어떤 집계에 속한다"는 검사로 묶는다. 텍스트 contains 테스트(`DeveloperExperienceContractTest.everyOptionalPlatformIntegrationLaneHasAnExecutingWorkflowCaller`)를 main 빌드에 복제: 주석 안의 문자열에도 통과하고 lane마다 테스트를 써야 해서 기각 | +| 단순화의 보존 조건 | lane의 fail-closed 성질(아무것도 안 돌면 실패, `requires`, `rejectSkipped`)은 그대로 둔다. 변이 실험으로 이 장치는 테스트가 잘 지키고 있음을 확인했다 | +| 비용·부작용 | main 단계 시간이 PostgreSQL lane 11개만큼 늘어난다(측정 안 함). 컨테이너 lane은 `exclusiveRealServerLane`으로 하나씩 돌기 때문에 합산 시간이 그대로 더해진다 | +| 재검토 조건 | integration lane 수가 늘어 main 단계가 30분을 넘으면 집계를 잡 단위로 쪼갠다 | +| 완료 기준 | 위 14개 lane이 어떤 workflow 실행 기록에 나온다. 새 lane을 집계 밖에 만들면 build-logic 테스트가 실패한다 | +| 검증 방법 | `./gradlew ci mainCheck integrationCheck --dry-run`과 workflow 인자를 대조하는 테스트, 그리고 의도적으로 집계 밖 lane을 하나 만든 TestKit 변이 | + +### 08-02 — strict lane은 build cache도 쓰지 않아서 바뀐 것이 없어도 매번 다시 돈다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(성능), 실험으로 확인 | +| 관련 관점 | 14, 20, 9 | +| 근거 | `StrictTestLanePlugin.java:221` `test.getOutputs().upToDateWhen(ignored -> false)`. 실험(scratchpad `cc08`, Gradle 9.0.0): `@CacheableTask`에 `upToDateWhen { false }`를 주고 출력을 지운 뒤 다시 실행하면 캐시 항목이 있어도 `executed`. 같은 태스크에서 그 한 줄만 빼면 `FROM-CACHE`. 즉 이 한 줄이 up-to-date 판정뿐 아니라 build cache 적재까지 막는다. ci에서 매번 다시 도는 hermetic lane: `architectureTest` 41초, app-bootstrap `systemTest` 14초, `mongoStableContractTest` 10초, `webSecurityBoundaryTest` 5초, `httpClientStableContractTest` 4초, `httpClientSecurityTest` 약 2초, `spring62ApiSurfaceScan` 1초 미만(테스트 JVM 구간, ci 로그 시점 기준). 합계 약 77초 + JVM 기동 7회. 추가로 app-bootstrap `check`가 `systemTestLaneCheck`에 의존하고(`src/app-bootstrap/build.gradle:90-92`) `mainCheck`의 `qualificationCheck`도 같은 lane을 부른다. main push에는 `ci-quality-gates`와 `integration-main`이 둘 다 돌기 때문에 같은 systemTest가 두 번 돈다(mainCheck 로그에서 20:42에 다시 실행됨, 8개 테스트) | +| 발생 조건 | 모든 PR, main push, 로컬 `./gradlew :check` 반복 실행 | +| 영향 | PR 하나당 약 1~1.5분의 고정 비용. 문서만 고친 PR도 같다. 개발자가 `:adapter:outbound:persistence-mongo:check`를 두 번 연속 실행해도 465개 테스트가 다시 돈다 | +| 심각도·우선순위 | Medium · P2. 정확성 문제는 아니지만 모든 PR에 반복되는 비용이고, 이 lane 수가 늘수록 커진다 | +| 확실성 | 캐시 동작은 실험으로 확인(E3, 단일 태스크 실험). PR 단위 절감량은 ci 시점 측정값에서 계산한 추정 | +| 결정의 근거 | 코드 주석에 이유가 없다. 추정되는 의도는 "lane은 실행됐다는 사실 자체가 증거"라는 것이다. 하지만 캐시된 결과도 그 입력으로 실행해서 `doLast` 검사(아무것도 안 돎·skip·required 누락)를 통과한 결과다. hermetic lane에서는 입력이 같으면 결과가 같다 | +| 최소 개선 방향 | 카테고리로 나눈다: `TEST`·`ARCHITECTURE` lane은 `upToDateWhen(false)`를 빼서 캐시를 허용한다. 외부 이미지·네트워크·실제 시간에 기대는 `INTEGRATION`·`SYSTEM`·`PERFORMANCE`는 지금처럼 매번 돈다(이미지 태그가 입력으로 추적되지 않기 때문). app-bootstrap `check`→`systemTestLaneCheck` 연결은 지우거나, 남긴다면 `qualificationCheck`에서 app-bootstrap을 뺀다 | +| 대안 비교 | 현상 유지: 단순하지만 고정 비용. 전부 캐시 허용: 컨테이너 lane은 이미지가 바뀌어도 캐시 적중할 수 있어 기각. `cacheIf { category == TEST }` 같은 명시 선언(제안과 같은 효과를 이름으로 드러냄)이 가장 읽기 쉽다 | +| 단순화의 보존 조건 | lane이 실제로 실행될 때의 세 검사(0개 실행, skip, required 누락)는 그대로 둔다. `requires` 목록이 바뀌면 캐시 키도 바뀌어야 한다 — 현재 `filter.includeTestsMatching`은 Test 태스크 입력이라 키에 들어간다 | +| 비용·부작용 | 캐시된 lane은 로그에 `FROM-CACHE`로만 나와 "이번에 돌았다"는 증거가 없다. release 같은 증거 수집 잡에서는 `--rerun-tasks`로 강제하면 된다 | +| 재검토 조건 | build cache를 원격 캐시로 바꾸거나, lane이 외부 상태(파일·환경 변수)를 읽게 되면 그 lane은 캐시 대상에서 다시 뺀다 | +| 완료 기준 | 코드 변경 없이 `./gradlew ci`를 두 번 돌리면 두 번째에 hermetic lane이 `FROM-CACHE` 또는 `UP-TO-DATE`. main push에서 app-bootstrap systemTest가 한 번만 돈다 | +| 검증 방법 | build-logic TestKit: TEST 카테고리 lane을 두 번 실행해 두 번째 결과가 `UP_TO_DATE`/`FROM_CACHE`인지, INTEGRATION lane은 `SUCCESS`인지 단언 | + +### 08-03 — app-bootstrap의 PR 테스트가 저장소 문서를 읽고, 저장소 전체를 입력으로 잡는다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(규칙 불일치) + 성능 비용 | +| 관련 관점 | 23, 21, 14, 20 | +| 근거 | `AGENTS.md`("저장소 문서와 대조하는 테스트는 `mainStage()` 레인(`document-contract` 태그)으로 leaf `mainCheck`에서 돈다")와 `integration-main.yml` 주석("documentation-drift gates … are gone rather than demoted"). 그런데 app-bootstrap `src/test`의 15개 클래스가 저장소 파일을 읽는다(`ca.repository.root`·repository root 탐색). 예: `CapabilityStatusDocumentTest.java:25-35`는 `docs/capability-status.md` 본문에 특정 문자열이 있는지 단언한다. `DeveloperExperienceContractTest.java:280-284`는 `CLAUDE.md`에 `./gradlew :app-bootstrap:architectureTest` 문자열이 있는지 단언한다. 같은 클래스의 다른 테스트들은 workflow YAML 본문을 문자열로 검사한다. 태그가 없어서 PR `test`에서 돈다. 그리고 `src/app-bootstrap/build.gradle:321-334`가 모든 Test 태스크에 `docs/**`, `.github/**`, `infra/**`, `scripts/**`, 저장소의 모든 `*.md`·`**/*.gradle`을 입력으로 선언한다 | +| 발생 조건 | `CLAUDE.md`·`docs/` 문구 수정, 어느 leaf든 `build.gradle` 수정, workflow 수정 | +| 영향 | 문서 한 줄 수정이 PR 게이트를 실패시킬 수 있다(정책과 반대). 또 저장소의 어떤 문서·빌드 파일을 바꿔도 app-bootstrap `test`(321개, 약 11초), `architectureTest`, `systemTest`, `integrationTest`의 캐시가 모두 무효가 된다. 이 리뷰 문서를 추가하는 것만으로도 무효다 | +| 심각도·우선순위 | Medium · P2. 피해는 PR 시간과 소음이지만, 템플릿이 스스로 정한 규칙을 가장 큰 leaf가 어기고 있어 파생 프로젝트가 그대로 복제한다 | +| 확실성 | 규칙 위반은 직접 확인. 캐시 무효화는 Gradle 입력 선언에서 정적으로 도출(실행 측정 안 함) | +| 결정의 근거 | O-4a 수정(입력 미선언으로 UP-TO-DATE 거짓)에서 온 것이다. 정확성을 위해 입력을 넓혔고, 그 넓은 입력을 문서를 읽지 않는 테스트에까지 적용했다 | +| 최소 개선 방향 | 저장소를 읽는 15개 클래스를 `@Tag("document-contract")`(문서 대조) 또는 별도 lane으로 모으고, 그 lane에만 `repositoryContractInputs`를 준다. 문서 본문 문자열을 단언하는 테스트(`CapabilityStatusDocumentTest`, `DeveloperExperienceContractTest`의 CLAUDE.md 단언)는 mainStage로 옮기거나 지운다. workflow 구조 검사(서명 잡의 OIDC 권한 같은 보안 성질)는 YAML 파싱 테스트로 남기되 그 lane의 입력은 `.github/**`만 둔다 | +| 대안 비교 | 현상 유지: 정확하지만 PR 소음과 캐시 무효. 입력을 좁히기만: 문서 대조 테스트가 여전히 PR에 남아 규칙 위반은 그대로. 태그로 분리(제안): 규칙과 입력 범위가 같이 맞는다 | +| 단순화의 보존 조건 | O-4a의 성질(읽는 파일이 바뀌면 테스트가 다시 돈다)은 분리된 lane에서 유지한다 | +| 비용·부작용 | 문서 대조가 main 단계로 가면 PR에서는 못 잡고 merge 후에 잡는다. 이것이 AGENTS.md가 이미 고른 방향이다 | +| 재검토 조건 | 특정 문서 대조가 보안·릴리스 계약(예: OIDC 권한)이라 merge 전에 막아야 하면 그 테스트만 PR lane에 두고 이유를 주석에 적는다 | +| 완료 기준 | app-bootstrap `src/test`에서 저장소 파일을 읽는 클래스가 모두 태그·lane으로 분리된다. `docs/**`만 바꾼 커밋에서 app-bootstrap `test`가 `UP-TO-DATE`다 | +| 검증 방법 | `git grep -l 'ca.repository.root\|repositoryRoot' -- 'src/app-bootstrap/src/test'`가 태그 붙은 클래스만 나오는지, 문서만 바꾼 뒤 `:app-bootstrap:test`의 up-to-date 여부 | + +### 08-04 — 외부 컨테이너 이미지가 사라지면 main 단계가 통째로 멈춘다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(게이트 반응) + 구조적 위험(이미지 관리) | +| 관련 관점 | 16, 6, 18, 28, 9 | +| 근거 | (1) 이번 mainCheck 실패: MinIO lane 2개가 `ContainerFetchException`(Docker Hub `minio/minio` 저장소를 받을 수 없음)으로 실패. lane은 skip하지 않고 실패했다 — 이건 맞는 반응이다. (2) 하지만 CI의 main 단계는 `./gradlew :mainCheck --warning-mode=fail --stacktrace`(`integration-main.yml:81`)로 `--continue`가 없다. Gradle은 첫 실패 뒤 남은 태스크를 시작하지 않으므로, 외부 이미지 하나가 사라지면 env 계약·public path·전송 lane·문서 대조 lane의 결과가 그날 하나도 나오지 않는다(오케스트레이터는 `--continue`로 돌려서 나머지가 통과함을 확인했다). (3) 이미지 참조가 테스트 소스에 흩어져 있다: MinIO digest가 `MinioManagedObjectContractTest.java:51-52`, `MinioManagedObjectFaultTest.java:37-39`, evidence JSON 2개에 따로 있고, compose(`docker-compose.infra.yml:183`)는 다른 태그를 쓴다. `postgres:16-alpine`은 11곳에 떠 있는 태그(digest 아님)로 있다. httpclient는 build.gradle에서 httpbin digest를 주지만(`src/adapter/outbound/httpclient/build.gradle:219-224`) 테스트 기본값은 `kennethreitz/httpbin:latest`(`FailureInjectionContractTest.java:40`)다. Testcontainers 이미지 치환(`hub.image.name.prefix`·`ImageNameSubstitutor`)이나 미러 설정은 없다. (4) 같은 MinIO lane이 `object-storage-qualification.yml`(PR 경로 필터 + 주간)과 objectstorage `mainCheck`(`src/adapter/outbound/objectstorage/build.gradle:123-124`) 두 곳에서 돈다 | +| 발생 조건 | Docker Hub 저장소 삭제·이동, rate limit, 사내 네트워크에서 Docker Hub 차단 | +| 영향 | main 단계 신호 전체가 외부 공급원 하나에 묶인다. 이미지를 바꾸려면 Java 소스 여러 곳을 같이 고쳐야 하고, 빠뜨린 곳은 그 lane이 돌 때까지 모른다. 파생 서비스가 사내 레지스트리를 쓰려면 소스를 고쳐야 한다 | +| 심각도·우선순위 | Medium · P2. 지금 실제로 main 단계가 빨갛다. 데이터 피해는 없지만 다른 회귀를 가린다 | +| 확실성 | 실패와 `--continue` 부재는 직접 확인. "남은 태스크가 시작되지 않는다"는 Gradle 기본 동작이고, 이번 실행이 `--continue`로 돌아 CI와 같은 조건의 재현은 하지 않았다 | +| 결정의 근거 | 이미지를 digest로 고정한 것 자체는 좋은 선택이다(httpclient 주석이 이유를 적는다: 빨간 결과가 남의 이미지 push 때문이 아니게). 문제는 고정값을 한 곳에서 관리하지 않는 것과, 공급원이 사라졌을 때의 대응이 없는 것이다 | +| 최소 개선 방향 | (a) `integration-main.yml`의 main-check 단계에 `--continue`를 붙여 실패한 lane 이름이 전부 나오게 한다. (b) 테스트용 이미지를 한 파일(예: `src/config/testing/container-images.properties`)에 모으고, 테스트는 시스템 프로퍼티로 받는다. 각 Test 태스크가 그 파일을 입력으로 선언한다. compose·evidence JSON도 같은 값을 쓰거나, 다르면 그 이유를 적는다. (c) Testcontainers `hub.image.name.prefix`를 CI 변수로 받을 수 있게 해 사내 미러로 돌릴 수 있게 한다. (d) MinIO lane 중복은 하나만 남긴다 | +| 대안 비교 | 현상 유지: 이미지가 사라질 때마다 소스 여러 곳 수정. 공급원을 GHCR·Quay로 옮기기만: 같은 문제가 다른 공급원에서 반복. 사내 미러 의무화: 템플릿 기본값으로는 과하다 — 선택할 수 있게만 연다 | +| 단순화의 보존 조건 | digest 고정과 "받지 못하면 skip이 아니라 실패"는 유지한다 | +| 비용·부작용 | 이미지 목록 파일 하나와 읽는 헬퍼 하나가 생긴다. 이미지 갱신 PR이 그 파일 하나만 바꾸면 된다 | +| 재검토 조건 | 이미지 수가 5개 이하로 줄거나, 모든 컨테이너 테스트가 한 leaf로 모이면 파일 대신 상수 클래스 하나로 충분하다 | +| 완료 기준 | MinIO 이미지를 바꾸는 변경이 파일 1곳만 수정한다. main-check 잡이 실패해도 나머지 main lane 결과가 로그에 남는다 | +| 검증 방법 | `git grep -n 'minio/minio'` 결과가 이미지 목록 파일 하나. 존재하지 않는 digest로 바꾼 브랜치에서 main-check가 MinIO 두 lane만 실패로 보고하는지 | + +### 08-05 — registry에 없는 leaf 디렉터리는 조용히 빌드에서 빠진다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험 | +| 관련 관점 | 21, 20, 25 | +| 근거 | `ModuleRegistrySettingsInstaller.java`는 registry의 모듈만 `include`한다. `VerifyCleanArchitectureDependenciesTask`의 `declaredModules`도 settings가 포함한 프로젝트에서 나오므로, registry에 없는 디렉터리는 비교 대상이 되지 못한다. 현재는 미등록 `build.gradle`이 없다(`git ls-files '*build.gradle'`과 registry `source_path` 대조, build-logic·root·optional-platforms 제외) | +| 발생 조건 | 개발자가 새 leaf 디렉터리와 `build.gradle`을 만들고 registry 등록을 빠뜨림 | +| 영향 | 그 leaf는 컴파일도 테스트도 되지 않는데 `ci`는 초록이다. 직접 `::test`를 부르면 "project not found"로 드러나지만 `ci`만 보면 모른다 | +| 심각도·우선순위 | Low · P3. 발생하면 금방 드러날 가능성이 높고 현재 사례는 없다 | +| 결정의 근거 | 적용 제외 — 대안이 사실상 하나인 단순 guard 누락 | +| 최소 개선 방향 | settings 플러그인에서 `src/**/build.gradle` 중 registry에도 included build 목록에도 없는 파일이 있으면 실패하거나, `verifyCleanArchitectureDependencies`에 같은 검사를 둔다 | +| 완료 기준 | 미등록 `build.gradle`을 하나 만들면 `ci`가 실패한다 | +| 검증 방법 | `ModuleRegistryTest` 또는 TestKit에 미등록 디렉터리 사례 추가 | + +### 08-06 — 병렬·캐시 설정이 빌드와 lane 종류에 따라 다르게 적용된다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 개선 제안(성능) | +| 관련 관점 | 14, 23 | +| 근거 | (1) `src/optional-platforms/`에 `gradle.properties`가 없다. `-p optional-platforms`로 돌리면 `src/gradle.properties`(parallel, caching, workers.max=4, jvmargs)가 적용되지 않는다. PR의 optional-platforms 잡과 release의 gRPC 잡이 직렬·캐시 없이 돈다. (2) `StrictTestLanePlugin.java:187-199`는 TEST가 아닌 모든 lane에 build 전체에서 1개짜리 `exclusiveRealServerLane`을 건다. 주석은 "서버나 컨테이너를 띄우는 lane"이라고 하지만 `ARCHITECTURE` lane(ArchUnit, 서버 없음)도 포함된다 | +| 영향 | optional build 시간 미측정. ArchUnit lane(41초)이 서버 lane과 겹쳐 돌 수 없다 | +| 심각도·우선순위 | Low · P3 | +| 결정의 근거 | 적용 제외 — 설정 누락·조건 범위 문제 | +| 최소 개선 방향 | optional-platforms에 같은 `gradle.properties`를 두거나 `src/gradle.properties`를 가리키는 문장을 README에 적는다. 서비스 제한 조건을 `category != TEST && category != ARCHITECTURE`로 좁힌다 | +| 완료 기준 | optional build 로그에 parallel 실행. ArchUnit lane이 다른 lane과 동시에 돌 수 있다 | +| 검증 방법 | `-p optional-platforms ci --dry-run`의 `--parallel` 여부, build-logic TestKit | + +### 08-07 — SpotBugs·FindSecBugs가 신뢰도 HIGH만 보고한다 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 미검증(설정 사실은 확인, 영향은 미측정) | +| 관련 관점 | 15, 21 | +| 근거 | `QualityConventionsPlugin.java` `spotBugs.getReportLevel().set(Confidence.HIGH)`. FindSecBugs의 다수 규칙(SQL·경로 주입 등)은 보통 신뢰도 MEDIUM으로 보고된다. `exclude.xml`에는 `` 9개 | +| 영향 | 보안 정적분석이 돈다는 사실과 실제로 보는 범위가 다르다. 얼마나 놓치는지는 MEDIUM으로 한 번 돌려 봐야 안다 | +| 심각도·우선순위 | Low · P3 | +| 결정의 근거 | 코드에 이유가 없다. 오탐을 줄이려는 선택으로 보이지만 기록이 없다 | +| 최소 개선 방향 | 한 번 `Confidence.MEDIUM`으로 `qualityCheck`를 돌려 결과 수를 본다. 결과에 따라 MEDIUM + 제외 목록, 또는 HIGH 유지 + 이유 주석 | +| 완료 기준 | 설정 옆에 고른 신뢰도와 그 근거(측정한 결과 수)가 적혀 있다 | +| 검증 방법 | MEDIUM 실행 결과 수 비교 | + +## 4. 31절 시나리오 추적 + +이 영역은 요청을 처리하지 않는다. 그래서 요청 대신 "변경 하나"를 따라갔다. + +### 선택 어댑터 제거·추가 (적용) + +한 서비스가 JPA를 고르고, 다른 서비스가 JPA leaf 자체를 지운다고 가정했다. + +```text +app-bootstrap/build.gradle 주석 해제(runtimeOnly persistence-jpa) + -> strict lock 불일치 -> resolveAndLockAll --write-locks (주석이 안내) + -> modules.json app-bootstrap.allowed_dependencies에 이미 있음 -> 방향 게이트 통과 + -> systemTest가 main runtime graph로 기동 -> JPA가 켜진 기동을 검증 +``` + +| 항목 | 결과 | +| --- | --- | +| 입력의 신뢰 수준 | 개발자가 고친 build 파일. 잘못 고치면 strict lock과 방향 게이트가 막는다(M3) | +| 권한 판단 위치 | `modules.json` `allowed_dependencies`가 유일한 허용 목록. app-bootstrap은 capability 11개를 모두 미리 허용한다 | +| 규칙 소유 | registry(edge), `capabilityProjects` 목록(`app-bootstrap/build.gradle` 134~146행, ArchUnit 입력과 qualification jar), 주석 처리된 `runtimeOnly` 줄. capability 목록이 이 두 곳과 registry 세 곳에 있다 | +| 성공의 의미 | `ci` 초록 = 컴파일·단위·ArchUnit·systemTest(현재 조립). 고른 capability의 실제 벤더 lane은 PR에 없고, JPA readiness lane은 어디서도 돌지 않는다(08-01) | +| 오류 변환 | lock 불일치, 금지 edge 모두 Gradle 오류로 위치와 함께 나온다 | +| 제거(leaf 자체 삭제) | 선택 해제는 한 줄이지만 leaf 삭제는 아니다. app-bootstrap `build.gradle`에 `persistence-jpa`가 9번(`testImplementation`, `integrationTestImplementation`, testFixtures, `capabilityProjects`, `bootRunH2Classpath` 등) 나오고, app-bootstrap 테스트 7개 파일이 persistence 타입을 import한다. 파생 프로젝트가 JPA leaf를 지우려면 이 테스트들도 정리해야 한다. AGENTS.md 기준 7("한 줄을 지우면 기능이 완전히 사라진다")은 선택 해제에 대한 말이고, leaf 삭제 비용은 문서에 없다 | + +### 적용 제외 + +정상 쓰기, 중복·동시 요청, 외부 응답 지연, DB 오류, 메시지 중복, 세션·토큰, 다른 사용자 리소스, 큰 입력, 종료·재시작: 빌드·CI 영역에는 요청 경로가 없다. 각 영역 리뷰가 다룬다. "신·구 버전 공존"은 gRPC buf breaking 검사(`ci-quality-gates.yml` `grpc-proto-buf`)만 이 영역에 있고, 확인했다(PR·push에서 baseline 대비 `buf breaking`). + +## 5. 41절 설계 선택 검토 + +### 5.1 integration lane을 workflow가 이름으로 부르는 방식 + +1. 필요한 것: 컨테이너가 필요한 lane은 PR이 아니라 main 단계에서 실패가 보이게 돌아야 한다. +2. 지킬 성질: 선언한 strict lane은 어딘가에서 반드시 실행된다. +3. 현재 보장: 없다. lane 자체는 "실행되면 fail-closed"를 잘 지킨다(변이 3개 모두 테스트가 잡음). 하지만 "실행되는가"는 workflow 문자열에 달려 있고, 검사는 optional build 하나에 대한 문자열 contains 테스트뿐이다. +4. 대안: (a) 현상 유지, (b) 카테고리 집계를 workflow가 부르기, (c) 집계 + "모든 lane은 집계에 속한다" 검사. +5. 비용: (a) 누락 재발(지금 14개). (b) 잡 하나가 길어진다. (c) build-logic 테스트 하나 추가. +6. 현재 조건의 선택: (c). 집계는 이미 있고(`integrationCheck`), 부르지 않을 뿐이다. +7. 바뀔 조건: lane별 실패를 따로 보고 싶으면 집계를 여러 잡으로 나누되, 검사(c)는 유지한다. + +### 5.2 strict lane을 항상 다시 실행하는 방식(`upToDateWhen(false)`) + +1. 필요한 것: lane이 통과했다는 것이 "지정한 테스트가 실제로 돌았다"는 뜻이어야 한다. +2. 지킬 성질: 0개 실행·skip·required 누락이 성공으로 보고되지 않는다. +3. 현재 보장: `doLast` 검사로 지킨다. 그런데 이 검사는 캐시된 결과에도 이미 한 번 적용된 상태다. `upToDateWhen(false)`는 이 성질에 더하는 것이 없고, 외부 상태에 기대는 lane에서만 의미가 있다. +4. 대안: 현상 유지 / 카테고리별 캐시 허용 / 전부 캐시. +5. 비용: 현상 유지는 PR당 약 77초 + JVM 7회(08-02). 전부 캐시는 이미지 태그 변화를 못 본다. +6. 선택: 카테고리별. hermetic(TEST·ARCHITECTURE)만 캐시. +7. 바뀔 조건: hermetic lane이 저장소 파일이나 환경 변수를 읽기 시작하면 입력 선언을 먼저 하고, 못 하면 캐시에서 뺀다. + +### 5.3 저장소 대조 테스트를 어디서 돌리는가 + +1. 필요한 것: 빌드·workflow·문서의 일부 계약(OIDC 권한, Docker 단계 구조)은 회귀하면 안 된다. +2. 지킬 성질: 계약 회귀를 잡되, 문서 문구 수정으로 PR이 막히지 않는다(AGENTS.md의 정책). +3. 현재 보장: 정책은 3개 leaf만 따른다. app-bootstrap은 15개 클래스가 PR `test`에서 문서를 읽는다(08-03). +4. 대안: 현상 유지 / 전부 main 단계 / 보안·릴리스 계약만 PR, 나머지 main. +5. 비용: 현상 유지는 문서 수정 PR 소음과 캐시 무효. 전부 main은 OIDC 권한 회귀를 merge 후에 잡는다. +6. 선택: 세 번째. 보안 계약은 이유 주석과 함께 PR에 남긴다. +7. 바뀔 조건: 문서 대조 테스트가 거의 없어지면 lane 없이 태그 하나로 충분하다. + +## 6. 리팩토링 후보 + +| 무엇 | 왜 | 보존할 동작·실패 계약 | +| --- | --- | --- | +| lane 도달성 검사 추가, workflow가 카테고리 집계를 부르게 | 08-01 재발 방지 | lane의 fail-closed 검사 3종, `explicitOnly` 이유 출력 | +| hermetic lane 캐시 허용 | 08-02 | 실행 시 3종 검사. INTEGRATION·SYSTEM·PERFORMANCE는 매번 실행 | +| app-bootstrap 저장소 대조 테스트 분리, 입력 범위 축소 | 08-03 | 읽는 파일이 바뀌면 그 lane은 다시 돈다(O-4a) | +| 테스트 컨테이너 이미지 목록 한 파일로 | 08-04 | digest 고정, 받지 못하면 실패 | +| `-Duser.timezone=UTC`를 `JavaConventionsPlugin`의 모든 Test 태스크로 | O-10b, 28번 반복 | UTC 고정. lane이 jvmArgs를 덮어쓰는 현재 구조(`test.setJvmArgs`)에서 사라지지 않게 `jvmArgumentProviders`나 `systemProperty`로 넣는다 | +| httpclient 공통 sysprop을 `tasks.withType(Test).configureEach` 하나로 | O-10a | lane별 다른 값(`performance.assertions.enabled`, httpbin 이미지)은 그 lane에만 | +| 순수성 태스크 이름 `verifyModuleDependencyPurity` 계열로 통일 | BUILD-순수성-이름 | 루트 alias 이름이 바뀌면 workflow·문서 호출부도 같이 | +| `netty.version` override 삭제, `commons-lang3` override에 이유 주석, 카탈로그 주석 위치 수정 | O-11b·O-11c | 해석되는 버전이 바뀌지 않음을 lockfile diff 0으로 확인 | + +## 7. 기능 개발 패턴과 판단 지점 (매뉴얼 재료) + +### 템플릿이 주는 틀 + +- leaf 성격 선언: `ca.java-library` / `ca.spring-library` / `ca.platform-module` 중 하나. toolchain·lock·정적분석·Mockito agent·JUnit BOM이 따라온다. +- 추가 테스트 소스: `testing { suites { xxx(JvmTestSuite) } }` + 같은 이름의 `strictTestLanes { lane('xxx') { integration() … } }`. +- 아키텍처 경계: `modules.json`에 edge를 적으면 방향 게이트가 나머지를 막는다. +- 모범 테스트: `sample-portfolio`(GWT 100%), 공유 계약 예시 `WorkLogRepositoryContract`·`DurableOperationStoreContract`. + +### 빠진 것 + +- "새 leaf 추가" 순서를 한 곳에 적은 문서가 없다(registry → build.gradle → lock 생성 → capability면 app-bootstrap `capabilityProjects`·주석 줄 → README 3항목). +- "새 lane을 어디서 돌릴지" 고르는 기준과 검사가 없다(08-01). +- 테스트 컨테이너 이미지를 어디에 적는지 규칙이 없다(08-04). +- application 포트 83개 중 공유 계약을 가진 것은 소수다. 새 포트를 만들 때 계약 클래스를 같이 만들라는 틀(예시 계약 + 빈 템플릿)은 sample에만 있다. + +### 개발자가 내려야 하는 판단 + +1. 이 코드는 어느 leaf 소유인가 → `modules.json` `source_path`. 없는 leaf면 registry부터. +2. 이 테스트는 어떤 lane인가 → 외부 프로세스 없음 = `test`. 문서·저장소 파일 대조 = `@Tag("document-contract")` + `mainStage()`. 컨테이너·실제 서버 = 별도 suite + `integration()`/`system()`. 측정 = `performance()`. +3. 그 lane은 누가 실행하는가 → 지금은 사람이 workflow에 적어야 한다. 적지 않을 거면 `explicitOnly("이유")`. +4. 테스트가 저장소 파일을 읽는가 → 그 파일을 그 Test 태스크의 `inputs`로 선언한다. 넓게 잡으면 캐시가 무효가 된다(08-03). +5. 컨테이너 이미지는 digest로 고정했는가, 다른 테스트와 같은 값인가. +6. 의존성을 바꿨는가 → `./gradlew resolveAndLockAll --write-locks`, lock diff 확인. BOM이 관리하는 버전은 카탈로그에 적지 않는다. +7. 포트를 새로 만들었는가 → 포트 소유 모듈 testFixtures에 fake 하나와 추상 계약 하나, adapter 테스트가 같은 계약을 상속. + +## 8. 테스트 실행 성능 + +측정 조건: 오케스트레이터 `ci` 1회, 같은 머신에서 다른 에이전트가 함께 돌아 부하 9~31. 로컬 build cache가 거의 비어 643/663 태스크가 실제 실행. 숫자는 이 조건의 한 번 측정이다. + +| 항목 | 값 | +| --- | --- | +| `ci` 전체 | 434초(잠금 대기 포함), BUILD 7분 9초 | +| ci가 실행한 Test 태스크 | 58개, 테스트 6,115개, skip 8 | +| 테스트 클래스 시간 합 | 약 208초 | +| Test 태스크 JVM 구간 합 | 약 257초(4 worker로 겹쳐 실행) | +| 결론 | ci 시간의 대부분은 테스트가 아니라 컴파일(Error Prone 포함 55개)·SpotBugs 53개·Checkstyle 106개·Spotless 53개다. 태스크별 시간은 프로파일을 돌리지 않아 미측정 | + +가장 느린 테스트 클래스(ci): + +| 초 | leaf | 태스크 | 클래스 | 테스트 수 | +| --- | --- | --- | --- | --- | +| 9.3 | persistence-jpa | test | PersistenceJpaCapabilityAssemblyTest | 5 | +| 7.8 | app-bootstrap | systemTest | BootstrapCapabilityReachabilitySystemTest | 2 | +| 6.6 | app-bootstrap | architectureTest | AdapterBoundaryArchitectureTest | 17 | +| 5.9 | objectstorage | test | S3AsyncClientFactoryTest | 4 | +| 5.4 | app-bootstrap | systemTest | DefaultCompositionBootTest | 4 | +| 3.5 | objectstorage | test | ObjectStorageArchitectureTest | 1 | +| 3.5 | messaging-kafka | test | KafkaCapabilityActivationTest | 4 | +| 3.0 | cache-redis | test | RedisCapabilityActivationTest | 2 | +| 2.9 | redis-runtime | test | RedisRuntimeAutoConfigurationTest | 20 | +| 2.7 | graphql | test | GraphQlProductionClassesTest | 1 | +| 2.5 | objectstorage | test | LocalDevObjectStorageRecoveryTest | 5 | +| 2.5 | persistence-mongo | test | MongoCapabilityActivationTest | 4 | +| 2.5 | web | test | SecurityModeWebContractTest | 5 | +| 2.4 | notification-platform | test | ProviderCallbackIngressBridgeTest | 5 | +| 2.4 | fileserver-platform | test | FileserverPlatformAutoConfigurationTest | 11 | +| 2.4 | web | webSecurityBoundaryTest | CorsSecurityFilterIntegrationTest | 5 | +| 2.2 | web-fileserver | test | MvcUploadExecutorSaturationTest | 5 | +| 2.2 | cache-redis | test | RedisCapabilityCompositionTest | 9 | +| 2.1 | idempotency | test | IdempotencyAutoConfigurationTest | 6 | +| 2.1 | objectstorage | test | S3ProviderCompositionTest | 6 | + +leaf·태스크별 합(상위): objectstorage `test` 19.4초(130), app-bootstrap `architectureTest` 17.1초(181, JVM 구간 41초 — ArchUnit 클래스 import가 클래스 시간 밖에서 쓰인다), persistence-jpa `test` 16.6초(502), app-bootstrap `systemTest` 14.2초(8), app-bootstrap `test` 10.2초(321), graphql `test` 9.7초(377). + +Spring 컨텍스트: + +- `@SpringBootTest`/`@WebMvcTest`/`@DataJpaTest` 사용 파일은 49개로 적고, 대부분 system·integration suite에 있다. `@DirtiesContext` 0개. `@MockitoBean` 6개 파일은 모두 sample-portfolio다(컨트롤러 wire 테스트마다 mock 조합이 달라 클래스마다 컨텍스트 캐시 미스가 난다. sample 테스트 합은 마지막 기록(9월 28일)에서 5.9초라 비용은 작다. 다만 adopter가 복사하는 원본이라 패턴이 퍼진다). +- 가장 많이 쓰는 방식은 `ApplicationContextRunner` 109개 파일이다. 캐시가 없고 `run()`마다 작은 컨텍스트를 새로 만든다. ci에서 이 클래스 99개가 574개 테스트, 49.5초(테스트 시간의 26%)를 쓴다. 테스트당 약 86ms라 지금은 문제 없다. 가장 느린 20개 중 절반이 이 종류(조립·활성화 테스트)다. +- JUnit 병렬 실행 설정(`junit-platform.properties`) 없음. app-bootstrap `test`만 `maxParallelForks = 2`. + +Gradle 설정: `org.gradle.parallel=true`, `org.gradle.caching=true`, `workers.max=4`, configuration cache는 꺼져 있다(이유가 `src/gradle.properties`에 적혀 있고, `integration-main.yml` `configuration-cache` 잡이 저장 가능성을 매번 확인한다). optional-platforms는 이 설정을 받지 못한다(08-06). 강제 재실행 비용은 08-02. + +## 9. 테스트 작성 규칙 표본 조사 + +방법: 테스트 소스(`testFixtures` 제외)의 `@Test`·`@ParameterizedTest` 메서드 6,943개를 정규식으로 읽었다. 문장 수는 깊이 0의 `;` 개수로 셌다. 추정치다. + +| 규칙(AGENTS.md) | 결과 | +| --- | --- | +| 1. 행동 문장 이름 | 거의 지켜짐. `test` 접두·밑줄·대문자 시작 5개 | +| 2. `@DisplayName` 언어 | 규칙은 영어, 소유자 결정 5는 한국어. 실제 영어 2,272 / 한국어 172. 최근 수정 파일(예: `DeveloperExperienceContractTest`, `JpaReadinessRegistryTest`)은 한국어, 같은 클래스 안에서도 섞인다 | +| 3. GWT 주석, `// when` 하나 | 문장 3개 이상 3,514개 중 610개(17%)만 주석을 가짐. `// when` 2개 이상은 1개. 규칙은 "새로 쓰거나 고치는 테스트"에만 적용이라 위반으로 세지 않았다. 모범은 sample(100%)뿐이고 production leaf 중 최고는 support(53%) | +| 5. 약한 단언만 있는 테스트 | 단언이 하나이고 그것이 `isNotNull`/`isPresent`/`doesNotThrowAnyException`인 테스트 125개 | +| 예외 when 분리 | `assertThatThrownBy` 포함 1,528개, `catchThrowable` 227개 | +| 6. 포트당 fake 하나, 공유 계약 | 포트 83개 중 fake와 adapter가 같은 추상 계약을 상속하는 것은 소수(2절 TEST-F-1) | + +이 영역의 테스트가 위험을 잡는지: build-logic의 strict lane 장치에 변이 3개(0개 실행 검사 끄기, `rejectSkipped` 끄기, `explicitOnly` 필터 끄기)를 넣고 `StrictTestLaneConventionTest`를 돌렸다. 5개 테스트가 실패해 3개 변이를 모두 잡았다. 장치 자체의 테스트는 충분하다. 빠진 것은 "lane이 실행되는가"에 대한 검사다(08-01). + +## 10. 28개 관점 판정표 + +| 번호 | 관점 | 판정 | 한 줄 이유 | +| --- | --- | --- | --- | +| 1 | 코드 성숙도 | O | build-logic은 작은 플러그인으로 나뉘고 TestKit 테스트가 있다(main 2,854줄) | +| 2 | 구조적 성숙도 | O | registry 하나가 프로젝트 포함·방향·순수성의 근거이고 leaf별 태스크로 병렬 안전 | +| 3 | 변경 용이성 | P | 선택 해제는 한 줄이지만 capability 목록이 registry·`capabilityProjects`·주석 줄 세 곳, lane 추가는 workflow까지 손대야 함 | +| 4 | 인지 부하 | P | 주석은 이유를 잘 적지만 lane이 어디서 도는지 한눈에 볼 곳이 없다 | +| 5 | 위험 가시성 | P | readiness 카드·README가 실행되지 않는 lane을 근거로 든다(08-01) | +| 6 | 실패 성숙도 | P | lane은 fail-closed. 하지만 main 단계는 첫 실패에서 멈춘다(08-04) | +| 7 | 운영 성숙도 | > | 배포·운영은 다른 영역. release 서명·SBOM은 확인만 함 | +| 8 | 디버깅 가능성 | P | lane 실패 메시지가 구체적. 다만 main-check는 실패 하나 뒤 나머지 결과가 없다 | +| 9 | 유지보수 성숙도 | P | 지난 Nit 다수 남음(O-10a·b, O-11b·c, 이름) | +| 10 | 테스트 성숙도 | P | 장치 테스트는 강함(변이 3/3). 실제 벤더 lane 14개 미실행, GWT 17%, 공유 계약 소수 | +| 11 | 데이터 성숙도 | > | 마이그레이션 검증 lane이 안 도는 것은 08-01로 연결, 데이터 자체는 05 영역 | +| 12 | 동시성 성숙도 | - | 빌드 영역에 해당 없음(lane 직렬화 서비스만 확인) | +| 13 | 확장성 | P | leaf·lane이 늘면 이름 나열 방식의 누락 위험이 비례해서 커진다 | +| 14 | 성능 성숙도 | P | 테스트는 병목이 아님(클래스 합 208초). 강제 재실행 약 77초/PR, 중복 systemTest, optional build 설정 누락 | +| 15 | 보안 성숙도 | P | action SHA 고정, wrapper 검증, Trivy+KEV, cosign 서명. SpotBugs는 HIGH만(08-07) | +| 16 | 의존성 성숙도 | P | strict lock, 카탈로그, Renovate(보안만). 테스트 이미지 관리가 흩어짐(08-04), 효과 없는 override(O-11c) | +| 17 | API / Contract 성숙도 | O | `ca.api-surface`가 PR `check`에서 돈다(결정 20), buf lint·breaking | +| 18 | 배포 성숙도 | > | release.yml은 확인만, 배포 영역 | +| 19 | 설정 성숙도 | O | `verifyEnvKeys`가 main 단계에서 돈다(결정 4). 빌드 설정값은 이유와 함께 `gradle.properties`에 있음 | +| 20 | 개발자 경험 | P | leaf focused 명령이 단순. 문서 수정이 PR을 실패시킬 수 있고(08-03) hermetic lane이 캐시되지 않음 | +| 21 | Guardrail 성숙도 | P | 방향·순수성·lock·ignored-source는 M3~M4. lane 도달성·미등록 leaf는 M0(08-01, 08-05) | +| 22 | 추상화 성숙도 | O | `strictTestLanes` DSL 하나로 5개 구현을 대체했고 과하지 않다 | +| 23 | 일관성 | P | document-contract 규칙을 3개 leaf만 따름(08-03), 이미지 고정 방식 혼재, upload-artifact v4·v7 혼재 | +| 24 | 네이밍 / 의미 성숙도 | P | 순수성 태스크 이름, `web-load-abuse-and-shutdown` 잡 이름이 하는 일과 다름 | +| 25 | 조직 확장성 | P | 새 기여자가 lane 실행 위치를 알 방법이 workflow 검색뿐 | +| 26 | Ownership 성숙도 | ? | CODEOWNERS는 있으나 내용과 실제 리뷰 흐름은 확인 안 함 | +| 27 | 삭제 가능성 | P | 선택 해제는 쉬움. leaf 삭제는 app-bootstrap 테스트·빌드 9곳 수정 필요(4절) | +| 28 | 회복 가능성 | P | 외부 이미지가 사라졌을 때 미러·치환 경로가 없다(08-04) | + +## 부록 — 실행 명령 + +```bash +# 게이트 로그(오케스트레이터 실행, 읽기만) +scratchpad/gates/{summary.txt,ci.log,mainCheck.log} + +# 도달성 확인 (worktree wt-08, flock, 시작 부하 8.22) +./gradlew ci mainCheck --dry-run --console=plain # rc=0 +./gradlew integrationCheck --dry-run --console=plain # rc=0 + +# build cache 실험 (scratchpad/cc08, Gradle 9.0.0) +# upToDateWhen{false} + 출력 삭제 후 재실행 -> executed +# 같은 태스크에서 그 줄 제거 -> FROM-CACHE + +# 변이 실험 (worktree wt-08, 시작 부하 7.16, 18초) +./gradlew -p build-logic test --tests 'dev.caskeleton.buildlogic.strictlane.StrictTestLaneConventionTest' --continue +# 18개 중 5개 실패 = 변이 3개 모두 검출. 원복 확인(git status 깨끗) + +# 테스트 시간 집계: build/test-results/**/TEST-*.xml (ci 실행 구간 20:33~20:41) +``` diff --git a/docs/reviews/2026-11-01-maturity-review/09-performance-measurement.md b/docs/reviews/2026-11-01-maturity-review/09-performance-measurement.md new file mode 100644 index 00000000..998892be --- /dev/null +++ b/docs/reviews/2026-11-01-maturity-review/09-performance-measurement.md @@ -0,0 +1,556 @@ +# 09. 런타임 성능 실측 — 2026-11-01 성숙도 리뷰 + +이 문서는 코드 리뷰보다 측정 숫자를 앞에 둔다. 모든 숫자는 아래 「측정 조건」에서 나왔다. 같은 측정은 3회 반복했고, 표에는 중앙값을 적었다. 다른 세션이 같은 머신을 쓰고 있었으므로 측정 직전 load average를 함께 적었다. load average가 15를 넘은 회차는 표에 `(부하 높음)`으로 표시했다. + +## 1. 범위 (36.1) + +| 항목 | 기록 | +| --- | --- | +| 대상 | `clean-architecture-backend-template`, Gradle 루트 `src/` | +| 커밋 | `main` `01a8a2a70`. 측정은 별도 worktree(`/wt-09`)에서 했다. 메인 repo에서는 Gradle을 돌리지 않았다. | +| 목적과 실행 구성 | (1) 기본 조합 `app-bootstrap` bootJar, `local` 프로필. (2) `sample-portfolio` bootJar + PostgreSQL 16(alpine, Docker, `--cpus 4 --memory 1g`), `local` 프로필. | +| 규모 목표 | 템플릿에 명시된 지연·처리량 목표가 없다. 그래서 「좋다/나쁘다」 대신 요청당 비용(SQL 수, 지연, 처리량)과 그 비용이 데이터 수에 비례하는지를 판정 기준으로 썼다. | +| 읽은 코드·설정 | `app-bootstrap/build.gradle`, `app-bootstrap/src/main/resources/{application.yml,application-local.yml,config/*.yml}`, `sample-portfolio/build.gradle`, `sample-portfolio/src/main/resources/application.yml`, `sample-portfolio` 의 web controller·use case·persistence adapter·entity·mapper·migration(V7), `adapter/outbound/persistence-jpa` 의 `SpringTransaction`·`module-defaults/persistence-jpa.yml`, `adapter/inbound/web` 의 `JwtDecoderConfig`·`PageParams`·`PresentationWebConfig`·필터 4종, `composition/service-runtime` 의 `ManagementSecurityConfig`, `Dockerfile` JVM 옵션 | +| 실행한 측정 | 아래 「측정 명령」 절. bootJar 빌드 1회, 기동 3~4회씩, SQL 수 세기, 부하 측정 약 45회(워밍업 포함), 설정만 바꾼 실험 3종, JFR 2회, 동시 중복 생성 실험 3회 | +| 확인 못 한 것 | 아래 「미검증」 절 | +| 게이트 결과 | 오케스트레이터 실행: `ci` rc=0. `mainCheck` rc=1 — `objectStorageMinioContractTest`·`objectStorageMinioFaultTest`가 `minio/minio` 이미지 pull 실패(공급원 소멸)로 실패. 이 영역의 숫자와 무관하다. | +| 이전 리뷰와 비교 | 이전 리뷰에는 성능 실측 영역이 없었다. 성능 관련 지난 발견(05-persistence-jpa의 N+1·Hikari 항목)만 2절에서 재확인했다. 지난 리뷰의 실행 숫자는 쓰지 않았다. | + +### 측정 조건 + +| 항목 | 값 | +| --- | --- | +| 하드웨어 | 22 vCPU, RAM 30 GiB, Linux 7.0.0. 다른 세션(프론트 vitest, 게이트)이 같은 머신에서 돌았다. | +| JVM | OpenJDK 21.0.12.1, `-Xmx1g -XX:+ExitOnOutOfMemoryError`, G1 기본. 컨테이너가 아니라 호스트에서 `java -jar`로 띄웠다. Dockerfile의 `MaxRAMPercentage=75`는 호스트에서 22 GiB 힙이 되므로 1 GiB 컨테이너에 가까운 `-Xmx1g`를 골랐다. | +| DB | `postgres:16-alpine`, 127.0.0.1:25432, `--cpus 4 --memory 1g`, 튜닝 없음 | +| 데이터 | `work_log` 10,000행(행마다 `tech_stack` 2행, `link` 1행, `content` 500자). `poster`는 측정 중 쌓여 23,071행까지 늘었다. | +| 부하 도구 | `wrk`·`hey`·`ab` 미설치. JDK `HttpClient`로 만든 닫힌 루프 생성기(`perf/Load.java`). 동시성 N개 스레드가 응답을 받자마자 다음 요청을 보낸다. 측정 시간의 앞 20%는 워밍업으로 버린다. 부하 생성기가 같은 호스트에서 돈다. | +| 캐시 | 애플리케이션 캐시 없음(샘플 기본값 `disabled`). PG 버퍼 캐시는 워밍업 뒤 상태. | + +### 측정 명령 (다시 돌리는 법) + +스크립트는 모두 `/perf/`에 두고 썼다. 핵심 명령만 옮긴다. 무거운 실행은 전부 `flock `으로 감쌌다. + +```bash +# 0) worktree와 jar +git -C worktree add /wt-09 01a8a2a70 +cd /wt-09/src +flock ./gradlew :app-bootstrap:bootJar :sample-portfolio:bootJar --console=plain -q + +# 1) jar 구성 +unzip -l app-bootstrap/build/libs/app-bootstrap-0.0.1-SNAPSHOT.jar | awk '$4 ~ /BOOT-INF\/lib\/.*\.jar$/' + +# 2) 기동 측정 (run-app.sh: 백그라운드 기동 → "Started ... in" 대기 → 3초 뒤 RSS·heap·빈 수·스레드 수) +# 빈 수는 spring.jmx.enabled=true + management.endpoints.jmx.exposure.include=beans 로 켜고 +# Attach API로 Beans MBean을 부르는 Beans.java 로 셌다(코드 변경 없음). +java -Xmx1g -XX:+ExitOnOutOfMemoryError -Dspring.jmx.enabled=true \ + -Dmanagement.endpoints.jmx.exposure.include=beans -jar +awk '/VmRSS/{print $2}' /proc//status ; jcmd GC.heap_info ; java Beans.java + +# 기본 조합 +SPRING_PROFILES_ACTIVE=local MANAGEMENT_SERVER_PORT=19001 ./run-app.sh boot-N +# 샘플 +docker run -d --name perf09-pg -e POSTGRES_DB=ca_skeleton -e POSTGRES_USER=ca_skeleton \ + -e POSTGRES_PASSWORD=ca_skeleton -p 127.0.0.1:25432:5432 --cpus 4 --memory 1g postgres:16-alpine +APP_DATASOURCE_URL=jdbc:postgresql://127.0.0.1:25432/ca_skeleton APP_SERVER_PORT=18081 \ + MANAGEMENT_SERVER_PORT=19002 SPRING_PROFILES_ACTIVE=local ./run-app.sh sample-N + +# 3) 요청당 SQL 수: PG 쪽에서 모든 문장을 로그로 남기고, 요청 하나 전후의 로그 줄을 센다(앱 설정 변경 없음) +docker exec perf09-pg psql -U ca_skeleton -d ca_skeleton -c "alter system set log_statement='all'" +docker exec perf09-pg psql -U ca_skeleton -d ca_skeleton -c "select pg_reload_conf()" +./sqlcount.sh list20 "http://localhost:18081/api/worklogs" # LOG: statement|execute 줄 수 +# 측정 뒤 log_statement='none' 으로 되돌리고 부하 측정 + +# 4) 부하: java Load.java <동시성> <초> [body.json] +java -Xmx512m Load.java GET http://localhost:18081/api/worklogs/ 16 15 + +# 5) 설정만 바꾼 실험 +java ... -Dspring.jpa.properties.hibernate.default_batch_fetch_size=100 -jar +SPRING_THREADS_VIRTUAL_ENABLED=true ./run-app.sh sample-vt + +# 6) JFR (부하 중 20초) +jcmd JFR.start name=p settings=profile filename=getone.jfr duration=20s +jfr print --events jdk.ExecutionSample getone.jfr # 상위 프레임 집계 +``` + +### 미검증 + +| 항목 | 이유 | +| --- | --- | +| `POST /api/worklogs`(대표 쓰기)와 `POST /api/worklogs:batchCreate`의 SQL 수·지연 | 단독 실행한 샘플에서 이 경로가 항상 500으로 끝난다(09-03). 대신 같은 outbox 패턴을 쓰는 `POST /api/posters`를 쟀다. | +| async-profiler 기반 CPU flame graph | `asprof` 미설치. JFR(`jdk.ExecutionSample`)로 대신했다. | +| 컨테이너 안(cgroup 1 GiB) 기동 시간·RSS | 이미지 빌드는 이 영역 범위 밖이고 base image pull이 필요하다. 호스트 `-Xmx1g`로 근사했다. | +| 장시간(수십 분) 메모리·커넥션 누적 | 측정 창이 회차당 15~20초다. 누수 판정 근거가 없다. | +| Redis·Kafka·Mongo 등 capability를 켠 조합 | 기본 조합과 샘플만 쟀다. | +| 실제 IdP를 거친 JWT 검증 비용 | 샘플은 모든 경로를 `permitAll`로 연다. 기본 조합에는 JWT로 보호된 업무 엔드포인트가 없다. 토큰 없는 401 경로만 쟀다. | + +## 2. 지난 발견 재확인 + +| ID (출처) | 내용 | 상태 | 근거 | +| --- | --- | --- | --- | +| 05-persistence-jpa 「N+1 구조적으로 불가」 | persistence-jpa leaf에 연관관계가 없어 N+1이 없다 | 바뀜 | leaf 안에서는 여전히 사실이다. 그러나 템플릿이 따라 하라고 내놓은 `sample-portfolio`의 목록 API가 N+1이다(09-01). 실측 SQL 46개/페이지(20건). | +| 05-persistence-jpa M8 | `HibernateEnversHistoryReader.revisions`가 1+N | 해결 | `adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/envers/HibernateEnversHistoryReader.java:82` — 리비전 번호를 한 번에 읽고, 리비전별 `find()` 루프가 없다. | +| 05-persistence-jpa H6 | 트랜잭션 포트가 `HikariDataSource`로 언랩을 강제 | 해결 | `persistence-jpa/src/main` 아래 `HikariDataSource` 참조 0건(grep). | +| 05-persistence-jpa 「풀 env 조정 부분」 | `keepalive-time`·`leak-detection-threshold`·`validation-timeout`이 env 없이 하드코딩 | 남음 | `adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml:55,63,72`. 주석이 여전히 "UNSUPPORTED_IMPL_DECISION … delegated"라고 적는다. 성능 결함은 아니다. | +| maintainability-review #16 | hikari `connection-timeout` 주석이 이력 서술 | 남음(Low) | `persistence-jpa.yml:28-38`. 같은 키를 샘플은 30000으로 덮는다(09-08). | + +## 3. 측정 결과 + +### 3.1 아티팩트와 기동 + +| 항목 | 기본 조합 `app-bootstrap` | `sample-portfolio` | +| --- | --- | --- | +| bootJar 크기 | 41.4 MB | 99.0 MB | +| `BOOT-INF/lib` jar 수 / 합계 | 114개 / 39.2 MiB | 203개 / 93.9 MiB | +| 큰 의존성 | tomcat-embed-core 3.6 MB, spring-web 2.2, prometheus exposition 2.1, spring-security-config 2.1, **jackson-databind 3.1.5 1.9 + jackson-databind 2.21.5 1.7**, **kotlin-stdlib 1.8**(OTLP okhttp sender) | hibernate-core 14.5 MB, byte-buddy 9.0, s3 3.8, **h2 2.7**, aspectjweaver 2.2, netty 13개 | +| 기동 `Started ... in` (3회) | 3.637 / 3.179 / 3.435 s → **중앙값 3.44 s** (4번째 회차 3.592) | 8.596(첫 회, Flyway 23개 적용) / 8.045 / 7.662 s → **중앙값 8.05 s** (VT 회차 7.607) | +| JVM 시작부터 (`process running for`) | 3.55~4.07 s | 8.13~9.09 s | +| 기동 3초 뒤 RSS | 499~512 MB | 511~558 MB | +| heap used / Metaspace used | 109~115 MB / 55 MB | 98~112 MB / 106 MB | +| 스프링 빈 수 | **407** | **603** | +| 스레드 수 | 55~59 (VT 기본 on) | 79~81 (VT 기본 off) | +| 직전 load average | 7.2~9.0 | 7.4~7.8 | + +뒤 회차(3.4절 실험)에서 같은 샘플 jar는 load avg 4.7~19 사이에서 6.47~6.84 s(7회)로 떴다. 기동 시간은 머신 부하에 따라 ±20% 움직인다. 기본 조합은 마지막 회차에서도 3.436 s였다. + +샘플 기동 로그에서 0.25초 넘는 공백은 다섯 곳이다(2회차): Spring Data 저장소 스캔 0.76 s, Tomcat 초기화 1.13 s, JPA 0.53 s, Hibernate 부팅 0.89 s, 나머지 빈 생성부터 Flyway 연결까지 2.34 s. 한 곳이 지배하지 않는다. 기동 시간은 템플릿 규모(빈 600개)에 비례하는 일반적인 값이다. 결함으로 보지 않는다. + +### 3.2 요청당 SQL 수 (PG 문장 로그, 1회 요청) + +| 요청 | SQL 문장 수 | 내역 | +| --- | --- | --- | +| `GET /api/worklogs` (size 20) | **46** | `SHOW TRANSACTION ISOLATION LEVEL` 1, `BEGIN READ ONLY` 1, 본문 select 1, `count(*)` 1, **tech_stack select 20, link select 20**, COMMIT 1, 빈 validation 1 | +| `GET /api/worklogs?size=100&sort=periodStart,desc` | **206** | 위와 같고 lazy select가 200 | +| `GET /api/worklogs?category=BACKEND` | 46 | 같은 모양 | +| `GET /api/worklogs?page=490` (offset 9,800) | 46 | 같은 모양 | +| `GET /api/worklogs/{id}` | 7 | SHOW 1, BEGIN 1, select 1, lazy 2, COMMIT 1, 빈 validation 1 | +| `PATCH /api/worklogs/{id}` (title만) | 13 | select 3 + update 1 + **link delete 1·insert 1 + tech_stack delete 1·insert 2** + SHOW/BEGIN/COMMIT | +| `DELETE /api/worklogs/{id}` | 9 | `count(*)`(existsById) + select + 컬렉션 delete 2 + 본문 delete | +| `POST /api/posters` | 7 | SHOW, BEGIN, `upper(title)=upper(?)` 검사, insert poster, insert outbox_event, COMMIT | +| `GET /api/posters` | 5 | | + +동시 8개로 `GET /api/worklogs/{id}` 50회를 보낸 묶음에서도 `SHOW TRANSACTION ISOLATION LEVEL`은 정확히 50회였다. 즉 트랜잭션마다 1회다(09-05). + +### 3.3 지연·처리량 (플랫폼 스레드, 샘플 기본값) + +동시성 16, 15초(앞 3초 버림), 3회 중앙값. 모든 회차 오류 0, 상태 코드 전부 200/201. + +| 요청 | rps (3회) | 중앙값 rps | p50 | p95 | p99 | load avg | +| --- | --- | --- | --- | --- | --- | --- | +| `GET /api/worklogs/{id}` | 5348 / 5521 / 5954 | **5521** | 2.70 ms | 4.29 ms | 5.93 ms | 8.6~15.5 | +| `GET /api/worklogs` (20건) | 806 / 837 / 829 | **829** | 15.54 ms | 38.88 ms | 41.22 ms | 16.9~17.9 (부하 높음) | +| `GET /api/worklogs?size=100` | 174 / 171 / 185 | **174** | 94.70 ms | 108.17 ms | 134.79 ms | 10.9~16.4 | +| `POST /api/posters` | 671 / 373 / 432 | **432** | 22.55 ms | 70.22 ms | 74.11 ms | 8.3~10.7 | + +동시성 64: + +| 요청 | 스레드 | 중앙값 rps | p50 | p95 | p99 | load avg | +| --- | --- | --- | --- | --- | --- | --- | +| `GET /api/worklogs/{id}` | 플랫폼 | 5418 | 11.13 ms | 22.51 ms | 31.51 ms | 5.4~13.3 | +| `GET /api/worklogs/{id}` | 가상(`SPRING_THREADS_VIRTUAL_ENABLED=true`) | 5325 | 11.55 ms | 19.97 ms | 24.60 ms | 19.0~22.4 (부하 높음) | + +가상 스레드 동시성 16: `GET /{id}` 5702 rps(p50 2.71 ms), `GET /worklogs` 738 rps(3회 중 1회가 334 rps로 튐, load 23~25, 부하 높음 — 비교에 쓰지 않는다). + +Hikari 지표(플랫폼 인스턴스, 동시 16·64 회차 누적): `hikaricp_connections_acquire_seconds` 평균 5.5 ms(2946 s / 536,852회), 최대 106 ms, `pending` 0, `timeout_total` 0, `max` 10. + +읽는 법: + +- 단건 조회는 동시 16과 64에서 처리량이 같다(5.4~5.5k rps). 동시성을 4배로 올리면 p50만 4배가 된다. 병목은 앱 스레드가 아니라 커넥션 10개와 DB 왕복이다. 그래서 가상 스레드를 켜도 처리량이 변하지 않았다. +- 목록 20건은 단건보다 **처리량이 6.7배 낮다**. SQL 문장 수는 7 → 46으로 6.6배다. 숫자가 거의 같다. 목록 비용의 대부분이 N+1 왕복이다. +- 목록 100건은 20건보다 처리량이 4.8배 낮다. SQL은 46 → 206으로 4.5배다. 페이지 크기에 선형이다. +- `POST /api/posters` 처리량은 회차마다 떨어졌다(671 → 373 → 432). 같은 회차 동안 `poster` 행이 늘었다. 제목 중복 검사가 순차 스캔이라 행 수에 비례해 느려진다(09-02). + +### 3.4 설정만 바꾼 실험 + +코드는 바꾸지 않았다. JVM 시스템 프로퍼티만 바꿨다. + +**(a) `hibernate.default_batch_fetch_size=100`** (`-Dspring.jpa.properties.hibernate.default_batch_fetch_size=100`). 이 키는 `persistence-jpa.yml:150`에 env(`APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE`)로 이미 열려 있고 기본값이 0이다. + +| 요청 | SQL 수 (기본 → 실험) | rps (3회, 실험) | 중앙값 rps (기본 → 실험) | p50 (기본 → 실험) | p95 | load avg | +| --- | --- | --- | --- | --- | --- | --- | +| `GET /api/worklogs` (20건) | 46 → **8** | 2371 / 2415 / 2411 | 829 → **2411 (2.9배)** | 15.54 → 4.27 ms | 38.88 → 38.10 ms | 8.2~9.5 | +| `GET /api/worklogs?size=100` | 206 → **8** | 465 / 530 / 527 | 174 → **527 (3.0배)** | 94.70 → 16.10 ms | 108.17 → 69.88 ms | 6.2~8.6 | +| `GET /api/worklogs/{id}` | 7 → 7 | — | — | — | — | — | + +같은 세션(load 12.7)에서 기본 설정으로 다시 잰 목록 20건은 847 rps, p50 15.42 ms였다. 위 「기본」 값과 같은 수준이다. + +목록 20건의 p95(약 38 ms)와 p99(약 41 ms)는 SQL을 46 → 8로 줄여도 그대로였다. p50만 줄었다. 이 꼬리는 DB 왕복이 아닌 다른 원인이다. 응답이 큰 요청(목록)에서만 보이고 작은 응답(단건 p95 3~4 ms)에서는 보이지 않는다. TCP delayed ACK(리눅스 기본 40 ms)와 응답 분할 쓰기의 상호작용이 의심되지만 확인하지 않았다(미검증, 「다음 측정 후보」). + +**(b) 관측(observation) 비용 A/B** — `management.observations.enable.spring.security=false` + `management.metrics.data.repository.autotime.enabled=false`. 끄면 `spring_security_*` 시계열 26개와 `spring_data_repository_*` 6개가 사라지는 것을 `/actuator/prometheus`로 확인했다. `GET /api/worklogs/{id}`, 동시 16, 15초, A·B를 번갈아 2회씩 두 묶음(A, B, A2, B2). + +| 변형 | rps (4회) | 중앙값 | p50 | p95 | load avg | +| --- | --- | --- | --- | --- | --- | +| A 기본(관측 켬) | 6620 / 6512 / 6588 / 6700 | 6604 | 2.30~2.36 ms | 3.10~3.24 ms | 10.4~19.2 | +| B 관측 끔 | 6755 / 6787 / 6849 / 7094 | 6818 (+3.2%) | 2.17~2.26 ms | 2.90~3.15 ms | 14.9~18.3 (부하 높음) | + +차이는 3% 수준이다. 이 경로는 CPU가 아니라 커넥션·DB 왕복이 병목이라, 관측 비용은 처리량에 작게 나타난다. 결함으로 올리지 않았다. 다만 JFR에서 Micrometer 프레임이 CPU 표본의 16%를 차지했으므로(3.5절), CPU가 병목인 서비스에서는 더 크게 보일 수 있다. + +**(c) 가상 스레드** — 3.3절. 처리량 차이 없음. + +**(d) 기본 조합의 필터 체인 바닥값** — `app-bootstrap`, `local`, 공개 경로 `GET /api/healthcheck`와 토큰 없는 보호 경로(401). 동시 16, 15초, 3회. 이 수치가 「DB 없이 보안·관측·로깅 필터만 지나는 요청」의 비용이다. + +| 요청 | rps (3회) | 중앙값 | p50 | p95 | p99 | load avg | +| --- | --- | --- | --- | --- | --- | --- | +| `GET /api/healthcheck` → 200 | 26521 / 27276 / 27130 | **27130** | 0.51 ms | 0.91 ms | 1.40 ms | 10.2~14.8 | +| `GET /api/anything` 토큰 없음 → 401 | 26291 / 26670 / 26690 | **26670** | 0.52 ms | 0.95 ms | 1.42 ms | 15.3~16.3 (부하 높음) | + +필터 체인 자체의 비용은 요청당 0.5 ms 안팎이다. 샘플 단건 조회(2.7 ms)의 대부분은 DB 쪽이다. + +### 3.5 요청당 CPU (JFR) + +`settings=profile`, 15초, 동시 16, 샘플 기본 설정(플랫폼 스레드). 같은 회차 처리량: 단건 4801 rps, 목록 20건 847 rps(load 9.6~12.7). JFR은 스택을 64프레임에서 자르므로 「스택에 포함」 비율은 바깥 프레임(Tomcat, 필터) 쪽이 실제보다 낮게 나온다. + +| 요청 | 표본 수 | 스택에 포함된 비율 (상위) | 잎 프레임 소유자 (상위) | +| --- | --- | --- | --- | +| `GET /api/worklogs/{id}` | 2146 | Tomcat 21%, **Micrometer 16%**, Spring MVC 14%, Hibernate 14%, Spring Security 9%, pgjdbc 6%, logback 5%, 앱 코드 4%, Jackson 3%, Hikari 3% | Tomcat 20%, Micrometer 16%, JDK 14%, Hibernate 12% | +| `GET /api/worklogs` (20건) | 682 | **Hibernate 31%**, Micrometer 11%, Tomcat 10%, pgjdbc 9%, 앱 코드 7%, logback 6%, Jackson 5% | Hibernate 29%, JDK 12%, Tomcat 10% | + +- 목록에서는 Hibernate가 CPU의 1/3이다. lazy 컬렉션 40개를 초기화하고 바인딩하는 비용이다(09-01). +- 단건에서 Micrometer가 16%다. 가장 바깥 Micrometer 프레임은 `Meter$Id.equals`, `KeyValues.of`, `SimpleObservation.start/stop`, `MetricsTurboFilter.decide`(logback 이벤트마다 카운터)였다. Spring Security의 `ObservationFilterChainDecorator`가 보안 필터마다 observation을 열고 닫는 것이 보였다. (b)의 A/B에서 이 둘을 끄면 처리량이 3% 올랐다. +- 앱 필터(`WebMvcRequestIdFilter`, `RequestLoggingFilter`, `CacheControlFilter`, `JsonBodyLimitFilter`)는 합쳐 2% 이하였다. 요청 본문을 통째로 버퍼링하는 필터는 없다(`JsonBodyLimitFilter`는 스트림을 감싼다). +- 직렬화(Jackson) 비용은 3~5%로 작다. + +로그량: 샘플은 요청마다 `RequestLoggingFilter`가 INFO 한 줄을 쓴다. 약 53.7만 요청에 콘솔 로그 112 MB(요청당 약 210 B)였다. 운영에서 로그 수집 비용으로 그대로 이어진다. 비용 기록이지 결함은 아니다. + +## 4. 새 발견 + +요약: High 2, Medium 4, Low 5. P1 2, P2 4, P3 5. 경로는 모두 `src/` 기준이고 샘플 패키지 접두사 `sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/`는 `/`로 줄였다. + +| ID | 제목 | 성격 | 심각도·우선순위 | 다른 영역 | +| --- | --- | --- | --- | --- | +| 09-01 | 샘플 목록 API가 N+1 — 페이지 20건에 SQL 46개 | 확인된 결함 | Medium · P2 | > 04 persistence, 01 feature pattern | +| 09-02 | 포스터 제목 중복 규칙이 동시 요청에서 깨지고, 검사 쿼리가 순차 스캔 | 확인된 결함 | **High · P1** | > 04 persistence | +| 09-03 | 단독 실행한 샘플에서 대표 쓰기 `POST /api/worklogs`가 항상 500 | 확인된 결함 | **High · P1** | > 07 bootstrap/sample, 02 inbound-web | +| 09-04 | 단독 실행한 샘플에서 `/api/v3/api-docs`가 500 | 확인된 결함 | Medium · P2 | > 02 inbound-web | +| 09-05 | 트랜잭션마다 `SHOW TRANSACTION ISOLATION LEVEL` 왕복 1회 | 확인된 결함(비용) | Low · P3 | > 04 persistence | +| 09-06 | 제목 하나 고치는 PATCH가 컬렉션 테이블을 전부 지우고 다시 넣음 | 확인된 결함(비용) | Medium · P2 | > 04 persistence | +| 09-07 | JDBC batch 기본 꺼짐 + 동기 `batchCreate` 1000건을 한 트랜잭션에서 처리 | 구조적 위험(미측정) | Medium · P2 | > 04 persistence | +| 09-08 | 샘플의 런타임 기본값이 기본 조합과 다름(가상 스레드·풀 대기·로그 레벨) | 확인된 결함(일관성) | Low · P3 | > 07 bootstrap | +| 09-09 | persistence-jpa가 H2 드라이버를 운영 아티팩트에 실어 보냄 | 개선 제안 | Low · P3 | > 04 persistence, 08 build | +| 09-10 | `local` 프로필이 `server.port`를 8080으로 고정해 `APP_SERVER_PORT`를 무시 | 확인된 결함(DX) | Low · P3 | > 07 bootstrap | +| 09-11 | 기본 조합 jar에 Jackson 2·3과 kotlin-stdlib가 함께 실림 | 개선 제안 | Low · P3 | > 08 build | + +### 09-01. 샘플 목록 API가 N+1 — 페이지 20건에 SQL 46개 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 14 성능, 13 확장성, 5 위험 가시성, 23 일관성, 9 유지보수 | +| 근거 | `/adapter/outbound/persistence/repository/WorkLogRepositoryAdapter.java:79-80` — `findAll(pageRequest)` 뒤 `WorkLogPersistenceMapper::toDomain`. `/adapter/outbound/persistence/mapper/WorkLogPersistenceMapper.java:50-51` — `getTechStack()`·`getLinks()`로 lazy 컬렉션 두 개를 건드린다. `/adapter/outbound/persistence/entity/WorkLogEntity.java:52-60` — 두 `@ElementCollection(fetch = LAZY)`. 응답은 요약형인데(`WorkLogWebMapper.toSummary` — id·title·category·status·period만) 엔티티 전체(`content` 최대 10,000자 포함)와 컬렉션을 다 읽는다. 같은 모듈에 요약 전용 projection(`WorkLogJpaRepository.findRecentSummaryRows`, `WorkLogSummaryQueryPort`, `ListRecentWorkLogSummariesUseCase`)이 있지만 HTTP 목록은 그 길을 쓰지 않는다. `persistence-jpa.yml:150`의 `default_batch_fetch_size` 기본값은 0이다. | +| 실행 결과 | PG 문장 로그: size 20 → 46문장, size 100 → 206문장(= 2N + 6). 처리량: 단건 5521 rps vs 목록 20건 829 rps vs 100건 174 rps. JFR: 목록 CPU의 31%가 Hibernate. 설정 한 줄(`default_batch_fetch_size=100`)로 8문장, 2411 rps(2.9배)·527 rps(3.0배). | +| 발생 조건 | 목록 호출마다. 페이지 크기에 선형. 데이터 총량과는 무관(offset 9,800도 46문장). 상한 100이 있어 무한히 커지지는 않는다(`PageParams.MAX_SIZE`). | +| 영향 | 같은 커넥션 풀(10개)에서 목록 처리량이 단건의 1/7로 떨어진다. 목록과 다른 요청이 섞이면 목록이 커넥션을 오래 잡아 다른 요청의 대기도 늘어난다. 템플릿을 복사한 서비스가 이 모양(`@ElementCollection` + 엔티티 전체 매핑 + 요약 응답)을 그대로 가져간다. | +| 심각도·우선순위 | Medium · P2. 페이지 상한이 있어 자원 고갈로 번지지 않는다. 다만 샘플이 「따라 할 기준」이므로 복제 범위가 넓다. | +| 확실성 | 직접 측정. 남은 가정 없음. | +| 결정의 근거 | 기록된 의도: 엔티티 주석은 "CQRS-lite projection read … skipping aggregate hydration and lazy @ElementCollection joins"(`WorkLogJpaRepository.java:19-21`)라고 적는다. 즉 팀은 이 비용을 알고 projection을 만들었다. 그런데 HTTP 목록이 그 projection을 쓰지 않는다. 위험이 코드에 드러나지 않고 「어느 쿼리 경로를 쓰는지」를 기억해야 하는 상태다. | +| 최소 개선 방향 | 목록 use case가 요약 projection을 쓰게 한다(필터·정렬·count를 projection 쿼리에 추가). | +| 대안 비교 | (1) 현상 유지 — 비용 그대로. (2) `default_batch_fetch_size` 기본값을 50~100으로 — 한 줄, 모든 lazy 로딩이 IN 쿼리로 묶임(46 → 8 확인). 하지만 응답에 필요 없는 `content`와 컬렉션을 여전히 읽는다. (3) **요약 projection 사용**(고른 방법) — 응답에 필요한 열만 읽는다. SQL 3~4개(+count), 컬렉션 0. 이미 있는 코드를 재사용한다. (4) `@EntityGraph`/`join fetch` — 컬렉션 2개를 동시에 fetch join하면 곱집합과 페이지네이션 경고(HHH90003004)가 생긴다. 기각. 권장: (3)을 샘플에 적용하고, (2)를 persistence-jpa 기본값으로 켤지는 04 영역이 따로 판단한다. | +| 단순화의 보존 조건 | 응답 JSON 모양(`WorkLogSummaryResponse`), `meta.page.total`, 정렬 허용 필드(`WorkLogWebMapper.SORT_FIELDS`), 카테고리 필터, 400 `SIZE_EXCEEDS_MAX`는 그대로여야 한다. OpenAPI 스냅샷이 바뀌지 않아야 한다. | +| 비용·부작용 | projection 쿼리에 정렬·필터를 추가하는 코드 20~40줄. 도메인 `WorkLog`를 목록에 쓰지 않게 되므로 목록과 상세의 모델이 갈린다(이미 응답은 갈려 있다). | +| 재검토 조건 | 목록 응답이 techStack·links를 포함하게 되면 (2) 또는 별도 IN 쿼리로 다시 비교한다. | +| 완료 기준 | `GET /api/worklogs?size=100`의 SQL 문장 수가 페이지 크기와 무관한 상수(≤ 6)다. | +| 검증 방법 | Testcontainers 통합 테스트에서 Hibernate statistics(`prepareStatementCount`)로 size 20과 100의 문장 수가 같은지 단언한다. 이 문서의 `sqlcount.sh` 절차로 재측정한다. | + +### 09-02. 포스터 제목 중복 규칙이 동시 요청에서 깨지고, 검사 쿼리가 순차 스캔 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 12 동시성, 11 데이터, 14 성능, 5 위험 가시성, 21 Guardrail | +| 근거 | `/application/poster/CreatePosterUseCase.java:47-51` — 같은 트랜잭션 안에서 `existsByTitle` 확인 후 insert. `/adapter/outbound/persistence/repository/PosterRepositoryAdapter.java:89-90` → `existsByTitleIgnoreCase` → SQL `where upper(title)=upper(?)`. `sample-portfolio/src/main/resources/db/sample-migration/V7__poster.sql:31` — `CREATE INDEX ix_poster_title ON poster (title)`: 유일 제약이 없고, `upper(title)` 식에는 쓸 수 없는 인덱스다. | +| 실행 결과 | (a) 같은 제목으로 동시 16개 `POST /api/posters`를 3번: 응답 201 30개·409 18개, DB에는 제목마다 **10행**(`race-1`·`race-2`·`race-3` 각 10). (b) `EXPLAIN ANALYZE`: 23,071행에서 `Seq Scan on poster … Rows Removed by Filter: 23071`, 7.2 ms. (c) `POST /api/posters` 처리량이 행이 쌓이는 동안 671 → 373 → 432 rps로 떨어졌다. | +| 발생 조건 | (a) 같은 제목 생성이 겹치면 READ COMMITTED에서 두 트랜잭션 모두 「없음」을 본다. 더블 클릭·재시도만으로 발생한다. (b) 생성 요청마다 테이블 전체를 읽는다. | +| 영향 | 409 `POSTER_ALREADY_EXISTS`로 약속한 규칙이 지켜지지 않는다. 중복 행 각각에 `outbox_event`도 생긴다(같은 트랜잭션에서 append). 템플릿이 31절의 「중복·동시 요청」 시나리오를 보여 주는 바로 그 자리에서 잘못된 패턴(DB 제약 없는 check-then-insert)을 가르친다. 생성 비용이 행 수에 비례해 커진다. | +| 심각도·우선순위 | High · P1. 계약 위반을 재현했다. 샘플이 복제 기준이므로 파생 서비스로 퍼진다. 샘플 안에서만 보면 Medium이지만 템플릿의 대표 예제라는 점에서 올렸다. | +| 확실성 | 직접 재현. 다중 인스턴스가 아니라 단일 인스턴스에서도 재현된다. | +| 결정의 근거 | 적용 제외 — 가이드 31절이 「DB 유일성 제약과 충돌 처리가 충분한지 먼저 본다」고 정한 경우이고, 다른 선택지(락·직렬화 격리)는 그보다 비싸다. | +| 최소 개선 방향 | 마이그레이션 V9: `CREATE UNIQUE INDEX uq_poster_title_ci ON poster (upper(title))`(또는 `lower`). 어댑터가 유일 제약 위반(SQLSTATE 23505, 제약 이름)을 `PosterTitleAlreadyExistsException`으로 바꾼다. 사전 `exists` 검사는 빠른 실패용으로 남겨도 되고 빼도 된다. 같은 인덱스가 순차 스캔도 없앤다. 기존 `ix_poster_title`은 쓰는 곳을 확인한 뒤 정리한다. | +| 완료 기준 | 같은 제목 동시 16개 생성에서 201이 정확히 1개, 나머지는 409이고 DB에 1행. `EXPLAIN`이 인덱스 스캔이다. | +| 검증 방법 | Testcontainers PostgreSQL에서 `CountDownLatch`로 동시 생성 테스트. 마이그레이션 테스트에 기존 중복 데이터가 있을 때의 처리(실패 메시지)를 넣는다. | + +### 09-03. 단독 실행한 샘플에서 대표 쓰기 `POST /api/worklogs`가 항상 500 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함 | +| 관련 관점 | 6 실패, 17 API 계약, 20 개발자 경험, 10 테스트, 8 디버깅 | +| 근거 | `/bootstrap/security/SamplePublicAccessSecurityConfig.java:24-27` — `securityMatcher("/**")` + `anyRequest().permitAll()`, `@Order(-100)`. 이 체인에는 resource server가 없어 Bearer 토큰도 읽지 않는다. `/adapter/inbound/web/controller/WorkLogController.java:221-228` — 인증 주체가 없으면 owner `null`. `/domain/worklog/WorkLogOwner.java:10` — `requireNonNull(value, "owner is required")` → `NullPointerException` → `GlobalExceptionHandler`가 500 `INTERNAL_ERROR`. 같은 이유로 `POST /api/worklogs:batchCreate`(`WorkLogController.java:167`)도 같다. | +| 실행 결과 | `java -jar sample-portfolio.jar` + PostgreSQL에서 README 예시 본문으로 `POST /api/worklogs` → 500, 로그 `java.lang.NullPointerException: owner is required at WorkLogOwner.of(WorkLogOwner.java:10)`. 시스템 테스트(`systemTest`, `webSystemTest`)에는 이 경로를 실제 서버로 부르는 테스트가 없다(grep). | +| 발생 조건 | `Dockerfile.sample`로 만든 데모 이미지와 `bootRun`처럼 샘플을 단독으로 띄우는 모든 경우. | +| 영향 | 샘플의 대표 쓰기 흐름(검증·outbox·멱등성 시연)을 실제로 실행해 볼 수 없다. 인증 부재가 401이 아니라 500으로 보여 원인을 찾기 어렵다. README의 curl 예시는 경로도 틀렸다(`sample-portfolio/README.md:11,26,37,48`의 `/work-logs`, 실제 경로는 `/api/worklogs`). | +| 심각도·우선순위 | High · P1. 템플릿이 배포 가능한 데모(`Dockerfile.sample`)로 내놓은 구성에서 대표 기능이 실패한다. 데이터 피해는 없다. | +| 확실성 | 직접 재현. | +| 결정의 근거 | 적용 제외 — 기대 동작(인증 없으면 401, 또는 데모용 고정 owner)이 둘 중 하나로 정해지기만 하면 되는 단순 결함이다. 어느 쪽을 고를지는 07 영역·소유자 판단이다. | +| 최소 개선 방향 | 둘 중 하나. (1) 샘플 공개 체인이 쓰기 메서드는 JWT를 요구하도록 바꾸고 인증 없음을 401로 돌려준다. (2) 데모 프로필에서만 고정 owner(`demo`)를 넣는 `AuditContextPort`/owner 공급자를 둔다. 어느 쪽이든 owner 누락은 500이 아니라 4xx로 변환한다. README 경로를 고친다. | +| 완료 기준 | 단독 실행한 샘플에서 README의 curl이 그대로 성공(또는 문서화된 401)한다. | +| 검증 방법 | `webSystemTest`에 실제 서버로 `POST /api/worklogs`를 부르는 테스트를 하나 추가한다. | + +### 09-04. 단독 실행한 샘플에서 `/api/v3/api-docs`가 500 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(원인은 추론) | +| 관련 관점 | 17 API 계약, 10 테스트, 20 개발자 경험 | +| 근거 | 실행 결과: `GET /v3/api-docs` → 404 `ROUTE_NOT_FOUND`, `GET /api/v3/api-docs` → 500, 로그 `ClassCastException: class dev.caskeleton.shared.response.Envelope cannot be cast to class [B`. `adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/config/PresentationWebConfig.java:24-25`가 springdoc 컨트롤러에도 `/api` 접두사를 붙인다. `adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java:26-49`는 모든 컨트롤러에 적용되고, JSON 응답이면 `Envelope`로 감싼다. springdoc은 `byte[]`를 JSON 타입으로 돌려주므로 `ByteArrayHttpMessageConverter`가 `Envelope`를 받는다(추론). 스냅샷 테스트(`OpenApiSnapshotTest.java:43-51`)는 별도 슬라이스 앱으로 `/v3/api-docs`를 불러 이 조합을 보지 않는다. | +| 영향 | 실제로 띄운 샘플에서 OpenAPI 문서를 받을 수 없다. 계약 스냅샷 테스트는 통과하므로 게이트는 초록이다. | +| 심각도·우선순위 | Medium · P2. | +| 결정의 근거 | 적용 제외 — 단순 결함. | +| 최소 개선 방향 | `EnvelopeBodyAdvice.supports`가 `byte[]`/`String`/springdoc 컨트롤러를 제외하거나, springdoc 컨트롤러에 `@OwnsAbsoluteWebRoute` 같은 접두사 예외를 준다. | +| 완료 기준·검증 | 전체 샘플 조합(`SamplePortfolioApplication`)을 띄우는 테스트에서 OpenAPI 문서 경로가 200이다. | + +### 09-05. 트랜잭션마다 `SHOW TRANSACTION ISOLATION LEVEL` 왕복 1회 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(비용) | +| 관련 관점 | 14 성능, 22 추상화 | +| 근거 | `adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java:93` — 모든 템플릿에 `ISOLATION_READ_COMMITTED`를 명시. 기본값이 아닌 격리 수준이 지정되면 Spring이 트랜잭션 시작 때 `Connection.getTransactionIsolation()`을 부르고, pgjdbc는 이를 매번 서버 왕복(`SHOW TRANSACTION ISOLATION LEVEL`)으로 처리한다. | +| 실행 결과 | 동시 8개 단건 조회 50회 → `SHOW TRANSACTION ISOLATION LEVEL` 정확히 50회. 단건 조회 1회의 DB 왕복 6개 중 1개다. | +| 영향 | 모든 트랜잭션에 왕복 1회(로컬 DB에서 수십~수백 µs, 원격 DB면 RTT 1회)가 붙는다. 단건 조회 기준 DB 왕복의 약 17%. PostgreSQL 기본 격리 수준이 이미 READ COMMITTED이므로 얻는 것이 없다. | +| 심각도·우선순위 | Low · P3. | +| 결정의 근거 | 기록된 의도: "all pinned to READ_COMMITTED"(`SpringTransaction.java` 클래스 주석). DB 기본값이 바뀌어도 격리 수준이 흔들리지 않게 하려는 고정으로 읽힌다(추론). | +| 대안 비교 | (1) 현상 유지 — 의도는 코드에 드러나지만 왕복 비용. (2) `ISOLATION_DEFAULT` + Hikari `transaction-isolation: TRANSACTION_READ_COMMITTED` — 커넥션을 만들 때 한 번만 설정, 트랜잭션마다 왕복 없음. 풀 설정이 격리 수준을 소유하게 되어 의도가 설정 파일로 옮겨간다. (3) `ISOLATION_DEFAULT` + 기동 시 `SHOW default_transaction_isolation` 검사 — 검사는 1회. 권장 (2). | +| 단순화의 보존 조건 | 모든 `TransactionPort` 경로가 READ COMMITTED로 도는 것. `inNew` 30초 타임아웃과 읽기 전용 플래그는 그대로. | +| 재검토 조건 | 모드별로 다른 격리 수준(예: 일부 쓰기에 REPEATABLE READ)이 필요해지면 (1)이 맞다. | +| 완료 기준·검증 | PG 문장 로그(또는 `pg_stat_statements`)에서 단건 조회 1회당 `SHOW TRANSACTION ISOLATION LEVEL` 0회, 그리고 트랜잭션 안에서 `SHOW transaction_isolation`이 `read committed`인 통합 테스트. | + +### 09-06. 제목 하나 고치는 PATCH가 컬렉션 테이블을 전부 지우고 다시 넣음 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(비용) | +| 관련 관점 | 14 성능, 11 데이터, 12 동시성 | +| 근거 | `/adapter/outbound/persistence/repository/WorkLogRepositoryAdapter.java` `save` — 도메인 객체에서 새 엔티티를 만들고(`WorkLogPersistenceMapper.toEntity`) `jpa.save`(merge)한다. 새 `List` 인스턴스가 들어가므로 Hibernate가 컬렉션 전체를 교체로 본다. | +| 실행 결과 | `PATCH {"title":"patched2"}` 1회 = 13문장: select 3, update 1, `delete from work_log_link` 1 + insert 1, `delete from work_log_tech_stack` 1 + insert 2. | +| 영향 | 바뀌지 않은 자식 행도 매번 삭제·삽입된다. WAL·인덱스 갱신·락 범위가 커진다. 자식 행이 많을수록 커진다(행 수에 선형). 감사·CDC를 붙이면 가짜 변경 이벤트가 생긴다. | +| 심각도·우선순위 | Medium · P2. | +| 결정의 근거 | 기록된 의도: 도메인에 감사 필드를 두지 않고 어댑터에서 붙이기 위해 엔티티를 새로 만든다(README 참조 주석). 이 선택의 비용이 컬렉션 교체다. | +| 대안 비교 | (1) 현상 유지. (2) 기존 관리 엔티티를 읽어 필드를 복사(`existing.apply(domain)`)하고 컬렉션은 내용이 다를 때만 `clear/addAll` — 변경 없는 컬렉션은 SQL 0. (3) 컬렉션을 JSON/배열 컬럼으로 — 스키마 변경. 권장 (2). | +| 단순화의 보존 조건 | `@Version` 낙관적 잠금과 412 응답, `created_*` 보존·`updated_*` 갱신, ETag 값. | +| 완료 기준·검증 | 제목만 바꾸는 PATCH의 SQL에 `delete from work_log_link`/`work_log_tech_stack`가 없다(Hibernate statistics 단언). | + +### 09-07. JDBC batch 기본 꺼짐 + 동기 `batchCreate` 1000건을 한 트랜잭션에서 처리 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 구조적 위험(미측정 — 09-03 때문에 실행 불가) | +| 관련 관점 | 14 성능, 13 확장성, 12 동시성 | +| 근거 | `adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml:147-150` — `batch_size` 0, `order_inserts` false. `/adapter/inbound/web/controller/WorkLogController.java:178` — `MAX_BATCH_SIZE = 1000`, 「Sync = atomic」 한 트랜잭션. 항목마다 work_log insert 1 + tech_stack k + link m + outbox insert 1. | +| 발생 조건 | 1000건 요청 1회 = 최소 약 3,000~5,000 왕복을 한 커넥션이 한 트랜잭션으로 잡는다. JSON 본문 상한(`JsonBodyLimitFilter`)이 크기를 막지만 건수 1000은 허용한다. | +| 영향 | 요청 하나가 커넥션 1개를 수 초 잡는다. 풀이 10개이므로 동시에 몇 건만 와도 다른 요청이 `connection-timeout`(기본 5 s)까지 기다린다. | +| 심각도·우선순위 | Medium · P2. 측정하지 못했으므로 High로 올리지 않았다. | +| 최소 개선 방향 | (1) 샘플에서 `APP_JPA_HIBERNATE_BATCH_SIZE`·`ORDER_INSERTS`를 켜고 `HibernateJpaBatchExecutor`의 증명 방식을 따른다. (2) 동기 배치 상한을 100 정도로 낮추고 그 이상은 기존 비동기 operation(`OperationsController`)으로 보낸다. | +| 완료 기준·검증 | 09-03을 고친 뒤 1000건 요청의 SQL 왕복 수와 커넥션 점유 시간을 측정해 문서화한다. | + +### 09-08. 샘플의 런타임 기본값이 기본 조합과 다름 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(일관성) | +| 관련 관점 | 23 일관성, 19 설정, 14 성능 | +| 근거 | 가상 스레드: `app-bootstrap/src/main/resources/application.yml:54-57` `SPRING_THREADS_VIRTUAL_ENABLED:true` vs `sample-portfolio/src/main/resources/application.yml:69-71` `:false`. 풀 대기: `persistence-jpa.yml:38` `connection-timeout` 5000(주석: fail-fast 원칙) vs 샘플 `application.yml:36` 30000. 앱 로그 레벨: `app-bootstrap/.../config/observability.yml:108` INFO vs 샘플 `application.yml:139` DEBUG. 샘플 파일 머리말은 "Mirrors app-bootstrap/application.yml"이라고 적는다. | +| 실행 결과 | 스레드 수 55~59(기본) vs 79~81(샘플). 가상 스레드 켜기/끄기의 처리량 차이는 없었다(3.3절, 커넥션 10개가 병목). | +| 영향 | 샘플로 측정한 숫자(대기 시간, 스레드 수)가 기본 조합의 동작을 대표하지 않는다. 풀이 마른 상황에서 샘플은 30초를 기다리고 기본 조합은 5초에 실패한다. | +| 심각도·우선순위 | Low · P3. | +| 최소 개선 방향 | 샘플이 기본값을 덮어쓰는 키를 지우고 모듈 기본값을 따르게 한다. 다르게 둘 이유가 있으면 그 키 옆에 이유를 적는다. | +| 완료 기준·검증 | 두 조합의 effective 값 비교 테스트(이미 있는 `ProfileSeparationContractTest` 계열에 키 목록 추가). | + +### 09-09. persistence-jpa가 H2 드라이버를 운영 아티팩트에 실어 보냄 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 개선 제안 | +| 관련 관점 | 16 의존성, 15 보안, 18 배포 | +| 근거 | `adapter/outbound/persistence-jpa/build.gradle:82` — `runtimeOnly 'com.h2database:h2'`. 실행 결과: 샘플 bootJar에 `BOOT-INF/lib/h2-2.4.240.jar`(2.7 MB). JPA를 켠 모든 서비스 jar에 같은 일이 생긴다. | +| 영향 | 운영 이미지에 쓰지 않는 인메모리 DB 엔진이 들어간다. 크기 2.7 MB와 취약점 스캔 대상이 늘어난다. H2 콘솔 설정은 없다(`spring.h2.console` grep 0건, Boot 기본값 꺼짐). | +| 심각도·우선순위 | Low · P3. | +| 대안 비교 | (1) 현상 유지 — `bootRunH2` 편의. (2) H2를 `bootRunH2Classpath`·테스트 구성에만 둔다(`app-bootstrap/build.gradle`의 `bootRunH2`가 이미 별도 classpath를 만든다). 권장 (2). | +| 완료 기준·검증 | `unzip -l` 결과 bootJar에 `h2-*.jar`가 없고 `bootRunH2`가 여전히 뜬다. | + +### 09-10. `local` 프로필이 `server.port`를 8080으로 고정 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 확인된 결함(DX) | +| 관련 관점 | 20 개발자 경험, 19 설정 | +| 근거 | `app-bootstrap/src/main/resources/application-local.yml:127` `port: 8080`. 실행 결과: `APP_SERVER_PORT=18080`을 줬는데 `Tomcat started on port 8080`. 파일 머리말은 「완전한 독립 설정」이라 의도된 모양이지만, 이 키만은 env를 받을 이유가 있다. | +| 영향 | 같은 머신에서 두 서비스(또는 기본 조합과 샘플)를 동시에 띄우면 포트 충돌. env로 피할 수 없다. | +| 심각도·우선순위 | Low · P3. | +| 최소 개선 방향 | `port: ${APP_SERVER_PORT:8080}`. | + +### 09-11. 기본 조합 jar에 Jackson 2·3과 kotlin-stdlib가 함께 실림 + +| 필드 | 내용 | +| --- | --- | +| 성격 | 개선 제안 | +| 관련 관점 | 16 의존성, 18 배포 | +| 근거 | 기본 조합 `BOOT-INF/lib`: `jackson-databind-3.1.5`(1.9 MB)와 `jackson-databind-2.21.5`(1.7 MB)·`jackson-core-2.21.5`·`jackson-dataformat-yaml-2.21.5`·`jackson-datatype-jsr310-2.21.5`, `kotlin-stdlib-2.2.21`(1.8 MB)·`okhttp-jvm`·`okio-jvm`. 2 계열의 출처는 logstash encoder와 OTel 쪽으로 추정한다(미확인 — `dependencyInsight` 미실행). kotlin은 `opentelemetry-exporter-sender-okhttp`를 따라온다. | +| 영향 | 기본 jar 39 MiB 중 약 5~6 MiB. 두 Jackson 계열의 보안 패치를 따로 추적해야 한다. | +| 심각도·우선순위 | Low · P3. | +| 최소 개선 방향 | `./gradlew :app-bootstrap:dependencyInsight --dependency com.fasterxml.jackson.core:jackson-databind`로 출처를 확인한다. OTLP sender를 JDK HttpClient 구현(`opentelemetry-exporter-sender-jdk`)으로 바꾸면 kotlin·okhttp가 빠진다. | + +## 5. 31절 시나리오 추적 + +이 영역은 실측이므로, 실제로 요청을 보내 따라간 시나리오만 적는다. + +### 5.1 큰 입력·목록 조회 — `GET /api/worklogs?size=100&sort=periodStart,desc` + +```text +HTTP → 보안 체인(샘플: permitAll) → 앱 필터 4개 → WorkLogController.list + → PageParams.of (size 1..100 검사) ← 상한 있음 + → ListWorkLogsUseCase.handle → tx.inRead ← 트랜잭션 시작: SHOW ISOLATION + BEGIN READ ONLY + → WorkLogRepositoryAdapter.findPage + → select work_log … offset/limit ← 1 + → select count(*) ← 1 + → 행마다 tech_stack select, link select ← 200 (N+1) + → COMMIT + → toSummary (컬렉션 안 씀) → Envelope + meta.page → Jackson +``` + +| 항목 | 결과 | +| --- | --- | +| 입력 신뢰 수준 | 외부 입력. `page`·`size`·`sort`·`category` 모두 컨트롤러 경계에서 검사(size ≤ 100, sort 문법·허용 필드, enum). | +| 인가 위치 | 샘플은 없음(permitAll). | +| 규칙 소유 | 페이지 상한은 web 어댑터 `PageParams`. | +| 트랜잭션 | use case가 `inRead`로 연다. 읽기 전용, READ COMMITTED. | +| 외부 부작용 | 없음. | +| 성공의 의미 | 200, `meta.page.total` 포함. | +| 오류 변환 | size 초과 → 400 `VALIDATION_FAILED`/`SIZE_EXCEEDS_MAX`, 정렬 문법 오류 → 400 `SORT_SYNTAX_INVALID`(실행으로 확인). | +| 진단 정보 | 응답 `meta.requestId/traceId/correlationId`, 요청마다 INFO 로그 1줄. | +| 판정 | 응답 크기와 페이지 크기는 제한된다. **호출 수는 페이지 크기에 비례**한다(206문장). 깊은 offset(page 490)도 허용되고 비용은 같았다(인덱스 없는 정렬 + offset 9,800 → `EXPLAIN` 12.8 ms). 데이터 총량이 늘면 `count(*)`와 offset 정렬이 함께 커진다. | + +### 5.2 중복·동시 요청 — `POST /api/posters` 같은 제목 16개 동시 + +| 항목 | 결과 | +| --- | --- | +| 요청 식별 | 없음. 멱등성 키를 받지 않는다(샘플의 멱등성은 poster image 경로에만). | +| DB 제약 | 제목에 유일 제약 없음(`V7__poster.sql:31`). | +| 규칙 소유 | `CreatePosterUseCase`의 사전 `exists` 검사 하나. | +| 트랜잭션 | `inWrite`, READ COMMITTED — 겹친 트랜잭션은 서로의 미커밋 insert를 못 본다. | +| 외부 부작용 | 같은 트랜잭션의 `outbox_event` insert. 중복 행마다 이벤트도 중복. | +| 결과 | 제목마다 10행. **계약 위반 재현**(09-02). | + +### 5.3 정상 쓰기 요청 — `POST /api/worklogs` + +실행 불가. 단독 실행에서 500(09-03). 대신 같은 모양(검사 → insert → outbox append, 한 트랜잭션)인 `POST /api/posters`를 쟀다: 7문장, 432 rps(행 증가 중), p50 22.6 ms. + +### 적용 제외 + +| 시나리오 | 사유 | +| --- | --- | +| 외부 응답 지연·유실 | 샘플의 외부 호출(`RepoStatsPortClient.fetchRaw`)은 스텁이다. 요청 경로에 실제 동기 외부 호출이 없다. 05 영역(httpclient)이 다룬다. | +| DB 오류·경쟁 | 09-02의 경쟁 외에는 이 영역에서 다루지 않았다(> 04). | +| 메시지 중복·역순, 신·구 버전, 여러 서버 작업, 세션·토큰, 다른 사용자 리소스, 종료·재시작, 선택 어댑터 제거 | 성능 실측 범위 밖. 각 담당 영역(06, 07, 02, 04). | + +## 6. 41절 설계 선택 검토 + +### 6.1 커넥션 풀 10개 + (기본 조합) 가상 스레드 on + +| 질문 | 답 | +| --- | --- | +| 1. 무엇이 필요한가 | 요청 동시성이 커져도 DB 연결 수를 작게 유지하고, 풀이 마르면 오래 기다리지 않는 것. | +| 2. 지킬 성질 | DB 커넥션 상한(10), 대기 상한(`connection-timeout` 5 s), REQUIRES_NEW 깊이를 고려한 최소 풀 크기(`persistence-jpa.yml:15-22` 주석의 공식). | +| 3. 현재 보장 | 풀 크기·대기 시간은 설정으로 고정, `HikariPoolConstraintValidator`가 기동 때 값 관계를 검사한다. 가상 스레드를 켜면 Tomcat `threads.max: 200`이 더 이상 요청 동시성을 막지 않는다. 그러면 동시성 상한은 풀 대기열뿐이다. | +| 4. 대안 | (a) 현상 유지. (b) 플랫폼 스레드(샘플 기본) — 스레드 200개가 상한. (c) 가상 스레드 + 앱 입구의 동시 실행 제한(web-advanced의 opt-in `VirtualThreadAdmissionGuard`). (d) 풀 크기를 CPU에 맞춰 키움. | +| 5. 얻고 잃는 것 | 실측: 단건 조회 처리량은 (a)·(b) 모두 약 5.4k rps, 동시 16→64에서 p50만 2.7→11 ms. Hikari 평균 획득 대기 5.5 ms. 즉 지금 부하에서는 스레드 모델이 결과를 바꾸지 않는다. (a)는 블로킹 외부 호출이 섞일 때 스레드 고갈이 없다. 대신 폭주 시 대기가 풀 앞에 무한히 쌓이고 5 s 뒤 일괄 실패한다. (b)는 200에서 멈추고 나머지는 accept 큐(100)·커넥션(8192)에서 기다린다. | +| 6. 왜 이 선택인가 | 기록된 의도는 "Java 21 virtual threads for Tomcat request handlers". 측정으로 보면 DB가 병목인 한 손해도 이득도 없다. 외부 HTTP 호출이 많은 서비스에서 이득이 생긴다. | +| 7. 바뀔 조건 | 풀 대기(`hikaricp_connections_pending`)가 지속적으로 0보다 크면 (c)를 기본 경로로 고려한다. DB 왕복이 없는 CPU 위주 서비스면 차이 없음. | + +판정: 선택은 타당하다. 다만 샘플이 반대 기본값을 써서(09-08) 템플릿이 하나의 답을 보여 주지 않는다. + +### 6.2 `SpringTransaction`의 READ COMMITTED 명시 + +41.2 일곱 질문의 답은 09-05 표에 있다. 요약: 의도(격리 수준 고정)는 지킬 가치가 있지만, 같은 보장을 풀 설정(Hikari `transaction-isolation`)으로 옮기면 트랜잭션마다 왕복 1회가 없어진다. 모드별로 다른 격리 수준이 필요해지면 지금 방식이 맞다. + +### 6.3 목록 조회가 도메인 집계를 통째로 읽기 (vs 요약 projection) + +| 질문 | 답 | +| --- | --- | +| 1. 필요 | 페이지·정렬·필터가 되는 요약 목록. | +| 2. 지킬 성질 | 응답 모양, 페이지 메타, 정렬 허용 필드. | +| 3. 현재 보장 | 집계 전체를 읽어 요약으로 줄인다(09-01). 요약 projection은 따로 있지만 HTTP가 쓰지 않는다. | +| 4. 대안 | 09-01 대안 비교 (1)~(4). | +| 5. 비용 | 실측: 46문장 vs (batch fetch) 8문장, 829 vs 2411 rps. projection은 측정하지 않았지만 lazy 0개라 8문장보다 적다(추론). | +| 6. 선택 이유 | 기록 없음. 같은 모듈에 projection이 있다는 사실은 의도가 projection 쪽이었음을 보여 준다. | +| 7. 바뀔 조건 | 목록 응답이 컬렉션을 포함하게 되면 batch fetch가 낫다. | + +## 7. 리팩토링 후보 + +| 대상 | 무엇을 왜 | 보존해야 할 동작·타입·실패 계약 | +| --- | --- | --- | +| `ListWorkLogsUseCase` + `WorkLogRepository.findPage` / `WorkLogSummaryQueryPort` | 목록 읽기 경로가 둘(집계형 `findPage`, 요약형 `findRecentSummaries`)로 갈라져 있다. HTTP 목록을 요약형 하나로 합치면 N+1이 사라지고 중복 경로가 하나 준다. | `WorkLogSummaryResponse` JSON, `meta.page`(number·size·total·sort), 정렬 필드 집합, 카테고리 필터, 400 코드. OpenAPI 스냅샷 불변. | +| `WorkLogRepositoryAdapter.save` | 새 엔티티 merge → 관리 엔티티에 변경 적용. 컬렉션 재작성(09-06)과 adapter 안의 두 번째 `findById`가 없어진다. | `@Version` 충돌 시 412, 감사 필드 의미(created 보존, updated 갱신), 반환 도메인 객체의 version. | +| `SpringTransaction.template` | 격리 수준 명시를 풀 설정으로 이동(09-05). | 모든 모드 READ COMMITTED, `inNew` 30 s, 읽기 전용, `inRootWrite` 중첩 거부. | +| `CreatePosterUseCase` | 사전 검사 + DB 유일 제약 변환(09-02). | 409 `POSTER_ALREADY_EXISTS` 응답 모양, 대소문자 무시 비교 의미. | + +## 8. 기능 개발 패턴과 판단 지점 (매뉴얼 재료) + +### 템플릿이 주는 틀 + +- 페이지 파라미터 검사(`PageParams`, 상한 100)와 `meta.page` 응답 모양. +- 요약 projection 예시(`WorkLogJpaRepository.findRecentSummaryRows` + `WorkLogSummaryQueryPort`). +- JPA 성능 손잡이(`APP_JPA_HIBERNATE_BATCH_SIZE`, `…ORDER_INSERTS`, `…DEFAULT_BATCH_FETCH_SIZE`, `…GENERATE_STATISTICS`)와, batch가 실제로 일어났는지 증명하는 `HibernateJpaBatchExecutor`. +- Hikari 풀 기본값과 값 관계 검사(`HikariPoolConstraintValidator`), Prometheus의 `hikaricp_*` 지표. +- JFR·SQL 로그를 켤 수 있는 설정 경로(코드 변경 없이 이 문서의 모든 측정이 가능했다). + +### 빠진 것 + +- 「요청 하나에 SQL이 몇 개인가」를 단언하는 테스트 틀이 없다. Hibernate statistics 손잡이는 있지만 그것으로 문장 수를 고정하는 예제 테스트가 없다. 그래서 09-01·09-06이 게이트를 통과했다. +- 성능 기준선(숫자)이 없다. gRPC에는 performance lane이 있지만 HTTP·JPA 경로에는 없다. +- 동시 생성 경쟁을 재현하는 테스트 예시가 없다(09-02). +- 샘플을 단독으로 띄워 대표 요청을 한 바퀴 도는 스모크가 없다(09-03·09-04). + +### 개발자가 여기서 내려야 하는 판단 + +1. **목록 응답이 집계 전체를 필요로 하는가?** 아니면 요약 projection으로 읽는다. 필요하면 컬렉션마다 batch fetch 또는 별도 IN 쿼리를 쓴다. `@ElementCollection`을 쓰면 「목록에서 몇 번 읽히는가」를 먼저 센다. +2. **유일해야 하는 값인가?** 그렇다면 DB 유일 제약(대소문자 무시면 식 인덱스)을 먼저 만들고, 사전 검사는 친절한 오류용으로만 둔다. +3. **수정 시 무엇을 다시 쓰는가?** 새 엔티티를 merge하면 컬렉션이 전부 다시 쓰인다. 관리 엔티티에 변경만 적용한다. +4. **동기 배치의 상한은 몇인가?** 「한 트랜잭션에서 커넥션을 몇 초까지 잡아도 되는가」로 정한다. 넘으면 비동기 operation으로 보낸다. 배치를 쓰면 `batch_size`와 `order_inserts`를 켠다. +5. **스레드 모델과 풀 크기**: 요청 경로에 블로킹 외부 호출이 있으면 가상 스레드가 이득이다. DB만 있으면 풀 크기와 쿼리 수가 처리량을 정한다. 풀 대기 지표(`hikaricp_connections_pending`, `acquire_seconds`)를 대시보드에 둔다. +6. **새 엔드포인트의 SQL 수를 테스트로 고정할 것인가?** 목록·쓰기 경로에는 고정한다. 단건 조회는 선택. + +### 다음 측정 후보 + +- 목록 응답 p95 ≈ 38 ms 고정 꼬리의 원인(TCP delayed ACK 의심) — `ss -ti`, `tcpdump`, 응답 크기별 분포로 확인. +- 09-03 수정 뒤 `POST /api/worklogs`와 `batchCreate` 1000건의 SQL 수·커넥션 점유 시간. +- 30분 이상 부하에서 heap·RSS·커넥션 추이. +- 컨테이너(cgroup 1 GiB) 안 기동 시간과 RSS. + +## 9. 28개 관점 판정표 + +기호: O 충족, P 부분, X 미충족, ? 미검증, - 적용 제외, > 다른 영역. + +| 번호 | 관점 | 판정 | 이유 | +| --- | --- | --- | --- | +| 1 | 코드 성숙도 | > | 01·04 영역. 이 영역은 측정 경로의 코드만 읽었다. | +| 2 | 구조적 성숙도 | > | 01 영역. | +| 3 | 변경 용이성 | P | 성능 손잡이 대부분이 env로 열려 있어 코드 없이 바꿀 수 있었다. 목록 읽기 경로가 둘로 갈려 있다(09-01). | +| 4 | 인지 부하 | P | 「어느 쿼리 경로가 HTTP에 쓰이는가」를 따라가야 비용을 안다. | +| 5 | 위험 가시성 | X | N+1·컬렉션 재작성·중복 경쟁이 코드에 드러나지 않는다. 주석은 projection이 있다고 말하지만 실제 경로는 다르다(09-01, 09-02, 09-06). | +| 6 | 실패 성숙도 | P | 페이지·정렬 오류는 깔끔한 400. 인증 부재가 500으로 새는 경로가 있다(09-03). | +| 7 | 운영 성숙도 | P | Hikari·HTTP·보안 지표가 Prometheus에 있다. 성능 기준선이 없다. | +| 8 | 디버깅 가능성 | O | requestId·traceId가 응답과 로그에 있다. 코드 수정 없이 SQL 로그·JFR·빈 수를 얻었다. | +| 9 | 유지보수 성숙도 | P | 샘플 설정이 모듈 기본값을 말없이 덮는다(09-08). | +| 10 | 테스트 성숙도 | X | 요청당 SQL 수, 동시 생성 경쟁, 단독 실행 샘플의 대표 쓰기·OpenAPI 경로를 잡는 테스트가 없다. 게이트는 초록인데 09-02·09-03·09-04가 실행으로 재현된다. | +| 11 | 데이터 성숙도 | X | 제목 유일 규칙이 DB에 없다(09-02). | +| 12 | 동시성 성숙도 | X | check-then-insert 경쟁 재현(09-02). | +| 13 | 확장성 | P | 페이지 상한·풀 상한이 있다. 목록 비용이 페이지 크기에 선형, 포스터 생성 비용이 행 수에 선형(09-01, 09-02). | +| 14 | 성능 성숙도 | P | 기동 3.4 s(기본)/6.5~8.0 s(샘플), 필터 체인 0.5 ms, 단건 2.7 ms는 양호. 목록 N+1, 트랜잭션마다 추가 왕복, 성능 기준선 부재. | +| 15 | 보안 성숙도 | > | 02 영역. 측정 중 본 것: H2 jar 동봉(09-09), 샘플 전체 permitAll은 의도된 데모 구성. | +| 16 | 의존성 성숙도 | P | Jackson 2·3 공존, kotlin·okhttp, H2 동봉(09-09, 09-11). | +| 17 | API / Contract 성숙도 | P | 실제 서버의 `/api/v3/api-docs` 500, README 경로 불일치(09-03, 09-04). | +| 18 | 배포 성숙도 | > | 08 영역. jar 크기만 측정(41.4 / 99.0 MB). | +| 19 | 설정 성숙도 | P | env 손잡이는 충분하다. 샘플·local 프로필이 일부 키를 고정·덮어쓴다(09-08, 09-10). | +| 20 | 개발자 경험 | P | 샘플 단독 실행 시 대표 쓰기 실패, local 포트 고정(09-03, 09-10). | +| 21 | Guardrail 성숙도 | P | 풀 값 관계 검사와 batch 증명 장치는 있다. SQL 수·유일 제약 같은 성능·데이터 가드는 없다. | +| 22 | 추상화 성숙도 | - | 성능 실측 범위 밖(09-05의 격리 수준 위치만 언급). | +| 23 | 일관성 | P | 기본 조합과 샘플의 스레드·풀 대기·로그 기본값 불일치(09-08). | +| 24 | 네이밍 / 의미 성숙도 | - | 범위 밖. | +| 25 | 조직 확장성 | - | 범위 밖. | +| 26 | Ownership 성숙도 | - | 범위 밖. | +| 27 | 삭제 가능성 | - | 범위 밖(H2 분리는 09-09). | +| 28 | 회복 가능성 | ? | 장시간·장애 조건 측정을 하지 않았다. | + +## 정리 상태 + +측정에 쓴 프로세스(샘플·기본 조합 JVM)와 컨테이너 `perf09-pg`는 모두 내렸고, 이 측정에서만 받은 `postgres:16-alpine` 이미지도 지웠다. worktree `/wt-09`는 `git worktree remove --force`로 지웠다. 측정 스크립트와 원시 출력(`Load.java`, `Beans.java`, `run-app.sh`, `sqlcount.sh`, `bench.sh`, `phase3.sh`, `phase4.sh`, `bench-*.txt`, `sql-*.txt`, `*.jfr`, `jfr-summary.txt`)은 세션 scratchpad의 `perf/`에 남아 있다. 이 문서의 「측정 명령」 절만으로 다시 만들 수 있다. diff --git a/docs/reviews/2026-11-01-maturity-review/README.md b/docs/reviews/2026-11-01-maturity-review/README.md new file mode 100644 index 00000000..65862998 --- /dev/null +++ b/docs/reviews/2026-11-01-maturity-review/README.md @@ -0,0 +1,380 @@ +# 백엔드 성숙도 리뷰 — 2026-11-01 + +> 기준: `clean-architecture-frontend-template/docs/reviews/TEMPLATE-MATURITY-REVIEW-GUIDE.md`(31절 Backend 시나리오). 기준 커밋: `main` `01a8a2a70`(리뷰 후속 Wave 1–3 머지 직후). repo 전체를 9개 영역으로 나눠 영역 에이전트가 병렬로 읽고 실험했다. 이 문서는 오케스트레이터가 결과를 모으고 High 발견을 코드에서 다시 확인한 것이다. 영역 문서는 리뷰 시점 기록이라 수정 후에도 고치지 않는다. + +## 1. 사용 결정 (36.5-1) + +| 용도 | 결정 | 막는 항목 | +|---|---|---| +| 기본 조합(web·observability·cores)으로 새 서비스 시작 | **조건부 사용 가능** | 02-03(JWT audience가 비면 검증 안 함), 07-01(트레이스가 나가지 않음), 07-02(prod 기동 검사가 마이그레이션 뒤에 돔), 04-01(커밋 중 끊김을 재시도 가능으로 응답) | +| 짝 프론트 템플릿과 그대로 붙여 쓰기 | **사용 보류** | 02-02(Envelope의 null 필드를 프론트 strict 스키마가 거절), 02-01(처리 중 409의 클라이언트 행동이 계약에 없음) | +| sample-portfolio를 새 기능의 따라 할 예시로 복제 | **사용 보류** | 07-03·09-03(실행 중 권한 검사 없음, 대표 쓰기 500), 09-02(중복 규칙이 DB 제약 없이 조회 후 insert), 04-09·09-01(목록 N+1), 01-02(onboarding fixture가 기동 실패 모양) | +| 알림(notification) capability를 여러 인스턴스로 운영 | **사용 보류** | 05-01(발송 중 crash → 같은 알림 재발송), 04-02(정산 job 중복 처리) | +| outbox relay + Kafka로 운영 | 사용 보류 | 06-01(재시도 가능한 거부를 즉시 DEAD, 같은 aggregate 뒤 이벤트까지 막힘), 06-03(broker 5분 정지로 대량 DEAD) | +| Redis 멱등성·캐시 capability | 조건부 사용 가능 | 05-02(renew가 lease를 늘리지 못함 — 현재 호출자 없음), 05-03(revision 조건 무시) | +| HTTP client capability | 조건부 사용 가능 | 05-05(4xx가 breaker를 연다), 05-06(전체 시간 예산이 진행 중 요청을 못 끊음) | +| 파일 서버 capability | 조건부 사용 가능 | 05-07(copy가 디스크 수위·쿼터 우회), 05-08(소유자 검사를 지워도 테스트 통과) | +| GraphQL 공개 | 사용 보류 | 03-01(복잡도 점수가 목록 크기를 놓침) | +| gRPC operation ledger 채택 | 사용 보류 | 03-10(`IN_PROGRESS` 회수 없음), 03-11(설정만 있고 처리 코드 없음) | +| 이 repo의 CI를 머지 차단 장치로 믿기 | 조건부 | 08-01(strict lane 14개를 어떤 workflow도 돌리지 않음), 05-09·08-04(MinIO 이미지 소멸로 mainCheck 빨강, main 단계가 첫 실패에서 멈춤) | + +## 2. 차단 항목 — High와 P1 (36.5-3) + +같은 결함을 두 영역이 적은 것은 하나로 합쳤다. "코드 확인"은 오케스트레이터가 해당 줄을 직접 읽었다는 뜻이다. "에이전트 실행"은 영역 에이전트가 worktree에서 실행해 재현했다는 뜻이다. + +### 2.1 High (21건, 합친 뒤 19건) + +| ID | 내용 | 재확인 | +|---|---|---| +| [05-01](05-outbound-capabilities.md) | 알림 attempt를 `notStarted()`(PROVEN, false)로 저장한 채 provider를 호출한다. 발송 중 워커가 죽으면 recovery가 "확실히 시작 안 함"으로 읽고 다시 큐에 넣는다 → 같은 알림 재발송 | 코드 확인: `DeliveryAttemptFactory.java:54-56` → `NotificationDispatchService.java:189-216`(갱신 없이 `submitOutsideTransaction`) → `LeaseRecoveryService.java:101-106` | +| [04-02](04-persistence.md) | 알림 정산 job claim(`SELECT … FOR UPDATE SKIP LOCKED`)이 트랜잭션 없이 돈다. 잠금이 문장 끝에서 풀려 여러 인스턴스가 같은 job을 처리한다 | 코드 확인: `JdbcReconciliationJobStore.java:43-52,117-123`(`jdbc.query`만), `ReconciliationJobWorker.java:81`(트랜잭션 없음) | +| [04-01](04-persistence.md) | 커밋 중 연결이 끊기면(`08*`) `DB_UNAVAILABLE`(retryable)로 답한다. 실제로는 커밋됐을 수 있어 재시도가 쓰기를 중복시킨다. ADR-JPA-003과 반대 | 코드 확인: `PersistenceExceptionTranslator.java:97-99`, `SpringTransaction.java:98-105`(커밋 단계 구분 없음) + 에이전트 실험 테스트 | +| [06-01](06-messaging.md) | platform의 `retryable` 정보를 버리고 NOT_TRANSMITTED 거부를 `REJECTED_BEFORE_SEND`로 바꿔 즉시 DEAD. 종료 중·permit 부족도 DEAD가 되고 같은 aggregate 뒤 이벤트가 막힌다 | 코드 확인: `PlatformIntegrationEventPublishAdapter.java:140-151`, `PublishPendingOutboxEventsUseCase.java:149-153` + 에이전트 실행(`SHUTTING_DOWN retryable=true` → DEAD) | +| [06-03](06-messaging.md) (P2) | 재시도 3회·30초 고정이라 broker가 약 5분 멈추면 대량 DEAD, 복구는 row마다 수동 SQL | 에이전트 계산(실측 없음) | +| [05-02](05-outbound-capabilities.md) | Redis 멱등성 `renew()`가 `EXECUTING→EXECUTING` 전이라 Lua의 "이미 목표 상태" 분기에 걸려 항상 ALREADY, lease를 늘리지 않는다 | 코드 확인: `RedisIdempotencyStoreAdapter.java:183-190` + `IdempotencyScripts.java:101-108`. 현재 템플릿 안 호출자 없음(잠복) | +| [05-03](05-outbound-capabilities.md) | 캐시 `ONLY_IF_SOURCE_REVISION_NEWER`가 `ALWAYS`로 떨어져 조건 없이 SET | 코드 확인: `RedisCacheRegionAdapter.java:262-266`(`presenceOf`는 ONLY_IF_ABSENT만 구분) | +| [05-05](05-outbound-capabilities.md) | HTTP client: 404 같은 정상 4xx도 circuit breaker 실패로 센다 | 에이전트 코드 읽기(E1). 수정 단계에서 RED 테스트로 확인 | +| [05-06](05-outbound-capabilities.md) | HTTP client: 전체 시간 예산이 진행 중 attempt를 끊지 못한다(소켓 read-idle만 있음) | 에이전트 코드 읽기(E1). 수정 단계에서 확인 | +| [05-07](05-outbound-capabilities.md) | 파일 서버: copy가 디스크 수위 검사를 우회하고 쿼터는 기록만 한다 | 에이전트 코드 읽기(E1). 수정 단계에서 확인 | +| [03-01](03-inbound-realtime-graphql-grpc.md) | GraphQL 복잡도 점수가 `first` 생략·변수 기본값·일반 list에서 하위 비용을 곱하지 않고 페이지 상한 검사도 건너뛴다(`first:20` 410점, 생략 40점) | 에이전트 실행(임시 테스트 재현) | +| [03-10](03-inbound-realtime-graphql-grpc.md) | gRPC ledger `IN_PROGRESS` 행에 만료·회수가 없다. 소유자가 죽으면 key가 영구히 막힌다 | 코드 확인: `GrpcOperationLedgerRepository.java:76-92`(회수는 `FAILED_TERMINAL`만), `GrpcIdempotencyInterceptor.java:118-121`. 채택 전 차단(03-11) | +| [02-01](02-inbound-web.md) | "처리 중" 응답은 `409 IDEMPOTENT_IN_FLIGHT`, `retryable=false`, `Retry-After` 없음. "같은 키로 재전송"이 백엔드 어디에도 없고 runbook·error-codes.yaml은 없는 헤더·polling을 말한다 | 에이전트 실행(`@WebMvcTest` 출력) + 문서 대조 | +| [02-02](02-inbound-web.md) | 실제 Envelope에 `data:null`·`error:null`·`meta.page:null`이 항상 실린다. 짝 프론트 strict 스키마가 거절한다. 백엔드 `doesNotExist` 단언은 null도 통과시킨다 | 에이전트 실행(`@WebMvcTest` 출력) + 프론트 코드 읽기 | +| [02-03](02-inbound-web.md) + [07-05](07-bootstrap-composition-config.md) | JWT audience가 비면(템플릿 기본값) 검증을 건너뛴다. env 레지스트리는 `required: true`. role은 모든 client의 `resource_access`에서 합친다 | 코드 확인: `SecuritySettings.java:35-42` | +| [07-01](07-bootstrap-composition-config.md) | 자체 `Tracer`에 span processor·exporter가 없어 OTLP endpoint를 넣어도 아무것도 나가지 않는다 | 코드 확인: `TracingConfig.java:66-91`(`SdkTracerProvider`에 sampler만) + 에이전트 실행(exporter 0개) | +| [07-02](07-bootstrap-composition-config.md) | prod 기동 검사(TLS·Flyway)가 `afterSingletonsInstantiated`에서 돌아 DB 연결·마이그레이션이 먼저 실행된다 | 코드 확인: `StartupRuleRunner.java:35`. PostgreSQL 실측 없음 | +| [07-03](07-bootstrap-composition-config.md) + [09-03](09-performance-measurement.md) | 샘플이 `WebSecurityAutoConfiguration`을 통째로 빼면서 `MethodSecurityConfig`도 빠졌다. `@RequiresPermission`이 동작하지 않아 익명 삭제 가능, owner가 null이라 `POST /api/worklogs`는 항상 500 | 코드 확인: `SamplePortfolioApplication.java:31`, `WebSecurityAutoConfiguration.java:41-49` + 에이전트 실행(`java -jar`로 500 재현) | +| [09-02](09-performance-measurement.md) | 포스터 제목 중복 규칙이 DB 유일 제약 없이 "조회 후 insert". 같은 제목 16개 동시 요청 3회 모두 10행씩 들어감. 검사 쿼리는 순차 스캔 | 에이전트 실행(동시 요청 실측) | +| [08-01](08-build-ci-test.md) + [04-04](04-persistence.md) + [03-12](03-inbound-realtime-graphql-grpc.md) | CI가 한 번도 돌리지 않는 strict lane 14개(JPA 실 PostgreSQL 11, web 부하·종료 2, sample 전체 기동 1). `integration-main.yml:96`은 `integrationCheck --dry-run`만 한다. persistence-fileserver는 자기 테스트가 0개 | 에이전트 `--dry-run` 그래프와 workflow 15개 대조. 04 영역이 그중 4 lane을 직접 돌려 44건 통과 | + +### 2.2 P1 (High 제외) + +| ID | 심각도 | 내용 | 재확인 | +|---|---|---|---| +| [05-09](05-outbound-capabilities.md) + [08-04](08-build-ci-test.md) | Medium | MinIO 이미지(`minio/minio@sha256:4c4a48…`)를 받을 수 없어 mainCheck가 빨갛다. 이미지 참조가 네 곳에 복사돼 있고 main 단계는 `--continue` 없이 돌아 다른 lane 결과를 가린다 | 오케스트레이터 실행: Docker Hub `minio/minio` pull 거부, `alpine:3`는 성공, `quay.io/minio/minio`도 해당 digest·태그 없음 | +| [04-03](04-persistence.md) | Medium | JPA 양방향 연관관계 금지(사용자 원칙)를 막는 장치가 없고 `docs/jpa/entity-mapping-guide.md:50-57`과 testFixtures 예제는 `mappedBy` 양방향을 가르친다. 운영 엔티티 28개는 지금 연관관계 0개 | 에이전트 전수 확인 | +| [05-08](05-outbound-capabilities.md) | Medium | 파일 서버 copy·download의 소유자 검사를 지워도 442개 테스트가 전부 통과(소유자 결정 14의 회귀 방지 없음) | 에이전트 변이 실험 | +| [06-02](06-messaging.md) | Medium | platform 종료 순서가 앱 outbox relay를 모른다 | 에이전트 코드 읽기 | + +## 3. 확인된 강점 (36.5-2) + +- **PR 게이트가 녹색이다.** `ci` rc=0(434초). leaf check(compile·test·Spotless·Checkstyle·Error Prone) 전체, `architectureCheck`(의존 방향·순수성·ArchUnit 181건), `qualityCheck`(SpotBugs·FindSecBugs)가 통과했다. +- **지난 리뷰의 High/P1이 모두 닫혔다.** 9개 영역 모두 "남은 High/P1 없음"으로 재확인했다. 남은 것은 문서·테스트 규칙(W4·W5) 성격이다. +- **JPA 엔티티는 사용자 원칙을 지킨다.** 운영 엔티티 28개에 연관관계 매핑이 하나도 없다(04 영역). 막는 장치만 없다(04-03). +- **실 PostgreSQL lane은 돌리면 통과한다.** JPA 4 lane 44건(04), gRPC ledger 18건(03). 문제는 CI가 돌리지 않는다는 것(08-01)이다. +- **테스트가 빠르다.** 테스트 결과 XML 984개 합계 약 208초, 가장 느린 클래스 9.3초(08 영역). ci 434초의 병목은 테스트 실행이 아니다. +- **기본 조합이 가볍다.** bootJar 41.4 MB, 기동 중앙값 3.44초, 빈 407개. 필터 체인만 지나는 요청 27k rps(09 영역). +- **변이 실험 대부분을 테스트가 잡는다.** strict lane 장치 3/3, GraphQL 구조 상한·STOMP destination, outbox offset 검사 등. 잡지 못한 것은 각 발견으로 적었다(05-08, 06-05, 01-03, 02-09). + +## 4. 반복되는 원인 (36.5-4) + +1. **결과 불명을 "확실함"으로 기록한다.** 05-01(시작 안 함 PROVEN으로 저장 후 호출), 04-01(커밋 중 끊김을 재시도 가능으로), 06-01(재시도 가능 거부를 확정 거부로), 05-17(Redis 연결 실패를 결과 불명으로 — 반대 방향). 결과 불명 처리를 정한 문서(ADR-JPA-003, 알림 evidence 모델)는 있지만 경계마다 다시 구현되며 갈라졌다. +2. **중복·경쟁을 DB가 아니라 코드 순서로 막는다.** 09-02(조회 후 insert), 04-08(upsert), 04-02(트랜잭션 없는 SKIP LOCKED), 03-10(lease 없는 claim). 가이드 31절 "DB 유일성 제약과 충돌 처리가 충분한지 먼저 본다"에 해당한다. +3. **샘플이 운영 경로와 다르게 조립된다.** 07-03·09-03(보안 자동 설정 통째 제외), 09-08(런타임 기본값 다름), 07-04(`Dockerfile.sample` 빌드 실패), 07-09·01-01(따라 할 예시가 세 갈래). 매뉴얼 재료가 될 예시가 실제로는 실행되지 않는다. +4. **설정·이미지 참조·식별자 규칙이 여러 벌이다.** `TenantId` 3벌(01-03), 이벤트 ID 문법 5곳(01-07), SQLState 분류표 2벌(04-06), MinIO 이미지 참조 4곳(05-09), 로그 설정 2곳(07-06). 사용자 원칙 "갈라진 중복 복사본은 결함"에 정면으로 걸린다. +5. **선언과 실행이 떨어져 있다.** strict lane을 선언하고 돌리지 않는다(08-01), 설정 키는 바인딩되지만 동작하지 않는다(05-15, 03-11), 레지스트리는 `required`인데 코드는 빈 값을 허용한다(02-03). + +## 5. 결정이 필요한 것 + +> 2026-11-01 22:00 소유자 결정: 아래 다섯 항목 모두 권장안으로 정했다. 05-09의 대체 이미지 선택만 보류(이미지 참조 한 곳·pull 실패 메시지 구분·main 단계 `--continue`까지 진행). + +| 항목 | 선택지 | 권고 | 승인자 | +|---|---|---|---| +| 02-01 처리 중 409 | (A) `retryable=true` + `Retry-After` + 계약 문서 고정 (B) `retryable=false` 유지, 문서만 (C) executor가 잠시 대기 후 replay (D) 키 조회 엔드포인트 | (A). 같은 키 재전송은 서버가 replay·in-flight·422로 안전하게 판정한다. 짝 프론트 분류기와 같이 바꾼다 | 템플릿 소유자(두 repo) | +| 02-02 Envelope null 필드 | (A) 백엔드가 `@JsonInclude(NON_NULL)`로 생략 (B) 프론트 strict 완화 | (A). 프론트의 "unknown field 거절" 방어를 유지한다 | 템플릿 소유자(두 repo) | +| 02-03 JWT audience·role 범위 | (A) audience 필수 + 자기 client role만 (B) prod에서만 필수 (C) 문서만 | (A). 기존 배포는 env 하나를 채워야 한다(호환성 깨짐) | 템플릿 소유자 | +| 05-09 MinIO 이미지 공급원 | (a) 조직 레지스트리 미러 (b) 다른 공식 레지스트리 (c) 커뮤니티 재배포 이미지 (d) 다른 S3 구현 (e) lane 제외 | 원본 digest를 가진 곳이 없고(로컬·quay.io 모두 없음) 조직 레지스트리도 없어 (a)(b)는 지금 불가. 단기: 이미지 참조를 한 곳으로 모으고 pull 실패를 별도 메시지로 구분, 대체 이미지는 소유자가 고른다 | 템플릿 소유자 | +| 07-01 트레이싱 | (A) 자체 Tracer를 지우고 Boot 4 tracing·OTLP 모듈로 (B) 자체 Tracer에 exporter 직접 연결 (C) 트레이싱 범위 제거 | (A) | 템플릿 소유자 | + +## 6. 미검증 (36.5-5) + +| 무엇 | 왜 | 확인하려면 | +|---|---|---| +| GitHub Actions 실제 실행 결과 | 원격이 `git.learn.hyeonworks.com`이고 외부 조회를 하지 않았다 | runner 결과 | +| 미실행 strict lane 14개 중 10개의 현재 통과 여부 | 04 영역이 4 lane만 돌렸다 | `integrationCheck` 실행 | +| MinIO 계약·fault lane | 이미지를 받을 수 없다 | 5절 결정 후 | +| 실제 다중 인스턴스 경쟁(05-01, 04-02, 06-01) | 코드 경로와 단위 실험만 했다 | 2개 인스턴스 + 실 DB 통합 테스트(수정 단계 RED 테스트로 일부 대체) | +| Redis·Toxiproxy·SES/SMTP·Kafka 실연 | 외부 서비스·컨테이너 lane을 돌리지 않았다 | 해당 lane | +| 실제 SIGTERM 종료 순서(06-02, 07-07) | 측정하지 않았다 | 컨테이너에서 종료 실측 | +| 실제 `docker build` | Dockerfile COPY 집합만 재현했다(`Dockerfile.sample` 실패) | 빌드 실행 | +| 짝 프론트와의 결합 실행(02-01, 02-02) | 프론트는 코드만 읽었다 | 두 템플릿 통합 환경 | + +## 7. 개선 순서 (36.5-6) + +| 순서 | 대상 | 이유 | 완료 기준 | +|---|---|---|---| +| 1 | 05-01, 04-02, 04-01, 06-01, 05-02, 05-03, 05-05, 05-06, 05-07, 03-01, 03-10, 07-02, 07-03+09-03, 09-02 | High·P1 중 결정이 필요 없는 코드 결함. 각각 막는 테스트를 먼저 넣는다 | 각 영역 문서의 완료 기준. 수정 전 실패하는 테스트가 있어야 한다 | +| 2 | 02-01, 02-02, 02-03+07-05, 07-01, 05-09+08-04 | 5절 결정 후 | 결정 내용대로 | +| 3 | 08-01+04-04+03-12, 04-03, 05-08, 06-02, 06-03 | CI·회귀 방지 장치와 P1 Medium | lane이 workflow에서 돌고, 금지 규칙이 ArchUnit으로 막고, 변이가 잡힌다 | +| 4 | 01-01, 01-02, 07-09, 01-05, 01-03, 01-07, 04-06 | 개발 매뉴얼(`docs/manual/`)과 기능 생성 명령의 재료. 예시 하나, 규칙 한 벌 | 생성 명령으로 만든 기능이 모든 게이트를 통과 | +| 5 | 나머지 P2·P3 | 영역별 | 각 영역 문서 | + +## 8. 재검토 조건 (36.5-7) + +- 개선 순서 1·2가 끝나면 해당 영역만 다시 본다. +- 개발 매뉴얼과 기능 생성 명령이 생기면 01·07 영역을 그 명령으로 만든 기능 기준으로 다시 본다. +- MinIO 대체 공급원이 정해지면 objectstorage 벤더 증거를 다시 측정한다. +- gRPC ledger나 Redis 멱등성 renew를 실제로 쓰는 경로가 생기면 03·05 영역을 다시 본다. + +## 9. 리뷰 범위 (36.1) + +- 기준 커밋 `01a8a2a70`. 게이트는 오케스트레이터가 한 번 실행했다(프론트 세션과 공유 잠금). + + | 게이트 | 결과 | 시간 | 실행 직전 부하 | + |---|---|---|---| + | `ci` | rc=0 | 434초(잠금 대기 포함) | load 9.15 | + | `mainCheck` | rc=1 — `objectStorageMinioContractTest`, `objectStorageMinioFaultTest`만 실패(이미지 pull 404). `sampleWebContractCheck`, sample `webSystemTest`, `verifyEnvKeys`, app-bootstrap `systemTest` 통과 | 162초 | load 20.68 | + +- 영역 9개와 담당 leaf: + + | 영역 | 범위 | + |---|---| + | [01](01-core-and-feature-pattern.md) core·기능 패턴 | `domain-core`, `shared-contract`, `application-core` + repo 전체 폴더 구조·리팩토링·새 기능 흐름 | + | [02](02-inbound-web.md) inbound web | `adapter:inbound:web*`, `composition:idempotency` HTTP 계약 | + | [03](03-inbound-realtime-graphql-grpc.md) realtime·graphql·grpc | `websocket`, `graphql`, `grpc` 어댑터 + `grpc:*`, `grpc-advanced:*` | + | [04](04-persistence.md) persistence | `persistence-jpa`, `-mongo`, `-fileserver`, `-notification`, 마이그레이션 | + | [05](05-outbound-capabilities.md) outbound capability | redis·cache·httpclient·objectstorage·notification·fileserver·identifier·support + `application-*` capability, composition | + | [06](06-messaging.md) messaging | `messaging:*`, `adapter:outbound:messaging(-kafka)`, `composition:outbox-relay` | + | [07](07-bootstrap-composition-config.md) bootstrap·설정 | `app-bootstrap`, `composition:service-runtime`, `sample-portfolio`, env 계약, Dockerfile, compose | + | [08](08-build-ci-test.md) build·CI·테스트 | `build-logic`, settings, 루트 lifecycle, workflow 15개, 테스트 lane, 테스트 실행 시간 | + | [09](09-performance-measurement.md) 성능 실측 | 기동·jar·SQL 수·처리량·JFR | + +## 10. 이번 라운드 추가 렌즈 요약 + +- **성능(09).** bootJar 기본 41.4 MB / 샘플 99.0 MB. 기동 중앙값 3.44초(빈 407) / 8.05초(빈 603). 요청당 SQL: 목록 20건 46개, 100건 206개, 단건 7개, 제목만 바꾸는 PATCH 13개. 처리량: 단건 5,521 rps, 목록 20건 829 rps. `default_batch_fetch_size=100`만으로 목록 2.9배. 관측 기능 비용 약 3%, 가상 스레드는 차이 없음. +- **테스트 성능(08).** 테스트 시간 합 약 208초. strict lane의 `upToDateWhen(false)`가 build cache 적재까지 막아 PR마다 약 77초가 매번 다시 돈다(08-02). PR `test`에 저장소 문서를 읽는 클래스 15개(08-03). +- **폴더 구조·기능 패턴(01·07).** 새 기능을 두는 모양이 세 가지(core 안, `application-*` capability, sample 수직)이고 고르는 기준이 없다(01-01). 따라 할 예시도 세 갈래(07-09). 01 영역 문서 7절에 "새 도메인 하나 추가" 단계별 틀·빠진 것·판단 지점과 생성 명령 후보 목록이 있다 — 매뉴얼 재료. +- **리팩토링 후보.** 각 영역 문서 6절. 공통: 식별자 문법·SQLState 표·이미지 참조를 한 곳으로(4절 원인 4). + +## 11. 28개 관점 판정 (36.2) + +영역별 기호: O 충족 · P 부분 · X 미충족 · ? 미검증 · - 적용 제외 · > 다른 영역. 종합은 평균하지 않는다. 한 영역이라도 X면 X다(35.7절). + +| 관점 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 종합 | +|---|---|---|---|---|---|---|---|---|---|---| +| 1 코드 성숙도 | O | P | P | P | P | P | P | O | > | P | +| 2 구조적 성숙도 | P | O | P | P | O | P | P | O | > | P | +| 3 변경 용이성 | P | P | P | P | P | P | P | P | P | P | +| 4 인지 부하 | P | P | P | P | P | P | P | P | P | P | +| 5 위험 가시성 | P | X | X | X | P | P | X | P | X | **X** | +| 6 실패 성숙도 | P | P | P | X | P | X | P | P | P | **X** | +| 7 운영 성숙도 | > | P | P | P | P | P | P | > | P | P | +| 8 디버깅 가능성 | P | O | P | P | P | P | P | P | O | P | +| 9 유지보수 성숙도 | P | P | P | P | P | P | P | P | P | P | +| 10 테스트 성숙도 | P | P | P | P | P | P | P | P | X | **X** | +| 11 데이터 성숙도 | P | - | P | P | P | P | > | > | X | **X** | +| 12 동시성 성숙도 | P | P | P | P | P | P | P | - | X | **X** | +| 13 확장성 | - | ? | X | P | ? | P | ? | P | P | **X** | +| 14 성능 성숙도 | O | ? | P | P | P | ? | P | P | P | P | +| 15 보안 성숙도 | P | X | P | O | P | O | P | P | > | **X** | +| 16 의존성 성숙도 | O | O | O | O | P | P | P | P | P | P | +| 17 API·계약 성숙도 | P | X | P | P | P | P | > | O | P | **X** | +| 18 배포 성숙도 | > | > | P | ? | > | X | P | > | > | **X** | +| 19 설정 성숙도 | - | P | P | P | P | P | P | O | P | P | +| 20 개발자 경험 | X | P | P | P | P | P | P | P | P | **X** | +| 21 Guardrail | P | P | P | P | P | P | P | P | P | P | +| 22 추상화 성숙도 | P | O | P | P | P | P | O | O | - | P | +| 23 일관성 | X | P | P | P | P | P | P | P | P | **X** | +| 24 네이밍·의미 | P | P | P | P | P | P | P | P | - | P | +| 25 조직 확장성 | P | P | - | P | ? | P | ? | P | - | P | +| 26 Ownership | P | P | P | P | P | P | P | ? | - | P | +| 27 삭제 가능성 | P | O | O | O | P | O | P | P | - | P | +| 28 회복 가능성 | > | P | X | P | P | X | - | P | ? | **X** | + +미충족(X)의 이유: +- 5 위험 가시성 — 02-03(레지스트리 required, 코드는 빈 값 허용), 03-01, 04-01, 07-03, 09-03: 위험이 기본값·설정 뒤에 숨어 있다. +- 6 실패 성숙도 — 04-01(커밋 중 끊김 오분류), 06-01·06-03(재시도 가능 실패를 DEAD로). +- 10 테스트 성숙도 — 09 영역: 대표 쓰기 500·동시 중복을 테스트가 잡지 못한다. 05-08 변이 생존. +- 11 데이터 성숙도 — 09-02: 중복 규칙에 DB 제약 없음. +- 12 동시성 성숙도 — 09-02, 04-02(트랜잭션 없는 SKIP LOCKED). +- 13 확장성 — 03-06·03-09: WebSocket·gRPC 연결·동시 호출 상한 없음. +- 15 보안 성숙도 — 02-03(audience 기본 꺼짐, 타 client role 합침). +- 17 API·계약 — 02-01, 02-02: 짝 프론트와 wire 계약 불일치. +- 18 배포 성숙도 — 06 영역: 종료 순서가 relay를 모름(06-02), broker 실연 lane 없음(06-09). +- 20 개발자 경험·23 일관성 — 01 영역: 새 기능 모양 세 갈래(01-01), 식별자·이름 규칙 여러 벌(01-03, 01-07, 01-12). +- 28 회복 가능성 — 03-10(ledger 영구 잠김), 06-03(DEAD 복구 수작업). + +## 12. 발견 색인 + +영역 문서에 36.3 양식으로 적힌 발견 119건: High 21 · Medium 64 · Low 34, P1 25 · P2 59 · P3 35. Critical 0. 두 영역이 같은 결함을 적은 묶음(07-03+09-03, 02-03+07-05, 08-01+04-04+03-12, 05-09+08-04, 04-09+09-01)은 색인에 각각 남기고 2절에서 합쳤다. 06·08 영역 문서는 원래 `NN-` 접두사로 적혀 있어 `06-`·`08-`로 바꿨다. + +| ID | 심각도 | 우선순위 | 내용 | +|---|---|---|---| +| [02-01](02-inbound-web.md) | High | P1 | "처리 중" 409의 클라이언트 행동이 코드·문서·짝 계약에서 서로 다르다 | +| [02-02](02-inbound-web.md) | High | P1 | 실제 Envelope JSON이 `data:null`·`error:null`·`meta.page`를 싣는데 짝 프론트 계약은 이를 거절한다 | +| [02-03](02-inbound-web.md) | High | P1 | JWT audience 검증이 기본으로 꺼져 있고, 모든 client의 role을 합친다 | +| [03-01](03-inbound-realtime-graphql-grpc.md) | High | P1 | GraphQL 복잡도 점수가 목록 크기를 놓친다 — 페이지 인자 생략·변수 기본값·일반 list 필드 | +| [03-10](03-inbound-realtime-graphql-grpc.md) | High | P1 | operation ledger의 `IN_PROGRESS` claim에 만료·회수가 없다 — 소유자가 죽으면 그 key는 영구히 막힌다 | +| [04-01](04-persistence.md) | High | P1 | 커밋 중 연결이 끊기면 "재시도 가능(DB_UNAVAILABLE)"으로 답한다 | +| [04-02](04-persistence.md) | High | P1 | 다중 인스턴스에서 알림 정산 job이 중복 처리된다 | +| [05-01](05-outbound-capabilities.md) | High | P1 | 알림 attempt를 "요청 시작 안 함(확정)"으로 저장한 채 provider를 호출한다 — 워커가 발송 중 죽으면 같은 알림이 다시 나간다 | +| [05-02](05-outbound-capabilities.md) | High | P1 | Redis 멱등성 `renew()`가 처리 lease를 연장하지 못한다 | +| [05-03](05-outbound-capabilities.md) | High | P1 | 캐시 `ONLY_IF_SOURCE_REVISION_NEWER`가 조건 없이 덮어쓴다 | +| [05-05](05-outbound-capabilities.md) | High | P1 | HTTP client: 4xx 응답이 circuit breaker 실패로 집계된다 | +| [05-06](05-outbound-capabilities.md) | High | P1 | HTTP client: 전체 시간 예산이 진행 중인 attempt를 끊지 못한다 | +| [05-07](05-outbound-capabilities.md) | High | P1 | 파일 서버: copy가 디스크 수위 검사를 우회하고, 쿼터는 기록만 한다 | +| [06-01](06-messaging.md) | High | P1 | 다시 시도하면 될 거부를 relay가 즉시 DEAD로 보낸다 | +| [07-01](07-bootstrap-composition-config.md) | High | P1 | 트레이스가 어디로도 나가지 않는다 — OTLP endpoint를 설정해도 span을 만들지도 보내지도 않는다 | +| [07-02](07-bootstrap-composition-config.md) | High | P1 | prod 기동 검사가 DB 연결과 Flyway 마이그레이션이 끝난 뒤에 돈다 | +| [07-03](07-bootstrap-composition-config.md) | High | P1 | 실행 중인 샘플에서는 `@RequiresPermission`이 아무 일도 하지 않는다 — 익명 삭제 가능, 생성은 500 | +| [08-01](08-build-ci-test.md) | High | P1 | CI가 실행하지 않는 strict lane 14개 | +| [09-02](09-performance-measurement.md) | High | P1 | 포스터 제목 중복 규칙이 동시 요청에서 깨지고, 검사 쿼리가 순차 스캔 | +| [09-03](09-performance-measurement.md) | High | P1 | 단독 실행한 샘플에서 대표 쓰기 `POST /api/worklogs`가 항상 500 | +| [06-03](06-messaging.md) | High | P2 | broker가 몇 분만 멈춰도 row가 대량으로 DEAD가 되고 복구는 수작업이다 | +| [04-03](04-persistence.md) | Medium | P1 | JPA 연관관계 원칙(양방향 금지)을 막는 장치가 없고, 템플릿 문서와 fixture는 반대로 가르친다 | +| [04-04](04-persistence.md) | Medium | P1 | 실 PostgreSQL lane 9개(57개 테스트)가 어떤 게이트·workflow에서도 돌지 않는다. persistence-fileserver는 자기 테스트가 0개다 | +| [05-08](05-outbound-capabilities.md) | Medium | P1 | 파일 서버: 소유자 검사를 지워도 테스트가 하나도 실패하지 않는다 | +| [05-09](05-outbound-capabilities.md) | Medium | P1 | 객체 저장소: MinIO 이미지 공급원이 사라져 mainCheck가 빨갛다 | +| [06-02](06-messaging.md) | Medium | P1 | platform 종료 순서가 앱 relay를 모른다 | +| [01-01](01-core-and-feature-pattern.md) | Medium | P2 | 새 기능을 어느 leaf에 두는지 세 가지 모양이 있고, 고르는 기준이 없다 | +| [01-02](01-core-and-feature-pattern.md) | Medium | P2 | onboarding fixture가 "새 기능의 계약 모양"으로 박아 둔 유스케이스가 실제로는 기동에 실패하는 모양이다 | +| [01-03](01-core-and-feature-pattern.md) | Medium | P2 | `TenantId`가 3벌이고 받아들이는 문법이 셋 다 다르다 | +| [01-04](01-core-and-feature-pattern.md) | Medium | P2 | `IllegalArgumentException` 하나가 "입력이 틀렸다"와 "서버 조립이 틀렸다"를 함께 뜻하고, web은 둘 다 로그 없이 400으로 바꾼다 | +| [01-05](01-core-and-feature-pattern.md) | Medium | P2 | application-core가 소유한 포트 중 절반이 "fake와 실제 adapter가 같은 계약 테스트를 통과한다"는 규칙 밖에 있다 | +| [02-04](02-inbound-web.md) | Medium | P2 | rate-limit 거부 본문이 실제 Tomcat에서 ISO-8859-1로 나가 한국어 문구가 깨진다 | +| [02-05](02-inbound-web.md) | Medium | P2 | CORS에 노출 헤더가 없어 브라우저가 계약 헤더를 못 읽는다 | +| [02-06](02-inbound-web.md) | Medium | P2 | `String`을 반환하는 컨트롤러는 `Accept: application/json`에서 500이 된다 | +| [02-07](02-inbound-web.md) | Medium | P2 | web-advanced 예외 10종이 문서의 상태 대신 500으로 나간다 | +| [03-02](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | GraphQL 요청 deadline(10초)이 실행 중에는 강제되지 않는다 | +| [03-03](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | N+1을 막는 길이 adopter 기억에만 있다 | +| [03-06](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | WebSocket 연결 수·구독 수·연결 수명 상한이 없고, STOMP 전송 한도가 코드에 드러나지 않는다 | +| [03-07](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | `SerializedOutboundWriter`의 offer와 close가 겹치면 노드 버퍼 예산이 영구히 샌다 | +| [03-08](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | `PlatformWebSocketHandler.stop()` 뒤에 들어온 연결은 1001을 받지 못한다 | +| [03-09](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | gRPC 어댑터 서버가 io.grpc 기본값으로 뜬다 — deadline·동시 호출·executor·메시지 크기 상한이 없고, 플랫폼 한도는 testkit 서버에만 적용된다 | +| [03-11](03-inbound-realtime-graphql-grpc.md) | Medium | P2 | `app.grpc.platform.operation-ledger-enabled`는 검증만 통과시키고 실제로 key를 처리하는 코드가 없다 | +| [04-05](04-persistence.md) | Medium | P2 | `@Version` 충돌이 변환되지 않고 500 INTERNAL_ERROR로 나간다 | +| [04-06](04-persistence.md) | Medium | P2 | SQLState 분류표가 두 벌이고 이미 갈라졌다 | +| [04-07](04-persistence.md) | Medium | P2 | bulk UPDATE가 `@Version`을 올리지 않는다 | +| [04-08](04-persistence.md) | Medium | P2 | upsert가 "찾고 없으면 넣기"라 동시 요청에서 깨진다 | +| [04-09](04-persistence.md) | Medium | P2 | sample 목록 조회가 N+1이다(페이지당 최대 202쿼리) | +| [04-10](04-persistence.md) | Medium | P2 | 기본 쓰기·읽기 트랜잭션에 시간 제한이 없다 | +| [04-11](04-persistence.md) | Medium | P2 | Mongo 트랜잭션 본문의 일시 오류가 재시도되지 않는다 | +| [04-12](04-persistence.md) | Medium | P2 | Mongo 기본 경로(URI만 준 배포)에 timeout·pool 제한이 없다 | +| [04-13](04-persistence.md) | Medium | P2 | persistence adapter가 정책을 소유하고, claim 토큰을 프로세스 메모리에 둔다 | +| [04-14](04-persistence.md) | Medium | P2 | notification·fileserver 영속 leaf가 테스트 규칙(공유 계약)을 따르지 않는다 | +| [04-15](04-persistence.md) | Medium | P2 | Mongo 라이브러리를 파생 서비스가 쓸 경로와 예시가 없다 | +| [05-04](05-outbound-capabilities.md) | Medium | P2 | 캐시 무효화와 느린 loader의 경합, stampede 보호 없음, 문서는 jitter를 주장 | +| [05-10](05-outbound-capabilities.md) | Medium | P2 | 알림: collapse 미지원 예외가 try 밖에서 터져 끝없이 재시도된다 | +| [05-11](05-outbound-capabilities.md) | Medium | P2 | 알림: SMTP 실패가 전부 "결과 불명"이 되어 재시도 없이 운영자 대기로 멈춘다 | +| [05-12](05-outbound-capabilities.md) | Medium | P2 | 파일 서버: tus PATCH가 쓰기를 커밋한 뒤 `file:read`를 요구한다 | +| [05-13](05-outbound-capabilities.md) | Medium | P2 | 파일 서버: 정리 worker가 기본으로 꺼져 있다 | +| [05-14](05-outbound-capabilities.md) | Medium | P2 | HTTP client: 기본 설정에서 결과 불명 분류가 틀린 경로로 나간다 | +| [05-15](05-outbound-capabilities.md) | Medium | P2 | HTTP client: 바인딩되지만 동작하지 않는 설정 키, 0 timeout 허용 | +| [05-16](05-outbound-capabilities.md) | Medium | P2 | capability 완료 기준 5가 영역 전체에서 지켜지지 않는다 | +| [05-17](05-outbound-capabilities.md) | Medium | P2 | Redis: 연결 실패를 "결과 불명"으로 보고하고, 시간 초과된 연결을 pool에 돌려준다 | +| [05-20](05-outbound-capabilities.md) | Medium | P2 | SES 콜백: replay 창 5분이 장애 뒤 SNS 재전송을 버린다 | +| [06-04](06-messaging.md) | Medium | P2 | aggregate 하나의 발행 속도가 poll 주기당 1건으로 묶인다 | +| [06-05](06-messaging.md) | Medium | P2 | relay가 꺼져 있거나 실패하는 동안 outbox 지표가 갱신되지 않는다 | +| [06-06](06-messaging.md) | Medium | P2 | application EventId 문법과 platform MessageId(UUID)가 다르다 | +| [06-07](06-messaging.md) | Medium | P2 | 샘플이 aggregate 순서 번호를 벽시계로 만든다 | +| [06-08](06-messaging.md) | Medium | P2 | 소비(consume)를 지원한다는 결정이 application 쪽 경로로 이어지지 않는다 | +| [06-09](06-messaging.md) | Medium | P2 | 실제로 쓰는 발행 경로에는 broker 실연 테스트가 없고, broker 실연 lane은 어떤 기본 게이트에도 없다 | +| [07-04](07-bootstrap-composition-config.md) | Medium | P2 | `Dockerfile.sample`은 빌드되지 않는다 | +| [07-05](07-bootstrap-composition-config.md) | Medium | P2 | prod에서 JWT audience를 비워도 기동하고, 경고도 없이 audience 검사를 끈다 | +| [07-06](07-bootstrap-composition-config.md) | Medium | P2 | 로그 설정이 두 군데에서 읽힌다 — `LoggingSettings`는 아무도 쓰지 않고, logback은 env 키를 직접 읽는다 | +| [07-07](07-bootstrap-composition-config.md) | Medium | P2 | 종료 시간 예산표에 async executor 대기 19초가 빠져 있다 | +| [07-08](07-bootstrap-composition-config.md) | Medium | P2 | 기본 조립 루트가 아직 선택 capability를 안다 (capability 기준 7 위반) | +| [07-09](07-bootstrap-composition-config.md) | Medium | P2 | 새 기능을 만들 때 따라 할 예시가 세 갈래다 | +| [08-02](08-build-ci-test.md) | Medium | P2 | strict lane은 build cache도 쓰지 않아서 바뀐 것이 없어도 매번 다시 돈다 | +| [08-03](08-build-ci-test.md) | Medium | P2 | app-bootstrap의 PR 테스트가 저장소 문서를 읽고, 저장소 전체를 입력으로 잡는다 | +| [08-04](08-build-ci-test.md) | Medium | P2 | 외부 컨테이너 이미지가 사라지면 main 단계가 통째로 멈춘다 | +| [09-01](09-performance-measurement.md) | Medium | P2 | 샘플 목록 API가 N+1 — 페이지 20건에 SQL 46개 | +| [09-04](09-performance-measurement.md) | Medium | P2 | 단독 실행한 샘플에서 `/api/v3/api-docs`가 500 | +| [09-06](09-performance-measurement.md) | Medium | P2 | 제목 하나 고치는 PATCH가 컬렉션 테이블을 전부 지우고 다시 넣음 | +| [09-07](09-performance-measurement.md) | Medium | P2 | JDBC batch 기본 꺼짐 + 동기 `batchCreate` 1000건을 한 트랜잭션에서 처리 | +| [01-06](01-core-and-feature-pattern.md) | Medium | P3 | `@RequiresPermission`은 application 계약인데, 검사는 web leaf가 켜 주는 AOP에만 있다 | +| [01-08](01-core-and-feature-pattern.md) | Medium | P3 | 장기 실행 작업(LRO) 공개 계약이 두 벌이다 | +| [01-09](01-core-and-feature-pattern.md) | Medium | P3 | 통합 이벤트를 만드는 규칙(tenant 범위·순서·correlation)을 기능마다 다시 정한다 | +| [02-08](02-inbound-web.md) | Low | P2 | Spring MVC 예외의 상태→코드 변환이 의미를 잃는다 | +| [02-09](02-inbound-web.md) | Low | P2 | JSON 본문 상한의 두 갈래가 테스트로 묶여 있지 않고, JSON 아닌 본문은 상한이 없다 | +| [01-07](01-core-and-feature-pattern.md) | Low | P3 | 이벤트 식별자 문법이 다섯 곳에 복사되어 있고 길이 상한이 둘로 갈린다 | +| [01-10](01-core-and-feature-pattern.md) | Low | P3 | application-core 한 이름공간에 커널·플랫폼 기능·(파생 시) 업무 기능이 섞인다 | +| [01-11](01-core-and-feature-pattern.md) | Low | P3 | 공용 다이제스트 헬퍼가 있는데 복사본이 남아 있고, 일부 leaf는 registry 때문에 복사가 강제된다 | +| [01-12](01-core-and-feature-pattern.md) | Low | P3 | 이름 규칙의 정본 문서가 없고, 같은 역할에 이름이 여러 가지다 | +| [01-13](01-core-and-feature-pattern.md) | Low | P3 | 참조 예시의 수정 유스케이스에 소유자 검사가 없다는 사실이 코드에 보이지 않는다 | +| [01-14](01-core-and-feature-pattern.md) | Low | P3 | 작은 결함 묶음 (각각 독립, Low / P3) | +| [02-10](02-inbound-web.md) | Low | P3 | `GlobalExceptionHandler`가 두 경로로 등록된다 | +| [02-11](02-inbound-web.md) | Low | P3 | `X-Correlation-Id` 허용 문자·길이가 요청 ID 규칙·짝 계약과 다르다 | +| [02-12](02-inbound-web.md) | Low | P3 | `Idempotency-Key` 헤더 검증이 컨트롤러마다 새로 쓰인다 | +| [03-04](03-inbound-realtime-graphql-grpc.md) | Low | P3 | `GraphQlDataLoaderRequestRegistry`는 도달 불가인데 README가 요청 스코프 장치로 설명한다 | +| [03-05](03-inbound-realtime-graphql-grpc.md) | Low | P3 | batch loader가 플랫폼 context 없이 불리면 `REQUEST_TIMEOUT`으로 나간다 | +| [03-12](03-inbound-realtime-graphql-grpc.md) | Low | P3 | ledger PG lane은 main push·nightly에서만 돌고 PR·릴리스 게이트에 없다 | +| [04-16](04-persistence.md) | Low | P3 | notification·fileserver leaf에 가까운 안내 문서가 없고 패키지가 평평하다 | +| [04-17](04-persistence.md) | Low | P3 | 미리 정한 UUID + primitive `long` version이라 `save()`가 merge로 동작한다 | +| [05-18](05-outbound-capabilities.md) | Low | P3 | 설정 prefix·바인딩 방식이 capability 기준 4와 다르다 | +| [05-19](05-outbound-capabilities.md) | Low | P3 | bootstrap이 알림·파일 서버 권한 이름을 안다 | +| [05-21](05-outbound-capabilities.md) | Low | P3 | identifier leaf: 이름·문서가 내용과 맞지 않는다 | +| [05-22](05-outbound-capabilities.md) | Low | P3 | 파일 서버: finalize가 writer lease 없이 돈다 | +| [05-23](05-outbound-capabilities.md) | Low | P3 | 작은 결함 묶음 (각각 독립, Low / P3) | +| [07-10](07-bootstrap-composition-config.md) | Low | P3 | 설정 오타·죽은 키가 기동에서도 게이트에서도 안 잡히는 곳이 있다 | +| [07-11](07-bootstrap-composition-config.md) | Low | P3 | 주석·문서가 현재 동작과 다르다 (이번에 새로 찾은 것) | +| [07-12](07-bootstrap-composition-config.md) | Low | P3 | virtual thread를 켠 상태에서 `server.tomcat.threads.max`는 동시 처리 상한이 아니다 | +| [07-13](07-bootstrap-composition-config.md) | Low | P3 | 기본 compose가 관리 포트 9001을 모든 인터페이스에 연다 | +| [07-14](07-bootstrap-composition-config.md) | Low | P3 | 프로필 검증기가 main class 이름을 문자열로 비교한다 | +| [08-05](08-build-ci-test.md) | Low | P3 | registry에 없는 leaf 디렉터리는 조용히 빌드에서 빠진다 | +| [08-06](08-build-ci-test.md) | Low | P3 | 병렬·캐시 설정이 빌드와 lane 종류에 따라 다르게 적용된다 | +| [08-07](08-build-ci-test.md) | Low | P3 | SpotBugs·FindSecBugs가 신뢰도 HIGH만 보고한다 | +| [09-05](09-performance-measurement.md) | Low | P3 | 트랜잭션마다 `SHOW TRANSACTION ISOLATION LEVEL` 왕복 1회 | +| [09-08](09-performance-measurement.md) | Low | P3 | 샘플의 런타임 기본값이 기본 조합과 다름 | +| [09-09](09-performance-measurement.md) | Low | P3 | persistence-jpa가 H2 드라이버를 운영 아티팩트에 실어 보냄 | +| [09-10](09-performance-measurement.md) | Low | P3 | `local` 프로필이 `server.port`를 8080으로 고정 | +| [09-11](09-performance-measurement.md) | Low | P3 | 기본 조합 jar에 Jackson 2·3과 kotlin-stdlib가 함께 실림 | + +## 13. 조치 현황 (개선 순서 1~3) + +리뷰 뒤 같은 기준 커밋(`01a8a2a70`)에서 수정했다. 발견마다 수정 에이전트 하나가 별도 worktree에서 실패하는 테스트를 먼저 쓰고(RED) 고친 뒤(GREEN) 패치를 냈다. 오케스트레이터가 패치를 메인 작업 트리에 합쳤다. **커밋하지 않았다**(commit policy `human-only`). 영역 문서는 리뷰 시점 기록이라 고치지 않았다. + +| ID | 상태 | GREEN (에이전트 worktree 실행) | RED (수정 전 실패) | 남은 것·결정 필요 | +|---|---|---|---|---| +| 05-01 | 충족 | application-notification 231 pass, PG BackgroundPass8/WorkerCrash6/Evidence5 pass | anAttemptLeftAsTheFactoryWroteItIsReconciledNotRequeued 등 3건 수정 전 실패 | 남음: WorkerCrashRecoveryContractTest 이름/설명 불일치, 05-10 원인 그대로 | +| 07-02 | 충족 | support68/persistence-jpa503/app-bootstrap329/sample295 pass | aViolatedRuleFailsTheBootBeforeAnyOtherBeanIsCreated, aProdPlaintextDatabaseUrlFailsTheBootBeforeTheDataSourceExists | 남음: 빈이 필요한 검사(SecretSourceValidator 등)는 기존 시점, 실 PG systemTest 미실행 | +| 04-01 | 충족 | persistence-jpa 519 pass, PG transaction IT 4 + jpaPlatformFailure 1 pass | connectionLossDuringCommitIsReportedAsCompletionUnknownNotRetryable, IT(57P01 미분류) | 남음: flush 실패와 COMMIT 실패 미구분(안전한 쪽), 08 접두어 두 곳(04-06), SPI 메서드 commitOutcomeUnknownStates() 추가(기본 구현) | +| 03-01 | 충족 | graphql test 392 + systemTest 29 pass | 단위 15중 11 실패(410 vs 40 등), systemTest 거부 3건 | 결정 필요: 크기 선언 없는 일반 list를 20개로 계산(기존 깊은 쿼리 거부 가능), first·last 둘 다면 큰 쪽 | +| 04-02 | 충족 | PG jpaPlatformContractTest 53 + schemaActivation 8 pass, leaf check 4개, architectureCheck pass | aClaimedJobIsNotHandedToAnotherInstance, twoConcurrentClaimsShareNoJob(40개 전부 겹침) | 결정 필요: 포트 claimDue 시그니처·ReconciliationJob.claimFence 변경(application-notification), lease는 기존 lease-duration 2분 재사용. 새 마이그레이션 V11 | +| 02-03+07-05 | 충족 | web 278, app-bootstrap test 321, verifyEnvKeys OK, sample test·webSystemTest pass | 6건(기동 허용, 첫 값만 비교, 타 client role 합침) | 남음: sample application.yml:196 audience 미사용 설정, env 미설정 시 ${} 문자열 남는지 미확인, app-bootstrap systemTest 미실행. 호환성 깨짐: 기존 배포는 APP_SECURITY_JWT_AUDIENCE 필수 | +| 09-02 | 충족 | sample check(test 295)+systemTest 3+integrationTest 55 pass, 동시성 3회 반복 pass | 16동시 생성에 DB 7행·outbox 7개 | 결정 필요: 마이그레이션 번호 V8_1(V9는 production과 합친 Flyway에서 충돌). 기존 중복 제목 있으면 마이그레이션 중단. 제목 변경 PATCH도 409 | +| 06-01+06-03 | 충족 | application-core 222, outbound:messaging 38, messaging-kafka 84, runtime-core 30, composition·starter·persistence-jpa·testkit, RunbookCoverage, architectureCheck pass | 11건(REJECTED_BEFORE_SEND, DEAD, 10분 장애 20행 DEAD) | 결정 필요: vendored messaging leaf 2곳 수정, 예산 설정 키화 안 함(일시 실패가 예산을 쓰지 않음). 한계: attempt_count가 일시 실패도 셈. 위험: 진짜 인증 오류도 5분 간격 무한 재시도(runbook 기재). PG 통합 미실행 | +| 07-03+09-03 | 충족 | web check 259+13, sample check 298·systemTest 8·webSystemTest 5, app-bootstrap 관련 test 15·IT 9, architectureCheck pass | 실서버+PG 5중 4 실패(익명 DELETE 204, demo-user DELETE 204, POST 500) | 결정 필요: 데모 계정 비밀번호=이름(README 공개), 익명 쓰기 401로 변경(export 포함). 남음: 기동 실패 rule 미구현, 09-04 api-docs 500은 다른 원인, qualityCheck 미실행 | +| 02-01+02-02 | 충족 | shared-contract 260, web 279, architectureCheck, app-bootstrap registry 테스트 19 pass | 7건(키 집합에 error/data/results, retryable false·Retry-After 없음) | 방법: shared-contract는 stdlib-only라 web 어댑터 Jackson mixin으로 null 생략. IN_FLIGHT retryable=true, Retry-After 2초. 남음: gRPC trailer·GraphQL extension retryable도 true로 바뀜(테스트 없음), 프론트 분류기·계약 §4.1/§6 갱신 필요, CORS Retry-After 노출(02-05) | +| 05-07+05-08 | 충족 | application-fileserver 272, composition 33, web-fileserver 142, architectureCheck pass; 05-08 변이(copy·prepare-download descriptor 제거) 새 테스트가 잡음 | 3건(수위 0.90 미거절, 쿼터 예약 없음, 실패 시 반환 없음) | 남음: 쿼터 상한 비교 없음(정책 결정 필요), 대상 namespace 허용 목록 없음, MOVE·READ_METADATA 소유자 테스트 없음 | +| 05-05+05-06 | 충족 | httpclient check(test 293, stableContract 20, security 9, spring62 7), spring70 20, perf 5, deadline 3회 반복 pass | 404×200에 약 100번째부터 breaker 열림, 예산 1초인데 Apache 5.58초 성공·JDK 2.05초 | 결정 필요: profile별 breaker 설정 키 없음. 남음: RETURN_RESULT 정책 5xx는 breaker 성공 기록, Toxiproxy 케이스·streaming·http3 미포함 | +| 05-02+05-03 | 충족 | cache-redis 143 + redis-runtime 49, 실 Redis redisTopologyTest 23 pass | fake 52중 7, 실 Redis 23중 3(renew ALREADY, 작은 revision RECORDED, ONLY_IF_OBSERVED INDETERMINATE) | 새 발견: ONLY_IF_OBSERVED가 application 계정 EVALSHA 권한 없어 실 Redis에서 INDETERMINATE → SCRIPT lane으로 이동해 수정. 결정 필요: revision 순서 규칙(10진 정수)을 포트(application-core)로 옮길지, cache 전용 배포의 script 권한 기동 probe, redis-runtime testFixtures 수정(leaf 경계) | +| 04-03 | 충족 | persistence-jpa 507, jpaPlatformContractTest(PG) 15, sample check, app-bootstrap architectureTest, architectureCheck pass | 빈 조건에서 새 규칙 테스트 4 실패, 운영 패키지 임시 양방향 엔티티로 JpaProductionArchitectureTest 실패 확인 | 결정 필요: @JoinColumn 단방향 @OneToMany 허용(문서엔 예외), sample test 의존성·lockfile 변경. DisplayName은 AGENTS.md(영어) 따름 — 소유자 결정 5(한국어)와 AGENTS.md 불일치는 08 영역 기존 지적 | +| 03-10 | 충족 | core-api 89, runtime 278, ledger-jpa 12, 실 PG integrationTest 30, 동시 재claim 5회 반복 pass | 계약 in-memory 4, PG 5, interceptor 4 실패 | 결정 필요: TTL을 설정 키 대신 interceptor 생성자 인자(starter가 interceptor 미조립 03-11), 넘겨받기는 ledger commit이 mutation과 같은 트랜잭션일 때만 안전(ADR 기재). 남음: COMMITTED 보존 기간 정리 없음 | +| 05-09 | 부분 충족(결정 대기) | objectstorage check 136, architectureCheck pass, 실제 lane 2개는 'pinned image unavailable'로 실패(의도) | 7중 4(원 예외 그대로 등) | 남음: 대체 이미지 소유자 결정 필요, compose minio/mc도 Docker Hub | +| 06-02 | 충족 | outbox-relay check 20, 종료 순서 테스트 3회 반복 pass | relayFinishesItsRunningCycleBeforeThePlatformClosesAdmission(회차 미기록 상태로 platform 정지) | 남음: 남은 claim lease 해제 없음(OutboxStorePort 메서드 필요), 테스트에 platform phase 값 MAX-1024 하드코딩 | +| 07-01 | 충족 | service-runtime 98, shared-contract 260, web 273, app-bootstrap check 321 + systemTest 10, architectureCheck, verifyDependencyLocks, verifyEnvKeys pass | TracingExportSystemTest 로컬 수신기에 아무것도 안 옴→이후 trace id 불일치 | 결정 필요: shared-contract(ActiveTrace)·web 필터까지 범위 확장. 남음: sample 테스트 미실행(합친 뒤 게이트에서), lockfile 재생성 확인 | +| 08-01+08-04+03-12 | 충족 | verifyStrictLaneStages(RED 44건→GREEN), build-logic 87, 14 lane Docker 실행 82 pass, spring70 20, webAdvanced 124, ledger 18, configuration-cache dry-run 5 lifecycle pass | verifyStrictLaneStages 44건 | 남음: integration-check 잡 실행 시간 미측정(timeout 240분), websocketNginx·messagingCertification·mongo lane 로컬 미실행, 다른 workflow '>-' 블록 --stacktrace 결함 22곳(미확인·미수정). 결정 필요: integration 잡 5개 대체, 중복 lane, CLAUDE.md/AGENTS.md에 performanceCheck 추가 | + +### 13.1 합친 뒤 전체 게이트 + +19개 패치를 모두 합친 메인 작업 트리에서 오케스트레이터가 실행했다(프론트 세션과 공유 잠금). + +| 게이트 | 결과 | 시간 | 실행 직전 부하 | +|---|---|---|---| +| `ci` | rc=0 | 397초 | load 22.19 | +| `mainCheck` | rc=1 — `objectStorageMinioContractTest`, `objectStorageMinioFaultTest` 2건만 실패. 둘 다 이제 `PinnedImageUnavailableException: pinned image unavailable: minio/minio@sha256:4c4a48…`(05-09 의도대로). 새로 mainCheck에 들어간 `:sample-portfolio:systemTest` 포함 나머지 통과 | 118초 | load 18.97 | +| `:verifyStrictLaneStages --dry-run` (새 PR 게이트, 08-01) | rc=0 | 45초 | load 8.81 | +| `-p optional-platforms ci` (gRPC 플랫폼) | rc=0 | 71초 | load 8.99 | +| `:integrationCheck` (컨테이너 lane 37개 전부) | rc=1 — MinIO lane 2개만 실패(위와 같은 이유). 나머지 35 lane 통과: JPA 실 PostgreSQL 11 lane, notification·sample·Redis·Mongo·websocket nginx·messaging certification 등. 04-01·04-02·09-02 수정이 실 DB에서 함께 통과 | 794초 | load 23.84 | + +남은 빨강은 05-09 하나(대체 이미지 미정)다. `releaseCheck`, `qualityCheck` 단독, `performanceCheck`, gRPC ledger PG lane(`-p optional-platforms integrationCheck`)은 합친 트리에서 다시 돌리지 않았다(ledger는 03-10 수정 에이전트가 30건 통과 확인). + +### 13.2 결정이 필요한 것 (수정 중 새로 생김) + +| 항목 | 내용 | 권고 | +|---|---|---| +| 03-01 list 기본 크기 | 크기를 선언하지 않은 일반 list를 원소 20개로 계산한다. 이전에 통과하던 깊은 목록 쿼리가 거부될 수 있다 | 유지. 필요한 필드만 `estimatedListSize` 선언 | +| 04-02 포트 변경 | `ReconciliationJobStorePort.claimDue`에 lease 인자, `ReconciliationJob.claimFence` 추가(application-notification) | 유지 | +| 06-01 vendored 수정 | messaging runtime-core·kafka의 retryable 표시를 고쳤다. 예산 설정 키는 만들지 않았다. 진짜 인증 오류도 5분 간격 무한 재시도(runbook 기재) | 유지. 인증 오류 경보 임계는 운영에서 정한다 | +| 07-03 데모 계정 | 샘플이 공개 데모 계정 HTTP Basic을 쓴다(비밀번호=계정 이름, README 공개). 익명 쓰기는 401 | 샘플 한정이라 유지. 운영 복제 금지를 README에 명시됨 | +| 09-02 마이그레이션 번호 | `V8_1`(V9는 운영 마이그레이션과 합친 Flyway에서 충돌) | 유지. 샘플 번호 규칙을 매뉴얼에 적는다 | +| 05-02/03 revision 규칙 | revision은 10진 정수만. 규칙을 포트(application-core)로 옮길지, cache 전용 배포의 script 권한 기동 확인 | 포트로 옮긴다(후속) | +| 05-05 breaker 설정 키 | client별 breaker 설정 키 없음 | 후속 | +| 05-07 쿼터 상한 | 쿼터는 기록만 하고 상한 비교 없음 | 정책 결정 필요 | +| 03-10 TTL | 설정 키 대신 interceptor 생성자 인자(starter가 아직 조립 안 함, 03-11) | 03-11과 함께 | +| 07-01 범위 | trace id를 맞추려고 shared-contract(`ActiveTrace`)·web 필터까지 바꿈 | 유지 | +| 08-01 단계 | integration 잡 5개를 `:integrationCheck` 하나로, `performanceCheck` 신설. 루트 `CLAUDE.md`/`AGENTS.md` 단계 목록 미반영 | 유지하고 문서 반영 | +| 04-03 DisplayName | 에이전트가 AGENTS.md(영어)를 따름. 소유자 결정 5(한국어)와 AGENTS.md 불일치(08 영역 기존 지적) | AGENTS.md를 소유자 결정에 맞춘다 | +| 05-09 MinIO 대체 이미지 | 여전히 미정. lane 2개는 구분된 메시지로 실패 | 소유자 결정 | + diff --git a/docs/runbooks/auth-audience-mismatch.md b/docs/runbooks/auth-audience-mismatch.md index 3f079076..5677e363 100644 --- a/docs/runbooks/auth-audience-mismatch.md +++ b/docs/runbooks/auth-audience-mismatch.md @@ -18,7 +18,8 @@ status: stub ## Diagnosis - Check token `aud` claim value -- Compare against configured `spring.security.oauth2.resourceserver.jwt.audiences` +- Compare against configured `app.security.audience` (`APP_SECURITY_JWT_AUDIENCE`, comma-separated; + the token must name at least one) ## Action diff --git a/docs/runbooks/grpc-platform-operations.md b/docs/runbooks/grpc-platform-operations.md index 07d0639d..d218f26e 100644 --- a/docs/runbooks/grpc-platform-operations.md +++ b/docs/runbooks/grpc-platform-operations.md @@ -38,8 +38,17 @@ the time, and which half is not knowable from the status. 6. If the method is not keyed, there is no ledger row. Resolve it against the business resource, or escalate to the service owner. This is the case the keyed profile exists to avoid. +7. `IN_PROGRESS` means a claim exists and has not finished. If its owner died, the claim is not + stuck forever: once it is older than the claim TTL (the `claimTtl` given to + `GrpcIdempotencyInterceptor`), the next retry of the same request takes it over and runs again, + and a later reconciler pass sees that attempt's `COMMITTED` or `FAILED_TERMINAL`. Until a retry + arrives, the case stays pending. The re-run is safe only when the ledger commit is recorded in the + mutation's own transaction; if this service commits them separately, check the business resource + before letting the retry through. + **Escalate when** the reconciler's pending list grows across passes. That means the ledger is -unreachable rather than slow. +unreachable rather than slow. A case pending as `IN_PROGRESS` for longer than the claim TTL with no +retry arriving is a caller that gave up; it needs the business resource checked, not a ledger fix. --- diff --git a/docs/runbooks/outbox-dead-letter.md b/docs/runbooks/outbox-dead-letter.md index 5b137700..44dbaecd 100644 --- a/docs/runbooks/outbox-dead-letter.md +++ b/docs/runbooks/outbox-dead-letter.md @@ -23,11 +23,12 @@ status: stub ### Step 1 — 확인 1. ERROR log에서 `OUTBOX_DEAD_LETTER` 라인 확인: `event_id`, `event_type`, `correlation_id`, 마지막 실패 원인 예외 추출 2. DB에서 DEAD row 확인: `SELECT * FROM outbox_event WHERE status = 'DEAD' ORDER BY occurred_at;` -3. **차단 영향 파악 (중요)**: strict per-aggregate FIFO 정책상 DEAD row는 같은 `aggregate_id`의 후행 이벤트를 계속 차단함 — - `SELECT count(*) FROM outbox_event b WHERE b.status <> 'PUBLISHED' AND EXISTS (SELECT 1 FROM outbox_event d WHERE d.status='DEAD' AND d.aggregate_id=b.aggregate_id AND d.occurred_at < b.occurred_at);` +3. **차단 영향 파악 (중요)**: strict per-aggregate FIFO 정책상 DEAD row는 같은 aggregate(`tenant_scope`, `aggregate_type`, `aggregate_id`)의 후행 이벤트를 계속 차단함. 순서는 `(aggregate_sequence, event_index)`로 비교한다(claim SQL `PostgreSqlOutboxClaimRepository`와 같은 키) — + `SELECT count(*) FROM outbox_event b WHERE b.status <> 'PUBLISHED' AND EXISTS (SELECT 1 FROM outbox_event d WHERE d.status='DEAD' AND d.tenant_scope=b.tenant_scope AND d.aggregate_type=b.aggregate_type AND d.aggregate_id=b.aggregate_id AND (d.aggregate_sequence < b.aggregate_sequence OR (d.aggregate_sequence = b.aggregate_sequence AND d.event_index < b.event_index)));` ### Step 2 — 임시 격리 -- DEAD는 max attempts(3) 소진의 최종 상태 — 자동 재시도 없음, 수동 개입 필수 +- DEAD는 확정 거부(`REJECTED_BEFORE_SEND`·`REJECTED_AFTER_BROKER`) 또는 분류되지 않은 발행 예외의 max attempts(3) 소진의 최종 상태 — 자동 재시도 없음, 수동 개입 필수 +- broker 정지·종료 중 거부·Kafka 인증/인가 실패는 DEAD가 되지 않는다(FAILED로 계속 재시도). 이것들로 DEAD가 보이면 이 변경 이전에 생긴 행이다 - 차단된 aggregate가 비즈니스 크리티컬하면 아래 §4의 수동 처분(재발행 또는 skip)을 우선 수행 ## 3. Diagnosis @@ -35,7 +36,7 @@ status: stub - log query: `{service="app"} | error.code="OUTBOX_DEAD_LETTER" | stats count by event_type` - 마지막 실패 원인 분류: - poison event (payload 직렬화/계약 위반) → payload 자체 결함, 재발행해도 실패 — 수정 후 재발행 또는 skip - - broker 장기 outage 중 attempts 소진 → broker 회복 후 재발행으로 해결 가능 + - broker 장기 outage 중 attempts 소진 → 현재 relay에서는 일어나지 않는다(일시적 실패는 예산을 쓰지 않음). 이전 버전에서 생긴 행은 broker 회복 후 재발행으로 해결 가능 - 구성 오류 (Kafka disabled 상태에서 producer 활성) → 구성 수정 후 재발행 - 가능한 원인 우선순위: 구성 오류 > broker outage > poison payload @@ -43,6 +44,8 @@ status: stub - **재발행 (기본)**: 원인 해소 후 해당 row를 다시 claim 가능 상태로 되돌림 — `UPDATE outbox_event SET status = 'PENDING', attempt_count = 0, next_attempt_at = now() WHERE event_id = '' AND status = 'DEAD';` + 장애 구간 전체를 한 번에 되돌리려면(원인이 해소된 것을 확인한 뒤): + `UPDATE outbox_event SET status = 'PENDING', attempt_count = 0, next_attempt_at = now() WHERE status = 'DEAD' AND occurred_at BETWEEN '<장애 시작>' AND '<장애 끝>';` (outbox_event에는 DEAD가 된 시각 컬럼이 없어 이벤트 발생 시각으로 고른다 — 먼저 같은 조건의 SELECT로 대상을 확인한다) (consumer는 at-least-once + idempotencyKey dedupe 의무가 있으므로 중복 발행은 안전) - **skip (영구 폐기)**: 이벤트가 더 이상 유효하지 않으면 PUBLISHED로 마킹해 FIFO 차단을 해제 — `UPDATE outbox_event SET status = 'PUBLISHED' WHERE event_id = '' AND status = 'DEAD';` diff --git a/docs/runbooks/outbox-publish-failed.md b/docs/runbooks/outbox-publish-failed.md index e2ea1957..5d35c179 100644 --- a/docs/runbooks/outbox-publish-failed.md +++ b/docs/runbooks/outbox-publish-failed.md @@ -40,8 +40,9 @@ status: stub 3. `outbox.pending.size` status 분포 확인 (FAILED 누적 vs PENDING 누적) ### Step 2 — 임시 격리 -- 일시 실패는 자동 backoff 재시도(30s × 2^(attempt-1) + jitter, max attempts 3)가 동작 — 즉시 수동 개입 불필요 -- broker 장기 다운이면 DEAD 전이 누적 전에 broker 회복을 우선 (max attempts 소진 시 `runbook://outbox/dead-letter`로 이관) +- 일시 실패는 자동 backoff 재시도(30s × 2^(attempt-1) + jitter, 상한 5분)가 동작 — 즉시 수동 개입 불필요 +- broker 정지·종료 중 거부·Kafka 인증/인가 실패(`AMBIGUOUS`, `REJECTED_RETRYABLE`)는 시도 예산을 쓰지 않는다 — 장애가 길어도 DEAD가 되지 않고, broker가 돌아오면 늦어도 약 5분 30초 안에 자동 재발행된다 +- max attempts 3은 adapter가 분류하지 못하고 던진 발행 예외에만 적용된다 (소진 시 `runbook://outbox/dead-letter`로 이관) - relay 자체를 멈춰야 하면 `app.outbox.relay-enabled=false`로 스케줄러 비활성 (이벤트는 outbox 테이블에 안전하게 보존됨 — 유실 없음) ## 3. Diagnosis @@ -55,7 +56,8 @@ status: stub - 가능한 원인: - broker outage/네트워크 → broker 측 회복 대기 - Kafka adapter 미구성(enabled인데 brokers 누락은 기동 시 차단됨) / disabled 상태에서 producer 활성화 - - poison event (직렬화 불가/payload 계약 위반) → 재시도 무의미, attempts 소진 후 DEAD로 흘러감 (의도된 동작) + - poison event (직렬화 불가/payload 계약 위반) → 확정 거부(`REJECTED_*`)면 바로, 분류되지 않은 예외면 attempts 소진 후 DEAD로 흘러감 (의도된 동작) + - 같은 행의 `OUTBOX_PUBLISH_FAILED`가 5분 간격으로 끝없이 반복되고 원인이 Kafka 인증/인가면 credential·ACL이 실제로 틀린 것이다 — 고치면 다음 재시도에서 저절로 빠진다 - 동일 aggregate head 실패로 후행 이벤트가 FIFO 게이트에 차단되어 lag 증가 (strict per-aggregate FIFO — 설계 의도) ## 4. Mitigation diff --git a/docs/study/graphql-walkthrough.ko.md b/docs/study/graphql-walkthrough.ko.md index 069478a1..b8b7f532 100644 --- a/docs/study/graphql-walkthrough.ko.md +++ b/docs/study/graphql-walkthrough.ko.md @@ -1136,12 +1136,19 @@ GQL-007이 *"named fragment가 custom introspection gate를 우회하고 variabl > *Guessing it from the operation root would price `order { customer { orders { … } } }` as three > root fields and miss the multiplication entirely.* -**(2) 카디널리티는 스키마가 아니라 요청에서 온다.** +**(2) 목록을 돌려주는 필드는 클라이언트가 어떻게 물어도 원소 수만큼 곱한다.** page 필드(스키마에 +`first`/`last` 가 있거나 catalog 에 connection 으로 등록)는 리터럴 → 요청 변수 → 연산의 변수 +기본값 → 스키마 인자 기본값 순서로 page 를 찾고, 없으면 기본 page 크기로 곱한다. 찾은 값은 전부 +상한으로 검사한다. page 인자가 없는 일반 list 는 catalog 에 선언한 추정 크기(없으면 기본 page +크기)로 차원마다 곱한다. connection 객체 바로 안의 `edges`·`nodes` 는 이미 곱한 page 라서 다시 +곱하지 않는다. -> *a connection's children are multiplied by the effective page size, and a page size supplied -> through a variable is resolved from the request variables rather than assumed to be the default. -> That is the difference between a budget and a suggestion — `first: $n` would otherwise cost the -> same at 1 and at 1000.* +> *Pricing an omitted argument as one row was the bypass: `items(first: 20)` scored 410 while +> `items` scored 40, and four nested lists added up instead of multiplying.* + +2026-11-01 리뷰 03-01 이 이 구멍을 찾았다. 그 전 javadoc 은 "변수로 준 page 를 요청 변수에서 +읽는다"까지만 말했고, 변수 기본값과 생략한 인자, 일반 list 는 1 로 계산됐다. 상세는 +`src/adapter/inbound/graphql/README.md` 의 「목록을 돌려주는 필드는…」 절. **(3) 순회 자체가 유한하다.** 기본 `maximumVisitedNodes = 200_000`, fragment cycle은 확장 경로 추적으로 끊는다. javadoc이 왜 검증된 문서에도 경계를 유지하는지 쓴다 — 이 scorer는 pre-execution diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md new file mode 100644 index 00000000..911f7f51 --- /dev/null +++ b/docs/web/http-contract.md @@ -0,0 +1,98 @@ +# HTTP wire 계약 + +이 백엔드의 HTTP 응답을 읽는 클라이언트(짝 프론트, 파생 서비스의 다른 앱)가 기대해도 되는 것을 한 +곳에 적는다. 응답 모양과 멱등성 응답의 뜻은 이 문서가 정본이다. 다른 문서(web README 예외 표, +`docs/web/runbook.md`, `docs/registries/error-codes.yaml` 주석)는 이 문서를 가리키고 같은 문장을 쓴다. + +코드가 이 문서를 지키는지는 다음 테스트가 확인한다. + +- 응답 원문의 키 집합: `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java` +- 멱등성 응답의 status·code·retryable·`Retry-After`: `IdempotencyExceptionMappingTest`, + `RetryAfterAdvisorTest`, `OperationalErrorTest` + +## 1. Envelope 키 존재 규칙 + +JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). **값이 `null`인 필드는 키째 생략한다.** +빈 목록(`[]`)은 `null`이 아니므로 생략하지 않는다. + +| 응답 | 최상위 키 | 없는 키 | +| --- | --- | --- | +| 성공 | `success`(=`true`), `data`, `meta` | `error` | +| 실패 | `success`(=`false`), `error`, `meta` | `data` | +| bulk 전체 성공 | `success`(=`true`), `results`, `meta` | `error` | +| bulk 부분 실패 | `success`(=`false`), `error`(`code=BATCH_PARTIAL_FAILURE`, `details`=항목별 결과), `meta` | `results` | + +- `success`가 판별자다. 클라이언트는 `success`로 갈라 읽고, 키가 있는지로 판단하지 않는다. +- 성공인데 `data`가 `null`이면 `data` 키도 없다. 본문이 아예 없는 응답(204)은 Envelope가 아니다. +- 빈 컬렉션 결과는 `"data": []`, 빈 bulk 결과는 `"results": []`, 항목 없는 부분 실패는 + `"details": []`로 나간다. + +### `error` 키 + +| 키 | 항상 있음 | 뜻 | +| --- | --- | --- | +| `code` | 예 | 안정된 기계용 식별자. 클라이언트는 이것으로 분기한다 | +| `category` | 예 | `Category` enum 이름(`VALIDATION`, `CONFLICT` …) | +| `message` | 예 | 사용자에게 보여도 되는 한국어 문구(`ClientErrorMessages`). 분기에 쓰지 않는다 | +| `retryable` | 예 | 같은 요청을 다시 보내도 안전하고 의미가 있는지 | +| `details` | 아니오 | 코드별 구조 정보(검증 실패 필드 목록, bulk 항목 결과). 없으면 키도 없다 | + +### `meta` 키 + +| 키 | 언제 있나 | +| --- | --- | +| `requestId` | 요청 id 필터(`WebMvcRequestIdFilter`)를 지난 모든 응답 | +| `traceId` | 위와 같음. 추적이 꺼져 있어도 필터가 만든 W3C trace id가 들어간다 | +| `correlationId` | 위와 같음. 값이 없으면 키가 없다 | +| `page` | 페이지 목록 응답에만. `number`·`size`·`total`·`sort`(미정렬이면 `sort: null`) | + +필터 앞에서 끊긴 응답(필터 체인 밖의 오류)은 id 키가 빠질 수 있다. 클라이언트는 `meta`의 모르는 +키를 무시한다. + +### 왜 이렇게 나가는가 + +`Envelope`·`BulkEnvelope`·`ApiError`·`ResponseMeta`는 `shared-contract`에 있고, 이 leaf는 Java +표준 라이브러리 외에는 의존하지 않는다. 그래서 `@JsonInclude`를 타입에 붙이지 않고, web 어댑터의 +`EnvelopeWireFormatConfig`가 Jackson mix-in으로 같은 규칙을 Boot의 `JsonMapper`에 등록한다. 이 +어댑터의 모든 HTTP writer(MVC 변환기, 보안 entry point, rate-limit interceptor)가 그 `JsonMapper`를 +쓴다. GraphQL·STOMP·gRPC는 이 타입들을 직렬화하지 않으므로 이 규칙의 영향을 받지 않는다. + +## 2. 멱등성 응답 + +`Idempotency-Key`를 받는 쓰기 엔드포인트(KEYED)는 `IdempotencyExecutor`를 거친다. 같은 키로 다시 +보낸 요청은 서버가 아래 넷 중 하나로 판정한다. 키는 인증 주체와 operation 범위 안에서만 같은 키다. + +| 경우 | status | `error.code` | `retryable` | `Retry-After` | 클라이언트 행동 | +| --- | --- | --- | --- | --- | --- | +| 재생(replay): 같은 키·같은 본문, 첫 요청 완료 | 첫 요청과 같은 성공 status | — (성공 Envelope) | — | 없음 | 첫 요청의 결과로 받아들인다. `meta`의 id는 이번 요청의 것이다 | +| 처리 중(in-flight): 같은 키, 첫 요청이 아직 실행 중 | 409 | `IDEMPOTENT_IN_FLIGHT` | `true` | `2` | 결과 불명. **같은 `Idempotency-Key`로** `Retry-After` 뒤 재전송한다. **새 키 금지** | +| 본문 불일치(mismatch): 같은 키·다른 본문 | 422 | `IDEMPOTENT_REQUEST_MISMATCH` | `false` | 없음 | 클라이언트 버그. 다시 보내지 않는다. 새 작업이면 새 키를 만든다 | +| 키 누락·형식 오류 | 400 | `BAD_PARAMETER` | `false` | 없음 | 키를 붙여 다시 보낸다 | + +- **처리 중을 `retryable=true`로 두는 이유.** 같은 키 재전송은 서버가 재생·처리 중·불일치로 안전하게 + 판정하므로, 다시 보내는 것이 맞는 행동이다. 새 키로 보내면 서버는 다른 요청으로 보고 막지 못해, + 첫 요청이 끝나면 같은 작업이 두 번 적용된다. +- **`Retry-After: 2`의 근거.** 기본 processing lease(`app.capabilities.idempotency.processing-lease`, + 30s)보다 짧아, 첫 시도가 아직 끝날 수 있는 동안 다시 묻는다. 너무 이르면 409를 한 번 더 받을 뿐이고 + 결과가 바뀌지는 않는다. lease를 2초보다 짧게 설정한 서비스는 이 값이 lease를 넘으므로 값을 다시 + 정한다(`RetryAfterAdvisor`, `docs/registries/error-codes.yaml`). +- executor는 기다리지 않는다. 처리 중이면 바로 409를 돌려준다. 키로 결과를 조회하는 엔드포인트는 없다. +- 키 누락 처리는 엔드포인트가 정한다(공용 검증 부품 없음, 리뷰 02-12). 템플릿 예시 + (`PosterImagePublicationController`)는 헤더가 없으면 `MissingRequestHeaderException`, 비었거나 + 256자를 넘으면 `IllegalArgumentException`으로 둘 다 400 `BAD_PARAMETER`다. 키를 요구하지 않는 + 엔드포인트는 키 없이 보호 없이 실행된다. + +같은 executor가 내는 나머지 두 실패: + +| 경우 | status | `error.code` | `retryable` | `Retry-After` | 클라이언트 행동 | +| --- | --- | --- | --- | --- | --- | +| 멱등성 저장소 응답 없음 | 503 | `IDEMPOTENCY_UNAVAILABLE` | `true` | 없음 | 작업 실행 전에 거부됐다. 같은 키로 나중에 다시 보낸다 | +| 이전 시도의 효과를 증명할 수 없음 | 500 | `IDEMPOTENCY_RECOVERY_REQUIRED` | `false` | 없음 | 재전송도 재실행도 안전하지 않다. 업무 데이터로 결과를 확인한다 | + +## 3. 바꿀 때 + +- 응답 키를 더하거나 빼면 `EnvelopeWireShapeTest`와 이 문서 1절을 같이 고친다. +- 멱등성 코드의 status·retryable·`Retry-After`를 바꾸면 `OperationalError`, `RetryAfterAdvisor`, + `docs/registries/error-codes.yaml`, 이 문서 2절을 같은 변경에서 고친다. +- 짝 프론트의 백엔드 계약 문서(`clean-architecture-frontend-template` + `docs/architecture/backend-api-and-server-state-contract.md` §4.1·§6)는 이 문서를 가리켜야 한다. diff --git a/docs/web/runbook.md b/docs/web/runbook.md index ee77c76f..a2f1389e 100644 --- a/docs/web/runbook.md +++ b/docs/web/runbook.md @@ -38,8 +38,10 @@ The idempotency key is the control, and there are exactly three ways it fails to 3. **The record expired.** TTL is per-operation with a 72h cap. A retry after expiry is a new request by definition. -A `409 IDEMPOTENT_IN_FLIGHT` is not a failure: an earlier attempt is still running and -the caller should retry after `Retry-After`. +A `409 IDEMPOTENT_IN_FLIGHT` (retryable=true, `Retry-After: 2`) is not a failure: an earlier +attempt is still running and its result is unknown. The caller resends with the **same** +`Idempotency-Key` after `Retry-After`; a new key is a new request and is how a write ends up +applied twice. The four idempotency answers are in `http-contract.md` §2. ## Rolling deploy stalls with instances half-drained diff --git a/src/README.md b/src/README.md index c0e0a6d2..5e77ea3c 100644 --- a/src/README.md +++ b/src/README.md @@ -27,8 +27,10 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 | `configContractCheck` | `:app-bootstrap:verifyEnvKeys`로 환경 설정 계약을 검사 | | `qualificationCheck` | 전체 기동(system) 레인과 보조 source set Checkstyle을 실행 | | `integrationCheck` | 선언된 strict integration lane(sample 포함)을 실행. 대부분 container runtime이 필요. 입력이 필요한 lane(Redis topology: `-Predis.topology.mode`, AWS: 보호 자격 증명 env)은 입력이 없으면 빠지고 집계가 그 이유를 출력 | +| `performanceCheck` | 선언된 strict performance lane(부하·종료·pool·자원 상한)을 실행. 실서버·container가 필요. `integration-main.yml` `performance-check`가 main·nightly에 돌림 | +| `verifyStrictLaneStages` | `--dry-run` 전용. `explicitOnly`가 아닌 strict lane이 workflow가 실제 실행하는 단계(`ci`·`:sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나의 계획에 있는지, 각 단계를 workflow가 `--dry-run` 없이 실행하는지 검사. PR 게이트가 돌림 | | `ci` | PR 게이트: 모든 leaf `check`(API surface 검사 포함, 소유자 결정 20) + `architectureCheck` + `qualityCheck` | -| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) | +| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + sample 전체 기동(`:sample-portfolio:systemTest`) + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) | | `releaseCheck` | tag 전용 검사: `verifyReleaseProvenance` + `verifyPublicPathSnapshot`(`ci`를 다시 돌리지 않음) | 따라서 로컬에서 한 모듈만 수정했다면 `./gradlew :domain-core:check`처럼 focused task를 @@ -489,7 +491,9 @@ Boot 기본값이 바뀌어도 wire 계약이 조용히 깨지지 않게 합니 - **`APP_SECURITY_JWT_ISSUER`** — OIDC issuer URI(Keycloak realm, Auth0 tenant 등). **필수** — 없으면 기동 실패. 예: `https://keycloak.example.com/realms/ca-skeleton`. -- **`APP_SECURITY_JWT_AUDIENCE`** — 기대하는 `aud` claim. 빈 값으로 두면 audience 검증을 건너뜁니다. +- **`APP_SECURITY_JWT_AUDIENCE`** — 기대하는 `aud` claim(쉼표 목록 가능, 하나라도 맞으면 통과). + JWT 모드에서 **필수** — 비어 있으면 기동 실패. 이 목록의 client 에 대한 `resource_access` role 만 + 권한으로 읽습니다. 예: `ca-skeleton-api`. - **`SECURITY_PUBLIC_PATHS`** — 인증을 우회하는 경로 CSV. `api-base-path` 뒤의 full path 를 씁니다(예: `/api/healthcheck`). 이 값의 변경은 `verifyPublicPathSnapshot` 게이트가 감시합니다(위 build.gradle 설명 참조). diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index b2e7b637..cd779ce7 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -188,6 +188,41 @@ data 다. GraphQL over HTTP 초안의 status 294 는 쓰지 않는다. 이 leaf 모델(`GraphQlHttpStatusMapper`, `GraphQlHttpProfile` 등)은 요청 경로에 없어서 2026-09-25 에 삭제했다(`docs/capability-status.md` 제거 표). +## 목록을 돌려주는 필드는 클라이언트가 어떻게 물어도 원소 수만큼 곱한다 + +복잡도 점수(`cost/GraphQlDocumentComplexityScorer`)는 실행 전에 매긴다. 목록 필드의 하위 비용에 +곱하는 수는 이렇게 정한다. + +| 필드 | 곱하는 수 | +| --- | --- | +| page 필드 — 스키마에 `first`/`last` 인자가 있거나 catalog 에 `connection=true` 로 등록 | 리터럴 → 요청 변수 → 연산의 변수 기본값 → 스키마 인자 기본값 순서로 찾은 page. 없으면 기본 page 크기(`defaultPageSize`). 찾은 값은 모두 `maximum-page-size` 로 검사하고, `first`·`last` 를 둘 다 주면 큰 쪽 | +| page 인자가 없는 일반 list | catalog 의 `GraphQlFieldCostDescriptor.estimatedListSize`, 선언이 없으면 기본 page 크기. `[[T]]` 는 차원마다 한 번 | +| page 필드가 돌려준 connection 객체 바로 안의 list(`edges`·`nodes`) | 곱하지 않는다. connection 이 이미 page 만큼 곱했다 | + +2026-11-01 리뷰(03-01) 전에는 인자가 값으로 보일 때만 곱했다. `items(first: 20)` 은 410 점, +`items` 는 40 점, list 4단 중첩은 100 점이었고 `query($n: Int = 100000)` 은 상한 검사 없이 +통과했다. 예산(기본 10,000)과 page 상한(기본 100)이 목록 필드가 생기는 순간 꺼져 있었다. + +**도입하는 서비스에 미치는 영향.** 크기를 선언하지 않은 일반 list 는 이제 원소 20 개로 계산된다. +작은 고정 목록(예: 태그 몇 개)이 예산을 많이 먹으면 `GraphQlCostCatalog` 빈에 +`new GraphQlFieldCostDescriptor("Item.tags", base, weight, false, 5)` 처럼 추정 크기를 선언한다. +점수가 커지는 쪽으로만 바뀌므로, 이전에 통과하던 깊은 목록 쿼리가 `GRAPHQL_COMPLEXITY_EXCEEDED` 로 +거부될 수 있다. + +**고른 방법과 버린 대안.** + +- 변수 기본값은 연산 문서의 `VariableDefinition` 기본값을 직접 읽는다. graphql-java 의 + `ValuesResolver.coerceVariableValues` 로 강제 변환한 값을 쓰는 방법은 버렸다. 그 호출은 잘못된 + 변수에서 예외를 던지므로, 지금 실행 단계가 내는 변수 오류가 비용 단계에서 다른 모양으로 나오게 + 된다. page 크기에 필요한 것은 Int 하나라서 직접 읽는 쪽이 오류 계약을 건드리지 않는다. +- 일반 list 의 크기는 스키마 지시어(`@listSize` 등)가 아니라 기존 cost catalog 에 선언한다. 비용 + 정책이 이미 catalog 한 곳에 있고, 지시어는 스키마 파일과 SDL 처리 경로를 하나 더 만든다. +- graphql-java 기본 `MaxQueryComplexityInstrumentation` 은 쓰지 않는다. 그것도 list 배수를 모르는 + 필드 개수 합이라 같은 구멍이 남고, 점수가 두 벌이 된다. +- 점수가 `long` 을 넘으면 `Long.MAX_VALUE` 에서 멈춘다(포화 산술). 목록마다 곱하면 적대적인 문서 + 몇 단으로 `long` 끝에 닿는데, 그때 `ArithmeticException` 이 내부 오류로 새지 않고 예산 초과로 + 거부되게 하기 위해서다. + ## 요청 단위 DB 트랜잭션을 열지 않는다 GraphQL 한 요청은 여러 root field 를 담을 수 있고, 각 root 는 자기 use case 를 호출한다. diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlComplexityCalculator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlComplexityCalculator.java index 26863611..90aae3a8 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlComplexityCalculator.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlComplexityCalculator.java @@ -23,7 +23,8 @@ public final class GraphQlComplexityCalculator { * Creates the calculator. * * @param catalog registered field costs - * @param defaultPageSize page size assumed when a connection omits {@code first}/{@code last} + * @param defaultPageSize page size assumed when a connection omits {@code first}/{@code last}, + * and the element count of a list whose size was never declared * @param maximumPageSize largest page size a client may request */ public GraphQlComplexityCalculator( @@ -39,24 +40,63 @@ public final class GraphQlComplexityCalculator { /** * Cost of a connection field. * + *

Both page arguments are checked against the maximum, and the larger one is the multiplier: + * which of the two a resolver honours is its business, and pricing the smaller one would let + * {@code first: 1, last: 100000} through on the strength of the argument it ignores. + * * @param coordinate schema coordinate of the connection field * @param first requested forward page size, or {@code null} * @param last requested backward page size, or {@code null} * @param childCost cost of one child subtree - * @throws GraphQlComplexityRejectedException when the requested page exceeds the maximum + * @throws GraphQlComplexityRejectedException when a requested page exceeds the maximum */ public GraphQlComplexityResult connectionCost( String coordinate, Integer first, Integer last, long childCost) { - int requested = first != null ? first : last != null ? last : defaultPageSize; - if (requested > maximumPageSize) { - throw new GraphQlComplexityRejectedException("page size exceeds maximum"); - } - if (requested < 1) { - throw new GraphQlComplexityRejectedException("page size must be positive"); - } + requireAllowedPage(first); + requireAllowedPage(last); + int requested = + first != null && last != null + ? Math.max(first, last) + : first != null ? first : last != null ? last : defaultPageSize; long root = catalog.require(coordinate).baseCost(); - return new GraphQlComplexityResult( - Math.addExact(root, Math.multiplyExact((long) requested, childCost))); + return new GraphQlComplexityResult(saturatedAdd(root, saturatedMultiply(requested, childCost))); + } + + /** + * Cost of a list-returning field that takes no page arguments. + * + *

A plain list is not one child, it is as many children as it holds. The registered {@link + * GraphQlFieldCostDescriptor#estimatedListSize()} is that count when the adopter declared one; + * otherwise the default page size stands in for it, because a list nobody sized is exactly the + * one whose size nobody bounded. A list of lists multiplies once per dimension. + * + * @param coordinate schema coordinate + * @param dimensions how many list wrappers the field type has, at least one + * @param childCost cost of one element's subtree + */ + public GraphQlComplexityResult listCost(String coordinate, int dimensions, long childCost) { + if (dimensions < 1) { + throw new IllegalArgumentException("a list field has at least one dimension"); + } + GraphQlFieldCostDescriptor descriptor = catalog.require(coordinate); + int size = + descriptor.estimatedListSize() == GraphQlFieldCostDescriptor.UNDECLARED_LIST_SIZE + ? defaultPageSize + : descriptor.estimatedListSize(); + long elements = childCost; + for (int dimension = 0; dimension < dimensions; dimension++) { + elements = saturatedMultiply(size, elements); + } + return new GraphQlComplexityResult(saturatedAdd(descriptor.weightedCost(), elements)); + } + + /** + * Whether a coordinate is registered as a paginated connection. + * + *

Such a field is priced at the default page even when its schema declares no page argument. + */ + public boolean connection(String coordinate) { + return catalog.require(coordinate).connection(); } /** @@ -67,7 +107,7 @@ public final class GraphQlComplexityCalculator { */ public GraphQlComplexityResult fieldCost(String coordinate, long childCost) { GraphQlFieldCostDescriptor descriptor = catalog.require(coordinate); - return new GraphQlComplexityResult(Math.addExact(descriptor.weightedCost(), childCost)); + return new GraphQlComplexityResult(saturatedAdd(descriptor.weightedCost(), childCost)); } /** @@ -85,4 +125,36 @@ public final class GraphQlComplexityCalculator { public int effectivePageSize(Integer first, Integer last) { return first != null ? first : last != null ? last : defaultPageSize; } + + private void requireAllowedPage(Integer requested) { + if (requested == null) { + return; + } + if (requested > maximumPageSize) { + throw new GraphQlComplexityRejectedException("page size exceeds maximum"); + } + if (requested < 1) { + throw new GraphQlComplexityRejectedException("page size must be positive"); + } + } + + /** + * Addition that stops at {@link Long#MAX_VALUE}. + * + *

Scores multiply with every nested list, so a few levels of a hostile document reach the end + * of {@code long}. Overflow must read as "over any budget", not as an arithmetic error that + * escapes the rejection path as an internal failure. + */ + static long saturatedAdd(long left, long right) { + long sum = left + right; + return ((left ^ sum) & (right ^ sum)) < 0 ? Long.MAX_VALUE : sum; + } + + /** Multiplication of non-negative values that stops at {@link Long#MAX_VALUE}. */ + static long saturatedMultiply(long left, long right) { + if (left == 0 || right == 0) { + return 0; + } + return left > Long.MAX_VALUE / right ? Long.MAX_VALUE : left * right; + } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorer.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorer.java index 1bcafac9..b67d7366 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorer.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorer.java @@ -12,7 +12,9 @@ import graphql.language.OperationDefinition; import graphql.language.Selection; import graphql.language.SelectionSet; import graphql.language.Value; +import graphql.language.VariableDefinition; import graphql.language.VariableReference; +import graphql.schema.GraphQLArgument; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLFieldsContainer; import graphql.schema.GraphQLList; @@ -20,6 +22,8 @@ import graphql.schema.GraphQLNonNull; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; import graphql.schema.GraphQLType; +import graphql.schema.InputValueWithState; +import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.Deque; @@ -36,10 +40,24 @@ import java.util.Objects; * against the schema. Guessing it from the operation root would price {@code order { customer { * orders { … } } }} as three root fields and miss the multiplication entirely. * - *

Cardinality comes from the request, not from the schema: a connection's children are - * multiplied by the effective page size, and a page size supplied through a variable is resolved - * from the request variables rather than assumed to be the default. That is the difference between - * a budget and a suggestion — {@code first: $n} would otherwise cost the same at 1 and at 1000. + *

Every field that returns many things multiplies its children, however the client phrased the + * request: + * + *

    + *
  • A paginated field — one whose schema declares {@code first}/{@code last}, or one registered + * as a connection — multiplies by the page it will be asked for. That page is the literal, or + * the request variable, or the operation's variable default, or the schema argument default, + * in that order; when none applies it is the default page size, never one. Each of these is + * checked against the maximum page size, so {@code ($n: Int = 100000)} is refused exactly as + * the literal would be. + *
  • A list-returning field without page arguments multiplies by its registered estimated size, + * or the default page size, once per list dimension. + *
  • The list fields directly inside a paginated object (a Relay connection's {@code edges} or + * {@code nodes}) are the page the connection already paid for, and are not multiplied again. + *
+ * + *

Pricing an omitted argument as one row was the bypass: {@code items(first: 20)} scored 410 + * while {@code items} scored 40, and four nested lists added up instead of multiplying. * *

Traversal is bounded, and fragment cycles are cut by tracking the expansion path. This runs on * documents that have passed validation, but the bound stays because the scorer is also used from @@ -50,6 +68,9 @@ public final class GraphQlDocumentComplexityScorer { /** Prefix that marks an introspection field, which is gated rather than priced. */ public static final String INTROSPECTION_FIELD_PREFIX = "__"; + private static final String FIRST = "first"; + private static final String LAST = "last"; + private final GraphQlComplexityCalculator calculator; private final int maximumVisitedNodes; @@ -79,7 +100,8 @@ public final class GraphQlDocumentComplexityScorer { * @param schema schema the document was validated against * @param document the parsed document * @param operation the selected operation - * @param variables the request variables, used to resolve page sizes + * @param variables the request variables as the client sent them, used to resolve page sizes; the + * operation's own variable defaults fill in what the client left out * @throws GraphQlComplexityRejectedException when a requested page exceeds the maximum * @throws GraphQlStructuralLimitException when traversal exceeds the node budget */ @@ -112,9 +134,10 @@ public final class GraphQlDocumentComplexityScorer { root, operation.getSelectionSet(), fragments, - variables == null ? Map.of() : variables, + PageVariables.of(operation, variables), new Counter(), - new ArrayDeque<>()); + new ArrayDeque<>(), + false); return new GraphQlComplexityResult(total); } @@ -123,9 +146,10 @@ public final class GraphQlDocumentComplexityScorer { GraphQLFieldsContainer parent, SelectionSet selectionSet, Map fragments, - Map variables, + PageVariables variables, Counter counter, - Deque expansionPath) { + Deque expansionPath, + boolean listsAreThePage) { if (selectionSet == null || parent == null) { return 0; @@ -137,16 +161,24 @@ public final class GraphQlDocumentComplexityScorer { if (selection instanceof Field field) { total = - Math.addExact( + GraphQlComplexityCalculator.saturatedAdd( total, - fieldCost(schema, parent, field, fragments, variables, counter, expansionPath)); + fieldCost( + schema, + parent, + field, + fragments, + variables, + counter, + expansionPath, + listsAreThePage)); } else if (selection instanceof InlineFragment inlineFragment) { GraphQLFieldsContainer target = inlineFragment.getTypeCondition() == null ? parent : fieldsContainer(schema, inlineFragment.getTypeCondition().getName()); total = - Math.addExact( + GraphQlComplexityCalculator.saturatedAdd( total, selectionSetCost( schema, @@ -155,7 +187,8 @@ public final class GraphQlDocumentComplexityScorer { fragments, variables, counter, - expansionPath)); + expansionPath, + listsAreThePage)); } else if (selection instanceof FragmentSpread spread) { FragmentDefinition fragment = fragments.get(spread.getName()); // A fragment already on this path is a cycle. Validation rejects it, but the scorer must @@ -169,7 +202,7 @@ public final class GraphQlDocumentComplexityScorer { : fieldsContainer(schema, fragment.getTypeCondition().getName()); expansionPath.push(spread.getName()); total = - Math.addExact( + GraphQlComplexityCalculator.saturatedAdd( total, selectionSetCost( schema, @@ -178,7 +211,8 @@ public final class GraphQlDocumentComplexityScorer { fragments, variables, counter, - expansionPath)); + expansionPath, + listsAreThePage)); expansionPath.pop(); } } @@ -190,9 +224,10 @@ public final class GraphQlDocumentComplexityScorer { GraphQLFieldsContainer parent, Field field, Map fragments, - Map variables, + PageVariables variables, Counter counter, - Deque expansionPath) { + Deque expansionPath, + boolean listsAreThePage) { if (field.getName().startsWith(INTROSPECTION_FIELD_PREFIX)) { // Introspection is an allow/deny decision made by the authorization stage. Pricing it here @@ -202,53 +237,110 @@ public final class GraphQlDocumentComplexityScorer { GraphQLFieldDefinition definition = parent.getFieldDefinition(field.getName()); String coordinate = parent.getName() + "." + field.getName(); - GraphQLFieldsContainer childContainer = - definition == null ? null : fieldsContainer(unwrap(definition.getType())); + if (definition == null) { + // Validation rejects an unknown field; price what is there rather than invent a type. + return calculator.fieldCost(coordinate, 0).total(); + } + int dimensions = listDimensions(definition.getType()); + boolean paginated = + definition.getArgument(FIRST) != null + || definition.getArgument(LAST) != null + || calculator.connection(coordinate); + long childCost = selectionSetCost( schema, - childContainer, + fieldsContainer(definition.getType()), field.getSelectionSet(), fragments, variables, counter, - expansionPath); + expansionPath, + // A connection object's own lists are the page it was charged for. + paginated && dimensions == 0); - Integer first = pageArgument(field, "first", variables); - Integer last = pageArgument(field, "last", variables); - if (first != null || last != null) { + if (paginated) { + Integer first = pageArgument(definition, field, FIRST, variables); + Integer last = pageArgument(definition, field, LAST, variables); return calculator.connectionCost(coordinate, first, last, childCost).total(); } + if (dimensions > 0 && !listsAreThePage) { + return calculator.listCost(coordinate, dimensions, childCost).total(); + } return calculator.fieldCost(coordinate, childCost).total(); } - private static Integer pageArgument(Field field, String name, Map variables) { + /** + * The page a field will be asked for, or {@code null} when nothing names one. + * + *

An argument the document leaves out still reaches the resolver as the schema default, so + * that default is the page; an explicit {@code null} is not replaced by it. + */ + private static Integer pageArgument( + GraphQLFieldDefinition definition, Field field, String name, PageVariables variables) { for (Argument argument : field.getArguments()) { - if (!argument.getName().equals(name)) { - continue; + if (argument.getName().equals(name)) { + return intValue(argument.getValue(), variables); } - return intValue(argument.getValue(), variables); } - return null; + GraphQLArgument declared = definition.getArgument(name); + if (declared == null || !declared.hasSetDefaultValue()) { + return null; + } + InputValueWithState fallback = declared.getArgumentDefaultValue(); + if (fallback.isLiteral() && fallback.getValue() instanceof Value literal) { + return intValue(literal, variables); + } + return fallback.isExternal() ? intValue(fallback.getValue()) : null; } - private static Integer intValue(Value value, Map variables) { + private static Integer intValue(Value value, PageVariables variables) { if (value instanceof IntValue intValue) { BigInteger raw = intValue.getValue(); // A literal outside int range cannot be a page size; treating it as the maximum lets the // calculator reject it rather than silently overflowing to something affordable. - return raw.bitLength() >= Integer.SIZE ? Integer.MAX_VALUE : raw.intValue(); + if (raw.bitLength() >= Integer.SIZE) { + return raw.signum() < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE; + } + return raw.intValue(); } if (value instanceof VariableReference reference) { - Object supplied = variables.get(reference.getName()); - if (supplied instanceof Number number) { - long asLong = number.longValue(); - return asLong > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) asLong; - } + return variables.resolve(reference.getName()); } return null; } + private static Integer intValue(Object supplied) { + if (!(supplied instanceof Number number)) { + // Not an Int: coercion rejects it after this stage, and pricing it as no page is the same + // answer the resolver would give an absent argument. + return null; + } + BigDecimal exact = new BigDecimal(number.toString()); + if (exact.compareTo(BigDecimal.valueOf(Integer.MAX_VALUE)) > 0) { + return Integer.MAX_VALUE; + } + if (exact.compareTo(BigDecimal.valueOf(Integer.MIN_VALUE)) < 0) { + return Integer.MIN_VALUE; + } + return exact.intValue(); + } + + private static int listDimensions(GraphQLType type) { + int dimensions = 0; + GraphQLType current = type; + while (true) { + if (current instanceof GraphQLNonNull nonNull) { + current = nonNull.getWrappedType(); + } else if (current instanceof GraphQLList list) { + dimensions++; + current = list.getWrappedType(); + } else { + return dimensions; + } + } + } + private static GraphQLObjectType rootType(GraphQLSchema schema, OperationDefinition operation) { OperationDefinition.Operation kind = operation.getOperation() == null @@ -282,6 +374,36 @@ public final class GraphQlDocumentComplexityScorer { return current; } + /** + * The values a variable reference can stand for, before graphql-java coerces them. + * + *

The request map holds only what the client sent. A variable it left out takes the + * operation's declared default, which is the value the resolver will see — reading the request + * map alone priced {@code ($n: Int = 100000)} as if no page had been asked for. A variable the + * client sent as {@code null} stays {@code null}; it does not fall back to the default. + */ + private record PageVariables(Map supplied, Map> defaults) { + + static PageVariables of(OperationDefinition operation, Map supplied) { + Map> defaults = new LinkedHashMap<>(); + for (VariableDefinition definition : operation.getVariableDefinitions()) { + if (definition.getDefaultValue() != null) { + defaults.put(definition.getName(), definition.getDefaultValue()); + } + } + return new PageVariables(supplied == null ? Map.of() : supplied, defaults); + } + + Integer resolve(String name) { + if (supplied.containsKey(name)) { + return intValue(supplied.get(name)); + } + Value fallback = defaults.get(name); + // A default is a constant literal by the grammar, so it cannot refer to another variable. + return fallback instanceof IntValue ? intValue(fallback, this) : null; + } + } + private static final class Counter { private int visited; diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlFieldCostDescriptor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlFieldCostDescriptor.java index 48a5a41f..2939969d 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlFieldCostDescriptor.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlFieldCostDescriptor.java @@ -9,10 +9,20 @@ import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; * @param baseCost fixed cost of resolving the field once * @param resolverWeight what the resolver actually does * @param connection whether the field returns a paginated connection, whose children multiply by - * page size + * page size even when it declares no {@code first}/{@code last} argument + * @param estimatedListSize how many elements a list-returning field without page arguments is + * expected to hold, multiplied into its children's cost; {@link #UNDECLARED_LIST_SIZE} means + * "not declared" and the client policy's default page size is used instead */ public record GraphQlFieldCostDescriptor( - String coordinate, long baseCost, GraphQlResolverWeight resolverWeight, boolean connection) { + String coordinate, + long baseCost, + GraphQlResolverWeight resolverWeight, + boolean connection, + int estimatedListSize) { + + /** No list size was declared; a plain list is then priced at the default page size. */ + public static final int UNDECLARED_LIST_SIZE = 0; public GraphQlFieldCostDescriptor { GraphQlSchemaCoordinate.parse(coordinate); @@ -22,6 +32,15 @@ public record GraphQlFieldCostDescriptor( if (resolverWeight == null) { throw new IllegalArgumentException("resolver weight is required"); } + if (estimatedListSize < UNDECLARED_LIST_SIZE) { + throw new IllegalArgumentException("estimated list size cannot be negative"); + } + } + + /** A descriptor that leaves a plain list's size to the default page size. */ + public GraphQlFieldCostDescriptor( + String coordinate, long baseCost, GraphQlResolverWeight resolverWeight, boolean connection) { + this(coordinate, baseCost, resolverWeight, connection, UNDECLARED_LIST_SIZE); } /** Base cost plus resolver weight, before any cardinality multiplier. */ diff --git a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformExecutionPathTest.java b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformExecutionPathTest.java index 6eb92d88..88a94ffd 100644 --- a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformExecutionPathTest.java +++ b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformExecutionPathTest.java @@ -17,8 +17,10 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.time.Instant; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.IntStream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -187,6 +189,48 @@ class GraphQlPlatformExecutionPathTest { assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED"); } + @Test + @DisplayName("page 인자를 생략한 list 는 기본 page 크기로 곱해져 resolver 전에 복잡도 초과로 거부된다") + void aPageOmittedListIsPricedAtTheDefaultPageAndRejected() { + // when + ResponseEntity response = post("{ platformPage { id } }"); + + // then + assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED"); + } + + @Test + @DisplayName("page 인자가 없는 일반 list 를 중첩하면 원소 수만큼 곱해져 resolver 전에 거부된다") + void aNestedPlainListIsMultipliedAndRejected() { + // when + ResponseEntity response = post("{ platformNodes { id child { id } } }"); + + // then + assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED"); + } + + @Test + @DisplayName("변수 기본값으로 숨긴 page 크기가 상한을 넘으면 resolver 전에 거부된다") + void aPageSizeHiddenInAVariableDefaultIsRejected() { + // when + ResponseEntity response = + post("query P($n: Int = 100000) { platformPage(first: $n) { id } }"); + + // then + assertThatRejected(response, "GRAPHQL_COMPLEXITY_EXCEEDED"); + } + + @Test + @DisplayName("예산 안의 작은 page 는 list resolver 까지 도달한다") + void aSmallPageWithinTheBudgetReachesTheResolver() { + // when + ResponseEntity response = post("{ platformPage(first: 2) { id } }"); + + // then + assertThat(response.getBody()).contains("\"platformPage\":[{\"id\":\"p-0\"},{\"id\":\"p-1\"}]"); + assertThat(RESOLVER_INVOCATIONS).hasValue(1); + } + @Test void anUnauthorizedCoordinateIsRejectedBeforeAnyResolverRuns() { ResponseEntity response = post("{ platformSecret }"); @@ -376,6 +420,21 @@ class GraphQlPlatformExecutionPathTest { return "must-never-be-returned"; } + @QueryMapping + List platformPage(@Argument Integer first) { + RESOLVER_INVOCATIONS.incrementAndGet(); + int size = first == null ? 0 : first; + return IntStream.range(0, size) + .mapToObj(index -> new PlatformNode("p-" + index, "page-" + index, null)) + .toList(); + } + + @QueryMapping + List platformNodes() { + RESOLVER_INVOCATIONS.incrementAndGet(); + return List.of(); + } + /** Reports which of the three variable cases actually reached coercion. */ @QueryMapping String platformEcho(@Argument String value) { @@ -429,7 +488,7 @@ class GraphQlPlatformExecutionPathTest { } /** - * A deny-by-default policy with three coordinates opened. + * A deny-by-default policy with the coordinates under test opened. * *

Deliberately the fail-closed shape an adopter is expected to ship, so the denial test is * exercising the same configuration a production deployment would have rather than a special @@ -445,6 +504,8 @@ class GraphQlPlatformExecutionPathTest { .allow(GraphQlSchemaCoordinate.parse("Query.platformNode"), anonymous) .allow(GraphQlSchemaCoordinate.parse("Query.platformStamp"), anonymous) .allow(GraphQlSchemaCoordinate.parse("Query.platformEcho"), anonymous) + .allow(GraphQlSchemaCoordinate.parse("Query.platformPage"), anonymous) + .allow(GraphQlSchemaCoordinate.parse("Query.platformNodes"), anonymous) .build(); } } diff --git a/src/adapter/inbound/graphql/src/systemTest/resources/graphql-platform/platform.graphqls b/src/adapter/inbound/graphql/src/systemTest/resources/graphql-platform/platform.graphqls index 04d2cc7a..9cced169 100644 --- a/src/adapter/inbound/graphql/src/systemTest/resources/graphql-platform/platform.graphqls +++ b/src/adapter/inbound/graphql/src/systemTest/resources/graphql-platform/platform.graphqls @@ -1,8 +1,9 @@ # Schema used by the execution-path evidence test. # # Shaped to exercise the policies the platform claims to enforce: a self-referencing type for depth, -# a repeatable field for alias budgets, a coordinate the authorization policy denies, and a custom -# scalar so wiring and coercion are proved on a real request rather than in a unit test. +# a repeatable field for alias budgets, a coordinate the authorization policy denies, a custom +# scalar so wiring and coercion are proved on a real request rather than in a unit test, and two +# list fields — one paginated, one plain — so list cardinality is priced on the real path. scalar Instant @@ -14,6 +15,9 @@ extend type Query { # The argument default is what makes the three variable cases distinguishable at the resolver: # an omitted variable falls back to it, an explicit null does not. platformEcho(value: String = "default-applied"): String! + + platformPage(first: Int): [PlatformNode!]! + platformNodes: [PlatformNode!]! } type PlatformNode { diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorerTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorerTest.java new file mode 100644 index 00000000..cc5d8dd7 --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorerTest.java @@ -0,0 +1,262 @@ +package dev.caskeleton.adapter.inbound.graphql.cost; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; + +import graphql.language.Document; +import graphql.language.OperationDefinition; +import graphql.parser.Parser; +import graphql.schema.GraphQLSchema; +import graphql.schema.idl.RuntimeWiring; +import graphql.schema.idl.SchemaGenerator; +import graphql.schema.idl.SchemaParser; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * A list-returning field costs its children once per element, however the client asks for it. + * + *

Every number below is priced against the production default: an empty catalogue, so each field + * is the conservative unregistered weight (base 10, weighted 20), a default page of 20 and a + * maximum page of 100. The review probe (2026-11-01, 03-01) measured {@code items(first: 20)} at + * 410 while {@code items} alone was 40 and four nested lists were 100 — the omitted argument, the + * variable default and the plain list each skipped the multiplication the explicit literal got. + */ +class GraphQlDocumentComplexityScorerTest { + + private static final String SDL = + """ + type Query { + items(first: Int, last: Int): [Item!]! + pagedWithDefault(first: Int = 50): [Item!]! + itemConnection(first: Int): ItemConnection + node: Item + } + type Item { + name: String! + children: [Item!]! + grid: [[Item!]!]! + } + type ItemConnection { + edges: [ItemEdge!]! + } + type ItemEdge { + node: Item! + } + """; + + private static final GraphQLSchema SCHEMA = + new SchemaGenerator() + .makeExecutableSchema( + new SchemaParser().parse(SDL), RuntimeWiring.newRuntimeWiring().build()); + + private static final long BUDGET = 10_000; + + private final GraphQlComplexityCalculator calculator = + new GraphQlComplexityCalculator(GraphQlCostCatalog.of(), 20, 100); + + @Test + @DisplayName("first 를 명시한 page 는 하위 비용을 그 크기만큼 곱한다") + void anExplicitPageMultipliesChildrenByThePageSize() { + // when + long score = score("query Q { items(first: 20) { name } }", Map.of()); + + // then + assertThat(score).isEqualTo(10L + 20L * 20L); + } + + @Test + @DisplayName("first 를 생략한 page 는 기본 page 크기로 곱해서 명시한 기본 page 와 같은 점수다") + void anOmittedPageArgumentCostsTheDefaultPage() { + // when + long score = score("query Q { items { name } }", Map.of()); + + // then + assertThat(score).isEqualTo(score("query Q { items(first: 20) { name } }", Map.of())); + } + + @Test + @DisplayName("first 에 명시한 null 은 생략과 같아서 기본 page 크기로 곱한다") + void anExplicitNullPageArgumentCostsTheDefaultPage() { + // when + long score = score("query Q { items(first: null) { name } }", Map.of()); + + // then + assertThat(score).isEqualTo(10L + 20L * 20L); + } + + @Test + @DisplayName("일반 list 를 4단 중첩하면 점수가 단마다 곱으로 늘어 예산을 넘는다") + void nestedPlainListsMultiplyRatherThanAdd() { + // given + String document = "query Q { items { children { children { children { name } } } } }"; + + // when + long score = score(document, Map.of()); + + // then + long innermost = 20L + 20L * 20L; + long second = 20L + 20L * innermost; + long first = 20L + 20L * second; + assertThat(score).isEqualTo(10L + 20L * first); + assertThatThrownBy(() -> calculator.verify(new GraphQlComplexityResult(score), BUDGET)) + .isInstanceOf(GraphQlComplexityRejectedException.class); + } + + @Test + @DisplayName("변수 기본값으로 숨긴 page 크기도 상한을 넘으면 page size exceeds maximum 으로 거부된다") + void aPageSizeHiddenInAVariableDefaultIsCheckedAgainstTheMaximum() { + // given + String document = "query Q($n: Int = 100000) { items(first: $n) { name } }"; + + // when + Throwable thrown = catchThrowable(() -> score(document, Map.of())); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlComplexityRejectedException.class) + .hasMessageContaining("page size exceeds maximum"); + } + + @Test + @DisplayName("요청이 보낸 변수 값은 변수 기본값보다 우선한다") + void aSuppliedVariableOverridesItsDefault() { + // when + long score = score("query Q($n: Int = 100000) { items(first: $n) { name } }", Map.of("n", 5)); + + // then + assertThat(score).isEqualTo(10L + 5L * 20L); + } + + @Test + @DisplayName("요청이 변수에 명시한 null 은 기본값을 쓰지 않고 기본 page 크기로 곱한다") + void anExplicitNullVariableCostsTheDefaultPage() { + // given + Map variables = new HashMap<>(); + variables.put("n", null); + + // when + long score = score("query Q($n: Int = 100000) { items(first: $n) { name } }", variables); + + // then + assertThat(score).isEqualTo(10L + 20L * 20L); + } + + @Test + @DisplayName("스키마가 page 인자에 준 기본값은 생략했을 때 resolver 가 받는 값이라 그 크기로 곱한다") + void aSchemaArgumentDefaultIsThePageAnOmittedArgumentGets() { + // when + long score = score("query Q { pagedWithDefault { name } }", Map.of()); + + // then + assertThat(score).isEqualTo(10L + 50L * 20L); + } + + @Test + @DisplayName("last 만 상한을 넘어도 first 가 있다는 이유로 통과하지 않는다") + void bothPageArgumentsAreCheckedAgainstTheMaximum() { + // given + String document = "query Q { items(first: 1, last: 100000) { name } }"; + + // when + Throwable thrown = catchThrowable(() -> score(document, Map.of())); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlComplexityRejectedException.class) + .hasMessageContaining("page size exceeds maximum"); + } + + @Test + @DisplayName("cost catalog 에 선언한 list 추정 크기가 기본 page 크기 대신 곱해진다") + void aDeclaredListSizeReplacesTheDefaultMultiplier() { + // given + var declared = + new GraphQlComplexityCalculator( + GraphQlCostCatalog.of( + new GraphQlFieldCostDescriptor( + "Item.children", 2, GraphQlResolverWeight.PROPERTY, false, 3)), + 20, + 100); + + // when + long score = score(declared, "query Q { items(first: 1) { children { name } } }", Map.of()); + + // then + assertThat(score).isEqualTo(10L + 1L * ((2L + 1L) + 3L * 20L)); + } + + @Test + @DisplayName("list 안의 list 는 차원마다 한 번씩 곱한다") + void eachListDimensionMultipliesOnce() { + // when + long score = score("query Q { node { grid { name } } }", Map.of()); + + // then + assertThat(score).isEqualTo(20L + (20L + 20L * 20L * 20L)); + } + + @Test + @DisplayName("connection 객체 안의 edges 는 connection 이 이미 곱한 그 page 라서 다시 곱하지 않는다") + void aConnectionsEdgesAreThePageTheConnectionAlreadyPaidFor() { + // when + long score = + score("query Q { itemConnection(first: 5) { edges { node { name } } } }", Map.of()); + + // then + assertThat(score).isEqualTo(10L + 5L * (20L + (20L + 20L))); + } + + @Test + @DisplayName("page 인자를 생략한 connection 은 기본 page 크기로 곱한다") + void anOmittedConnectionPageCostsTheDefaultPage() { + // when + long score = score("query Q { itemConnection { edges { node { name } } } }", Map.of()); + + // then + assertThat(score).isEqualTo(10L + 20L * (20L + (20L + 20L))); + } + + @Test + @DisplayName("곱이 long 범위를 넘을 만큼 깊은 list 도 산술 오류가 아니라 예산 초과로 거부된다") + void anOverflowingScoreSaturatesAndIsRejectedByTheBudget() { + // given + String document = + "query Q { items { " + "children { ".repeat(20) + "name" + " }".repeat(21) + " }"; + + // when + long score = score(document, Map.of()); + + // then + assertThat(score).isEqualTo(Long.MAX_VALUE); + assertThatThrownBy(() -> calculator.verify(new GraphQlComplexityResult(score), BUDGET)) + .isInstanceOf(GraphQlComplexityRejectedException.class); + } + + @Test + @DisplayName("list 가 아닌 단일 객체 필드는 하위 비용을 곱하지 않고 더한다") + void aSingleObjectFieldAddsItsChildrenOnce() { + // when + long score = score("query Q { node { name } }", Map.of()); + + // then + assertThat(score).isEqualTo(20L + 20L); + } + + private long score(String source, Map variables) { + return score(calculator, source, variables); + } + + private static long score( + GraphQlComplexityCalculator calculator, String source, Map variables) { + Document document = Parser.parse(source); + OperationDefinition operation = + document.getDefinitionsOfType(OperationDefinition.class).getFirst(); + return new GraphQlDocumentComplexityScorer(calculator) + .score(SCHEMA, document, operation, variables) + .total(); + } +} diff --git a/src/adapter/inbound/web-advanced/build.gradle b/src/adapter/inbound/web-advanced/build.gradle index a6f42767..829213f1 100644 --- a/src/adapter/inbound/web-advanced/build.gradle +++ b/src/adapter/inbound/web-advanced/build.gradle @@ -38,3 +38,9 @@ strictTestLanes { jvmArgs '-Duser.timezone=UTC' } } + +// The tests run in `test` already; the main stage runs the lane so its fail-closed selection is +// proven before release.yml names it, not first there (review 2026-11-01 08-01). +tasks.named('mainCheck') { + dependsOn 'webAdvancedTest' +} diff --git a/src/adapter/inbound/web/CLAUDE.md b/src/adapter/inbound/web/CLAUDE.md index bdbe286b..d6976b13 100644 --- a/src/adapter/inbound/web/CLAUDE.md +++ b/src/adapter/inbound/web/CLAUDE.md @@ -24,8 +24,9 @@ Package root: `dev.caskeleton.adapter.inbound.web`. Every service ships this leaf, so it holds only what the servlet production path reaches: its `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 +health and rate-limit beans; `WebSecurityAutoConfiguration` imports the JWT chain, so an application +with its own posture excludes only that root; `WebMethodSecurityAutoConfiguration` imports method +security and the permission port and stays when the chain is replaced; 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 diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index f80ec34d..24540436 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -41,8 +41,14 @@ production configuration and compare the result with the committed snapshot. - Spring Boot auto-config decoder 를 대체해 validator chain 을 기본값 의존이 아닌 **명시적 구성**으로 만든다. - **D2 — clock skew 60s 명시 고정**(`JwtTimestampValidator`). framework 기본값에 의존하면 Spring 업그레이드로 기본값이 바뀔 때 silent-drift 위험이 있어 여기서 못박는다. -- **D4 — issuer 검증**(`SecuritySettings.issuerUri()`). **D3 — audience 검증**(`SecuritySettings.audience()`), - 단 blank audience 면 검사 건너뜀(기존 settings 계약과 일치). +- **D4 — issuer 검증**(`SecuritySettings.issuerUri()`). **D3 — audience 검증**(`SecuritySettings.audience()`). + JWT 모드에서 audience 는 필수이고(비면 기동 실패, 메시지에 `APP_SECURITY_JWT_AUDIENCE`), 쉼표 목록을 + 받는다. 토큰 `aud` 가 설정 목록 중 하나라도 담으면 통과한다. "비우면 검사 생략"은 없앴다 — 같은 + issuer 의 다른 client 용 토큰이 통과하기 때문이다(2026-11-01 리뷰 02-03·07-05, 소유자 결정 대안 A). + 버린 대안: prod 프로필에서만 필수(dev·staging 이 열리고 보안이 프로필 이름에 걸린다), 문서 강조만. +- **role 범위**: `JwtToAuthenticatedPrincipalConverter` 는 `realm_access.roles` 와, `resource_access` 중 + **audience 목록에 있는 client** 의 roles 만 읽는다. 다른 client 가 같은 이름의 role 을 정의해도 이 + 서비스 권한이 되지 않는다. client id 와 audience 가 다른 IdP 구성이 생기면 별도 키를 둔다(지금은 없음). - **JWKS lazy discovery** (`SupplierJwtDecoder`): 기동 시 IdP 가 reachable 일 필요가 없고, 첫 decode 시점에 issuer-uri/`.well-known` 네트워크 호출이 일어난다(Spring Boot auto-config 와 동일한 lazy 동작). lazy 초기화 중 외부 discovery/JWKS I/O 실패는 필터 밖 runtime exception으로 탈출시키지 않고 @@ -121,6 +127,14 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML ## authz — 인가 (`@RequiresPermission` 강제) +### WebMethodSecurityAutoConfiguration — 인가는 인증 체인과 따로 켜진다 +- `MethodSecurityConfig`·`AuthorizationAdapter`·`RolePermissionRegistry`·`RolePermissionPolicy`(`app.authz`)는 + `WebSecurityAutoConfiguration`(JWT/session 체인)이 아니라 이 auto-configuration이 들여온다. +- 이유: 인증 방식(체인)을 바꾸는 애플리케이션은 `WebSecurityAutoConfiguration`만 뺀다. 둘이 한 root에 + 있을 때는 체인을 빼면 advisor도 같이 빠져서, 그 애플리케이션의 `@RequiresPermission`이 아무 경고 없이 + 주석이 됐다(샘플이 그랬다 — 익명 삭제 가능). 이제 체인을 바꿔도 권한 검사는 남는다. +- 메서드 보안까지 끄려면 이 클래스를 따로 exclude 해야 한다. 그 결정은 exclude 목록에 이름으로 드러난다. + ### MethodSecurityConfig - `RequiresPermission` 강제 지점을 Spring method security 에 배선한다. - `@EnableMethodSecurity(prePostEnabled = false)` — method-security 인프라는 켜되 `@PreAuthorize`/ @@ -213,8 +227,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML | `PageValidationException` | `VALIDATION_FAILED` | 400 | D18/D20/D21: 계약 범위 밖 페이지/정렬/필터 파라미터. field + reasonCode 를 details 로 | | `IdempotencyUnavailableException` | `IDEMPOTENCY_UNAVAILABLE` | 503 (retryable=true) | 조정 저장소가 응답하지 않아 action 전에 거부. carrier 분기 | | `IdempotencyRecoveryRequiredException` | `IDEMPOTENCY_RECOVERY_REQUIRED` | 500 (retryable=false) | 이전 시도의 외부 효과 여부를 판단할 수 없음. carrier 분기 | -| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=false) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 진단정보(scope digest)는 클라이언트 미도달 | -| `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 | D8: `Idempotency-Key` 를 다른 본문으로 재사용. fingerprint/scope 노출 금지 | +| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=true, `Retry-After: 2`) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 클라이언트 행동: 결과 불명. 같은 `Idempotency-Key`로 `Retry-After` 뒤 재전송. 새 키 금지(`docs/web/http-contract.md` §2). 진단정보(scope digest)는 클라이언트 미도달 | +| `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 (retryable=false) | D8: `Idempotency-Key` 를 다른 본문으로 재사용. 다시 보내지 않는다(`docs/web/http-contract.md` §2). fingerprint/scope 노출 금지 | | `PersistenceFailureException` (JPA `JpaPersistenceException` 포함) | `ex.errorCode()` (사전분류 `DB_*`) | 코드 결정 | adapter-persistence translator 가 SQLState→`DB_*` 로 이미 분류, JPA 예외는 `FailureCategory`→`DB_*`. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**(SQLState/제약명 담음, 서버 로그 전용) | | `DependencyFailureException` | `ex.errorCode()` (사전분류 `DEPENDENCY_*`) | 코드 결정 | adapter-outbound `OutboundHttpErrorMapper` 가 upstream 실패를 분류. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**. retryable + `retry_after_seconds` 있으면 `RetryAfterAdvisor` 로 `Retry-After` 부착 | | `HttpRequestMethodNotSupportedException` | `METHOD_NOT_ALLOWED` | 405 | D12: 405 는 지원 메서드를 나열한 `Allow` 헤더 필수 | @@ -238,7 +252,12 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML ### EnvelopeBodyAdvice - 컨트롤러는 도메인/DTO 타입을 반환하고, 이 advice 가 와이어 형태를 항상 - `{success, data | error, traceId}` 로 보장한다. + `{success, data | error, meta}` 로 보장한다. +- **null 필드는 키째 생략한다.** 성공에는 `error` 키가, 실패에는 `data` 키가, 단일 아이템 `meta` 에는 + `page` 키가 없다. 빈 목록은 생략하지 않는다. 규칙은 `EnvelopeWireFormatConfig` 의 Jackson mix-in 이 + Boot `JsonMapper` 에 등록한다(shared-contract 는 Jackson 에 의존하지 않으므로 타입에 애너테이션을 + 달지 않는다). 키 목록과 근거는 `docs/web/http-contract.md` §1, 원문 키 집합 단언은 + `EnvelopeWireShapeTest`. - 위치: sample 모듈이 아니라 adapter-web. 실행 앱은 adapter-web 에 의존하지만 sample-portfolio 에는 의존하지 않으므로, 응답 래핑이 실제로 동작하려면 여기 있어야 한다. @@ -417,6 +436,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML - 필드 `RETRY_AFTER_SECONDS` 는 error-codes.yaml 의 `retry_after_seconds` 컬럼 미러. 이 advisor 가 유일한 Retry-After 노출 지점이라 여기 중앙화한다. `DEPENDENCY_4XX_CLIENT` 는 비재시도(retryable=false)라 `shouldAdvise` 가드로 empty 반환. +- `IDEMPOTENT_IN_FLIGHT` 는 2초: 기본 processing lease(30s)보다 짧아 첫 시도가 끝날 수 있는 동안 + 같은 키로 다시 묻게 한다. 근거와 클라이언트 행동은 `docs/web/http-contract.md` §2. --- diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfig.java index 5496b284..32c3f7d1 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfig.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfig.java @@ -24,9 +24,9 @@ import org.springframework.web.client.RestClientException; /** * Custom {@link JwtDecoder} for the resource server with an explicit validator chain: timestamp - * (60s clock skew) + issuer, plus an optional audience check when configured. JWKS discovery is - * deferred via {@link SupplierJwtDecoder} so startup does not require the IdP to be reachable. See - * README for the design rationale. + * (60s clock skew) + issuer + audience (required). JWKS discovery is deferred via {@link + * SupplierJwtDecoder} so startup does not require the IdP to be reachable. See README for the + * design rationale. */ @Configuration @ConditionalOnProperty(name = "app.security.auth-mode", havingValue = "jwt", matchIfMissing = true) @@ -70,16 +70,21 @@ public class JwtDecoderConfig { return false; } - /** The explicit validator chain: timestamp (60s skew) + issuer + optional audience. */ - static OAuth2TokenValidator jwtValidator(String issuerUri, String audience) { + /** + * The explicit validator chain: timestamp (60s skew) + issuer + audience. The token's {@code aud} + * must name at least one configured audience; an empty list is refused, never read as "skip". + */ + static OAuth2TokenValidator jwtValidator(String issuerUri, List audiences) { + if (audiences.isEmpty()) { + throw new IllegalArgumentException( + "APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required"); + } List> validators = new ArrayList<>(); validators.add( taggedValidator( new JwtTimestampValidator(Duration.ofSeconds(60)), ERROR_TIMESTAMP_INVALID)); validators.add(taggedValidator(new JwtIssuerValidator(issuerUri), ERROR_ISSUER_MISMATCH)); - if (audience != null && !audience.isBlank()) { - validators.add(audienceValidator(audience)); - } + validators.add(audienceValidator(List.copyOf(audiences))); return new DelegatingOAuth2TokenValidator<>(validators); } @@ -98,9 +103,10 @@ public class JwtDecoderConfig { }; } - private static OAuth2TokenValidator audienceValidator(String audience) { + private static OAuth2TokenValidator audienceValidator(List audiences) { return jwt -> { - if (jwt.getAudience() != null && jwt.getAudience().contains(audience)) { + List tokenAudience = jwt.getAudience(); + if (tokenAudience != null && audiences.stream().anyMatch(tokenAudience::contains)) { return OAuth2TokenValidatorResult.success(); } OAuth2Error error = diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java index 3cab5f29..2ac7296e 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverter.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.inbound.web.auth; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; import dev.caskeleton.application.tenant.TenantId; import java.util.ArrayList; import java.util.Collection; @@ -22,8 +23,12 @@ import org.springframework.stereotype.Component; /** * Maps an OIDC JWT to a JwtAuthenticationToken whose principal is our {@link * AuthenticatedPrincipal}. We pull {@code sub} as the IdP user id and union Keycloak-style {@code - * realm_access.roles} with {@code resource_access[*].roles} into a single role set. Roles also - * become Spring authorities (ROLE_*). + * realm_access.roles} with {@code resource_access..roles} into a single role set. Roles + * also become Spring authorities (ROLE_*). + * + *

Only the clients named by {@code app.security.audience} contribute {@code resource_access} + * roles. Another client of the same issuer may define a role with the same name (for example {@code + * operation-submit}); reading every client would hand that role to this service. */ @Component public class JwtToAuthenticatedPrincipalConverter @@ -37,6 +42,13 @@ public class JwtToAuthenticatedPrincipalConverter */ public static final String TENANT_CLAIM = "tenant_id"; + /** The clients whose {@code resource_access} roles this service honours: its own audiences. */ + private final Set roleClients; + + public JwtToAuthenticatedPrincipalConverter(SecuritySettings settings) { + this.roleClients = Set.copyOf(settings.audience()); + } + @Override public AbstractAuthenticationToken convert(Jwt jwt) { Set roles = extractRoles(jwt); @@ -79,8 +91,8 @@ public class JwtToAuthenticatedPrincipalConverter } Map resourceAccess = jwt.getClaimAsMap("resource_access"); if (resourceAccess != null) { - for (Object client : resourceAccess.values()) { - if (client instanceof Map clientMap + for (String clientId : roleClients) { + if (resourceAccess.get(clientId) instanceof Map clientMap && clientMap.get("roles") instanceof Collection rolesCol) { rolesCol.forEach(x -> roles.add(String.valueOf(x))); } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java new file mode 100644 index 00000000..19c75caa --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java @@ -0,0 +1,38 @@ +package dev.caskeleton.adapter.inbound.web.envelope; + +import com.fasterxml.jackson.annotation.JsonInclude; +import dev.caskeleton.shared.response.ApiError; +import dev.caskeleton.shared.response.BulkEnvelope; +import dev.caskeleton.shared.response.Envelope; +import dev.caskeleton.shared.response.ResponseMeta; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import tools.jackson.databind.module.SimpleModule; + +/** + * Leaves a {@code null} field of the response envelope types off the wire: a success body carries + * no {@code error} key, a failure body no {@code data} key, a single item no {@code meta.page}, and + * an error without details no {@code details}. An empty list is not {@code null} and stays. + * + *

The rule lives here, not as {@code @JsonInclude} on the records, because {@code + * shared-contract} depends on the Java standard library only. Boot registers every {@link + * SimpleModule} bean on its {@code JsonMapper}, which every HTTP writer in this adapter uses — the + * MVC converters and the filter-level writers alike. The wire contract this produces is {@code + * docs/web/http-contract.md}. + */ +@Configuration +public class EnvelopeWireFormatConfig { + + @Bean + public SimpleModule envelopeWireFormatModule() { + SimpleModule module = new SimpleModule("EnvelopeWireFormatModule"); + module.setMixInAnnotation(Envelope.class, OmitNullFields.class); + module.setMixInAnnotation(BulkEnvelope.class, OmitNullFields.class); + module.setMixInAnnotation(ApiError.class, OmitNullFields.class); + module.setMixInAnnotation(ResponseMeta.class, OmitNullFields.class); + return module; + } + + @JsonInclude(JsonInclude.Include.NON_NULL) + private abstract static class OmitNullFields {} +} 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 8e07c90c..7ee65f38 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 @@ -5,6 +5,7 @@ import dev.caskeleton.adapter.inbound.web.config.OpenApiContractConfig; import dev.caskeleton.adapter.inbound.web.config.PresentationWebConfig; import dev.caskeleton.adapter.inbound.web.controller.HealthcheckController; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; +import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.adapter.inbound.web.filter.CacheControlFilter; import dev.caskeleton.adapter.inbound.web.filter.RequestLoggingFilter; @@ -20,8 +21,9 @@ import org.springframework.core.Ordered; /** * 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. + * endpoint, rate limiting and their settings. The JWT security chain is {@link + * WebSecurityAutoConfiguration}, a separate root an application can exclude on its own; method + * security is {@link WebMethodSecurityAutoConfiguration}, which stays when the chain is replaced. * *

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 @@ -44,6 +46,7 @@ import org.springframework.core.Ordered; PresentationWebConfig.class, HealthcheckController.class, EnvelopeBodyAdvice.class, + EnvelopeWireFormatConfig.class, GlobalExceptionHandler.class, CacheControlFilter.class, RequestLoggingFilter.class, diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMethodSecurityAutoConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMethodSecurityAutoConfiguration.java new file mode 100644 index 00000000..0c5c1c01 --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMethodSecurityAutoConfiguration.java @@ -0,0 +1,25 @@ +package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure; + +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 org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Import; + +/** + * The enforcement of {@code @RequiresPermission}: the method-security advisor, the + * role-to-permission authorization port and the {@code app.authz} policy it reads. + * + *

Separate from {@link WebSecurityAutoConfiguration} because the two answer different questions. + * That root decides how a request is authenticated (the JWT or session chain) and an application + * with its own posture replaces it. This one decides whether an authenticated caller may run a use + * case, and replacing the way callers authenticate must not switch it off. While both lived in one + * root, excluding the chain removed the advisor too, and every {@code @RequiresPermission} in that + * application became a comment that nothing reported. + */ +@AutoConfiguration +@EnableConfigurationProperties(RolePermissionPolicy.class) +@Import({AuthorizationAdapter.class, MethodSecurityConfig.class, RolePermissionRegistry.class}) +public class WebMethodSecurityAutoConfiguration {} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java index f287df42..60fc52df 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.adapter.inbound.web.mvc.filter.JsonBodyLimitFilter; import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; +import dev.caskeleton.shared.tracing.ActiveTrace; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -51,13 +52,19 @@ public class WebMvcPlatformAutoConfiguration { return new GlobalExceptionHandler(spanErrorRecorderProvider); } - /** Assigns the correlation identifiers, validating anything a caller proposed. */ + /** + * Assigns the correlation identifiers, validating anything a caller proposed. With a tracer in + * the composition the trace id is the tracer's: the filter runs inside Boot's server observation + * ({@code HIGHEST_PRECEDENCE + 1}), whose span is then the active one. + */ @Bean @ConditionalOnMissingBean - public WebMvcRequestIdFilter webMvcRequestIdFilter(WebMvcPlatformSettings properties) { + public WebMvcRequestIdFilter webMvcRequestIdFilter( + WebMvcPlatformSettings properties, ObjectProvider activeTrace) { return new WebMvcRequestIdFilter( properties.trustInboundRequestId(), - org.springframework.core.Ordered.HIGHEST_PRECEDENCE + 10); + org.springframework.core.Ordered.HIGHEST_PRECEDENCE + 10, + activeTrace.getIfAvailable(() -> ActiveTrace.NONE)); } /** Refuses a JSON body over the configured ceiling before the converter reads it. */ 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 index 71b42d85..e67d524e 100644 --- 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 @@ -4,10 +4,6 @@ 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; @@ -17,13 +13,15 @@ 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. + * How a request is authenticated in production: the JWT (or session) security filter chain, the + * envelope entry point and access-denied handler, CORS 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 + * posture — the 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. Excluding it does + * not switch off {@code @RequiresPermission}: that is {@link WebMethodSecurityAutoConfiguration}, + * which an application keeps while it replaces the chain. Before this root was split from the web + * root, 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. * @@ -33,18 +31,11 @@ import org.springframework.core.Ordered; */ @AutoConfiguration @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) -@EnableConfigurationProperties({ - CorsSettings.class, - RolePermissionPolicy.class, - SecuritySettings.class -}) +@EnableConfigurationProperties({CorsSettings.class, SecuritySettings.class}) @Import({ JwtDecoderConfig.class, JwtToAuthenticatedPrincipalConverter.class, RedisSessionWebConfig.class, - SecurityConfig.class, - AuthorizationAdapter.class, - MethodSecurityConfig.class, - RolePermissionRegistry.class + SecurityConfig.class }) public class WebSecurityAutoConfiguration {} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java index 27c9c3f7..845e8091 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java @@ -4,6 +4,7 @@ import dev.caskeleton.adapter.inbound.web.core.WebRequestId; import dev.caskeleton.adapter.inbound.web.core.WebTraceId; import dev.caskeleton.adapter.inbound.web.observability.HeaderSanitizer; import dev.caskeleton.shared.observability.MdcKeys; +import dev.caskeleton.shared.tracing.ActiveTrace; import dev.caskeleton.shared.tracing.TraceParent; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -31,7 +32,10 @@ import org.springframework.web.filter.OncePerRequestFilter; * investigation ends up reading somebody else's exchange. * *

The trace id is different: propagating an inbound {@code traceparent} is the entire point of - * distributed tracing, so it is honoured when it parses, and replaced when it does not. + * distributed tracing, so it is honoured when it parses, and replaced when it does not. When a + * tracer is running, its server span already made that decision — it continued a valid inbound + * trace or started a new one — and the filter takes the span's context as it is, so the id in the + * response and the logs is the id the exported spans carry. * *

This is the one place the identifiers are made. It puts them on MDC and on the response before * anything else runs — Spring Security included, so a {@code 401}/{@code 403} written inside the @@ -65,6 +69,7 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements private final boolean trustInboundRequestId; private final int order; + private final ActiveTrace activeTrace; /** A filter that mints its own request ids and propagates a valid inbound trace. */ public WebMvcRequestIdFilter() { @@ -79,8 +84,21 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements * @param order the filter order */ public WebMvcRequestIdFilter(boolean trustInboundRequestId, int order) { + this(trustInboundRequestId, order, ActiveTrace.NONE); + } + + /** + * A filter that takes the trace context from a running tracer when one has a span active. + * + * @param trustInboundRequestId whether a client may choose the request id + * @param order the filter order; it must run inside the tracer's server observation for the + * active span to be the request's + * @param activeTrace the tracer's active span, or {@link ActiveTrace#NONE} without a tracer + */ + public WebMvcRequestIdFilter(boolean trustInboundRequestId, int order, ActiveTrace activeTrace) { this.trustInboundRequestId = trustInboundRequestId; this.order = order; + this.activeTrace = activeTrace; } @Override @@ -145,7 +163,11 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements .orElseGet(() -> new WebRequestId(UUID.randomUUID().toString())); } - private static TraceParent resolveTrace(HttpServletRequest request) { + private TraceParent resolveTrace(HttpServletRequest request) { + Optional traced = activeTrace.current(); + if (traced.isPresent()) { + return traced.get(); + } // A malformed traceparent is replaced rather than rejected: refusing the request would let an // upstream misconfiguration take an API down, and the platform still needs a correlation id. return TraceParent.parse(request.getHeader(TRACEPARENT_HEADER)) diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java index e18414ea..3cbc483c 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java @@ -14,6 +14,9 @@ public final class RetryAfterAdvisor { private static final Map RETRY_AFTER_SECONDS = Map.of( "RATE_LIMIT_EXCEEDED", 1, + // Below the default processing lease (30s): the resend arrives while the first attempt + // can still finish, and an early resend costs one more 409. docs/web/http-contract.md. + "IDEMPOTENT_IN_FLIGHT", 2, "AUTH_KID_UNKNOWN", 5, "AUTH_JWKS_UNAVAILABLE", 30, "DEPENDENCY_TIMEOUT", 2, diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java index 1082930a..526bdde3 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java @@ -1,29 +1,29 @@ package dev.caskeleton.adapter.inbound.web.settings; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.bind.ConstructorBinding; /** * Exclusive JWT or Redis-backed browser-session security policy bound from {@code app.security.*}. + * + *

In JWT mode both {@code issuerUri} and {@code audience} are required. {@code audience} is a + * comma-separated list: a token passes when its {@code aud} names any of them, and only those + * clients' {@code resource_access} roles are read. */ @ConfigurationProperties(prefix = "app.security") public record SecuritySettings( AuthenticationMode authMode, String issuerUri, - String audience, + List audience, List publicPaths, SessionCookieSettings session) { - private static final Logger log = LoggerFactory.getLogger(SecuritySettings.class); - @ConstructorBinding public SecuritySettings( AuthenticationMode authMode, String issuerUri, - String audience, + List audience, List publicPaths, SessionCookieSettings session) { this.authMode = authMode == null ? AuthenticationMode.JWT : authMode; @@ -32,13 +32,15 @@ public record SecuritySettings( "APP_SECURITY_JWT_ISSUER (app.security.issuer-uri) is required"); } this.issuerUri = issuerUri == null ? "" : issuerUri.trim(); - if (audience == null) { - if (this.authMode == AuthenticationMode.JWT) { - log.warn("APP_SECURITY_JWT_AUDIENCE is missing; skipping audience validation"); - } - this.audience = ""; - } else { - this.audience = audience.trim(); + this.audience = + audience == null + ? List.of() + : audience.stream().map(String::trim).filter(value -> !value.isEmpty()).toList(); + if (this.authMode == AuthenticationMode.JWT && this.audience.isEmpty()) { + // No "skip the check" default: a token minted for another client of the same issuer must + // not authenticate here. + throw new IllegalArgumentException( + "APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required"); } if (publicPaths == null) { this.publicPaths = List.of(); @@ -48,7 +50,7 @@ public record SecuritySettings( this.session = session == null ? SessionCookieSettings.defaults() : session; } - public SecuritySettings(String issuerUri, String audience, List publicPaths) { + public SecuritySettings(String issuerUri, List audience, List publicPaths) { this(AuthenticationMode.JWT, issuerUri, audience, publicPaths, null); } 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 2dcddba2..3b3038a2 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,3 +1,4 @@ dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration +dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMethodSecurityAutoConfiguration dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfigTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfigTest.java index c986a18b..2422f804 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfigTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfigTest.java @@ -1,11 +1,14 @@ package dev.caskeleton.adapter.inbound.web.auth; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import org.springframework.security.oauth2.jwt.Jwt; @@ -21,7 +24,7 @@ class JwtDecoderConfigTest { private static final String AUDIENCE = "ca-skeleton-api"; private final OAuth2TokenValidator validator = - JwtDecoderConfig.jwtValidator(ISSUER, AUDIENCE); + JwtDecoderConfig.jwtValidator(ISSUER, List.of(AUDIENCE)); private Jwt.Builder validJwt() { Instant now = Instant.now(); @@ -76,11 +79,44 @@ class JwtDecoderConfigTest { } @Test - void blankAudienceSkipsTheAudienceCheck() { - OAuth2TokenValidator noAud = JwtDecoderConfig.jwtValidator(ISSUER, ""); - Jwt jwt = validJwt().audience(List.of("anything")).build(); - assertThat(noAud.validate(jwt).hasErrors()) - .as("a blank configured audience disables audience validation") - .isFalse(); + @DisplayName("설정한 audience 목록 중 하나라도 토큰 aud에 있으면 통과한다") + void aTokenNamingAnyConfiguredAudiencePasses() { + // given + OAuth2TokenValidator listed = + JwtDecoderConfig.jwtValidator(ISSUER, List.of("ca-skeleton-admin", AUDIENCE)); + Jwt jwt = validJwt().audience(List.of("account", AUDIENCE)).build(); + + // when + OAuth2TokenValidatorResult result = listed.validate(jwt); + + // then + assertThat(result.hasErrors()).isFalse(); + } + + @Test + @DisplayName("토큰에 aud claim이 없으면 AUTH_AUDIENCE_MISMATCH 오류 코드로 거부한다") + void aTokenWithoutAnAudClaimIsRejectedAsAudienceMismatch() { + // given + Jwt jwt = validJwt().claims(claims -> claims.remove("aud")).build(); + + // when + OAuth2TokenValidatorResult result = validator.validate(jwt); + + // then + assertThat(result.getErrors()) + .extracting(OAuth2Error::getErrorCode) + .containsExactly(JwtDecoderConfig.ERROR_AUDIENCE_MISMATCH); + } + + @Test + @DisplayName("audience 목록이 비면 검사를 건너뛰지 않고 검증기 조립을 거부한다") + void anEmptyAudienceListIsRefusedInsteadOfSkippingTheCheck() { + // when + Throwable thrown = catchThrowable(() -> JwtDecoderConfig.jwtValidator(ISSUER, List.of())); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("APP_SECURITY_JWT_AUDIENCE"); } } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java index abbbd658..8d62ceac 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtToAuthenticatedPrincipalConverterTest.java @@ -3,9 +3,11 @@ package dev.caskeleton.adapter.inbound.web.auth; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; import dev.caskeleton.application.tenant.TenantId; import java.util.List; import java.util.Locale; +import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; @@ -14,6 +16,8 @@ import org.springframework.security.oauth2.server.resource.InvalidBearerTokenExc class JwtToAuthenticatedPrincipalConverterTest { + private static final String OWN_CLIENT = "ca-skeleton-api"; + @Test void roleAuthoritiesUseLocaleIndependentUppercase() { Locale originalDefault = Locale.getDefault(); @@ -26,7 +30,7 @@ class JwtToAuthenticatedPrincipalConverterTest { .claim("roles", List.of("admin")) .build(); - var authentication = new JwtToAuthenticatedPrincipalConverter().convert(jwt); + var authentication = converter().convert(jwt); assertThat(authentication.getAuthorities()) .extracting(GrantedAuthority::getAuthority) @@ -42,7 +46,7 @@ class JwtToAuthenticatedPrincipalConverterTest { Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "acme").build(); // when - var authentication = new JwtToAuthenticatedPrincipalConverter().convert(jwt); + var authentication = converter().convert(jwt); // then assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).tenant()) @@ -52,7 +56,7 @@ class JwtToAuthenticatedPrincipalConverterTest { @Test void aTokenWithoutATenantClaimHasNoTenant() { // when - var authentication = new JwtToAuthenticatedPrincipalConverter().convert(token().build()); + var authentication = converter().convert(token().build()); // then assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).tenant()).isEmpty(); @@ -65,8 +69,7 @@ class JwtToAuthenticatedPrincipalConverterTest { Jwt jwt = token().claim(JwtToAuthenticatedPrincipalConverter.TENANT_CLAIM, "ac me").build(); // when - Throwable thrown = - catchThrowable(() -> new JwtToAuthenticatedPrincipalConverter().convert(jwt)); + Throwable thrown = catchThrowable(() -> converter().convert(jwt)); // then assertThat(thrown) @@ -74,6 +77,56 @@ class JwtToAuthenticatedPrincipalConverterTest { .hasMessage("the token's tenant claim is malformed"); } + @Test + @DisplayName("같은 issuer의 다른 client role은 이 서비스의 권한이 되지 않는다") + void anotherClientsRolesGrantNoAuthority() { + // given + Jwt jwt = + token() + .claim( + "resource_access", + Map.of("other-app", Map.of("roles", List.of("operation-submit")))) + .build(); + + // when + var authentication = converter().convert(jwt); + + // then + assertThat(authentication.getAuthorities()).isEmpty(); + assertThat(((AuthenticatedPrincipal) authentication.getPrincipal()).roles()).isEmpty(); + } + + @Test + @DisplayName("설정한 client의 role과 realm role은 권한이 된다") + void theOwnClientsRolesAndRealmRolesBecomeAuthorities() { + // given + Jwt jwt = + token() + .claim("realm_access", Map.of("roles", List.of("user"))) + .claim( + "resource_access", + Map.of( + OWN_CLIENT, + Map.of("roles", List.of("operation-submit")), + "other-app", + Map.of("roles", List.of("file-admin")))) + .build(); + + // when + var authentication = converter().convert(jwt); + + // then + assertThat(authentication.getAuthorities()) + .extracting(GrantedAuthority::getAuthority) + .containsExactlyInAnyOrder("ROLE_USER", "ROLE_OPERATION-SUBMIT"); + } + + private static JwtToAuthenticatedPrincipalConverter converter() { + return new JwtToAuthenticatedPrincipalConverter( + new SecuritySettings( + "https://issuer.example/realms/ca-skeleton", List.of(OWN_CLIENT), List.of())); + } + private static Jwt.Builder token() { return Jwt.withTokenValue("token").header("alg", "none").subject("user-1"); } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/RedisSessionWebConfigTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/RedisSessionWebConfigTest.java index 63749b77..c807490b 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/RedisSessionWebConfigTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/RedisSessionWebConfigTest.java @@ -23,7 +23,9 @@ class RedisSessionWebConfigTest { void jwtModeCreatesNoSessionFilterOrCookieSerializer() { runner .withPropertyValues( - "app.security.auth-mode=jwt", "app.security.issuer-uri=https://issuer.example") + "app.security.auth-mode=jwt", + "app.security.issuer-uri=https://issuer.example", + "app.security.audience=ca-skeleton-api") .run( context -> { assertThat(context).hasNotFailed(); diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityModeWebContractTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityModeWebContractTest.java index ef920653..00aee3f5 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityModeWebContractTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityModeWebContractTest.java @@ -157,6 +157,7 @@ class SecurityModeWebContractTest { .withPropertyValues( "app.security.auth-mode=jwt", "app.security.issuer-uri=https://issuer.example", + "app.security.audience=ca-skeleton-api", "app.security.public-paths=/probe", "app.cors.enabled=false") .run( @@ -177,6 +178,7 @@ class SecurityModeWebContractTest { .withPropertyValues( "app.security.auth-mode=jwt", "app.security.issuer-uri=https://issuer.example", + "app.security.audience=ca-skeleton-api", "app.cors.enabled=false") .run( context -> { diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java index ce2655c0..8dcbc3a4 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java @@ -1,6 +1,9 @@ package dev.caskeleton.adapter.inbound.web.envelope; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -25,7 +28,11 @@ import org.springframework.web.bind.annotation.RestController; controllers = EnvelopeBodyAdviceTest.Probe.class, excludeAutoConfiguration = SecurityAutoConfiguration.class) @AutoConfigureMockMvc(addFilters = false) -@Import({EnvelopeBodyAdviceTest.Probe.class, EnvelopeBodyAdvice.class}) +@Import({ + EnvelopeBodyAdviceTest.Probe.class, + EnvelopeBodyAdvice.class, + EnvelopeWireFormatConfig.class +}) class EnvelopeBodyAdviceTest { @Autowired MockMvc mvc; @@ -54,7 +61,7 @@ class EnvelopeBodyAdviceTest { .andExpect(status().isOk()) .andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.data.k").value("v")) - .andExpect(jsonPath("$.error").doesNotExist()); + .andExpect(content().string(not(containsString("\"error\"")))); } @Test @@ -79,7 +86,7 @@ class EnvelopeBodyAdviceTest { .andExpect(status().isOk()) .andExpect(jsonPath("$.results[0].k").value("v")) .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data").doesNotExist()); + .andExpect(content().string(not(containsString("\"data\"")))); } @SpringBootConfiguration diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java new file mode 100644 index 00000000..8f7abc31 --- /dev/null +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java @@ -0,0 +1,195 @@ +package dev.caskeleton.adapter.inbound.web.envelope; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.application.idempotency.IdempotencyInFlightException; +import dev.caskeleton.shared.observability.MdcKeys; +import dev.caskeleton.shared.response.BulkEnvelope; +import dev.caskeleton.shared.response.BulkItemResult; +import dev.caskeleton.shared.response.Envelope; +import dev.caskeleton.shared.response.PageMeta; +import dev.caskeleton.shared.response.ResponseMeta; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * The raw JSON keys a client receives — the wire contract in {@code docs/web/http-contract.md}. + * + *

Asserted on the response text, never with {@code jsonPath(..).doesNotExist()}: that matcher + * passes for a key that is present with a {@code null} value, which is exactly the difference a + * strict client rejects. + */ +@WebMvcTest( + controllers = EnvelopeWireShapeTest.Probe.class, + excludeAutoConfiguration = SecurityAutoConfiguration.class) +@AutoConfigureMockMvc(addFilters = false) +@Import({ + EnvelopeWireShapeTest.Probe.class, + EnvelopeBodyAdvice.class, + GlobalExceptionHandler.class, + EnvelopeWireFormatConfig.class +}) +class EnvelopeWireShapeTest { + + private static final JsonMapper READER = JsonMapper.builder().build(); + + @Autowired MockMvc mvc; + + @RestController + static class Probe { + + @GetMapping("/probe/item") + public Map item() { + ids(true); + return Map.of("k", "v"); + } + + @GetMapping("/probe/empty-list") + public List emptyList() { + ids(true); + return List.of(); + } + + @GetMapping("/probe/page") + public Envelope> page() { + return Envelope.ok( + List.of("a"), + new ResponseMeta("req-1", "trace-1", "corr-1").withPage(new PageMeta(0, 20, 1, "id"))); + } + + @GetMapping("/probe/in-flight") + public Map inFlight() { + ids(false); + throw IdempotencyInFlightException.forScopeDigest("CREATE::v1::" + "a".repeat(64)); + } + + @GetMapping("/probe/bulk-ok") + public BulkEnvelope bulkOk() { + return BulkEnvelope.allOk(List.of(), new ResponseMeta("req-1", "trace-1", "corr-1")); + } + + @GetMapping("/probe/bulk-partial") + public BulkEnvelope bulkPartial() { + return BulkEnvelope.partial( + List.of(), new ResponseMeta("req-1", "trace-1", "corr-1")); + } + + private static void ids(boolean withCorrelation) { + MDC.put(MdcKeys.REQUEST_ID, "req-1"); + MDC.put(MdcKeys.TRACE_ID, "trace-1"); + if (withCorrelation) { + MDC.put(MdcKeys.CORRELATION_ID, "corr-1"); + } + } + } + + @AfterEach + void clearMdc() { + MDC.clear(); + } + + @Test + @DisplayName("성공 응답 원문에는 success·data·meta 키만 있고 error 키는 없다") + void successBodyCarriesOnlySuccessDataAndMetaKeys() throws Exception { + // when + JsonNode body = rawBody("/probe/item"); + + // then + assertThat(keys(body)).containsExactlyInAnyOrder("success", "data", "meta"); + assertThat(keys(body.get("meta"))) + .containsExactlyInAnyOrder("requestId", "traceId", "correlationId"); + } + + @Test + @DisplayName("빈 목록 data는 생략되지 않고 빈 배열로 나간다") + void emptyListDataIsKeptAsAnEmptyArray() throws Exception { + // when + JsonNode body = rawBody("/probe/empty-list"); + + // then + assertThat(keys(body)).containsExactlyInAnyOrder("success", "data", "meta"); + assertThat(body.get("data").isArray() && body.get("data").isEmpty()).isTrue(); + } + + @Test + @DisplayName("목록 응답의 meta에만 page 키가 있다") + void pagedBodyCarriesPageInMeta() throws Exception { + // when + JsonNode body = rawBody("/probe/page"); + + // then + assertThat(keys(body.get("meta"))) + .containsExactlyInAnyOrder("requestId", "traceId", "correlationId", "page"); + } + + @Test + @DisplayName("실패 응답 원문에는 success·error·meta 키만 있고 data·null 필드는 없다") + void failureBodyCarriesOnlySuccessErrorAndMetaKeys() throws Exception { + // when + JsonNode body = rawBody("/probe/in-flight"); + + // then + assertThat(keys(body)).containsExactlyInAnyOrder("success", "error", "meta"); + assertThat(keys(body.get("error"))) + .containsExactlyInAnyOrder("code", "category", "message", "retryable"); + assertThat(keys(body.get("meta"))).containsExactlyInAnyOrder("requestId", "traceId"); + } + + @Test + @DisplayName("bulk 전체 성공은 빈 results를 남기고 error 키를 싣지 않는다") + void bulkSuccessKeepsEmptyResultsWithoutErrorKey() throws Exception { + // when + JsonNode body = rawBody("/probe/bulk-ok"); + + // then + assertThat(keys(body)).containsExactlyInAnyOrder("success", "results", "meta"); + assertThat(body.get("results").isArray() && body.get("results").isEmpty()).isTrue(); + } + + @Test + @DisplayName("bulk 부분 실패는 results 키 없이 error의 빈 details 목록을 남긴다") + void bulkPartialFailureCarriesErrorWithoutResultsKey() throws Exception { + // when + JsonNode body = rawBody("/probe/bulk-partial"); + + // then + assertThat(keys(body)).containsExactlyInAnyOrder("success", "error", "meta"); + JsonNode details = body.get("error").get("details"); + assertThat(details.isArray() && details.isEmpty()).isTrue(); + } + + private JsonNode rawBody(String path) throws Exception { + String text = mvc.perform(get(path)).andReturn().getResponse().getContentAsString(); + return READER.readTree(text); + } + + private static Set keys(JsonNode node) { + Set keys = new TreeSet<>(); + node.properties().forEach(entry -> keys.add(entry.getKey())); + return keys; + } + + @SpringBootConfiguration + @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) + static class TestBootstrap {} +} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java index 47183f22..2e1a8412 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java @@ -2,12 +2,14 @@ package dev.caskeleton.adapter.inbound.web.error; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; import dev.caskeleton.application.idempotency.IdempotencyInFlightException; import dev.caskeleton.application.idempotency.IdempotencyRequestMismatchException; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.ClientErrorMessages; import dev.caskeleton.shared.response.Envelope; import dev.caskeleton.shared.tracing.SpanErrorRecorder; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.http.ResponseEntity; @@ -18,7 +20,8 @@ class IdempotencyExceptionMappingTest { private final GlobalExceptionHandler handler = new GlobalExceptionHandler(SpanErrorRecorder.NOOP); @Test - void inFlightMapsToNonRetryable409ConflictWithTheConflictMessage() { + @DisplayName("처리 중 409는 retryable=true와 Retry-After를 실어 같은 키 재전송을 알린다") + void inFlightMapsToRetryable409WithRetryAfterSoTheClientResendsTheSameKey() { // given IdempotencyInFlightException inFlight = IdempotencyInFlightException.forScopeDigest(SCOPE_DIAGNOSTIC); @@ -30,19 +33,22 @@ class IdempotencyExceptionMappingTest { assertThat(response) .extracting( r -> r.getStatusCode().value(), + r -> r.getHeaders().getFirst(ApiHeaders.RETRY_AFTER), r -> r.getBody().error().code(), r -> r.getBody().error().category(), r -> r.getBody().error().retryable(), r -> r.getBody().error().message()) .containsExactly( 409, + "2", "IDEMPOTENT_IN_FLIGHT", "CONFLICT", - false, + true, ClientErrorMessages.of(Category.CONFLICT)); } @Test + @DisplayName("다른 본문으로 키를 재사용하면 Retry-After 없는 재시도 불가 422다") void mismatchMapsToNonRetryable422ValidationWithTheValidationMessage() { // given IdempotencyRequestMismatchException mismatch = @@ -55,12 +61,14 @@ class IdempotencyExceptionMappingTest { assertThat(response) .extracting( r -> r.getStatusCode().value(), + r -> r.getHeaders().getFirst(ApiHeaders.RETRY_AFTER), r -> r.getBody().error().code(), r -> r.getBody().error().category(), r -> r.getBody().error().retryable(), r -> r.getBody().error().message()) .containsExactly( 422, + null, "IDEMPOTENT_REQUEST_MISMATCH", "VALIDATION", false, 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 1f8af93b..fb23add4 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 @@ -37,6 +37,7 @@ class WebAutoConfigurationRegistrationTest { 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.WebMethodSecurityAutoConfiguration", "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration"); @Test diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java index 3d3fa5dd..2e0aea33 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java @@ -76,6 +76,31 @@ class WebMvcRequestIdFilterTest { .isPresent(); } + @Test + @DisplayName("tracer가 span을 열어 두었으면 응답·MDC의 trace id는 그 span의 것이다") + void theActiveSpanOfARunningTracerNamesTheTrace() throws Exception { + // given + TraceParent serverSpan = + TraceParent.of("4bf92f3577b34da6a3ce929d0e0e4736", "00f067aa0ba902b7", true); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(WebMvcRequestIdFilter.TRACEPARENT_HEADER, "garbage"); + MockHttpServletResponse response = new MockHttpServletResponse(); + Map duringChain = new HashMap<>(); + + // when + new WebMvcRequestIdFilter(false, 0, () -> java.util.Optional.of(serverSpan)) + .doFilter(request, response, (rq, rs) -> duringChain.putAll(mdc())); + + // then + assertThat(WebMvcRequestIdFilter.traceId(request).orElseThrow().value()) + .isEqualTo(serverSpan.traceId()); + assertThat(duringChain) + .containsEntry(MdcKeys.TRACE_ID, serverSpan.traceId()) + .containsEntry(MdcKeys.SPAN_ID, serverSpan.spanId()); + assertThat(response.getHeader(WebMvcRequestIdFilter.TRACEPARENT_HEADER)) + .isEqualTo(serverSpan.toHeader()); + } + @ParameterizedTest @ValueSource( strings = { diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisorTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisorTest.java index 2d6ce109..d08c8f10 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisorTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisorTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.observability; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.shared.error.OperationalError; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class RetryAfterAdvisorTest { @@ -45,10 +46,17 @@ class RetryAfterAdvisorTest { @Test void nonRetryableCodeHasNoRetryAfterValue() { - assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.IDEMPOTENT_IN_FLIGHT)) + assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.IDEMPOTENT_REQUEST_MISMATCH)) .isEmpty(); } + @Test + @DisplayName("처리 중 409는 기본 processing lease(30s)보다 짧은 2초 Retry-After를 준다") + void idempotentInFlightHasRetryAfter2s() { + assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.IDEMPOTENT_IN_FLIGHT)) + .hasValue(2); + } + // feature-outbound-http-client-baseline D12: dependency codes — rows 636~711 in // docs/registries/error-codes.yaml, retry_after_seconds column. diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java index 1dfb2098..2ee531e1 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java @@ -4,15 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.test.system.CapturedOutput; -import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.context.annotation.Configuration; -@ExtendWith(OutputCaptureExtension.class) class SecuritySettingsTest { private final ApplicationContextRunner runner = @@ -29,15 +26,59 @@ class SecuritySettingsTest { } @Test - void audienceMissingWarnsAndDefaultsToEmpty(CapturedOutput output) { - runner - .withPropertyValues("app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(SecuritySettings.class).audience()).isEmpty(); - assertThat(output.getOut()).contains("APP_SECURITY_JWT_AUDIENCE is missing"); - }); + @DisplayName("JWT 모드에서 audience가 없으면 env 키 이름을 담아 기동을 거부한다") + void aJwtModeWithoutAnAudienceFailsStartupNamingTheEnvKey() { + // given + var withoutAudience = + runner.withPropertyValues( + "app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton"); + + // when + withoutAudience.run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasStackTraceContaining("APP_SECURITY_JWT_AUDIENCE"); + }); + } + + @Test + @DisplayName("JWT 모드에서 audience가 빈 값이거나 공백 항목뿐이면 기동을 거부한다") + void aJwtModeWithABlankAudienceFailsStartup() { + // given + var blankAudience = + runner.withPropertyValues( + "app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton", + "app.security.audience= , "); + + // when + blankAudience.run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasStackTraceContaining("APP_SECURITY_JWT_AUDIENCE"); + }); + } + + @Test + @DisplayName("audience는 쉼표 목록을 받아 공백을 다듬은 목록으로 묶는다") + void aCommaSeparatedAudienceBindsAsATrimmedList() { + // given + var listedAudiences = + runner.withPropertyValues( + "app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton", + "app.security.audience=ca-skeleton-api, ca-skeleton-admin"); + + // when + listedAudiences.run( + context -> { + // then + assertThat(context).hasNotFailed(); + assertThat(context.getBean(SecuritySettings.class).audience()) + .containsExactly("ca-skeleton-api", "ca-skeleton-admin"); + }); } @Test @@ -60,7 +101,8 @@ class SecuritySettingsTest { List paths = new ArrayList<>(List.of("/healthcheck")); SecuritySettings settings = - new SecuritySettings("http://localhost:8081/realms/ca-skeleton", "ca-skeleton-api", paths); + new SecuritySettings( + "http://localhost:8081/realms/ca-skeleton", List.of("ca-skeleton-api"), paths); paths.add("/admin/**"); assertThat(settings.publicPaths()).containsExactly("/healthcheck"); @@ -83,6 +125,7 @@ class SecuritySettingsTest { assertThat(settings.authMode()) .isEqualTo(SecuritySettings.AuthenticationMode.REDIS_SESSION); assertThat(settings.issuerUri()).isEmpty(); + assertThat(settings.audience()).isEmpty(); assertThat(settings.session().cookieName()).isEqualTo("APP_SESSION"); assertThat(settings.session().sameSite()).isEqualTo("Strict"); }); 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 121ac91a..3a650c0b 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 @@ -29,7 +29,8 @@ import org.springframework.security.web.SecurityFilterChain; * 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. + * compilation rather than the gate. The third root, {@code WebMethodSecurityAutoConfiguration}, is + * left in: no fixture route runs a permissioned use case, so it decides nothing here. */ // 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 diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 83d178ab..4478b3f2 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -122,7 +122,10 @@ Redis checks a script's inner commands against the ACL only when they run, so a nothing proved `EVALSHA` and nothing else: an account granted by category (`@read`/`@write`) lacks `TIME` and failed every rate-limit and idempotency request after a clean start. A deployment whose effective Redis account lacks script permissions fails during startup rather than at the first -request. Cache-only deployments do not run this probe. +request. Cache-only deployments do not run this probe, although the cache's conditional intents +(`ONLY_IF_OBSERVED`, `ONLY_IF_SOURCE_REVISION_NEWER`) also run on the SCRIPT lane: a cache-only +deployment whose script-lane account lacks `EVALSHA` finds out as `INDETERMINATE` conditional +writes, not at startup. At runtime, `redisRequired` (redis-runtime) probes the SCRIPT lane too when a script role is selected, so a broken advanced-account credential makes the pod unready instead of leaving the @@ -153,6 +156,24 @@ script to perform: inside one Redis execution. A stale source load therefore cannot overwrite a value written between observation and replacement. +`ONLY_IF_SOURCE_REVISION_NEWER` is an atomic server-side revision comparison. The source revision +must be a non-negative decimal integer without leading zeros (a row version, an offset, epoch +millis); any other revision is refused with `IllegalArgumentException` before anything is sent, +because text order would rank revision `10` below `9`. The script reads the stored envelope's +schema version, revision and generation and writes only when: + +- nothing is stored, or the stored entry is from an older region generation (already invalidated); +- otherwise, the stored revision is a decimal integer and the caller's is strictly greater. + +Everything else — an equal or smaller revision, a stored revision with no numeric order (for +example one written by `UPSERT` as `rev-1`), another schema version, a generation newer than the +writer knows — is `NOT_RECORDED_CONDITION`. + +Both conditional intents run registered scripts, so they borrow the SCRIPT lane (the advanced +account when one is configured, the application account otherwise). The application account is not +granted `EVALSHA`; on the REGULAR lane every conditional write came back `INDETERMINATE`. `UPSERT` +and `ONLY_IF_ABSENT` stay on the REGULAR lane. + ### Region invalidation Region invalidation increments a generation key; it never scans/deletes the keyspace. @@ -184,6 +205,15 @@ programs atomically. `RedisIdempotencyConfig` contributes only the `IdempotencyS revision) come from app-bootstrap `IdempotencySettings`. This leaf reads only `key-version` and `command-timeout` under `app.capabilities.idempotency`. +`renew` has its own program rather than the generic transition. Renewal keeps the record in +`EXECUTING`, and the transition answers "already in the target state" before it reads the revision +(that answer exists for a retry whose first reply was lost), so a renewal sent through it was always +`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. The renew program checks owner, +operation, revision and state, then extends `leaseUntil` from Redis `TIME` and bumps the revision. +A lost renewal reply is recognised by what the renewal recorded — the revision it started from and +the lease it asked for: the same lease is `ALREADY_RENEWED_SAME_OPERATION` with the current handle, +a different lease is `OPERATION_CONFLICT`. + Redis `TIME` determines lease deadlines. A failure after a command may have executed is returned as an indeterminate outcome; the adapter does not convert an ambiguous write into a clean unavailable result that would invite duplicate execution. diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScripts.java index 05ca89da..0964afde 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScripts.java @@ -22,9 +22,88 @@ final class CacheScripts { return 1 """; + /** + * Replaces the entry only when the caller's source revision is strictly newer than the stored + * one. + * + *

Revisions are canonical non-negative decimal integers, compared by length and then digit by + * digit, so the order is numeric at any length (no 2^53 limit, no locale collation). The stored + * envelope header is {@code digest|version|revision|generation|...}; the digest is not + * re-verified here, the reader does that on lookup. + * + *

The write applies when nothing is stored, or when the stored entry belongs to an older + * region generation (semantically invalidated). It is refused when the stored entry has another + * schema version, a newer generation than the writer knows, or a revision that has no numeric + * order: nothing proves the caller's revision is newer than any of those. + */ + private static final String REPLACE_IF_REVISION_NEWER = + """ + local function canonicalDecimal(text) + return string.match(text, '^%d+$') ~= nil + and (string.len(text) == 1 or string.sub(text, 1, 1) ~= '0') + end + local function strictlyNewer(candidate, stored) + if string.len(candidate) ~= string.len(stored) then + return string.len(candidate) > string.len(stored) + end + for i = 1, string.len(candidate) do + local a = string.byte(candidate, i) + local b = string.byte(stored, i) + if a ~= b then + return a > b + end + end + return false + end + local current = redis.call('GET', KEYS[1]) + if current ~= false then + if string.sub(current, 65, 65) ~= '|' then + return 0 + end + local fields = {} + local cursor = 66 + for i = 1, 3 do + local stop = string.find(current, '|', cursor, true) + if stop == nil then + return 0 + end + fields[i] = string.sub(current, cursor, stop - 1) + cursor = stop + 1 + end + if fields[1] ~= ARGV[4] then + return 0 + end + local storedGeneration = tonumber(fields[3]) + local writerGeneration = tonumber(ARGV[5]) + if storedGeneration == nil or storedGeneration > writerGeneration then + return 0 + end + if storedGeneration == writerGeneration then + if not canonicalDecimal(fields[2]) or not strictlyNewer(ARGV[1], fields[2]) then + return 0 + end + end + end + redis.call('SET', KEYS[1], ARGV[2], 'PX', ARGV[3]) + return 1 + """; + private final RegisteredLuaScript replaceIfObserved = new RegisteredLuaScript(REPLACE_IF_OBSERVED); + private final RegisteredLuaScript replaceIfRevisionNewer = + new RegisteredLuaScript(REPLACE_IF_REVISION_NEWER); + + /** + * Whether a revision has the numeric order {@link #replaceIfRevisionNewer} compares by. + * + * @param revision the source revision + * @return true for a canonical non-negative decimal integer + */ + static boolean hasNumericOrder(String revision) { + return revision.matches("0|[1-9][0-9]*"); + } + CompletionStage replaceIfObserved( SemanticRedisCommands commands, byte[] key, @@ -40,4 +119,24 @@ final class CacheScripts { .evaluateForLong(commands, key, arguments) .thenApply(applied -> applied != null && applied == 1L); } + + CompletionStage replaceIfRevisionNewer( + SemanticRedisCommands commands, + byte[] key, + String sourceRevision, + byte[] replacement, + long ttlMillis, + int schemaVersion, + long writerGeneration) { + List arguments = + List.of( + sourceRevision.getBytes(StandardCharsets.US_ASCII), + replacement, + Long.toString(ttlMillis).getBytes(StandardCharsets.US_ASCII), + Integer.toString(schemaVersion).getBytes(StandardCharsets.US_ASCII), + Long.toString(writerGeneration).getBytes(StandardCharsets.US_ASCII)); + return replaceIfRevisionNewer + .evaluateForLong(commands, key, arguments) + .thenApply(applied -> applied != null && applied == 1L); + } } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java index e680d83c..c0c25158 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.cache; import dev.caskeleton.adapter.outbound.cache.redis.SemanticRedisCall; import dev.caskeleton.adapter.outbound.cache.redis.keyspace.CapabilityKeyspace; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; @@ -54,6 +55,12 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort keyDigest; @@ -103,6 +110,8 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort implements CacheRegionPort 0 ? ttl : softTtl; byte[] physicalKey = keys.entryKey(keyDigest.apply(key)); + boolean scripted = + intent == CacheRecordIntent.ONLY_IF_OBSERVED + || intent == CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER; // The write is marked sent only when the write command itself is handed to the driver. A // failure before that point — lane refusal, connection, the generation read — wrote nothing. - return call.run( - "record", - session -> { - resolveGeneration(session, now); - CacheEnvelope envelope = - new CacheEnvelope( - CacheEnvelope.CURRENT_SCHEMA_VERSION, - metadata.sourceRevision(), - keys.generation(), - now.plus(effectiveSoft), - now.plus(ttl), - absence, - payload); - session.markSent(); - Boolean applied = - metadata.intent() == CacheRecordIntent.ONLY_IF_OBSERVED - // Compare and replacement are one server-side execution. A GET followed by SET - // would let a concurrent writer land between them and then be overwritten by - // this stale source load. - ? session.await( - scripts.replaceIfObserved( - session.commands(), - physicalKey, - metadata.observedToken().value(), - envelope.encode(), - ttl.toMillis())) - // The physical TTL is the hard expiry and nothing else. - : session.await( - session - .commands() - .set(physicalKey, envelope.encode(), presenceOf(metadata.intent()), ttl)); - return Boolean.TRUE.equals(applied) - ? CacheRecordOutcome.RECORDED - : CacheRecordOutcome.NOT_RECORDED_CONDITION; - }, - () -> CacheRecordOutcome.DEGRADED_UNAVAILABLE, - () -> CacheRecordOutcome.INDETERMINATE); - } - - private static dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence - presenceOf(CacheRecordIntent intent) { - return intent == CacheRecordIntent.ONLY_IF_ABSENT - ? dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence.IF_ABSENT - : dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence.ALWAYS; + return (scripted ? scriptCall : call) + .run( + "record", + session -> { + resolveGeneration(session, now); + CacheEnvelope envelope = + new CacheEnvelope( + CacheEnvelope.CURRENT_SCHEMA_VERSION, + metadata.sourceRevision(), + keys.generation(), + now.plus(effectiveSoft), + now.plus(ttl), + absence, + payload); + session.markSent(); + // Each condition is checked and applied in one server-side execution. A GET followed + // by SET would let a concurrent writer land between them and then be overwritten by + // this stale source load. The physical TTL is the hard expiry and nothing else. + Boolean applied = + switch (intent) { + case ONLY_IF_OBSERVED -> + session.await( + scripts.replaceIfObserved( + session.commands(), + physicalKey, + metadata.observedToken().value(), + envelope.encode(), + ttl.toMillis())); + case ONLY_IF_SOURCE_REVISION_NEWER -> + session.await( + scripts.replaceIfRevisionNewer( + session.commands(), + physicalKey, + metadata.sourceRevision(), + envelope.encode(), + ttl.toMillis(), + CacheEnvelope.CURRENT_SCHEMA_VERSION, + keys.generation())); + case ONLY_IF_ABSENT -> + session.await( + session + .commands() + .set(physicalKey, envelope.encode(), WritePresence.IF_ABSENT, ttl)); + case UPSERT -> + session.await( + session + .commands() + .set(physicalKey, envelope.encode(), WritePresence.ALWAYS, ttl)); + }; + return Boolean.TRUE.equals(applied) + ? CacheRecordOutcome.RECORDED + : CacheRecordOutcome.NOT_RECORDED_CONDITION; + }, + () -> CacheRecordOutcome.DEGRADED_UNAVAILABLE, + () -> CacheRecordOutcome.INDETERMINATE); } @Override diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java index b0a0681e..b0ddddda 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java @@ -130,6 +130,56 @@ public final class IdempotencyScripts { return {'APPLIED', attempt, rev + 1, owner, '', ''} """; + /** + * Renew: extend the processing lease of an EXECUTING record, and nothing else. + * + *

Not the generic {@link #TRANSITION}. Renewal does not change the state, so the transition's + * "already in the target state" answer — which exists for a retry whose first reply was lost — + * would match every renewal before the revision was ever read, and the lease would never move. + * + *

A lost renewal reply is recognised by what the renewal itself recorded instead: the revision + * it started from and the lease it asked for. A retry from that revision with the same lease is + * the same renewal; with a different lease it is a different request, because confirming it would + * leave the caller believing it holds the record for a lease the record does not carry. + */ + private static final String RENEW = + """ + local state = redis.call('HGET', KEYS[1], 'state') + if state == false then + return {'ABSENT', 0, 0, '', '', ''} + end + local owner = redis.call('HGET', KEYS[1], 'owner') + local rev = tonumber(redis.call('HGET', KEYS[1], 'rev')) + local attempt = tonumber(redis.call('HGET', KEYS[1], 'attempt')) + local op = redis.call('HGET', KEYS[1], 'op') + if owner ~= ARGV[1] then + return {'NOT_OWNER', attempt, rev, owner, '', ''} + end + if op ~= ARGV[3] then + return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''} + end + local handleRev = tonumber(ARGV[2]) + if rev ~= handleRev then + if state == 'EXECUTING' and rev == handleRev + 1 + and redis.call('HGET', KEYS[1], 'renewedFromRev') == ARGV[2] then + if redis.call('HGET', KEYS[1], 'renewedLease') == ARGV[4] then + return {'ALREADY', attempt, rev, owner, '', ''} + end + return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''} + end + return {'NOT_OWNER', attempt, rev, owner, '', ''} + end + if state ~= 'EXECUTING' then + return {'WRONG_STATE', attempt, rev, owner, state, ''} + end + local t = redis.call('TIME') + local nowMillis = (tonumber(t[1]) * 1000) + math.floor(tonumber(t[2]) / 1000) + redis.call('HSET', KEYS[1], + 'leaseUntil', nowMillis + tonumber(ARGV[4]), 'rev', rev + 1, + 'renewedFromRev', ARGV[2], 'renewedLease', ARGV[4]) + return {'APPLIED', attempt, rev + 1, owner, '', ''} + """; + /** Release before execution: only from CLAIMED, and only by the owner that holds it. */ private static final String RELEASE = """ @@ -184,6 +234,7 @@ public final class IdempotencyScripts { private final RegisteredLuaScript claim = new RegisteredLuaScript(CLAIM); private final RegisteredLuaScript transition = new RegisteredLuaScript(TRANSITION); + private final RegisteredLuaScript renew = new RegisteredLuaScript(RENEW); private final RegisteredLuaScript release = new RegisteredLuaScript(RELEASE); private final RegisteredLuaScript inspect = new RegisteredLuaScript(INSPECT); @@ -196,6 +247,10 @@ public final class IdempotencyScripts { return run(transition, commands, key, arguments); } + CompletionStage renew(SemanticRedisCommands commands, byte[] key, List arguments) { + return run(renew, commands, key, arguments); + } + CompletionStage release( SemanticRedisCommands commands, byte[] key, List arguments) { return run(release, commands, key, arguments); diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java index a57aa348..16af2059 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java @@ -32,6 +32,8 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.concurrent.CompletionStage; +import java.util.function.Function; import java.util.function.Predicate; /** @@ -183,11 +185,19 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort public IdempotencyMutationResult renew( IdempotencyOwner ownerHandle, Duration processingLeaseTtl, OperationId operationId) { Objects.requireNonNull(processingLeaseTtl, "processing lease TTL must be non-null"); - return transition( + // Its own program, not the generic transition: EXECUTING -> EXECUTING is "already in the + // target state" to the transition, which answered ALREADY without ever extending the lease. + return ownerMutation( ownerHandle, - operationId, - new Transition( - "EXECUTING", "EXECUTING", "", Long.toString(processingLeaseTtl.toMillis()), ""), + session -> + scripts.renew( + session.commands(), + keys.recordKey(ownerHandle.scope()), + List.of( + ownerHandle.ownerToken(), + Long.toString(ownerHandle.stateRevision()), + operationId.value(), + Long.toString(processingLeaseTtl.toMillis()))), Map.of( ScriptStatus.APPLIED, IdempotencyRenewOutcome.RENEWED, ScriptStatus.ALREADY, IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION, @@ -429,15 +439,34 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort O indeterminate, O unavailable, Predicate carriesOwner) { + return ownerMutation( + ownerHandle, + session -> + scripts.transition( + session.commands(), + keys.recordKey(ownerHandle.scope()), + transition.arguments(ownerHandle, operationId)), + outcomes, + indeterminate, + unavailable, + carriesOwner); + } + + /** + * Runs one owner-checked program and maps its verdict, carrying the refreshed handle when the + * outcome leaves the caller still owning the record. + */ + private > IdempotencyMutationResult ownerMutation( + IdempotencyOwner ownerHandle, + Function> program, + Map outcomes, + O indeterminate, + O unavailable, + Predicate carriesOwner) { return call.effect( "transition", session -> { - IdempotencyScripts.Reply reply = - session.await( - scripts.transition( - session.commands(), - keys.recordKey(ownerHandle.scope()), - transition.arguments(ownerHandle, operationId))); + IdempotencyScripts.Reply reply = session.await(program.apply(session)); O outcome = outcomes.getOrDefault(reply.status(), indeterminate); return new IdempotencyMutationResult<>( outcome, diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java index dc898f50..00ddb74e 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java @@ -27,6 +27,8 @@ import dev.caskeleton.application.cache.CacheRegionPort; import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; +import dev.caskeleton.application.idempotency.IdempotencyOwner; +import dev.caskeleton.application.idempotency.IdempotencyRenewOutcome; import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.lease.LeaseAcquireOutcome; @@ -126,6 +128,83 @@ class LiveRedisSemanticPortsTest { assertThat(((CacheLookup.Hit) lookup).value()).isEqualTo("payload"); } + private CacheRegionPort conditionalCache() { + return new RedisCacheRegionAdapter<>( + runtime(true), + new RedisCacheRegionAdapter.CacheKeys(NAMESPACE, "orders", 1), + key -> "hv1:" + Integer.toHexString(key.hashCode()), + value -> value.getBytes(StandardCharsets.UTF_8), + stored -> new String(stored, StandardCharsets.UTF_8), + Clock.systemUTC(), + Duration.ofSeconds(30), + Duration.ofMinutes(5), + Duration.ofSeconds(10), + Duration.ofSeconds(2)); + } + + @Test + @DisplayName("실제 Redis에서 ONLY_IF_SOURCE_REVISION_NEWER는 저장된 것보다 작은 revision을 거부한다") + void theRevisionConditionRefusesAnOlderRevisionOnARealServer() { + // given + CacheRegionPort cache = conditionalCache(); + String key = "order-" + UUID.randomUUID(); + cache.record(key, "fresh", new CacheRecordMetadata("7", CacheRecordIntent.UPSERT)); + + // when + CacheRecordOutcome outcome = + cache.record( + key, + "stale", + new CacheRecordMetadata("6", CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER)); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + assertThat(((CacheLookup.Hit) cache.lookup(key)).value()).isEqualTo("fresh"); + } + + @Test + @DisplayName("실제 Redis에서 ONLY_IF_SOURCE_REVISION_NEWER는 숫자로 더 큰 revision을 기록한다") + void theRevisionConditionRecordsANumericallyNewerRevisionOnARealServer() { + // given + CacheRegionPort cache = conditionalCache(); + String key = "order-" + UUID.randomUUID(); + cache.record(key, "old", new CacheRecordMetadata("9", CacheRecordIntent.UPSERT)); + + // when + // DEGRADED_UNAVAILABLE or INDETERMINATE here means EVALSHA was refused on the lane it ran on. + CacheRecordOutcome outcome = + cache.record( + key, + "new", + new CacheRecordMetadata("10", CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER)); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED); + assertThat(((CacheLookup.Hit) cache.lookup(key)).value()).isEqualTo("new"); + } + + @Test + @DisplayName("실제 Redis의 ACL 계정 구성에서 ONLY_IF_OBSERVED 조건부 교체가 실행된다") + void theObservedConditionRunsUnderTheDeploymentAccounts() { + // given + CacheRegionPort cache = conditionalCache(); + String key = "order-" + UUID.randomUUID(); + cache.record(key, "first", new CacheRecordMetadata("rev-1", CacheRecordIntent.UPSERT)); + CacheLookup.Hit observed = (CacheLookup.Hit) cache.lookup(key); + + // when + // On the REGULAR lane the application account has no EVALSHA, and this degraded every time. + CacheRecordOutcome outcome = + cache.record( + key, + "second", + new CacheRecordMetadata( + "rev-2", CacheRecordIntent.ONLY_IF_OBSERVED, observed.observationToken())); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED); + } + // ========================================================================= // Rate limit / idempotency / lease: the script lane, the advanced account // ========================================================================= @@ -369,6 +448,51 @@ class LiveRedisSemanticPortsTest { .isInstanceOf(IdempotencyClaimOutcome.InProgress.class); } + @Test + @DisplayName("실제 Redis에서 renew한 처리 lease는 원래 lease가 지난 뒤에도 다른 claim을 막는다") + void aRenewedProcessingLeaseOutlivesTheOriginalLeaseOnARealServer() throws InterruptedException { + // given + RedisIdempotencyStoreAdapter store = + new RedisIdempotencyStoreAdapter( + runtime(true), + new RedisIdempotencyStoreAdapter.IdempotencyKeys(NAMESPACE, 1), + new IdempotencyScripts(), + Clock.systemUTC(), + Duration.ofSeconds(2)); + IdempotencyScopeDigest scope = + new IdempotencyScopeDigest( + UUID.randomUUID().toString().replace("-", "") + + UUID.randomUUID().toString().replace("-", ""), + 1, + "CHARGE_CARD"); + IdempotencyClaimAttempt first = store.newClaimAttempt(new OperationId("operation-renew-aaaa")); + IdempotencyOwner claimed = + ((IdempotencyClaimOutcome.Acquired) + store.claim( + new IdempotencyClaimRequest( + scope, + new RequestFingerprint("0".repeat(64)), + first, + Duration.ofSeconds(1), + Duration.ofHours(1), + "json-v2", + 1))) + .owner(); + IdempotencyOwner executing = + store.markExecutionStarted(claimed, first.operationId()).owner().orElseThrow(); + assertThat(store.renew(executing, Duration.ofSeconds(30), first.operationId()).outcome()) + .isEqualTo(IdempotencyRenewOutcome.RENEWED); + // Past the one-second lease the claim was taken with; Redis TIME decides, not this JVM. + Thread.sleep(1500); + + // when + IdempotencyClaimOutcome other = + store.claim(claim(scope, store.newClaimAttempt(new OperationId("operation-renew-bbbb")))); + + // then + assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class); + } + private static IdempotencyClaimRequest claim( IdempotencyScopeDigest scope, IdempotencyClaimAttempt attempt) { return new IdempotencyClaimRequest( diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java index 015d5b65..52cc6e8b 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java @@ -311,6 +311,123 @@ class RedisCacheRegionAdapterTest { .isEqualTo(CacheRecordOutcome.RECORDED); } + private static CacheRecordMetadata newerThan(String sourceRevision) { + return new CacheRecordMetadata(sourceRevision, CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER); + } + + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 저장된 것보다 작은 revision을 기록하지 않는다") + void onlyIfSourceRevisionNewerRefusesAnOlderRevision() { + // given + RedisCacheRegionAdapter cache = cache(T0); + cache.record("order-1", "fresh", new CacheRecordMetadata("7", CacheRecordIntent.UPSERT)); + + // when + // A slow loader that read the source at revision 6 finishes after the revision-7 write. + CacheRecordOutcome outcome = cache.record("order-1", "stale", newerThan("6")); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + assertThat(((CacheLookup.Hit) cache.lookup("order-1")).value()).isEqualTo("fresh"); + } + + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 저장된 것과 같은 revision을 기록하지 않는다") + void onlyIfSourceRevisionNewerRefusesTheSameRevision() { + // given + RedisCacheRegionAdapter cache = cache(T0); + cache.record("order-1", "first", new CacheRecordMetadata("7", CacheRecordIntent.UPSERT)); + + // when + CacheRecordOutcome outcome = cache.record("order-1", "second", newerThan("7")); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + assertThat(((CacheLookup.Hit) cache.lookup("order-1")).value()).isEqualTo("first"); + } + + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 더 큰 revision을 숫자 순서로 판단해 기록한다") + void onlyIfSourceRevisionNewerRecordsANumericallyNewerRevision() { + // given + RedisCacheRegionAdapter cache = cache(T0); + cache.record("order-1", "old", new CacheRecordMetadata("9", CacheRecordIntent.UPSERT)); + + // when + // "10" sorts before "9" as text. The order is numeric, or revision 10 could never replace 9. + CacheRecordOutcome outcome = cache.record("order-1", "new", newerThan("10")); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED); + CacheLookup.Hit hit = (CacheLookup.Hit) cache.lookup("order-1"); + assertThat(hit.value()).isEqualTo("new"); + assertThat(hit.sourceRevision()).isEqualTo("10"); + } + + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 비어 있는 키에 기록한다") + void onlyIfSourceRevisionNewerRecordsIntoAnAbsentKey() { + // given + RedisCacheRegionAdapter cache = cache(T0); + + // when + CacheRecordOutcome outcome = cache.record("order-1", "first", newerThan("1")); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED); + assertThat(((CacheLookup.Hit) cache.lookup("order-1")).value()).isEqualTo("first"); + } + + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 region 무효화 전 세대의 항목을 revision과 관계없이 교체한다") + void onlyIfSourceRevisionNewerReplacesAnEntryFromAnInvalidatedGeneration() { + // given + RedisCacheRegionAdapter cache = cache(T0); + cache.record("order-1", "before", new CacheRecordMetadata("9", CacheRecordIntent.UPSERT)); + cache.invalidateRegion(); + + // when + // The invalidated entry is semantically gone; its revision is no longer a fact to defend. + CacheRecordOutcome outcome = cache.record("order-1", "after", newerThan("3")); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED); + assertThat(((CacheLookup.Hit) cache.lookup("order-1")).value()).isEqualTo("after"); + } + + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 순서를 비교할 수 없는 저장 revision을 덮어쓰지 않는다") + void onlyIfSourceRevisionNewerRefusesWhenTheStoredRevisionIsNotComparable() { + // given + RedisCacheRegionAdapter cache = cache(T0); + cache.record("order-1", "upserted", upsert()); + + // when + // "rev-1" has no numeric order, so nothing proves revision 2 is newer than it. + CacheRecordOutcome outcome = cache.record("order-1", "conditional", newerThan("2")); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + assertThat(((CacheLookup.Hit) cache.lookup("order-1")).value()).isEqualTo("upserted"); + } + + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER에 10진 정수가 아닌 revision을 주면 Redis에 보내기 전에 거부한다") + void onlyIfSourceRevisionNewerRejectsARevisionWithoutANumericOrder() { + // given + RedisCacheRegionAdapter cache = cache(T0); + + // when + Throwable refused = + org.assertj.core.api.Assertions.catchThrowable( + () -> cache.record("order-1", "payload", newerThan("rev-2"))); + + // then + assertThat(refused) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ONLY_IF_SOURCE_REVISION_NEWER"); + } + @Test @DisplayName("an unreachable Redis degrades: the cache is bypassed, nothing fails") void anUnreachableRedisDegrades() { diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java index db1ca3d3..68129ffa 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java @@ -257,6 +257,116 @@ class RedisIdempotencyStoreAdapterTest { .isEqualTo(IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED); } + @Test + @DisplayName("renew는 RENEWED와 함께 더 새 revision의 owner 핸들을 돌려준다") + void renewReturnsAHandleAtTheNewRevision() { + // given + IdempotencyOwner executing = executing(); + + // when + var renewed = store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.RENEWED); + assertThat(renewed.owner().orElseThrow().stateRevision()) + .isGreaterThan(executing.stateRevision()); + } + + @Test + @DisplayName("renew한 처리 lease는 원래 lease가 지난 뒤에도 다른 요청의 claim을 IN_PROGRESS로 막는다") + void aRenewedLeaseStillExcludesAnotherClaimPastTheOriginalExpiry() { + // given + IdempotencyOwner executing = executing(); + gateway.advance(Duration.ofSeconds(20)); + store.renew(executing, Duration.ofSeconds(30), OPERATION); + // 40 seconds after the claim: past the original 30-second lease, inside the renewed one. + gateway.advance(Duration.ofSeconds(20)); + + // when + IdempotencyClaimOutcome other = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION))); + + // then + // TAKEN_OVER here would hand a running operation to a second worker: the effect happens twice. + assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class); + } + + @Test + @DisplayName("renew 응답을 잃고 같은 핸들로 다시 renew하면 ALREADY_RENEWED와 현재 revision 핸들을 받는다") + void aRenewRetriedAfterALostReplyIsAlreadyRenewed() { + // given + IdempotencyOwner executing = executing(); + var first = store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // when + // The first reply was lost, so the caller still holds the pre-renewal handle. + var retried = store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(retried.outcome()).isEqualTo(IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION); + assertThat(retried.owner().orElseThrow().stateRevision()) + .isEqualTo(first.owner().orElseThrow().stateRevision()); + } + + @Test + @DisplayName("lost reply 재시도가 다른 lease 길이를 요청하면 이미 적용된 renew로 확인하지 않는다") + void aRenewRetryAskingForADifferentLeaseIsAConflict() { + // given + IdempotencyOwner executing = executing(); + store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // when + var retried = store.renew(executing, Duration.ofSeconds(90), OPERATION); + + // then + // Confirming it would leave the caller believing it holds the record for 90 seconds. + assertThat(retried.outcome()).isEqualTo(IdempotencyRenewOutcome.OPERATION_CONFLICT); + } + + @Test + @DisplayName("renew한 뒤 받은 핸들로 complete할 수 있다") + void theRenewedHandleCanComplete() { + // given + IdempotencyOwner renewed = + store.renew(executing(), Duration.ofSeconds(30), OPERATION).owner().orElseThrow(); + + // when + IdempotencyCompleteOutcome outcome = + store.complete(renewed, new StoredResponse("{}"), Duration.ofHours(1), OPERATION); + + // then + assertThat(outcome).isEqualTo(IdempotencyCompleteOutcome.COMPLETED); + } + + @Test + @DisplayName("실행을 시작하지 않은 claim은 renew할 수 없다") + void renewBeforeExecutionStartedIsNotInProgress() { + // given + IdempotencyOwner claimed = + ((IdempotencyClaimOutcome.Acquired) store.claim(claim(store.newClaimAttempt(OPERATION)))) + .owner(); + + // when + var renewed = store.renew(claimed, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.NOT_IN_PROGRESS); + } + + @Test + @DisplayName("lease를 넘겨받은 뒤 이전 owner는 renew할 수 없다") + void aTakenOverOwnerCannotRenew() { + // given + IdempotencyOwner executing = executing(); + gateway.advance(Duration.ofSeconds(60)); + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION))); + + // when + var renewed = store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.NOT_OWNER); + } + @Test @DisplayName("an expired processing lease can be taken over, and the attempt increments") void anExpiredLeaseIsTakenOver() { diff --git a/src/adapter/outbound/httpclient/README.md b/src/adapter/outbound/httpclient/README.md index 778b4ccb..e061ed39 100644 --- a/src/adapter/outbound/httpclient/README.md +++ b/src/adapter/outbound/httpclient/README.md @@ -37,7 +37,10 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d ## What the platform decides for you - **Time.** One effective deadline covers pool acquire, DNS, connect, TLS, write, read, and every - retry backoff. Streaming splits setup, idle, and total lifetime. + retry backoff. It is checked before each attempt and also ends an attempt still in flight: Apache + cancels the request at the deadline, the JDK transport bounds its exchange timeout by the time + left, and the caller gets `HttpDeadlineExceededException`. Streaming splits setup, idle, and total + lifetime. - **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or `PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it. - **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline, @@ -45,6 +48,9 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d raises `HttpAmbiguousExecutionException` instead of being retried or reported as a plain failure. - **Order.** Every physical attempt passes Circuit Breaker → Rate Limiter → Bulkhead, and holds no permit while a backoff waits. +- **Circuit.** The breaker counts transport failures and 5xx, 408, and 429 against the upstream. + Any other 4xx (404, 409, 422 …) is a healthy answer, even when it reaches the caller as + `HttpRemoteErrorException`. - **Resources.** Connections and buffers are reclaimed after success, error, decode failure, size rejection, and cancellation alike. - **Secrets.** No URL, query value, path variable, token, cookie, or idempotency key reaches a log, diff --git a/src/adapter/outbound/httpclient/build.gradle b/src/adapter/outbound/httpclient/build.gradle index 8b0ebc83..bfda230a 100644 --- a/src/adapter/outbound/httpclient/build.gradle +++ b/src/adapter/outbound/httpclient/build.gradle @@ -237,6 +237,14 @@ strictTestLanes { // httpClientFailureInjectionTest (needs Docker), httpClientPerformanceTest (machine-dependent // bounds) and jmh (minutes) stay out deliberately. Attaching them would make `check` fail on a // laptop without Docker, which teaches people to skip `check`. +// spring70CompatibilityTest selects the same tagged suite httpClientStableContractTest runs in +// `check`, under the name the release gate and the support matrix quote. The main stage runs it so the +// name's fail-closed selection is proven before a release tag, not first on one (review 2026-11-01 +// 08-01). +tasks.named('mainCheck') { + dependsOn 'spring70CompatibilityTest' +} + tasks.named('check') { dependsOn 'httpClientStableContractTest', 'httpClientSecurityTest', diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheBlockingTransportProvider.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheBlockingTransportProvider.java index e8fe892e..2ac93ca4 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheBlockingTransportProvider.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheBlockingTransportProvider.java @@ -21,7 +21,6 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import org.springframework.http.client.ClientHttpRequestFactory; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; /** * Blocking default transport (design D-06, §13.4). @@ -84,7 +83,7 @@ public final class ApacheBlockingTransportProvider implements BlockingTransportP meterRegistry.ifPresent( registry -> ApachePoolMetricsBinder.bind(registry, profile.name(), runtime.pool())); listener.onRuntimeCreated(profile.name(), ID); - return new HttpComponentsClientHttpRequestFactory(runtime.client()); + return new DeadlineAwareApacheRequestFactory(runtime.client()); } /** Live pool statistics; the pool-saturation and leak suites assert on these. */ diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/DeadlineAwareApacheRequestFactory.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/DeadlineAwareApacheRequestFactory.java new file mode 100644 index 00000000..ab4f3c8a --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/DeadlineAwareApacheRequestFactory.java @@ -0,0 +1,34 @@ +package dev.caskeleton.adapter.outbound.httpclient.apache; + +import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline; +import java.net.URI; +import org.apache.hc.client5.http.classic.HttpClient; +import org.apache.hc.core5.concurrent.Cancellable; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; + +/** + * Spring's Apache request factory with every request cancellable at the attempt deadline. + * + *

The classic client's timeouts are all per-gap (connect, response header, socket read idle), so + * none of them bounds a slow-drip response. Apache's own answer is request cancellation: {@code + * HttpUriRequestBase.cancel()} cancels a pending pool lease or closes the leased connection + * immediately, which wakes the blocked read on the caller's thread. The request is registered with + * {@link AttemptDeadline} when it is created, on the caller's thread, inside the attempt scope. + */ +final class DeadlineAwareApacheRequestFactory extends HttpComponentsClientHttpRequestFactory { + + DeadlineAwareApacheRequestFactory(HttpClient httpClient) { + super(httpClient); + } + + @Override + protected ClassicHttpRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) { + ClassicHttpRequest request = super.createHttpUriRequest(httpMethod, uri); + if (request instanceof Cancellable cancellable) { + AttemptDeadline.abortOnExpiry(() -> cancellable.cancel()); + } + return request; + } +} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/dynamic/DefaultDynamicTargetGateway.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/dynamic/DefaultDynamicTargetGateway.java index b0321b3c..ae7a380c 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/dynamic/DefaultDynamicTargetGateway.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/dynamic/DefaultDynamicTargetGateway.java @@ -162,6 +162,7 @@ public final class DefaultDynamicTargetGateway implements DynamicTargetGateway { credentials, 1, runtime.support().clock().instant(), + deadline, metadata); } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java new file mode 100644 index 00000000..ce9ed51a --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java @@ -0,0 +1,44 @@ +package dev.caskeleton.adapter.outbound.httpclient.jdk; + +import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.time.Duration; +import java.util.Objects; +import java.util.concurrent.Executor; +import org.springframework.core.task.SimpleAsyncTaskExecutor; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.ClientHttpRequest; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.JdkClientHttpRequestFactory; + +/** + * Spring's JDK request factory with the exchange timeout bounded by the attempt deadline. + * + *

Spring's JDK request enforces its read timeout over the whole exchange: when it fires it + * cancels the pending response or closes the body stream, which also ends a slow-drip body. That + * timeout is fixed per factory, so a factory is made per request with {@code min(response-header + * timeout, remaining deadline)} from {@link AttemptDeadline}. The factory only holds references; + * the client and the write executor are shared. + */ +final class DeadlineAwareJdkRequestFactory implements ClientHttpRequestFactory { + + private final HttpClient client; + private final Executor writeExecutor; + private final Duration exchangeTimeout; + + DeadlineAwareJdkRequestFactory(HttpClient client, Duration exchangeTimeout) { + this.client = Objects.requireNonNull(client, "jdk http client"); + this.exchangeTimeout = Objects.requireNonNull(exchangeTimeout, "exchange timeout"); + // The executor Spring would pick itself, chosen once instead of once per request. + this.writeExecutor = client.executor().orElseGet(SimpleAsyncTaskExecutor::new); + } + + @Override + public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { + JdkClientHttpRequestFactory delegate = new JdkClientHttpRequestFactory(client, writeExecutor); + delegate.setReadTimeout(AttemptDeadline.bound(exchangeTimeout)); + return delegate.createRequest(uri, httpMethod); + } +} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkBlockingTransportProvider.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkBlockingTransportProvider.java index c7f1dde5..64fab27f 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkBlockingTransportProvider.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkBlockingTransportProvider.java @@ -16,7 +16,6 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import org.springframework.http.client.ClientHttpRequestFactory; -import org.springframework.http.client.JdkClientHttpRequestFactory; /** * Lightweight blocking alternative (design D-06, §13.5). @@ -62,8 +61,8 @@ public final class JdkBlockingTransportProvider implements BlockingTransportProv HttpClient client = clientFactory.create(profile, tlsMaterialResolver.apply(profile)); clients.put(new TransportResourceKey(profile.name(), generation), client); - JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(client); - factory.setReadTimeout(profile.timeout().responseHeader()); + ClientHttpRequestFactory factory = + new DeadlineAwareJdkRequestFactory(client, profile.timeout().responseHeader()); listener.onRuntimeCreated(profile.name(), ID); return factory; } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/CircuitBreakerStatusPolicy.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/CircuitBreakerStatusPolicy.java new file mode 100644 index 00000000..4815a55a --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/CircuitBreakerStatusPolicy.java @@ -0,0 +1,33 @@ +package dev.caskeleton.adapter.outbound.httpclient.resilience; + +import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus; +import java.util.Objects; + +/** + * Which upstream status codes the circuit breaker records as a failure (design §18.1). + * + *

The breaker protects callers from an upstream that is failing or overloaded. A status counts + * against the upstream only when it says exactly that: a 5xx, a 408 (the server gave up waiting), + * or a 429 (the server is shedding load). Every other 4xx is the upstream working correctly and + * answering a request it judged — a 404 for a missing record, a 409 for a conflict, a 422 for a + * rejected payload — and is recorded as a success. Counting those used to open the breaker on a + * perfectly healthy lookup API and reject every call of the profile for the breaker's wait time. + * + *

Transport failures (connect, timeout, reset) never reach this policy: they are exceptions, and + * the pipeline records every exception as a failure. + */ +public final class CircuitBreakerStatusPolicy { + + private static final int REQUEST_TIMEOUT = 408; + private static final int TOO_MANY_REQUESTS = 429; + + private CircuitBreakerStatusPolicy() {} + + /** Whether this status is evidence that the upstream itself is failing or overloaded. */ + public static boolean countsAsUpstreamFailure(HttpStatus status) { + Objects.requireNonNull(status, "status"); + return status.serverError() + || status.value() == REQUEST_TIMEOUT + || status.value() == TOO_MANY_REQUESTS; + } +} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java index 481fe677..09ee5c05 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.httpclient.restclient; import dev.caskeleton.adapter.outbound.httpclient.api.HttpMethod; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpClientException; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpFailureMetadata; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException; import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; @@ -11,9 +12,12 @@ import dev.caskeleton.adapter.outbound.httpclient.auth.RequestCredentials; import dev.caskeleton.adapter.outbound.httpclient.observation.AttemptObservation; import dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptOutcome; import dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptProgressTracker; +import dev.caskeleton.adapter.outbound.httpclient.resilience.CircuitBreakerStatusPolicy; +import dev.caskeleton.adapter.outbound.httpclient.resilience.Deadline; import dev.caskeleton.adapter.outbound.httpclient.resilience.ProtocolEvidence; import dev.caskeleton.adapter.outbound.httpclient.security.PreparedOperation; import dev.caskeleton.adapter.outbound.httpclient.security.PreparedTarget; +import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure; import java.net.URI; import java.time.Duration; @@ -44,9 +48,41 @@ public final class BlockingAttemptExecutor { RequestCredentials credentials, int attemptNumber, Instant startedAt, + Deadline deadline, HttpFailureMetadata baseMetadata) { Objects.requireNonNull(runtime, "runtime"); + Objects.requireNonNull(deadline, "deadline"); + ExecutionSupport support = runtime.support(); + // The deadline scope is what lets the effective deadline end an attempt that is already in + // flight. Before it, the deadline was only checked before an attempt started, and a slow-drip + // upstream kept a started attempt alive past the total budget for as long as no single gap + // reached a stage timeout. The transport reads the scope (see AttemptDeadline). + try (AttemptDeadline.Scope scope = AttemptDeadline.open(deadline.remaining(support.clock()))) { + return executeWithin( + scope, + runtime, + prepared, + responseType, + statusHandlingPolicy, + credentials, + attemptNumber, + startedAt, + baseMetadata); + } + } + + private AttemptOutcome executeWithin( + AttemptDeadline.Scope scope, + BlockingClientRuntime runtime, + PreparedOperation prepared, + ResponseType responseType, + StatusHandlingPolicy statusHandlingPolicy, + RequestCredentials credentials, + int attemptNumber, + Instant startedAt, + HttpFailureMetadata baseMetadata) { + ExecutionSupport support = runtime.support(); AttemptProgressTracker tracker = new AttemptProgressTracker(); AttemptObservation observation = @@ -108,18 +144,14 @@ public final class BlockingAttemptExecutor { tracker.firstByteDelivered()); } }, - outcome -> - outcome.failureCategory() == FailureCategory.REMOTE_STATUS - ? outcome.failure().map(failure -> (Throwable) failure) - : Optional.empty()); - stopObservation(observation, attemptOutcome); - return attemptOutcome; + BlockingAttemptExecutor::upstreamFailure); + return finish(observation, scope, attemptOutcome); } catch (HttpClientException stable) { - AttemptOutcome outcome = + return finish( + observation, + scope, AttemptOutcome.failed( - stable, stable.category(), Optional.empty(), tracker.firstByteDelivered()); - stopObservation(observation, outcome); - return outcome; + stable, stable.category(), Optional.empty(), tracker.firstByteDelivered())); } catch (RuntimeException engineFailure) { TransportFailure classified = runtime.failureClassifier().classify(engineFailure, tracker.stage()); @@ -137,14 +169,64 @@ public final class BlockingAttemptExecutor { .withStage(classified.stage()); HttpClientException mapped = support.exceptionMapper().map(classified, metadata, engineFailure); - AttemptOutcome outcome = + return finish( + observation, + scope, AttemptOutcome.failed( - mapped, classified.category(), Optional.empty(), tracker.firstByteDelivered()); - stopObservation(observation, outcome); - return outcome; + mapped, classified.category(), Optional.empty(), tracker.firstByteDelivered())); } } + /** + * Stops the observation with the attempt's outcome, naming the deadline when it ended the + * attempt. + * + *

A deadline abort reaches the executor as whatever the engine threw when its connection was + * closed — a reset, a truncated body, a read timeout. Reported as that, a caller would see a + * transport fault on a healthy upstream and the retry policy would judge the wrong cause. A + * failure that ends after the deadline passed is therefore reported as the deadline. Two outcomes + * keep their own meaning: a response that completed stays a success, and a complete error + * response (a remote status) stays the upstream's answer — both arrived, whatever the clock says. + */ + private AttemptOutcome finish( + AttemptObservation observation, AttemptDeadline.Scope scope, AttemptOutcome outcome) { + AttemptOutcome reported = outcome; + if (!outcome.successful() + && outcome.failureCategory() != FailureCategory.REMOTE_STATUS + && scope.expired()) { + HttpClientException cause = outcome.failure().orElseThrow(); + reported = + AttemptOutcome.failed( + new HttpDeadlineExceededException( + "effective deadline reached while the attempt was in flight", + cause.metadata(), + cause), + FailureCategory.DEADLINE_EXCEEDED, + Optional.empty(), + outcome.firstByteDelivered()); + } + stopObservation(observation, reported); + return reported; + } + + /** + * The failure the circuit breaker records for a returned outcome, if any. + * + *

Only a remote status that {@link CircuitBreakerStatusPolicy} counts against the upstream is + * a breaker failure. A 404 thrown to the caller as {@code HttpRemoteErrorException} is still a + * healthy answer for the breaker. + */ + private static Optional upstreamFailure(AttemptOutcome outcome) { + if (outcome.failureCategory() != FailureCategory.REMOTE_STATUS) { + return Optional.empty(); + } + boolean countsAgainstUpstream = + outcome.status().map(CircuitBreakerStatusPolicy::countsAsUpstreamFailure).orElse(true); + return countsAgainstUpstream + ? outcome.failure().map(failure -> (Throwable) failure) + : Optional.empty(); + } + private void stopObservation(AttemptObservation observation, AttemptOutcome outcome) { if (outcome.failureCategory() == FailureCategory.RESPONSE_TIMEOUT || outcome.failureCategory() == FailureCategory.POOL_ACQUIRE_TIMEOUT diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGateway.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGateway.java index 7aff3d2e..670b2a49 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGateway.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGateway.java @@ -173,6 +173,7 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway { credentials, attemptNumber, startedAt, + deadline, metadata.withAttempt(attemptNumber)); } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java new file mode 100644 index 00000000..bde2d067 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java @@ -0,0 +1,158 @@ +package dev.caskeleton.adapter.outbound.httpclient.transport; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +/** + * The time the physical attempt running on this thread has left before the logical call's effective + * deadline (design D-10, §15.2). + * + *

The gateway checks the deadline before an attempt starts, but a stage timeout only bounds one + * gap: an upstream that sends a byte every second never trips a three-second read-idle timeout and + * can hold the caller, its virtual thread and a pooled connection indefinitely. The gateway opens a + * {@link Scope} around each attempt and the transport — the only party that can actually stop an + * exchange — reads it: + * + *

    + *
  • a transport with a cancellable request registers the cancel with {@link + * #abortOnExpiry(Runnable)}, and the scope runs it when the deadline passes; + *
  • a transport whose engine already enforces a whole-exchange timeout bounds that timeout with + * {@link #bound(Duration)}. + *
+ * + *

The scope is thread-confined because a blocking attempt runs on the caller's thread from + * request creation to the last body byte. When no scope is open — a transport used outside the + * gateway — both methods leave the transport's own behaviour unchanged. + */ +public final class AttemptDeadline { + + private static final ThreadLocal CURRENT = new ThreadLocal<>(); + + private AttemptDeadline() {} + + /** + * Opens the deadline scope for one attempt on the current thread. + * + * @param remaining the time left before the logical call's effective deadline + */ + public static Scope open(Duration remaining) { + Objects.requireNonNull(remaining, "remaining deadline"); + Scope scope = new Scope(remaining.isNegative() ? Duration.ZERO : remaining, CURRENT.get()); + CURRENT.set(scope); + return scope; + } + + /** The current attempt's remaining time, or empty when no attempt scope is open. */ + public static Optional remaining() { + return Optional.ofNullable(CURRENT.get()).map(Scope::remaining); + } + + /** A stage timeout no longer than the current attempt's remaining time. */ + public static Duration bound(Duration stageTimeout) { + Objects.requireNonNull(stageTimeout, "stage timeout"); + return remaining() + .filter(remaining -> remaining.compareTo(stageTimeout) < 0) + .orElse(stageTimeout); + } + + /** + * Registers how to abort the exchange the current attempt is about to start. + * + *

Runs the abort at once if the deadline has already passed. Does nothing when no scope is + * open. + */ + public static void abortOnExpiry(Runnable abort) { + Objects.requireNonNull(abort, "abort"); + Scope scope = CURRENT.get(); + if (scope != null) { + scope.register(abort); + } + } + + /** One attempt's deadline; closing it cancels the pending abort and restores the outer scope. */ + public static final class Scope implements AutoCloseable { + + private final long endNanos; + private final Scope outer; + private final CompletableFuture timer = new CompletableFuture<>(); + private final CompletableFuture expiry; + private final List aborts = new ArrayList<>(); + private boolean fired; + private boolean closed; + + private Scope(Duration remaining, Scope outer) { + this.endNanos = System.nanoTime() + remaining.toNanos(); + this.outer = outer; + // The JDK's shared delay scheduler, the same one Spring's JDK request uses for its timeout. + // Completing the future on close() also cancels the scheduled task, so a finished attempt + // leaves nothing behind. + this.expiry = + timer + .completeOnTimeout(null, remaining.toNanos(), TimeUnit.NANOSECONDS) + .thenRun(this::expire); + } + + /** Whether the deadline passed while this attempt was running. */ + public boolean expired() { + synchronized (this) { + if (fired) { + return true; + } + } + return System.nanoTime() - endNanos >= 0; + } + + Duration remaining() { + long left = endNanos - System.nanoTime(); + return left > 0 ? Duration.ofNanos(left) : Duration.ZERO; + } + + private void register(Runnable abort) { + boolean runNow; + synchronized (this) { + runNow = fired; + if (!runNow && !closed) { + aborts.add(abort); + } + } + if (runNow) { + abort.run(); + } + } + + private void expire() { + List toRun; + synchronized (this) { + if (closed) { + return; + } + fired = true; + toRun = List.copyOf(aborts); + aborts.clear(); + } + toRun.forEach(Runnable::run); + } + + @Override + public void close() { + synchronized (this) { + closed = true; + aborts.clear(); + } + timer.complete(null); + expiry.cancel(false); + if (CURRENT.get() == this) { + if (outer == null) { + CURRENT.remove(); + } else { + CURRENT.set(outer); + } + } + } + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/CircuitBreakerStatusPolicyTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/CircuitBreakerStatusPolicyTest.java new file mode 100644 index 00000000..526850cd --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/CircuitBreakerStatusPolicyTest.java @@ -0,0 +1,41 @@ +package dev.caskeleton.adapter.outbound.httpclient.resilience; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class CircuitBreakerStatusPolicyTest { + + @ParameterizedTest(name = "{0} -> {1}") + @CsvSource({ + "400, false", + "401, false", + "403, false", + "404, false", + "409, false", + "410, false", + "422, false", + "408, true", + "429, true", + "500, true", + "501, true", + "502, true", + "503, true", + "504, true", + "599, true" + }) + @DisplayName("5xx·408·429만 상대 서버 장애로 세고 나머지 4xx는 정상 응답으로 센다") + void onlyServerSideStatusesCountAgainstTheUpstream(int status, boolean upstreamFailure) { + // given + HttpStatus answered = new HttpStatus(status); + + // when + boolean counted = CircuitBreakerStatusPolicy.countsAsUpstreamFailure(answered); + + // then + assertThat(counted).isEqualTo(upstreamFailure); + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/AttemptDeadlineEnforcementTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/AttemptDeadlineEnforcementTest.java new file mode 100644 index 00000000..70cba6c5 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/AttemptDeadlineEnforcementTest.java @@ -0,0 +1,81 @@ +package dev.caskeleton.adapter.outbound.httpclient.restclient; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; +import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType; +import dev.caskeleton.adapter.outbound.httpclient.profile.TimeoutSettings; +import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType; +import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; +import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; +import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; +import java.time.Duration; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +/** + * The total-call budget ends an attempt that is still in flight (finding 05-06, design D-10). + * + *

The upstream answers at once and then sends one body byte every 50 ms. No gap reaches the + * read-idle (3 s) or response-header (2 s) timeout, and the whole body would take 5 s, so only the + * one-second total budget can end the call on time. + */ +class AttemptDeadlineEnforcementTest { + + private static final Duration TOTAL_CALL = Duration.ofSeconds(1); + private static final Duration TOLERANCE = Duration.ofMillis(500); + + @ParameterizedTest(name = "{0}") + @EnumSource( + value = TransportType.class, + names = {"APACHE", "JDK"}) + @DisplayName("바이트를 조금씩 흘리는 상대 서버라도 호출은 전체 시간 예산 안에 deadline 초과로 끝난다") + void aSlowDripResponseIsCutOffAtTheTotalDeadline(TransportType transport) throws Exception { + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = + TestGateways.forProfile( + ClientProfiles.builder("slow") + .baseUrl(server.uri("/")) + .transport(transport) + .timeout(withTotalCall(TOTAL_CALL)) + .build())) { + // given + server.enqueueSlowDripBody(200, 100, Duration.ofMillis(50)); + long started = System.nanoTime(); + + // when + Throwable failure = + catchThrowable( + () -> + harness + .gateway() + .exchange( + harness.profile().name(), + HttpOperation.get(new OperationName("slow-read"), "/slow", Map.of()), + ResponseType.of(String.class))); + + // then + Duration elapsed = Duration.ofNanos(System.nanoTime() - started); + assertThat(failure).isInstanceOf(HttpDeadlineExceededException.class); + assertThat(elapsed).isLessThan(TOTAL_CALL.plus(TOLERANCE)); + } + } + + private static TimeoutSettings withTotalCall(Duration totalCall) { + TimeoutSettings base = ClientProfiles.timeouts(); + return new TimeoutSettings( + base.dns(), + base.connect(), + base.tlsHandshake(), + base.proxyConnect(), + base.requestWriteIdle(), + base.responseHeader(), + base.readIdle(), + totalCall); + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java new file mode 100644 index 00000000..c284d6af --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java @@ -0,0 +1,89 @@ +package dev.caskeleton.adapter.outbound.httpclient.restclient; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpCircuitOpenException; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; +import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType; +import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; +import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What the per-profile circuit breaker counts as an upstream failure, end to end (finding 05-05). + * + *

The library defaults are kept on purpose (a 100-call window, a 50% failure threshold), so 200 + * calls are enough to open the breaker twice over if a status were miscounted. + */ +class CircuitBreakerStatusAccountingTest { + + private static final int CALLS = 200; + private static final int LIBRARY_DEFAULT_WINDOW = 100; + + @Test + @DisplayName("정상 응답인 404가 200번 이어져도 circuit이 열리지 않고 모든 호출이 상대 서버에 닿는다") + void aRunOfNotFoundAnswersNeverOpensTheCircuit() throws Exception { + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = TestGateways.apache(server.uri("/"))) { + // given + for (int i = 0; i < CALLS; i++) { + server.enqueueStatus(404); + } + List failures = new ArrayList<>(); + + // when + for (int i = 0; i < CALLS; i++) { + failures.add(catchThrowable(() -> getUser(harness))); + } + + // then + assertThat(failures) + .hasSize(CALLS) + .allSatisfy( + failure -> + assertThat(failure) + .isExactlyInstanceOf(HttpRemoteErrorException.class) + .isNotInstanceOf(HttpCircuitOpenException.class)); + assertThat(server.requestCount()).isEqualTo(CALLS); + } + } + + @Test + @DisplayName("503이 창 하나를 채우면 circuit이 열려 다음 호출은 상대 서버에 보내지 않고 거절한다") + void aWindowOfServiceUnavailableAnswersOpensTheCircuit() throws Exception { + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = TestGateways.apache(server.uri("/"))) { + // given + List windowFailures = new ArrayList<>(); + for (int i = 0; i < LIBRARY_DEFAULT_WINDOW; i++) { + server.enqueueStatus(503); + windowFailures.add(catchThrowable(() -> getUser(harness))); + } + assertThat(windowFailures) + .allSatisfy(f -> assertThat(f).isInstanceOf(HttpRemoteErrorException.class)); + + // when + Throwable next = catchThrowable(() -> getUser(harness)); + + // then + assertThat(next).isInstanceOf(HttpCircuitOpenException.class); + assertThat(server.requestCount()).isEqualTo(LIBRARY_DEFAULT_WINDOW); + } + } + + private static void getUser(TestGateways.Harness harness) { + harness + .gateway() + .exchange( + harness.profile().name(), + HttpOperation.get(new OperationName("get-user"), "/users/1", Map.of()), + ResponseType.of(String.class)); + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java new file mode 100644 index 00000000..388bb2c6 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java @@ -0,0 +1,96 @@ +package dev.caskeleton.adapter.outbound.httpclient.transport; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class AttemptDeadlineTest { + + @Test + @DisplayName("attempt scope가 없으면 단계 timeout을 그대로 둔다") + void withoutAScopeTheStageTimeoutIsUnchanged() { + // given + Duration stage = Duration.ofSeconds(2); + + // when + Duration bounded = AttemptDeadline.bound(stage); + + // then + assertThat(bounded).isEqualTo(stage); + assertThat(AttemptDeadline.remaining()).isEmpty(); + } + + @Test + @DisplayName("남은 deadline이 단계 timeout보다 짧으면 단계 timeout을 남은 시간으로 줄인다") + void aShorterRemainingDeadlineBoundsTheStageTimeout() { + try (AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ofMillis(300))) { + // given + Duration stage = Duration.ofSeconds(2); + + // when + Duration bounded = AttemptDeadline.bound(stage); + + // then + assertThat(bounded).isLessThanOrEqualTo(Duration.ofMillis(300)).isPositive(); + assertThat(scope.expired()).isFalse(); + } + } + + @Test + @DisplayName("deadline이 지나면 등록된 중단 동작을 실행하고 scope는 만료로 보고한다") + void theRegisteredAbortRunsWhenTheDeadlinePasses() throws Exception { + try (AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ofMillis(50))) { + // given + CountDownLatch aborted = new CountDownLatch(1); + AttemptDeadline.abortOnExpiry(aborted::countDown); + + // when + boolean ran = aborted.await(2, TimeUnit.SECONDS); + + // then + assertThat(ran).isTrue(); + assertThat(scope.expired()).isTrue(); + } + } + + @Test + @DisplayName("deadline 전에 attempt가 끝나면 중단 동작은 실행되지 않고 scope도 풀린다") + void closingTheScopeBeforeTheDeadlineCancelsTheAbort() throws Exception { + // given + AtomicInteger aborts = new AtomicInteger(); + AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ofMillis(100)); + AttemptDeadline.abortOnExpiry(aborts::incrementAndGet); + + // when + scope.close(); + + // then + Thread.sleep(300); + assertThat(aborts).hasValue(0); + assertThat(AttemptDeadline.remaining()).isEmpty(); + } + + @Test + @DisplayName("이미 지난 deadline에 등록한 중단 동작은 바로 실행된다") + void anAbortRegisteredAfterExpiryRunsAtOnce() throws Exception { + try (AttemptDeadline.Scope scope = AttemptDeadline.open(Duration.ZERO)) { + // given + CountDownLatch expired = new CountDownLatch(1); + AttemptDeadline.abortOnExpiry(expired::countDown); + assertThat(expired.await(2, TimeUnit.SECONDS)).isTrue(); + AtomicInteger late = new AtomicInteger(); + + // when + AttemptDeadline.abortOnExpiry(late::incrementAndGet); + + // then + assertThat(late).hasValue(1); + assertThat(scope.expired()).isTrue(); + } + } +} diff --git a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/MockHttpServer.java b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/MockHttpServer.java index c13b8f58..ec333e96 100644 --- a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/MockHttpServer.java +++ b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/MockHttpServer.java @@ -151,6 +151,21 @@ public final class MockHttpServer implements AutoCloseable { .setBodyDelay(delay.toMillis(), TimeUnit.MILLISECONDS)); } + /** + * Sends headers at once, then the body one byte per {@code gap}; drives total-deadline tests. + * + *

Every gap stays shorter than any idle timeout a test profile uses, so only a whole-call + * budget can end the exchange before the body is complete. + */ + public void enqueueSlowDripBody(int status, int bodyBytes, Duration gap) { + server.enqueue( + new MockResponse() + .setResponseCode(status) + .setHeader("Content-Type", "text/plain") + .setBody("x".repeat(bodyBytes)) + .throttleBody(1, gap.toMillis(), TimeUnit.MILLISECONDS)); + } + public RecordedHttpRequest takeRequest(Duration timeout) throws InterruptedException { RecordedRequest recorded = server.takeRequest(timeout.toMillis(), TimeUnit.MILLISECONDS); if (recorded == null) { diff --git a/src/adapter/outbound/messaging/README.md b/src/adapter/outbound/messaging/README.md index 9d54608f..bdd68c58 100644 --- a/src/adapter/outbound/messaging/README.md +++ b/src/adapter/outbound/messaging/README.md @@ -31,9 +31,16 @@ seam과 그 위의 `MessagePublisher`·`OutboxEnvelopeJson`은 outbox를 canonic 있을 때만 생성된다. exact `ValidatedIntegrationEvent.envelopeBytes()`를 보존하고 platform의 중앙 publish pipeline을 탄다. producer id는 host/pod/process 이름에서 추측하지 않는다. -`OutboxMessagePublishAdapter`는 claim된 row의 validated event를 그대로 bridge에 넘기고 platform의 -네 가지 결과(CONFIRMED·AMBIGUOUS·REJECTED_BEFORE_SEND·REJECTED_AFTER_BROKER)를 relay에 돌려준다. -다시 직렬화하지 않는다. +`OutboxMessagePublishAdapter`는 claim된 row의 validated event를 그대로 bridge에 넘기고 platform +결과를 application 결과(CONFIRMED·AMBIGUOUS·REJECTED_BEFORE_SEND·REJECTED_AFTER_BROKER· +REJECTED_RETRYABLE)로 번역해 relay에 돌려준다. 다시 직렬화하지 않는다. + +platform `REJECTED` 중 `FailureDescriptor.retryable()`이 true인 것(종료 중 `SHUTTING_DOWN`, permit +대기 초과, `PUBLISH_RUNTIME_UNAVAILABLE`, `KAFKA_TRANSPORT_CLOSED`, Kafka 인증·인가 실패)은 +`REJECTED_RETRYABLE`로 번역한다. relay는 이 값을 DEAD로 보내지 않고 재시도한다. 확정 거부 두 값으로 +번역하면 "같은 payload는 또 거부된다"로 읽혀 커밋된 이벤트와 그 aggregate의 뒤 이벤트가 바로 +멈춘다(2026-11-01 리뷰 06-01). `AMBIGUOUS`로 번역하지 않은 이유: 동작은 같지만 "전송됐을 수 +있음"이라는 거짓 정보가 남아 중복 경고를 오염시킨다. ## outbox 발행 포트에는 대역이 없다 diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java index eb366e81..7f39a975 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java @@ -15,6 +15,7 @@ import dev.caskeleton.messaging.api.TenantContext; import dev.caskeleton.messaging.api.TraceContext; import dev.caskeleton.messaging.api.destination.DestinationName; import dev.caskeleton.messaging.api.destination.MessageDestination; +import dev.caskeleton.messaging.api.error.FailureDescriptor; import dev.caskeleton.messaging.api.header.HeaderName; import dev.caskeleton.messaging.api.header.HeaderValue; import dev.caskeleton.messaging.api.header.MessageHeaders; @@ -137,6 +138,16 @@ public final class PlatformIntegrationEventPublishAdapter implements Integration return new CausationId(canonicalMessageId(value)); } + /** + * Translates the platform's result into the application's outcome. + * + *

A platform rejection carries a {@code retryable} flag, and the platform sets it on refusals + * that are about the moment — shutting down, permits exhausted, transport closed, credentials + * refused. The application reads both of its definite rejections as "the same payload is refused + * again" and dead-letters at once, so a retryable rejection translated into one of them parks a + * committed event, and its aggregate behind it, for a cause that clears on its own. It gets its + * own value instead. + */ private static OutboxPublishOutcome mapOutcome(PublishResult result) { Objects.requireNonNull(result, "publish result must not be null"); if (result.completion() == PublishCompletion.CONFIRMED) { @@ -145,6 +156,9 @@ public final class PlatformIntegrationEventPublishAdapter implements Integration if (result.completion() == PublishCompletion.AMBIGUOUS) { return OutboxPublishOutcome.AMBIGUOUS; } + if (result.failure().map(FailureDescriptor::retryable).orElse(false)) { + return OutboxPublishOutcome.REJECTED_RETRYABLE; + } return result.evidence().transmission() == TransmissionEvidence.NOT_TRANSMITTED ? OutboxPublishOutcome.REJECTED_BEFORE_SEND : OutboxPublishOutcome.REJECTED_AFTER_BROKER; diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java index 12d6393c..5787930f 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java @@ -33,6 +33,7 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class PlatformIntegrationEventPublishAdapterTest { @@ -102,6 +103,50 @@ class PlatformIntegrationEventPublishAdapterTest { .isEqualTo(OutboxPublishOutcome.REJECTED_AFTER_BROKER); } + @Test + @DisplayName("platform이 다시 시도해도 된다고 표시한 거부는 확정 거부로 번역하지 않는다") + void aRefusalThePlatformMarksRetryableIsNotTranslatedIntoADefiniteRejection() { + // given: the runtime refused because it is shutting down, and said a retry may succeed + RecordingPublisher publisher = + new RecordingPublisher( + PublishResult.rejected( + Duration.ZERO, + FailureDescriptor.of( + FailureCategory.TRANSIENT_INFRASTRUCTURE, + "SHUTTING_DOWN", + "the messaging runtime stopped accepting new publishes"))); + PlatformIntegrationEventPublishAdapter bridge = + new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service"); + + // when + OutboxPublishOutcome outcome = + bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join(); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_RETRYABLE); + } + + @Test + @DisplayName("다시 시도해도 같은 결과인 거부는 지금처럼 확정 거부로 번역한다") + void aRefusalThePlatformMarksFinalStaysADefiniteRejection() { + // given: the runtime refused a destination this application may not publish to + RecordingPublisher publisher = + new RecordingPublisher( + PublishResult.rejected( + Duration.ZERO, + FailureDescriptor.of( + FailureCategory.CONFIGURATION, "PUBLISH_FORBIDDEN", "not allowed"))); + PlatformIntegrationEventPublishAdapter bridge = + new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service"); + + // when + OutboxPublishOutcome outcome = + bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join(); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND); + } + @Test void incompatibleApplicationIdentityFailsClosedBeforePublisherInvocation() { RecordingPublisher publisher = new RecordingPublisher(confirmed()); diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformWorkerConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformWorkerConfig.java index c7d75608..ba78083f 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformWorkerConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformWorkerConfig.java @@ -70,6 +70,10 @@ class NotificationPlatformWorkerConfig { reconciliation::reconcile, clock, properties.leaseDuration(), + // The claim lease reuses the delivery lease rather than adding a setting. One pass asks + // up to claimBatchSize providers in turn, so a pass slower than the lease lets another + // instance re-ask its remaining jobs; the claim fence keeps those answers recorded once. + properties.leaseDuration(), properties.claimBatchSize(), properties.maxAdditionalAttempts() + 1); } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ReconciliationJobWorker.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ReconciliationJobWorker.java index 807b6f1d..7d6c7490 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ReconciliationJobWorker.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ReconciliationJobWorker.java @@ -22,6 +22,11 @@ import java.util.function.Function; * will not change, so the job is completed and the attempt stays visibly ambiguous for an operator * — a busy loop against a capability that does not exist is how a background worker burns a * connection pool while achieving nothing. + * + *

Every instance runs this worker, so the claim is a lease: the jobs a pass takes are this + * instance's until {@code claimLease} has passed, and no transaction is held while the provider is + * asked. A pass that outlives its lease may find a job taken over by another instance; the store + * then ignores this pass's write for it, so the job is asked about twice but recorded once. */ public final class ReconciliationJobWorker { @@ -32,6 +37,7 @@ public final class ReconciliationJobWorker { reconciler; private final Clock clock; private final Duration retryBackoff; + private final Duration claimLease; private final int batchSize; private final int maxAttempts; @@ -42,6 +48,7 @@ public final class ReconciliationJobWorker { * @param reconciler asks one attempt's provider * @param clock the clock * @param retryBackoff how long to wait before asking again + * @param claimLease how long one pass owns the jobs it claimed; must cover the whole pass * @param batchSize how many jobs one pass handles * @param maxAttempts how many times one job may ask before it is left to an operator */ @@ -53,6 +60,7 @@ public final class ReconciliationJobWorker { reconciler, Clock clock, Duration retryBackoff, + Duration claimLease, int batchSize, int maxAttempts) { this.jobs = Objects.requireNonNull(jobs, "jobs"); @@ -62,6 +70,10 @@ public final class ReconciliationJobWorker { if (retryBackoff.isNegative() || retryBackoff.isZero()) { throw new IllegalArgumentException("retryBackoff must be positive and finite"); } + this.claimLease = Objects.requireNonNull(claimLease, "claimLease"); + if (claimLease.isNegative() || claimLease.isZero()) { + throw new IllegalArgumentException("claimLease must be positive"); + } if (batchSize < 1) { throw new IllegalArgumentException("batchSize"); } @@ -78,7 +90,7 @@ public final class ReconciliationJobWorker { * @return how many jobs reached a terminal decision */ public int reconcileOnce() { - List due = jobs.claimDue(batchSize, clock.instant()); + List due = jobs.claimDue(batchSize, clock.instant(), claimLease); int settled = 0; for (ReconciliationJob job : due) { // One job's failure is not the pass's: a provider that is refusing connections would diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ReconciliationJobWorkerTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ReconciliationJobWorkerTest.java index e54982d6..ad25e7bd 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ReconciliationJobWorkerTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ReconciliationJobWorkerTest.java @@ -33,12 +33,14 @@ class ReconciliationJobWorkerTest { private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final Duration CLAIM_LEASE = Duration.ofMinutes(2); private final RecordingJobs jobs = new RecordingJobs(); private final Map answers = new java.util.HashMap<>(); private final ReconciliationJobWorker worker = - new ReconciliationJobWorker(jobs, answers::get, CLOCK, Duration.ofMinutes(5), 10, 3); + new ReconciliationJobWorker( + jobs, answers::get, CLOCK, Duration.ofMinutes(5), CLAIM_LEASE, 10, 3); @Test @DisplayName("a confirmed outcome completes the job") @@ -125,6 +127,21 @@ class ReconciliationJobWorkerTest { assertThat(jobs.rescheduled.get(0).getKey()).isEqualTo(failing.id()); } + @Test + @DisplayName("한 번의 pass는 설정된 lease 동안 소유하도록 job을 claim한다") + void aPassClaimsItsJobsForTheConfiguredLease() { + // given + due(0); + + // when + worker.reconcileOnce(); + + // then + assertThat(jobs.claimLeases) + .as("without a lease the claim ends with the statement and every instance takes the job") + .containsExactly(CLAIM_LEASE); + } + private ReconciliationJob due(int attempts) { ReconciliationJob job = new ReconciliationJob( @@ -135,7 +152,8 @@ class ReconciliationJobWorkerTest { attempts, Optional.empty(), NOW, - NOW); + NOW, + 1); jobs.due.add(job); return job; } @@ -155,6 +173,7 @@ class ReconciliationJobWorkerTest { private final List due = new ArrayList<>(); private final List completed = new ArrayList<>(); private final List> rescheduled = new ArrayList<>(); + private final List claimLeases = new ArrayList<>(); @Override public ReconciliationJob schedule( @@ -163,7 +182,8 @@ class ReconciliationJobWorkerTest { } @Override - public List claimDue(int limit, Instant now) { + public List claimDue(int limit, Instant now, Duration lease) { + claimLeases.add(lease); return List.copyOf(due); } diff --git a/src/adapter/outbound/objectstorage/README.md b/src/adapter/outbound/objectstorage/README.md index bef00175..59841f81 100644 --- a/src/adapter/outbound/objectstorage/README.md +++ b/src/adapter/outbound/objectstorage/README.md @@ -91,3 +91,30 @@ composition side effects/lifecycle, routing replay/read behavior, and the readin cd src ./gradlew :adapter:outbound:objectstorage:check --console=plain ``` + +### MinIO qualification lanes + +`objectStorageMinioContractTest` and `objectStorageMinioFaultTest` (in `mainCheck`) run a real MinIO +and Toxiproxy. Their images are read from one file, +`src/test/resources/object-storage/minio-provider-evidence.json`, whose `image` digest is the +release the `status`, `excludedProfiles` and `limitations` beside it were measured on. +`MinioQualificationImage` (in `src/test`, checked by the leaf's `test` without Docker) reads it. + +- The image is pulled before any container is built. If it cannot be pulled the lane fails with + `pinned image unavailable: `: a supply failure, not an adapter defect. The lane does + not skip, because a skipped vendor lane would be green with no vendor evidence. +- A mirror of the same digest is set with `OBJECT_STORAGE_MINIO_IMAGE` or + `-PobjectStorageMinioImage=/@sha256:`. A value that does not end + in the evidence digest is refused: a different build is a new measurement, made by re-running the + lanes and rewriting the evidence file (image and findings together). +- The local compose runtime (`docker-compose.infra.yml`, `LOCAL_MINIO_IMAGE`) is a different, later + release and is not evidence; the comment there says why. + +As of 2026-11-01 a pull of `minio/minio` from Docker Hub answers "repository does not exist", so +these lanes fail with the message above until a mirror or a re-measured replacement is chosen +(review 05-09; the choice is an open owner decision). + +```bash +cd src +./gradlew :adapter:outbound:objectstorage:objectStorageMinioContractTest --console=plain +``` diff --git a/src/adapter/outbound/objectstorage/build.gradle b/src/adapter/outbound/objectstorage/build.gradle index 313b706f..f0c2a4f3 100644 --- a/src/adapter/outbound/objectstorage/build.gradle +++ b/src/adapter/outbound/objectstorage/build.gradle @@ -35,6 +35,12 @@ testing { } } } +// The MinIO lanes read their images from the one evidence file in src/test/resources +// (object-storage/minio-provider-evidence.json) through MinioQualificationImage in src/test, which +// the leaf's `test` checks without Docker. The integration runtime therefore sees the test output; +// its own tests are still only the classes each lane `requires`. +sourceSets.integrationTest.compileClasspath += sourceSets.test.output +sourceSets.integrationTest.runtimeClasspath += sourceSets.test.output configurations { integrationTestImplementation.extendsFrom testImplementation integrationTestRuntimeOnly.extendsFrom testRuntimeOnly @@ -82,14 +88,24 @@ tasks.named('test') { systemProperty 'objectstorage.readiness.registry', objectStorageReadinessRegistry.absolutePath } +// A mirror of the measured MinIO digest, for when the origin registry stops serving it (review +// 05-09). Either spelling reaches the lanes as one system property; MinioQualificationImage refuses +// a value that does not end in the evidence digest, because another build is a new measurement and +// is made by editing the evidence file, not by an override. +def minioImageOverride = (findProperty('objectStorageMinioImage') + ?: providers.environmentVariable('OBJECT_STORAGE_MINIO_IMAGE').getOrElse('')).toString() + strictTestLanes { lane('objectStorageMinioContractTest') { integration() sourceSet = 'integrationTest' - description = 'Runs the non-skipping exact-release MinIO managed object contract.' + description = 'Runs the non-skipping MinIO managed object contract on the evidence-pinned image.' requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectContractTest' rejectSkipped = true jvmArgs '-Duser.timezone=UTC' + if (minioImageOverride) { + systemProperty 'objectstorage.minio.image', minioImageOverride + } shouldRunAfter 'test' } lane('objectStorageMinioFaultTest') { @@ -99,6 +115,9 @@ strictTestLanes { requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectFaultTest' rejectSkipped = true jvmArgs '-Duser.timezone=UTC' + if (minioImageOverride) { + systemProperty 'objectstorage.minio.image', minioImageOverride + } shouldRunAfter 'objectStorageMinioContractTest' } lane('objectStorageAwsQualificationTest') { diff --git a/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectContractTest.java b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectContractTest.java index 66fe6062..2e37a796 100644 --- a/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectContractTest.java +++ b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectContractTest.java @@ -17,7 +17,6 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; -import org.testcontainers.utility.DockerImageName; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.async.AsyncRequestBody; @@ -48,8 +47,6 @@ import software.amazon.awssdk.services.s3.model.VersioningConfiguration; class MinioManagedObjectContractTest { - private static final String MINIO_IMAGE = - "minio/minio@sha256:4c4a4876193f030c81f57aabb22bcb9a73462010eb61fcab66908e03e5484af8"; private static final String REGION = "us-east-1"; private static final String BUCKET = "object-storage-contract"; private static final String VERSIONED_BUCKET = "object-storage-versioned"; @@ -68,7 +65,7 @@ class MinioManagedObjectContractTest { SECURE_RANDOM.nextBytes(keyBytes); String kmsKey = "contract-key:" + Base64.getEncoder().encodeToString(keyBytes); minio = - new GenericContainer<>(DockerImageName.parse(MINIO_IMAGE)) + new GenericContainer<>(QualificationImages.minio()) .withExposedPorts(9000) .withEnv("MINIO_ROOT_USER", accessKey) .withEnv("MINIO_ROOT_PASSWORD", secretKey) diff --git a/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectFaultTest.java b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectFaultTest.java index 668cb4d0..3854de1a 100644 --- a/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectFaultTest.java +++ b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectFaultTest.java @@ -34,25 +34,18 @@ class MinioManagedObjectFaultTest { private static final String CUT_CONNECTION_DOWNSTREAM = "CUT_CONNECTION_DOWNSTREAM"; private static final String CUT_CONNECTION_UPSTREAM = "CUT_CONNECTION_UPSTREAM"; - private static final DockerImageName MINIO_IMAGE = - DockerImageName.parse( - "minio/minio@sha256:4c4a4876193f030c81f57aabb22bcb9a73462010eb61fcab66908e03e5484af8"); - private static final DockerImageName TOXIPROXY_IMAGE = - DockerImageName.parse( - "ghcr.io/shopify/toxiproxy@sha256:" - + "9378ed52a28bc50edc1350f936f518f31fa95f0d15917d6eb40b8e376d1a214e") - .asCompatibleSubstituteFor("shopify/toxiproxy"); - // Every container below is declared in try-with-resources; the fluent `withX` chain returns the // same instance, which the compiler reads as a second, unclosed resource. @SuppressWarnings("resource") @Test void connectionCutProducesABoundedFailureAndRecoveryWithoutMutationReplay() throws Exception { + DockerImageName minioImage = QualificationImages.minio(); + DockerImageName toxiproxyImage = QualificationImages.toxiproxy(); String accessKey = "a" + UUID.randomUUID().toString().replace("-", ""); String secretKey = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID(); try (Network network = Network.newNetwork(); GenericContainer minio = - new GenericContainer<>(MINIO_IMAGE) + new GenericContainer<>(minioImage) .withNetwork(network) .withNetworkAliases("qualified-minio") .withExposedPorts(9000) @@ -60,7 +53,7 @@ class MinioManagedObjectFaultTest { .withEnv("MINIO_ROOT_PASSWORD", secretKey) .withCommand("server", "/data"); ToxiproxyContainer toxiproxy = - new ToxiproxyContainer(TOXIPROXY_IMAGE) + new ToxiproxyContainer(toxiproxyImage) .withNetwork(network) .withExposedPorts(TOXIPROXY_CONTROL_PORT, TOXIPROXY_PROXY_PORT)) { minio.start(); diff --git a/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/QualificationImages.java b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/QualificationImages.java new file mode 100644 index 00000000..f4b95cbb --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/QualificationImages.java @@ -0,0 +1,34 @@ +package dev.caskeleton.adapter.outbound.objectstorage.qualification; + +import org.testcontainers.images.RemoteDockerImage; +import org.testcontainers.utility.DockerImageName; + +/** + * The MinIO lanes' images, pulled before any container is built. + * + *

The references come from the evidence file through {@link MinioQualificationImage}; this class + * only supplies the pull, Testcontainers' own image resolution, so a missing image fails here as + * {@code pinned image unavailable: } instead of inside a container start. + */ +final class QualificationImages { + + private QualificationImages() {} + + // Loaded per call, not in a static initializer: a refused override then reads as its own + // message instead of an ExceptionInInitializerError. + static DockerImageName minio() { + MinioQualificationImage images = MinioQualificationImage.load(); + return pulled(images, images.minio()); + } + + static DockerImageName toxiproxy() { + MinioQualificationImage images = MinioQualificationImage.load(); + return pulled(images, images.toxiproxy()).asCompatibleSubstituteFor("shopify/toxiproxy"); + } + + private static DockerImageName pulled(MinioQualificationImage images, String reference) { + return DockerImageName.parse( + images.requireAvailable( + reference, ref -> new RemoteDockerImage(DockerImageName.parse(ref)).get())); + } +} diff --git a/src/adapter/outbound/objectstorage/src/integrationTest/resources/object-storage/minio-provider-evidence.json b/src/adapter/outbound/objectstorage/src/integrationTest/resources/object-storage/minio-provider-evidence.json deleted file mode 100644 index f4e41f21..00000000 --- a/src/adapter/outbound/objectstorage/src/integrationTest/resources/object-storage/minio-provider-evidence.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "schema": 1, - "providerType": "s3-compatible-minio-community-release-2024-01-16t16-07-38z", - "providerVersion": "release-2024-01-16t16-07-38z-sdk-2.30.0", - "image": "minio/minio@sha256:4c4a4876193f030c81f57aabb22bcb9a73462010eb61fcab66908e03e5484af8", - "toxiproxyImage": "ghcr.io/shopify/toxiproxy@sha256:9378ed52a28bc50edc1350f936f518f31fa95f0d15917d6eb40b8e376d1a214e", - "profile": "managed-common", - "status": "UNSUPPORTED", - "excludedProfiles": [ - "managed-single-create-only", - "conditional-control-create", - "managed-multipart-create-only", - "direct-single-create-only", - "direct-multipart-create-only" - ], - "limitations": [ - "PutObject If-None-Match was accepted and overwrote an existing object", - "stale PutObject If-Match returned HTTP 412 but create-if-absent control CAS is not safe", - "CompleteMultipartUpload accepted If-None-Match despite a pre-existing target and overwrote it", - "managed immutable create, conditional control creation, and multipart create-only are disabled", - "local single-node container evidence only", - "not AWS evidence", - "not production TLS or deployment-topology evidence" - ] -} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioQualificationImage.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioQualificationImage.java new file mode 100644 index 00000000..ee804ae2 --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioQualificationImage.java @@ -0,0 +1,138 @@ +package dev.caskeleton.adapter.outbound.objectstorage.qualification; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.Optional; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * The images the MinIO qualification lanes run, read from the one file that records what they were + * measured on. + * + *

{@code object-storage/minio-provider-evidence.json} is the source: its {@code image} is the + * release the {@code status}, {@code excludedProfiles} and {@code limitations} beside it describe. + * The contract and fault lanes used to repeat that digest in their own constants, and the evidence + * file existed twice (test and integrationTest). When Docker Hub stopped serving the repository + * there were four places to change and nothing to say they had to agree. + * + *

An operator may point the lane at a mirror with {@value #OVERRIDE_PROPERTY} or {@value + * #OVERRIDE_ENV}, but only at the same digest: a mirror of the measured bytes keeps the evidence + * true, any other build does not. A different build is a new measurement, so it is made by editing + * the evidence file — image and findings together — not by an override that would leave the old + * findings standing against new bytes. + * + *

A pull that fails is reported as {@link PinnedImageUnavailableException} before any container + * starts, so a vanished image reads as a supply failure and not as a broken adapter. The lane still + * fails; skipping would turn missing vendor evidence green. + */ +final class MinioQualificationImage { + + static final String OVERRIDE_PROPERTY = "objectstorage.minio.image"; + static final String OVERRIDE_ENV = "OBJECT_STORAGE_MINIO_IMAGE"; + private static final String EVIDENCE_RESOURCE = "/object-storage/minio-provider-evidence.json"; + private static final String EVIDENCE_FILE = "minio-provider-evidence.json"; + + private final String minio; + private final String toxiproxy; + + private MinioQualificationImage(String minio, String toxiproxy) { + this.minio = minio; + this.toxiproxy = toxiproxy; + } + + /** The committed evidence, with the operator's mirror if one is set. */ + static MinioQualificationImage load() { + return load(operatorOverride()); + } + + static MinioQualificationImage load(Optional override) { + try (InputStream in = MinioQualificationImage.class.getResourceAsStream(EVIDENCE_RESOURCE)) { + if (in == null) { + throw new IllegalStateException("evidence resource missing: " + EVIDENCE_RESOURCE); + } + return fromEvidence(new String(in.readAllBytes(), StandardCharsets.UTF_8), override); + } catch (IOException failure) { + throw new UncheckedIOException("cannot read " + EVIDENCE_RESOURCE, failure); + } + } + + static MinioQualificationImage fromEvidence(String json, Optional override) { + JsonNode evidence = JsonMapper.builder().build().readTree(json); + String measured = requireDigestPinned(evidence, "image"); + String toxiproxy = requireDigestPinned(evidence, "toxiproxyImage"); + String digest = digestOf(measured); + String minio = + override + .map(String::strip) + .filter(value -> !value.isEmpty()) + .map( + mirror -> { + if (!mirror.endsWith("@" + digest)) { + throw new IllegalStateException( + "MinIO image override " + + mirror + + " does not carry the evidence digest " + + digest + + ". A mirror must serve the measured bytes; a different build needs " + + "re-measured evidence written to " + + EVIDENCE_FILE + + " (image, status, excludedProfiles and limitations together)."); + } + return mirror; + }) + .orElse(measured); + return new MinioQualificationImage(minio, toxiproxy); + } + + String minio() { + return minio; + } + + String toxiproxy() { + return toxiproxy; + } + + /** + * Pulls {@code reference} (a no-op when it is already local) and returns it, or fails with a + * message that names the supply failure rather than whatever the container start would have + * thrown. + */ + String requireAvailable(String reference, ImagePull pull) { + try { + pull.pull(reference); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new PinnedImageUnavailableException(reference, interrupted); + } catch (Exception failure) { + throw new PinnedImageUnavailableException(reference, failure); + } + return reference; + } + + private static Optional operatorOverride() { + return Optional.ofNullable(System.getProperty(OVERRIDE_PROPERTY)) + .or(() -> Optional.ofNullable(System.getenv(OVERRIDE_ENV))); + } + + private static String requireDigestPinned(JsonNode evidence, String field) { + String reference = evidence.path(field).asString(""); + if (!reference.matches("[^@\\s]+@sha256:[0-9a-f]{64}")) { + throw new IllegalStateException( + EVIDENCE_FILE + " field " + field + " must pin an image by sha256 digest: " + reference); + } + return reference; + } + + private static String digestOf(String reference) { + return reference.substring(reference.indexOf('@') + 1); + } + + /** The pull step; the lanes pass Testcontainers' image resolution, unit tests a stand-in. */ + @FunctionalInterface + interface ImagePull { + void pull(String reference) throws Exception; + } +} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioQualificationImageTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioQualificationImageTest.java new file mode 100644 index 00000000..7c5295be --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioQualificationImageTest.java @@ -0,0 +1,105 @@ +package dev.caskeleton.adapter.outbound.objectstorage.qualification; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class MinioQualificationImageTest { + + private static final String DIGEST = + "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private static final String EVIDENCE = + """ + { + "image": "minio/minio@%s", + "toxiproxyImage": "ghcr.io/shopify/toxiproxy@sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + } + """ + .formatted(DIGEST); + + @Test + void anImageThatCannotBePulledFailsAsPinnedImageUnavailableRatherThanAsACodeDefect() { + // given + MinioQualificationImage images = + MinioQualificationImage.fromEvidence(EVIDENCE, Optional.empty()); + RuntimeException registryAnswer = new RuntimeException("repository does not exist"); + + // when + Throwable thrown = + catchThrowable( + () -> + images.requireAvailable( + images.minio(), + reference -> { + throw registryAnswer; + })); + + // then + assertThat(thrown) + .isInstanceOf(PinnedImageUnavailableException.class) + .hasMessage("pinned image unavailable: minio/minio@" + DIGEST) + .hasCause(registryAnswer); + } + + @Test + void aPulledImageIsTheReferenceTheContainerStartsFrom() { + // given + MinioQualificationImage images = + MinioQualificationImage.fromEvidence(EVIDENCE, Optional.empty()); + + // when + String started = images.requireAvailable(images.minio(), reference -> {}); + + // then + assertThat(started).isEqualTo("minio/minio@" + DIGEST); + } + + @Test + void aMirrorOverrideCarryingTheEvidenceDigestReplacesTheRegistry() { + // given + String mirror = "registry.example.internal/mirror/minio@" + DIGEST; + + // when + MinioQualificationImage images = + MinioQualificationImage.fromEvidence(EVIDENCE, Optional.of(mirror)); + + // then + assertThat(images.minio()).isEqualTo(mirror); + } + + @ParameterizedTest + @ValueSource( + strings = { + "minio/minio@sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "minio/minio:RELEASE.2024-01-16T16-07-38Z" + }) + void anOverrideThatDoesNotCarryTheEvidenceDigestIsRejectedUntilTheEvidenceIsRemeasured( + String override) { + // when + Throwable thrown = + catchThrowable(() -> MinioQualificationImage.fromEvidence(EVIDENCE, Optional.of(override))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessageContainingAll( + override, + "does not carry the evidence digest " + DIGEST, + "minio-provider-evidence.json"); + } + + @Test + void theCommittedEvidencePinsBothQualificationImagesByDigest() { + // when + MinioQualificationImage images = MinioQualificationImage.load(Optional.empty()); + + // then + assertThat(List.of(images.minio(), images.toxiproxy())) + .allMatch(reference -> reference.matches("[^@\\s]+@sha256:[0-9a-f]{64}")); + } +} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/PinnedImageUnavailableException.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/PinnedImageUnavailableException.java new file mode 100644 index 00000000..bb392709 --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/PinnedImageUnavailableException.java @@ -0,0 +1,9 @@ +package dev.caskeleton.adapter.outbound.objectstorage.qualification; + +final class PinnedImageUnavailableException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + PinnedImageUnavailableException(String reference, Throwable cause) { + super("pinned image unavailable: " + reference, cause); + } +} diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index 9417ed80..195b0df4 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -278,6 +278,14 @@ framework-neutral `shared.error.PersistenceFailureException` carrying one of the | `23513` | `DB_CHECK_VIOLATION` | H2 (`.h2` package) — H2 reports CHECK as 23513, not the standard 23514 the core table maps | | `HYT00` | `DB_QUERY_CANCELED` | H2 — H2 collapses statement and lock timeout into one state | +**Commit phase (`translateCommitFailure`, ADR-JPA-003):** once the action has returned and +`SpringTransaction` is committing a write transaction it began, a failure with `08*`, `40003`, a +vendor-contributed termination state (`SqlStateErrorMapping.commitOutcomeUnknownStates()`: +PostgreSQL `57P01`, `57P02`) or a transport break with no SQLState becomes +`TransactionCompletionUnknownException` → `DB_COMPLETION_UNKNOWN` (500, never retryable), not +`DB_UNAVAILABLE`: the server may already have committed. A commit the server definitely rejected +(e.g. a deferred `23505`) keeps its row above; a read-only commit keeps `DB_UNAVAILABLE`. + - A repository adapter that catches a `DataAccessException` calls `translator.translate(ex)` and rethrows the carrier (`ifPresent(e -> { throw e; })`); an empty result means an unknown SQLState — rethrow the original so the web catch-all diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index c6e775f6..f0fe0931 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -194,6 +194,16 @@ failure translation contract 다. 여기서는 SPI 구조와 fallback 근거만 실패시킨다. last-writer-wins merge는 mapping ownership drift를 숨기므로 허용하지 않는다. - `08*` connection-class prefix → `DB_UNAVAILABLE` 규칙은 맵 엔트리가 아니라 translator 가 직접 처리한다. 따라서 core 매핑 맵에는 `08*` 가 없다. +- **커밋 단계는 따로 분류한다(ADR-JPA-003).** `SpringTransaction` 은 본문이 끝난 뒤 자기가 연 + 쓰기 트랜잭션을 커밋하다 난 실패를 `translateCommitFailure` 로 보낸다. 여기서 `08*`·`40003`·벤더 + 종료 상태(`commitOutcomeUnknownStates()`, PostgreSQL 은 `57P01`·`57P02`)·SQLState 없는 전송 단절은 + `DB_UNAVAILABLE`(재시도 가능)이 아니라 `DB_COMPLETION_UNKNOWN`(재시도 불가)이 된다. 서버가 이미 + 커밋했을 수 있어 재시도가 쓰기를 중복시키기 때문이다. + - 커밋 전(연결 획득, 본문 실행) 연결 실패는 그대로 `DB_UNAVAILABLE` 이다. 풀 고갈·재시작까지 + 결과 불명으로 몰면 운영자가 그 신호를 무시하게 된다(ADR 의 "좁게" 원칙). + - 커밋 단계 안에서 Hibernate flush 실패와 COMMIT 자체 실패는 구분하지 않는다. flush 중 연결 단절은 + 실제로는 롤백이지만 결과 불명으로 보고된다 — 중복 쓰기보다 불필요한 조정(reconciliation)이 싸다. + - 읽기 전용 트랜잭션과 바깥 트랜잭션에 참여한 호출은 커밋할 쓰기가 없으므로 이 분류를 타지 않는다. - **Fallback:** 기여된 어떤 row 에도 없는 SQLState — 또는 cause chain 에 `SQLException` 자체가 없는 경우 — 는 `Optional.empty()` 를 반환한다. 호출부는 원본 예외를 web catch-all 까지 전파시켜 detail 누설 없는 generic `INTERNAL` 엔벨로프로 답하게 한다. translator @@ -581,7 +591,7 @@ holder 가 락을 잡을 수 있다. 막지 못한다. WARN 은 놓치기 쉬우므로, resolved 값이 `true`면 운영자가 실제 설정한 `APP_DATASOURCE_OPEN_IN_VIEW` 키를 메시지에 담아 부팅을 실패시킨다. - **읽기만 하고 re-bind 하지 않으며, 부재 값은 Spring 기본에 맡긴다.** `StartupRule`로 위반만 - 돌려주고 support의 `StartupRuleRunner`가 모든 싱글톤 생성 후 한 번 실행하며, 값이 *없으면* Spring Boot 기본(이 스켈레톤은 `application.yml`에서 OSIV off + 돌려주고 support의 `StartupRuleRunner`가 다른 싱글톤(DataSource·Flyway)을 만들기 전에 한 번 실행하며, 값이 *없으면* Spring Boot 기본(이 스켈레톤은 `application.yml`에서 OSIV off 가 기본)에 맡기며 *있는 `true`*만 거부한다. ### JpaDangerousConfigurationGuard (ddl-auto) diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java index 71a7b760..8cad7f27 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java @@ -1,14 +1,25 @@ package dev.caskeleton.adapter.outbound.persistence.failure; +import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; +import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext; +import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; +import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; import dev.caskeleton.shared.error.ApiErrorCode; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; +import java.io.IOException; import java.sql.SQLException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLRecoverableException; +import java.sql.SQLTransientConnectionException; +import java.time.Duration; import java.util.Collection; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import org.springframework.dao.DataAccessException; /** @@ -17,6 +28,10 @@ import org.springframework.dao.DataAccessException; * {@link Optional#empty()} for an unknown state). Mappings are merged from all {@link * SqlStateErrorMapping} SPI beans. See README "failure" for the SPI/fallback rationale and * CLAUDE.md for the SQLState → Error Code matrix. + * + *

A failed commit is classified by {@link #translateCommitFailure} instead: the same connection + * loss that is a retryable {@code DB_UNAVAILABLE} before the commit is an undetermined outcome + * during it (ADR-JPA-003). */ public class PersistenceExceptionTranslator { @@ -24,14 +39,19 @@ public class PersistenceExceptionTranslator { private static final String CONNECTION_CLASS_PREFIX = "08"; private final Map byExactSqlState; + private final Set vendorCommitOutcomeUnknownStates; public PersistenceExceptionTranslator(Collection mappings) { Objects.requireNonNull(mappings, "mappings"); Map merged = new LinkedHashMap<>(); Map contributors = new LinkedHashMap<>(); + Set commitOutcomeUnknown = new HashSet<>(); for (SqlStateErrorMapping mapping : mappings) { Objects.requireNonNull(mapping, "mapping"); String contributor = mapping.getClass().getName(); + commitOutcomeUnknown.addAll( + Objects.requireNonNull( + mapping.commitOutcomeUnknownStates(), contributor + ".commitOutcomeUnknownStates()")); Map exactMappings = Objects.requireNonNull(mapping.exactMappings(), contributor + ".exactMappings()"); for (Map.Entry entry : exactMappings.entrySet()) { @@ -60,6 +80,7 @@ public class PersistenceExceptionTranslator { } } this.byExactSqlState = Map.copyOf(merged); + this.vendorCommitOutcomeUnknownStates = Set.copyOf(commitOutcomeUnknown); } /** Classify {@code ex}, or {@link Optional#empty()} when its SQLState is unmapped or absent. */ @@ -88,6 +109,61 @@ public class PersistenceExceptionTranslator { code, "persistence failure classified from SQLState=" + sqlState, ex)); } + /** + * Classify a failure raised while committing a write transaction this call began. + * + *

A connection-class state ({@code 08*}), {@code 40003}, a vendor-contributed termination + * state, or a transport break with no SQLState at all means the commit request may have reached + * the server and been applied before the acknowledgement was lost. That becomes a {@link + * TransactionCompletionUnknownException} ({@code DB_COMPLETION_UNKNOWN}, never retryable), not + * the retryable {@code DB_UNAVAILABLE} the same state means before the commit. A commit the + * server definitely rejected — a deferred constraint, a serialization failure — keeps its {@link + * #translate(Throwable) ordinary} classification. + * + * @param operation the bounded name the failure is reported under + * @param elapsed how long the transaction ran before the commit failed + */ + public Optional translateCommitFailure( + Throwable ex, PersistenceOperationName operation, Duration elapsed) { + Objects.requireNonNull(ex, "ex"); + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(elapsed, "elapsed"); + String sqlState = extractSqlState(ex); + if (!leavesCommitOutcomeUnknown(sqlState, ex)) { + return translate(ex); + } + JpaFailureContext context = + JpaFailureContext.completionUnknown(operation, sqlState, 1, elapsed, null); + return Optional.of( + new TransactionCompletionUnknownException( + context, TransactionCompletionEvidence.UNKNOWN, ex)); + } + + private boolean leavesCommitOutcomeUnknown(String sqlState, Throwable ex) { + if (sqlState == null) { + return hasTransportBreak(ex); + } + return sqlState.startsWith(CONNECTION_CLASS_PREFIX) + || StandardSqlStateErrorMapping.STATEMENT_COMPLETION_UNKNOWN.equals(sqlState) + || vendorCommitOutcomeUnknownStates.contains(sqlState); + } + + /** A broken socket or a driver connection exception that carried no SQLState. */ + private static boolean hasTransportBreak(Throwable ex) { + for (Throwable t = ex; t != null; t = t.getCause()) { + if (t instanceof IOException + || t instanceof SQLRecoverableException + || t instanceof SQLTransientConnectionException + || t instanceof SQLNonTransientConnectionException) { + return true; + } + if (t.getCause() == t) { + break; + } + } + return false; + } + /** The matrix lookup: exact codes first, then the {@code 08*} connection-class prefix. */ private ApiErrorCode classify(String sqlState) { OperationalError exact = byExactSqlState.get(sqlState); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/SqlStateErrorMapping.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/SqlStateErrorMapping.java index 1dd45e08..069fa337 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/SqlStateErrorMapping.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/SqlStateErrorMapping.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.failure; import dev.caskeleton.shared.error.OperationalError; import java.util.Map; +import java.util.Set; /** * SPI for contributing exact SQLState → {@link OperationalError} mappings to the {@link @@ -15,4 +16,16 @@ public interface SqlStateErrorMapping { * translator's responsibility, not a map entry. */ Map exactMappings(); + + /** + * Vendor SQLStates that, when a commit fails with them, leave the commit outcome undetermined — + * the server may have committed before it reported the failure. Never {@code null}. + * + *

The vendor-neutral ones ({@code 08*}, {@code 40003}) and the transport break are the + * translator's own rule. Only a state a vendor reports instead of those belongs here, + * such as PostgreSQL's {@code 57P01} for a backend terminated mid-commit (ADR-JPA-003). + */ + default Set commitOutcomeUnknownStates() { + return Set.of(); + } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/StandardSqlStateErrorMapping.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/StandardSqlStateErrorMapping.java index cfa7393a..5cf7653e 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/StandardSqlStateErrorMapping.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/StandardSqlStateErrorMapping.java @@ -8,15 +8,22 @@ import java.util.Map; * returns. Vendor-specific states are contributed by the vendor module. See CLAUDE.md for the * SQLState → Error Code matrix. * - *

The constants are where these five codes are spelled. A vendor's own SQLSTATE vocabulary — - * {@code PostgreSqlState} — refers to them rather than repeating the literals, so {@code 40001} is - * written once, not once per table that happens to need it. + *

The constants are where these codes are spelled. A vendor's own SQLSTATE vocabulary — {@code + * PostgreSqlState} — refers to them rather than repeating the literals, so {@code 40001} is written + * once, not once per table that happens to need it. */ public class StandardSqlStateErrorMapping implements SqlStateErrorMapping { /** {@code 40001} serialization_failure. */ public static final String SERIALIZATION_FAILURE = "40001"; + /** + * {@code 40003} statement_completion_unknown. Not an exact row: it means "outcome unknown" only + * when a commit reports it, so {@link PersistenceExceptionTranslator#translateCommitFailure} owns + * it. + */ + public static final String STATEMENT_COMPLETION_UNKNOWN = "40003"; + /** {@code 23502} not_null_violation. */ public static final String NOT_NULL_VIOLATION = "23502"; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMapping.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMapping.java index 4520e869..f4b0835d 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMapping.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMapping.java @@ -4,6 +4,7 @@ import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping; import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlState; import dev.caskeleton.shared.error.OperationalError; import java.util.Map; +import java.util.Set; /** * PostgreSQL-specific {@link SqlStateErrorMapping} contributing vendor-only SQLState codes. See the @@ -22,8 +23,20 @@ public class PostgreSqlSqlStateErrorMapping implements SqlStateErrorMapping { OperationalError.DB_IDLE_IN_TX_TIMEOUT, PostgreSqlState.QUERY_CANCELED.code(), OperationalError.DB_QUERY_CANCELED); + /** + * A backend terminated mid-commit reports {@code 57P01}/{@code 57P02}, not a connection-class + * state, and the commit record may already be in the WAL when it does. + */ + private static final Set COMMIT_OUTCOME_UNKNOWN = + Set.of(PostgreSqlState.ADMIN_SHUTDOWN.code(), PostgreSqlState.CRASH_SHUTDOWN.code()); + @Override public Map exactMappings() { return MAPPINGS; } + + @Override + public Set commitOutcomeUnknownStates() { + return COMMIT_OUTCOME_UNKNOWN; + } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifier.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifier.java index 17322e0f..3b1636e4 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifier.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifier.java @@ -57,6 +57,9 @@ public final class PostgreSqlFailureClassifier { case LOCK_NOT_AVAILABLE -> FailureCategory.LOCK_NOT_AVAILABLE; case QUERY_CANCELED -> FailureCategory.QUERY_TIMEOUT; case IDLE_IN_TRANSACTION_TIMEOUT -> FailureCategory.TRANSACTION_TIMEOUT; + // The backend is gone; like 08*, whether a commit it was running landed is decided by the + // transaction phase, not here. + case ADMIN_SHUTDOWN, CRASH_SHUTDOWN -> FailureCategory.CONNECTION_UNAVAILABLE; case UNDEFINED_TABLE, UNDEFINED_COLUMN -> FailureCategory.SCHEMA_MISMATCH; case INSUFFICIENT_PRIVILEGE -> FailureCategory.UNKNOWN; }; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlState.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlState.java index 28ce2736..5ad4ca16 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlState.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlState.java @@ -24,7 +24,7 @@ public enum PostgreSqlState { SERIALIZATION_FAILURE(StandardSqlStateErrorMapping.SERIALIZATION_FAILURE), /** {@code 40003} statement_completion_unknown. */ - STATEMENT_COMPLETION_UNKNOWN("40003"), + STATEMENT_COMPLETION_UNKNOWN(StandardSqlStateErrorMapping.STATEMENT_COMPLETION_UNKNOWN), /** {@code 40P01} deadlock_detected. */ DEADLOCK_DETECTED("40P01"), @@ -50,6 +50,15 @@ public enum PostgreSqlState { /** {@code 25P03} idle_in_transaction_session_timeout. */ IDLE_IN_TRANSACTION_TIMEOUT("25P03"), + /** + * {@code 57P01} admin_shutdown — what the driver reports when the backend is terminated, + * including by {@code pg_terminate_backend} while a commit is in flight. + */ + ADMIN_SHUTDOWN("57P01"), + + /** {@code 57P02} crash_shutdown — another backend crashed and this one was terminated. */ + CRASH_SHUTDOWN("57P02"), + /** {@code 42P01} undefined_table — the schema is not what the provider expects. */ UNDEFINED_TABLE("42P01"), diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java index 95266179..597d415f 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java @@ -27,6 +27,10 @@ import org.springframework.core.env.Environment; * selects the module gets the guards with it and an application that removes the module keeps none * of them. Every guard raises a typed startup failure from {@code support.startup}, so exit codes * and the structured failure log are unchanged. + * + *

The environment rules are {@code static} beans: support's runner evaluates them before any + * other singleton exists — before the datasource below opens a connection and before Flyway + * migrates — and a static factory method does not create this class to do so. */ @AutoConfiguration @ConditionalOnProperty( @@ -58,33 +62,33 @@ class JpaStartupAutoConfiguration { /** Env-validation (exit 78): datasource connection env present before migration runs. */ @Bean - RequiredEnvironmentValidator requiredEnvironmentValidator() { + static RequiredEnvironmentValidator requiredEnvironmentValidator() { return new RequiredEnvironmentValidator(); } /** Profile check (exit 71): forbidden Flyway options stay off under the prod profile. */ @Bean - FlywayProdSafetyValidator flywayProdSafetyValidator() { + static FlywayProdSafetyValidator flywayProdSafetyValidator() { return new FlywayProdSafetyValidator(); } @Bean - OpenInViewSafetyValidator openInViewSafetyValidator() { + static OpenInViewSafetyValidator openInViewSafetyValidator() { return new OpenInViewSafetyValidator(); } @Bean - PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator() { + static PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator() { return new PostgreSqlTransportSecurityValidator(); } @Bean - PersistenceVendorProdSafetyValidator persistenceVendorProdSafetyValidator() { + static PersistenceVendorProdSafetyValidator persistenceVendorProdSafetyValidator() { return new PersistenceVendorProdSafetyValidator(); } @Bean - HikariPoolConstraintValidator hikariPoolConstraintValidator() { + static HikariPoolConstraintValidator hikariPoolConstraintValidator() { return new HikariPoolConstraintValidator(); } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java index 351a6046..9f639b60 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java @@ -1,12 +1,17 @@ package dev.caskeleton.adapter.outbound.persistence.transaction; +import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator; import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; import dev.caskeleton.application.transaction.Isolation; import dev.caskeleton.application.transaction.NestedRootTransactionRejectedException; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.shared.error.PersistenceFailureException; +import java.time.Duration; import java.util.Locale; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -17,15 +22,21 @@ import org.springframework.transaction.support.TransactionTemplate; * Spring-backed {@link TransactionPort}: one pre-built {@link TransactionTemplate} per mode, all * pinned to {@link Isolation#READ_COMMITTED}. See README "transaction" for why the templates are * pre-built (mutable-template race) and CLAUDE.md for the mode table. + * + *

A failure is classified by the phase it happened in. Before and during the action it goes + * through {@link PersistenceExceptionTranslator#translate(Throwable)}; once the action has returned + * and this call is committing a write transaction it began, it goes through {@link + * PersistenceExceptionTranslator#translateCommitFailure}, which reports a lost connection as + * completion-unknown rather than retryable (ADR-JPA-003). */ public class SpringTransaction implements TransactionPort { /** Upper bound on one {@link #inNew} transaction; the former compensation budget. */ static final int REQUIRES_NEW_TIMEOUT_SECONDS = 30; - private final TransactionTemplate writeTemplate; - private final TransactionTemplate readTemplate; - private final TransactionTemplate requiresNewTemplate; + private final ModeTemplate writeTemplate; + private final ModeTemplate readTemplate; + private final ModeTemplate requiresNewTemplate; private final PersistenceExceptionTranslator exceptionTranslator; public SpringTransaction(PlatformTransactionManager transactionManager) { @@ -55,7 +66,7 @@ public class SpringTransaction implements TransactionPort { false); // inNew is for outbox, audit and compensation writes, which usually run while the caller's own // transaction holds a second connection. An unbounded one could pin both for good. - this.requiresNewTemplate.setTimeout(REQUIRES_NEW_TIMEOUT_SECONDS); + this.requiresNewTemplate.template().setTimeout(REQUIRES_NEW_TIMEOUT_SECONDS); this.exceptionTranslator = exceptionTranslator; } @@ -82,27 +93,46 @@ public class SpringTransaction implements TransactionPort { return execute(requiresNewTemplate, action); } - private static TransactionTemplate template( + /** One mode's template and the bounded name a failed commit in it is reported under. */ + private record ModeTemplate( + TransactionTemplate template, PersistenceOperationName commitOperation) {} + + private static ModeTemplate template( PlatformTransactionManager transactionManager, TransactionMode mode, int propagation, boolean readOnly) { + String modeName = mode.name().toLowerCase(Locale.ROOT); TransactionTemplate template = new TransactionTemplate(transactionManager); - template.setName("application-" + mode.name().toLowerCase(Locale.ROOT)); + template.setName("application-" + modeName); template.setPropagationBehavior(propagation); template.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); template.setReadOnly(readOnly); - return template; + return new ModeTemplate( + template, + new PersistenceOperationName("transaction." + modeName.replace('_', '-') + ".commit")); } - private T execute(TransactionTemplate template, Supplier action) { + private T execute(ModeTemplate mode, Supplier action) { + long startedAt = System.nanoTime(); + // Set only once the action has returned in a write transaction this call began: from then on + // the only thing TransactionTemplate.execute still does is commit it. + AtomicBoolean committingOwnWrite = new AtomicBoolean(); try { - return template.execute(status -> action.get()); + return mode.template() + .execute( + status -> { + T result = action.get(); + committingOwnWrite.set(status.isNewTransaction() && !mode.template().isReadOnly()); + return result; + }); } catch (RuntimeException failure) { - throw exceptionTranslator - .translate(failure) - .map(RuntimeException.class::cast) - .orElse(failure); + Optional translated = + committingOwnWrite.get() + ? exceptionTranslator.translateCommitFailure( + failure, mode.commitOperation(), Duration.ofNanos(System.nanoTime() - startedAt)) + : exceptionTranslator.translate(failure); + throw translated.map(RuntimeException.class::cast).orElse(failure); } } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java index 73f8d638..b51e63d9 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java @@ -45,7 +45,9 @@ final class NotificationFixtures { migration("jpa/notification-platform", "V6__notification_projection_facts.sql"), migration("jpa/notification-platform", "V7__notification_collapse.sql"), migration("jpa/notification-platform", "V8__notification_admin_claim.sql"), - migration("jpa/notification-platform", "V9__notification_evidence_certainty.sql")); + migration("jpa/notification-platform", "V9__notification_evidence_certainty.sql"), + migration("jpa/notification-platform", "V10__variables_payload_envelope_guard.sql"), + migration("jpa/notification-platform", "V11__notification_reconciliation_claim_lease.sql")); } /** diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ReconciliationJobClaimContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ReconciliationJobClaimContractTest.java new file mode 100644 index 00000000..3384ef60 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ReconciliationJobClaimContractTest.java @@ -0,0 +1,257 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JdbcReconciliationJobStore; +import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJob; +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Whether two instances polling the reconciliation table can take the same job, against a real + * PostgreSQL. + * + *

Every call runs on its own pooled autocommit connection, as the worker's do: no transaction + * spans the claim and the provider call, so ownership has to be in the row. Row locks and {@code + * SKIP LOCKED} are vendor semantics a fake would only restate. + */ +@Tag("jpa-contract") +class ReconciliationJobClaimContractTest { + + private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); + private static final String TENANT = "tenant-a"; + private static final String PROFILE = "email-main"; + private static final Duration LEASE = Duration.ofMinutes(2); + + private static JpaPlatformContractSupport support; + + @BeforeAll + static void startServer() { + support = JpaPlatformContractSupport.start(); + } + + @AfterAll + static void stopServer() { + if (support != null) { + support.close(); + } + } + + @BeforeEach + void migrate() throws SQLException, IOException { + try (Connection connection = support.connection(); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA public CASCADE"); + statement.execute("CREATE SCHEMA public"); + for (String migration : NotificationFixtures.migrations()) { + statement.execute(migration); + } + } + } + + @Test + @DisplayName("한 인스턴스가 가져간 정산 job은 다른 인스턴스의 claim에 다시 나오지 않는다") + void aClaimedJobIsNotHandedToAnotherInstance() throws SQLException { + // given + scheduleDueJob(); + JdbcReconciliationJobStore first = store(); + JdbcReconciliationJobStore second = store(); + List firstClaim = first.claimDue(10, NOW, LEASE); + + // when + List secondClaim = second.claimDue(10, NOW, LEASE); + + // then + assertThat(firstClaim).hasSize(1); + assertThat(secondClaim) + .as( + "the claim commits with its statement; only the lease in the row still says who owns it") + .isEmpty(); + } + + @Test + @DisplayName("두 연결이 동시에 claim하면 겹쳐서 가져간 job이 없다") + void twoConcurrentClaimsShareNoJob() throws Exception { + // given + for (int i = 0; i < 40; i++) { + scheduleDueJob(); + } + CountDownLatch start = new CountDownLatch(1); + Callable> claimer = + () -> { + start.await(); + return store().claimDue(40, NOW, LEASE).stream().map(ReconciliationJob::id).toList(); + }; + ExecutorService pool = Executors.newFixedThreadPool(2); + List a; + List b; + try { + Future> left = pool.submit(claimer); + Future> right = pool.submit(claimer); + + // when + start.countDown(); + a = left.get(); + b = right.get(); + } finally { + pool.shutdownNow(); + } + + // then + Set overlap = new HashSet<>(a); + overlap.retainAll(b); + assertThat(overlap).as("a job taken by both instances is asked about twice").isEmpty(); + assertThat(a.size() + b.size()).isEqualTo(40); + } + + @Test + @DisplayName("lease가 지난 job은 다른 인스턴스가 다시 가져간다") + void aJobWhoseLeaseHasPassedIsClaimedAgain() throws SQLException { + // given + UUID id = scheduleDueJob(); + store().claimDue(10, NOW, LEASE); + + // when + List reclaimed = store().claimDue(10, NOW.plus(LEASE), LEASE); + + // then + assertThat(reclaimed) + .as("a holder that died mid-pass must not strand its jobs") + .extracting(ReconciliationJob::id) + .containsExactly(id); + } + + @Test + @DisplayName("lease가 1마이크로초라도 남은 job은 다른 인스턴스가 가져가지 못한다") + void aJobWhoseLeaseHasNotPassedIsNotClaimed() throws SQLException { + // given + scheduleDueJob(); + store().claimDue(10, NOW, LEASE); + + // when + List early = store().claimDue(10, NOW.plus(LEASE).minusNanos(1_000), LEASE); + + // then + assertThat(early).isEmpty(); + } + + @Test + @DisplayName("다른 인스턴스가 다시 가져간 job은 이전 소유자가 완료해도 지워지지 않는다") + void aSupersededHolderCannotCompleteTheJob() throws SQLException { + // given + UUID id = scheduleDueJob(); + ReconciliationJob stale = store().claimDue(10, NOW, LEASE).get(0); + store().claimDue(10, NOW.plus(LEASE), LEASE); + + // when + store().complete(stale); + + // then + assertThat(rowExists(id)).as("the new holder has not answered yet").isTrue(); + } + + @Test + @DisplayName("다른 인스턴스가 다시 가져간 job은 이전 소유자의 재예약이 시도 횟수를 올리지 않는다") + void aSupersededHolderCannotRescheduleTheJob() throws SQLException { + // given + UUID id = scheduleDueJob(); + ReconciliationJob stale = store().claimDue(10, NOW, LEASE).get(0); + store().claimDue(10, NOW.plus(LEASE), LEASE); + + // when + store().reschedule(stale, "STILL_UNKNOWN", NOW.plus(Duration.ofHours(1))); + + // then + assertThat(attemptsOf(id)) + .as("two holders counting one question would reach the attempt limit early") + .isZero(); + } + + @Test + @DisplayName("현재 소유자가 재예약하면 claim이 풀려 lease 만료 전이라도 다음 확인 시각에 다시 나온다") + void theHoldersRescheduleReleasesTheClaim() throws SQLException { + // given + UUID id = scheduleDueJob(); + ReconciliationJob held = store().claimDue(10, NOW, LEASE).get(0); + Instant nextCheck = NOW.plusSeconds(30); + store().reschedule(held, "STILL_UNKNOWN", nextCheck); + + // when + List next = store().claimDue(10, nextCheck, LEASE); + + // then + assertThat(next).extracting(ReconciliationJob::id).containsExactly(id); + assertThat(next.get(0).attempts()).isEqualTo(1); + } + + @Test + @DisplayName("현재 소유자가 완료하면 job이 지워진다") + void theHolderCompletesTheJob() throws SQLException { + // given + UUID id = scheduleDueJob(); + ReconciliationJob held = store().claimDue(10, NOW, LEASE).get(0); + + // when + store().complete(held); + + // then + assertThat(rowExists(id)).isFalse(); + } + + private static boolean rowExists(UUID id) { + Integer rows = + new JdbcTemplate(support.dataSource()) + .queryForObject( + "SELECT count(*) FROM notification_reconciliation_job WHERE id = ?", + Integer.class, + id); + return rows != null && rows > 0; + } + + private static int attemptsOf(UUID id) { + Integer attempts = + new JdbcTemplate(support.dataSource()) + .queryForObject( + "SELECT attempts FROM notification_reconciliation_job WHERE id = ?", + Integer.class, + id); + return attempts == null ? -1 : attempts; + } + + private UUID scheduleDueJob() throws SQLException { + UUID attemptId = NotificationFixtures.insertAttempt(support, TENANT, NOW, PROFILE); + return store() + .schedule(new DeliveryAttemptId(attemptId), new ProviderProfileId(PROFILE), NOW) + .id(); + } + + private static JdbcReconciliationJobStore store() { + return new JdbcReconciliationJobStore( + new JdbcTemplate(support.dataSource()), Clock.fixed(NOW, ZoneOffset.UTC)); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/JpaLifecycleAssociationContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/JpaLifecycleAssociationContractTest.java index 2cf244a3..a7f75204 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/JpaLifecycleAssociationContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/JpaLifecycleAssociationContractTest.java @@ -16,8 +16,11 @@ import org.junit.jupiter.api.Test; * Pins the Persistence Context semantics an application silently depends on (design §13, §14). * *

Every assertion here is a bug someone has shipped: merging and then modifying the original, - * expecting flush to commit, modifying a detached instance and wondering why nothing saved, or - * updating the inverse side of an association and getting no {@code UPDATE} at all. + * expecting flush to commit, modifying a detached instance and wondering why nothing saved. + * + *

The fixture's association is mapped from the parent's collection only, so the association + * contracts pin that one side: the collection writes the child's foreign key, and removing from it + * deletes the orphan. */ @Tag("jpa-contract") class JpaLifecycleAssociationContractTest { @@ -145,8 +148,8 @@ class JpaLifecycleAssociationContractTest { } @Test - @DisplayName("only the owning side writes the foreign key") - void onlyTheOwningSideWritesTheForeignKey() { + void addingToTheParentCollectionWritesTheChildForeignKey() { + // given Long parentId = jpa.inTransaction( entityManager -> { @@ -156,12 +159,16 @@ class JpaLifecycleAssociationContractTest { return parent.id(); }); - jpa.inTransactionDo( - entityManager -> { - var parent = entityManager.find(LifecycleParent.class, parentId); - assertThat(parent.children()).hasSize(1); - assertThat(parent.children().get(0).parent().id()).isEqualTo(parentId); - }); + // when + var childParentIds = + jpa.inTransaction( + entityManager -> + entityManager.find(LifecycleParent.class, parentId).children().stream() + .map(LifecycleChild::parentId) + .toList()); + + // then + assertThat(childParentIds).containsExactly(parentId); } @Test @@ -191,7 +198,7 @@ class JpaLifecycleAssociationContractTest { assertThat( entityManager .createQuery( - "select count(c) from LifecycleChild c where c.parent.id = :parentId", + "select count(c) from LifecycleChild c where c.parentId = :parentId", Long.class) .setParameter("parentId", parentId) .getSingleResult()) diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java index fbe44491..ac80e995 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java @@ -13,31 +13,41 @@ import dev.caskeleton.adapter.outbound.persistence.notification.platform.Notific import dev.caskeleton.adapter.outbound.persistence.notification.platform.ProviderEventJpaRepository; import dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientDeliveryJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; +import dev.caskeleton.application.notification.platform.api.ContactPointId; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.NormalizedEventType; import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; import dev.caskeleton.application.notification.platform.api.ProviderId; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.TemplateSelection; +import dev.caskeleton.application.notification.platform.api.content.EmailContent; +import dev.caskeleton.application.notification.platform.api.content.EmailOptions; import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; import dev.caskeleton.application.notification.platform.callback.DeliveryProjection; import dev.caskeleton.application.notification.platform.callback.ProjectionResult; import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFactory; import dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService; import dev.caskeleton.application.notification.platform.dispatch.NotificationRoutingPlanCodecPort; import dev.caskeleton.application.notification.platform.dispatch.NotificationVariablesCodecPort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; import dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint; import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; import dev.caskeleton.application.notification.platform.policy.RouteCandidate; +import dev.caskeleton.application.notification.platform.provider.ProviderCapabilities; +import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot; import dev.caskeleton.application.notification.platform.provider.ReconciliationResult; import dev.caskeleton.application.notification.platform.security.NotificationPayloadProtection; +import dev.caskeleton.application.notification.platform.template.RenderedNotificationContent; import dev.caskeleton.application.transaction.TransactionPort; import jakarta.persistence.EntityManagerFactory; import java.sql.Timestamp; @@ -45,6 +55,7 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -198,6 +209,27 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { assertThat(eventOf(attempt)).containsExactly("RECONCILIATION", "APPLIED"); } + @Test + void recoveryReconcilesAnAttemptLeftAsTheDispatcherWroteItBeforeTheCall() { + // given + // A worker killed during the SES/SMTP call leaves exactly the row DeliveryAttemptFactory wrote + // and the store persisted: nothing rewrites it until the outcome is recorded. + UUID delivery = + insertDelivery("DISPATCHING", Instant.now().minus(Duration.ofMinutes(10)), null); + UUID attempt = insertAttemptAsTheDispatcherWritesIt(delivery); + + // when + recovery().recoverOnce(); + + // then + assertThat(eventOf(attempt)) + .as("the provider may already have the message, so recovery asks it instead of requeuing") + .containsExactly("RECONCILIATION", "APPLIED"); + assertThat(deliveryState(delivery)) + .as("a requeue would hand the same notification to another worker, which sends it again") + .isNotEqualTo("READY_TO_DISPATCH"); + } + @Test void reconciliationRecordsAConfirmedAnswerOutsideAnyCallerTransaction() { // given @@ -346,10 +378,61 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { return delivery; } - /** An attempt that started and never completed: the provider may or may not have it. */ - private UUID insertStartedAttempt(UUID delivery, String providerId, String requestHash) { - UUID contact = UUID.randomUUID(); + /** + * The pre-call attempt row built by {@link DeliveryAttemptFactory} and inserted through the + * production store, rather than a row written by hand. + */ + private UUID insertAttemptAsTheDispatcherWritesIt(UUID delivery) { + UUID contact = insertContactPoint(); UUID attempt = UUID.randomUUID(); + RecipientDeliveryRecord recipient = + deliveries(context.getBean(RecipientDeliveryJpaRepository.class)) + .find(new RecipientDeliveryId(delivery)) + .orElseThrow(); + RouteCandidate route = + new RouteCandidate( + 0, + Channel.EMAIL, + new ContactPointId(contact), + new ProviderProfileId(PROFILE), + true, + true); + ProviderProfileSnapshot profile = + new ProviderProfileSnapshot( + new ProviderProfileId(PROFILE), + new ProviderId("ses"), + Channel.EMAIL, + "prod", + 1L, + new ProviderCapabilities( + false, + true, + true, + true, + true, + false, + false, + false, + 1, + 10_000L, + Duration.ofHours(1)), + Map.of()); + RenderedNotificationContent content = + new RenderedNotificationContent( + new EmailContent("subject", "body", Optional.empty(), List.of(), EmailOptions.DEFAULT), + "0".repeat(64), + new TemplateSelection("welcome", 1L, Locale.KOREAN), + Locale.KOREAN); + transactions.inWrite( + () -> + attempts.insertDispatching( + new DeliveryAttemptFactory(() -> attempt) + .create(recipient, route, profile, content, 1, clock.instant()))); + return attempt; + } + + private UUID insertContactPoint() { + UUID contact = UUID.randomUUID(); jdbc.update( "insert into notification_contact_point (id, tenant_id, owner_ref, type, environment," + " ciphertext, nonce, lookup_hmac, key_id, status, created_at, updated_at)" @@ -359,6 +442,13 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { new byte[] {1, 2, 3}, new byte[] {4, 5, 6}, UUID.randomUUID().toString().replace("-", "").repeat(2)); + return contact; + } + + /** An attempt that started and never completed: the provider may or may not have it. */ + private UUID insertStartedAttempt(UUID delivery, String providerId, String requestHash) { + UUID contact = insertContactPoint(); + UUID attempt = UUID.randomUUID(); jdbc.update( "insert into notification_delivery_attempt (id, recipient_delivery_id, contact_point_id," + " attempt_no, channel, provider_id, provider_profile_id, provider_request_id_hash," diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java index 68827d56..6cf1d029 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java @@ -98,12 +98,14 @@ final class PostgreSqlOptionalStreamLifecycle { // row still carrying plaintext fails the migration rather than meeting the mapper at // runtime, // where it would look like a decryption bug instead of an un-migrated table. + // V11 gives a reconciliation job claim a lease and a fence, so two instances cannot both + // hold one job. // // This list is the stream's contract, not a note about its length: the lifecycle below // disables, re-enables and interrupts the stream and asserts the applied set is unchanged // each time. So a migration added to the stream belongs here, and the version that landed // without being added is why the lane failed the first time anybody ran it. - List.of("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), + List.of("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"), List.of()); } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java index beef27be..5d066da2 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator; import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping; @@ -34,8 +35,8 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; *

The port is plain Spring {@code TransactionTemplate} per mode. What a real database adds over * the unit tests is the part a recording transaction manager cannot show: that a rollback really * removes the row, that {@code inNew} really commits on its own connection while the caller's - * transaction rolls back, and that a commit the server never acknowledged surfaces as a failure and - * is not replayed. + * transaction rolls back, and that a commit the server never acknowledged surfaces as a + * completion-unknown failure and is not replayed. */ class PostgreSqlTransactionIntegrationTest { @@ -144,7 +145,7 @@ class PostgreSqlTransactionIntegrationTest { @Test @Tag("jpa-failure") @Timeout(15) - void connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried() throws Exception { + void connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried() throws Exception { JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); SpringTransaction port = transactionPort(); AtomicInteger backendPid = new AtomicInteger(); @@ -189,7 +190,12 @@ class PostgreSqlTransactionIntegrationTest { })); assertThat(terminated.get(5, TimeUnit.SECONDS)).isTrue(); - assertThat(thrown).isInstanceOf(RuntimeException.class); + // The server may have committed before the connection dropped, so the caller must be told + // "outcome unknown, do not retry" — never the retryable DB_UNAVAILABLE (ADR-JPA-003). + assertThat(thrown).isInstanceOf(TransactionCompletionUnknownException.class); + PersistenceFailureException failure = (PersistenceFailureException) thrown; + assertThat(failure.errorCode()).isEqualTo(OperationalError.DB_COMPLETION_UNKNOWN); + assertThat(failure.errorCode().retryable()).isFalse(); assertThat(actionCalls).hasValue(1); assertThat(jdbc.queryForObject("select count(*) from readiness_commit_uncertain", Long.class)) .isZero(); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslatorTest.java index 4e84fedd..a0a9b9b2 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslatorTest.java @@ -3,17 +3,26 @@ package dev.caskeleton.adapter.outbound.persistence.failure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; +import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; +import java.io.EOFException; import java.sql.SQLException; +import java.time.Duration; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.transaction.TransactionSystemException; /** * feature-persistence-failure-baseline §SQLState → Error Code Matrix (standard rows) + §Edge @@ -222,6 +231,112 @@ class PersistenceExceptionTranslatorTest { .hasMessageContaining(OperationalError.DB_DEADLOCK.name()); } + // ---- commit phase (ADR-JPA-003, review 04-01) ---- + + private static final PersistenceOperationName COMMIT = + new PersistenceOperationName("transaction.write.commit"); + + private static TransactionSystemException commitFailureWith(Throwable cause) { + return new TransactionSystemException("Could not commit JDBC transaction", cause); + } + + @ParameterizedTest + @ValueSource(strings = {"08000", "08003", "08006", "40003"}) + @DisplayName("커밋이 연결 계열 상태나 40003으로 실패하면 재시도 불가인 결과 불명으로 분류한다") + void connectionLossDuringCommitIsCompletionUnknown(String sqlState) { + // given + TransactionSystemException failure = + commitFailureWith(new SQLException("connection lost", sqlState)); + + // when + Optional result = + translator.translateCommitFailure(failure, COMMIT, Duration.ofMillis(5)); + + // then + assertThat(result).containsInstanceOf(TransactionCompletionUnknownException.class); + PersistenceFailureException unknown = result.orElseThrow(); + assertThat(unknown.errorCode()).isEqualTo(OperationalError.DB_COMPLETION_UNKNOWN); + assertThat(unknown.errorCode().retryable()).isFalse(); + assertThat(((TransactionCompletionUnknownException) unknown).context().sqlState()) + .isEqualTo(sqlState); + } + + @Test + @DisplayName("SQLState 없이 소켓이 끊겨도 커밋 중이면 결과 불명으로 분류한다") + void transportBreakWithoutSqlStateDuringCommitIsCompletionUnknown() { + // given + TransactionSystemException failure = + commitFailureWith(new EOFException("unexpected end of stream")); + + // when + Optional result = + translator.translateCommitFailure(failure, COMMIT, Duration.ZERO); + + // then + assertThat(result).containsInstanceOf(TransactionCompletionUnknownException.class); + } + + @Test + @DisplayName("벤더가 기여한 종료 상태로 커밋이 실패하면 결과 불명으로 분류한다") + void vendorContributedTerminationStateDuringCommitIsCompletionUnknown() { + // given + PersistenceExceptionTranslator withVendor = + new PersistenceExceptionTranslator( + List.of(new StandardSqlStateErrorMapping(), new TerminationStateMapping())); + TransactionSystemException failure = + commitFailureWith(new SQLException("backend terminated", "57P01")); + + // when + Optional result = + withVendor.translateCommitFailure(failure, COMMIT, Duration.ZERO); + + // then + assertThat(result).containsInstanceOf(TransactionCompletionUnknownException.class); + } + + @Test + @DisplayName("서버가 커밋을 제약 위반으로 확실히 거절하면 원래 분류를 유지한다") + void commitDefinitelyRejectedKeepsItsOrdinaryClassification() { + // given + TransactionSystemException failure = + commitFailureWith(new SQLException("duplicate key", "23505")); + + // when + Optional result = + translator.translateCommitFailure(failure, COMMIT, Duration.ZERO); + + // then + assertThat(result).isPresent(); + assertThat(result.orElseThrow()).isNotInstanceOf(TransactionCompletionUnknownException.class); + assertThat(result.orElseThrow().errorCode()).isEqualTo(OperationalError.DB_UNIQUE_VIOLATION); + } + + @Test + @DisplayName("SQLState도 전송 단절도 없는 커밋 실패는 분류하지 않고 비워 둔다") + void commitFailureWithNeitherSqlStateNorTransportBreakIsLeftUnclassified() { + // given + TransactionSystemException failure = new TransactionSystemException("commit failed"); + + // when + Optional result = + translator.translateCommitFailure(failure, COMMIT, Duration.ZERO); + + // then + assertThat(result).isEmpty(); + } + + private record TerminationStateMapping() implements SqlStateErrorMapping { + @Override + public Map exactMappings() { + return Map.of(); + } + + @Override + public Set commitOutcomeUnknownStates() { + return Set.of("57P01"); + } + } + private record FirstMapping(Map exactMappings) implements SqlStateErrorMapping {} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMappingTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMappingTest.java index ce3dc846..844d0df1 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMappingTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMappingTest.java @@ -2,6 +2,8 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; +import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator; import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping; import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; @@ -10,13 +12,16 @@ import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; import java.sql.SQLException; +import java.time.Duration; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.transaction.TransactionSystemException; /** Unit tests for {@link PostgreSqlSqlStateErrorMapping}. */ class PostgreSqlSqlStateErrorMappingTest { @@ -100,4 +105,37 @@ class PostgreSqlSqlStateErrorMappingTest { assertThat(translator.translate(daoWithSqlState("40001")).orElseThrow().errorCode()) .isEqualTo(OperationalError.DB_SERIALIZATION_FAILURE); } + + @Test + @DisplayName("커밋 중 backend가 종료돼 57P01이 오면 결과 불명으로 분류한다") + void backendTerminatedDuringCommitIsCompletionUnknown() { + // given + TransactionSystemException commitFailure = + new TransactionSystemException( + "JDBC commit failed", + new SQLException("terminating connection due to administrator command", "57P01")); + + // when + Optional result = + translator.translateCommitFailure( + commitFailure, new PersistenceOperationName("transaction.write.commit"), Duration.ZERO); + + // then + assertThat(result).containsInstanceOf(TransactionCompletionUnknownException.class); + assertThat(result.orElseThrow().errorCode()).isEqualTo(OperationalError.DB_COMPLETION_UNKNOWN); + } + + @Test + @DisplayName("PostgreSQL이 기여하는 결과 불명 상태는 모두 PostgreSQL 표에 있는 상태다") + void everyCommitOutcomeUnknownStateIsAStateOfThePostgreSqlTable() { + // when + List unclassified = + pgMapping.commitOutcomeUnknownStates().stream() + .filter(code -> PostgreSqlState.fromCode(code).isEmpty()) + .toList(); + + // then + assertThat(pgMapping.commitOutcomeUnknownStates()).containsOnly("57P01", "57P02"); + assertThat(unclassified).isEmpty(); + } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifierTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifierTest.java index cf49c214..d692ec02 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifierTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifierTest.java @@ -23,7 +23,9 @@ class PostgreSqlFailureClassifierTest { "23514,CHECK_CONSTRAINT", "23502,NOT_NULL_CONSTRAINT", "55P03,LOCK_NOT_AVAILABLE", - "57014,QUERY_TIMEOUT" + "57014,QUERY_TIMEOUT", + "57P01,CONNECTION_UNAVAILABLE", + "57P02,CONNECTION_UNAVAILABLE" }) @DisplayName("each registered SQLSTATE maps to its category") void classifiesBySqlState(String state, FailureCategory expected) { diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfigurationTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfigurationTest.java index 5f52c3fd..5bff38b7 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfigurationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfigurationTest.java @@ -5,9 +5,13 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy; import dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier; import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets; +import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; +import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration; import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.DatabaseMetaData; +import java.util.concurrent.atomic.AtomicInteger; import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.DisplayName; @@ -129,6 +133,53 @@ class JpaStartupAutoConfigurationTest { }); } + @Test + @DisplayName("prod에서 sslmode=disable이면 DataSource를 만들거나 연결을 열기 전에 종료 코드 71로 기동이 실패한다") + void aProdPlaintextDatabaseUrlFailsTheBootBeforeTheDataSourceExists() { + // given + AtomicInteger dataSourcesCreated = new AtomicInteger(); + AtomicInteger connectionsOpened = new AtomicInteger(); + + // when + runner + .withConfiguration(AutoConfigurations.of(StartupRuleAutoConfiguration.class)) + .withInitializer(context -> context.getEnvironment().setActiveProfiles("prod")) + .withPropertyValues( + "spring.jpa.open-in-view=false", + "spring.datasource.url=jdbc:postgresql://db.invalid:5432/app?sslmode=disable") + .withBean( + DataSource.class, + () -> { + dataSourcesCreated.incrementAndGet(); + return new AbstractDataSource() { + @Override + public Connection getConnection() { + connectionsOpened.incrementAndGet(); + throw new IllegalStateException("a guarded boot must not reach the database"); + } + + @Override + public Connection getConnection(String username, String password) { + return getConnection(); + } + }; + }) + .run( + context -> { + // then + assertThat(context.getStartupFailure()) + .isInstanceOfSatisfying( + StartupFailureException.class, + failure -> { + assertThat(failure.errorCode()) + .isEqualTo(StartupErrorCode.PROFILE_MISMATCH); + assertThat(failure.getExitCode()).isEqualTo(71); + }); + assertThat(dataSourcesCreated).hasValue(0); + assertThat(connectionsOpened).hasValue(0); + }); + } + @Test void safetySettingsDefaultToEnabled() { runner diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java index 6f1f3a18..631f1932 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java @@ -1,12 +1,21 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.arch; +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 com.tngtech.archunit.core.importer.ClassFileImporter; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.FinalEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseCollectionParentEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseManyToManyEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseOneToOneEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.NoDefaultConstructorEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OrderEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningChildEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningManyToManyEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningOneToOneEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.UnidirectionalCollectionEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.BadOrderController; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.GoodOrderController; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.ListReturningController; @@ -89,4 +98,96 @@ class JpaArchitectureRulesTest { assertThatCode(() -> JpaArchitectureRules.entitiesFollowPortableMappingRules().check(classes)) .doesNotThrowAnyException(); } + + @Test + void anInverseOneToManyIsRefusedWithThePrincipleAndTheAlternatives() { + // given + var classes = + new ClassFileImporter() + .importClasses(InverseCollectionParentEntity.class, OwningChildEntity.class); + + // when + Throwable failure = + catchThrowable( + () -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)); + + // then + assertThat(failure) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("InverseCollectionParentEntity.children") + .hasMessageContaining("@OneToMany(mappedBy = \"parent\")") + .hasMessageContaining("one side only") + .hasMessageContaining("ID") + .hasMessageContaining("query"); + } + + @Test + void anInverseOneToOneIsRefused() { + // given + var classes = + new ClassFileImporter() + .importClasses(InverseOneToOneEntity.class, OwningOneToOneEntity.class); + + // when + Throwable failure = + catchThrowable( + () -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)); + + // then + assertThat(failure) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("InverseOneToOneEntity.partner") + .hasMessageContaining("@OneToOne(mappedBy = \"partner\")"); + } + + @Test + void anInverseManyToManyIsRefused() { + // given + var classes = + new ClassFileImporter() + .importClasses(InverseManyToManyEntity.class, OwningManyToManyEntity.class); + + // when + Throwable failure = + catchThrowable( + () -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)); + + // then + assertThat(failure) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("InverseManyToManyEntity.groups") + .hasMessageContaining("@ManyToMany(mappedBy = \"members\")"); + } + + @Test + void onlyTheMappedBySideOfABidirectionalPairIsReported() { + // given + var classes = + new ClassFileImporter() + .importClasses(InverseCollectionParentEntity.class, OwningChildEntity.class); + + // when + Throwable failure = + catchThrowable( + () -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)); + + // then + assertThat(failure) + .isInstanceOf(AssertionError.class) + .hasMessageNotContaining("OwningChildEntity.parent"); + } + + @Test + void unidirectionalAssociationsPass() { + var classes = + new ClassFileImporter() + .importClasses( + OwningChildEntity.class, + OwningOneToOneEntity.class, + OwningManyToManyEntity.class, + UnidirectionalCollectionEntity.class); + + assertThatCode(() -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)) + .doesNotThrowAnyException(); + } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseCollectionParentEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseCollectionParentEntity.java new file mode 100644 index 00000000..b860ca6e --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseCollectionParentEntity.java @@ -0,0 +1,34 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import java.util.ArrayList; +import java.util.List; + +/** + * Refused by the association rule: the inverse side of a bidirectional pair. + * + *

{@code mappedBy} declares that {@link OwningChildEntity#parent} writes the foreign key, so + * this list is a second copy of the same link that only an association helper keeps in step. + */ +@Entity +public class InverseCollectionParentEntity { + + @Id private Long id; + + @OneToMany(mappedBy = "parent") + private List children = new ArrayList<>(); + + protected InverseCollectionParentEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The inverse collection. */ + public List children() { + return List.copyOf(children); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseManyToManyEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseManyToManyEntity.java new file mode 100644 index 00000000..eb1d7ef1 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseManyToManyEntity.java @@ -0,0 +1,29 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; +import java.util.HashSet; +import java.util.Set; + +/** Refused by the association rule: the inverse side of a bidirectional many-to-many. */ +@Entity +public class InverseManyToManyEntity { + + @Id private Long id; + + @ManyToMany(mappedBy = "members") + private Set groups = new HashSet<>(); + + protected InverseManyToManyEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The inverse collection. */ + public Set groups() { + return Set.copyOf(groups); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseOneToOneEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseOneToOneEntity.java new file mode 100644 index 00000000..6e9d5139 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/InverseOneToOneEntity.java @@ -0,0 +1,27 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; + +/** Refused by the association rule: the inverse side of a bidirectional one-to-one. */ +@Entity +public class InverseOneToOneEntity { + + @Id private Long id; + + @OneToOne(mappedBy = "partner") + private OwningOneToOneEntity partner; + + protected InverseOneToOneEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The inverse reference. */ + public OwningOneToOneEntity partner() { + return partner; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningChildEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningChildEntity.java new file mode 100644 index 00000000..a800060d --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningChildEntity.java @@ -0,0 +1,35 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; + +/** + * Accepted by the association rule on its own: a unidirectional, lazy {@code @ManyToOne}. + * + *

It is the owning side of {@link InverseCollectionParentEntity}'s pair, and the rule reports + * the {@code mappedBy} side, not this one — the foreign key belongs here either way. + */ +@Entity +public class OwningChildEntity { + + @Id private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "parent_id") + private InverseCollectionParentEntity parent; + + protected OwningChildEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The owning reference. */ + public InverseCollectionParentEntity parent() { + return parent; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningManyToManyEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningManyToManyEntity.java new file mode 100644 index 00000000..6c0f1d56 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningManyToManyEntity.java @@ -0,0 +1,28 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; +import java.util.HashSet; +import java.util.Set; + +/** The owning side of {@link InverseManyToManyEntity}'s pair. */ +@Entity +public class OwningManyToManyEntity { + + @Id private Long id; + + @ManyToMany private Set members = new HashSet<>(); + + protected OwningManyToManyEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The owning collection. */ + public Set members() { + return Set.copyOf(members); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningOneToOneEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningOneToOneEntity.java new file mode 100644 index 00000000..9ecd3ccb --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/OwningOneToOneEntity.java @@ -0,0 +1,30 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToOne; + +/** The owning side of {@link InverseOneToOneEntity}'s pair. */ +@Entity +public class OwningOneToOneEntity { + + @Id private Long id; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "partner_id") + private InverseOneToOneEntity partner; + + protected OwningOneToOneEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The owning reference. */ + public InverseOneToOneEntity partner() { + return partner; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/UnidirectionalCollectionEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/UnidirectionalCollectionEntity.java new file mode 100644 index 00000000..100316bc --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/UnidirectionalCollectionEntity.java @@ -0,0 +1,36 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToMany; +import java.util.ArrayList; +import java.util.List; + +/** + * Accepted by the association rule: a unidirectional {@code @OneToMany} with its own join column. + * + *

Only one side maps the link, so there is nothing to keep in step. The guide still makes it the + * exception — a child the aggregate owns — rather than the default. + */ +@Entity +public class UnidirectionalCollectionEntity { + + @Id private Long id; + + @OneToMany + @JoinColumn(name = "owner_id") + private List lines = new ArrayList<>(); + + protected UnidirectionalCollectionEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The owned collection. */ + public List lines() { + return List.copyOf(lines); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionTest.java index a54e7c78..929044dc 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionTest.java @@ -2,14 +2,23 @@ package dev.caskeleton.adapter.outbound.persistence.transaction; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; +import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; import dev.caskeleton.application.transaction.NestedRootTransactionRejectedException; +import dev.caskeleton.shared.error.OperationalError; +import dev.caskeleton.shared.error.PersistenceFailureException; +import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; @@ -212,6 +221,116 @@ class SpringTransactionTest { assertThat(tm.rollbacks).isOne(); } + // ---- ADR-JPA-003 / review 04-01: a commit that loses its connection has an unknown outcome ---- + + @Test + @DisplayName("커밋 중 연결이 끊기면 재시도 불가인 DB_COMPLETION_UNKNOWN으로 알린다") + void connectionLossDuringCommitIsReportedAsCompletionUnknownNotRetryable() { + // given + RecordingTransactionManager tm = new RecordingTransactionManager(); + tm.commitFailure = + new TransactionSystemException( + "Could not commit JDBC transaction", + new SQLException("An I/O error occurred while sending to the backend.", "08006")); + SpringTransaction port = new SpringTransaction(tm); + + // when + Throwable thrown = catchThrowable(() -> port.inWrite(() -> "written")); + + // then + assertThat(thrown).isInstanceOf(TransactionCompletionUnknownException.class); + TransactionCompletionUnknownException unknown = (TransactionCompletionUnknownException) thrown; + assertThat(unknown.errorCode()).isEqualTo(OperationalError.DB_COMPLETION_UNKNOWN); + assertThat(unknown.errorCode().retryable()).isFalse(); + assertThat(unknown.retryable()).isFalse(); + assertThat(unknown.evidence()).isEqualTo(TransactionCompletionEvidence.UNKNOWN); + assertThat(unknown.context().sqlState()).isEqualTo("08006"); + } + + @Test + @DisplayName("트랜잭션을 열 때 연결에 실패하면 재시도 가능한 DB_UNAVAILABLE로 알린다") + void connectionFailureBeforeTheTransactionBeginsStaysRetryableUnavailable() { + // given + RecordingTransactionManager tm = new RecordingTransactionManager(); + tm.beginFailure = + new CannotCreateTransactionException( + "Could not open JDBC Connection for transaction", + new SQLException("Connection refused", "08001")); + SpringTransaction port = new SpringTransaction(tm); + + // when + Throwable thrown = catchThrowable(() -> port.inWrite(() -> "never-run")); + + // then + assertThat(thrown).isInstanceOf(PersistenceFailureException.class); + assertThat(((PersistenceFailureException) thrown).errorCode()) + .isEqualTo(OperationalError.DB_UNAVAILABLE); + assertThat(thrown).isNotInstanceOf(TransactionCompletionUnknownException.class); + } + + @Test + @DisplayName("본문 실행 중 연결이 끊기면 커밋 전이므로 재시도 가능한 DB_UNAVAILABLE로 알린다") + void connectionLossInsideTheActionStaysRetryableUnavailable() { + // given + RecordingTransactionManager tm = new RecordingTransactionManager(); + SpringTransaction port = new SpringTransaction(tm); + + // when + Throwable thrown = + catchThrowable( + () -> + port.inWrite( + () -> { + throw new DataAccessResourceFailureException( + "statement failed", new SQLException("connection lost", "08006")); + })); + + // then + assertThat(thrown).isInstanceOf(PersistenceFailureException.class); + assertThat(((PersistenceFailureException) thrown).errorCode()) + .isEqualTo(OperationalError.DB_UNAVAILABLE); + assertThat(tm.rollbacks).isOne(); + } + + @Test + @DisplayName("읽기 전용 트랜잭션의 커밋에서 연결이 끊기면 쓴 것이 없으므로 재시도 가능한 DB_UNAVAILABLE로 알린다") + void connectionLossDuringAReadOnlyCommitStaysRetryableUnavailable() { + // given + RecordingTransactionManager tm = new RecordingTransactionManager(); + tm.commitFailure = + new TransactionSystemException( + "Could not commit JDBC transaction", new SQLException("connection lost", "08006")); + SpringTransaction port = new SpringTransaction(tm); + + // when + Throwable thrown = catchThrowable(() -> port.inRead(() -> "read")); + + // then + assertThat(thrown).isInstanceOf(PersistenceFailureException.class); + assertThat(((PersistenceFailureException) thrown).errorCode()) + .isEqualTo(OperationalError.DB_UNAVAILABLE); + } + + @Test + @DisplayName("커밋이 제약 위반으로 확실히 거절되면 결과 불명이 아니라 그 위반 코드로 알린다") + void commitRejectedByTheServerKeepsItsDefiniteClassification() { + // given + RecordingTransactionManager tm = new RecordingTransactionManager(); + tm.commitFailure = + new TransactionSystemException( + "Could not commit JDBC transaction", + new SQLException("duplicate key value violates unique constraint", "23505")); + SpringTransaction port = new SpringTransaction(tm); + + // when + Throwable thrown = catchThrowable(() -> port.inWrite(() -> "written")); + + // then + assertThat(thrown).isInstanceOf(PersistenceFailureException.class); + assertThat(((PersistenceFailureException) thrown).errorCode()) + .isEqualTo(OperationalError.DB_UNIQUE_VIOLATION); + } + private static IllegalStateException catchAndReturn(Runnable action) { try { action.run(); @@ -226,6 +345,8 @@ class SpringTransactionTest { private final List definitions = new ArrayList<>(); private final List lifecycle = new ArrayList<>(); private boolean failCommit; + private RuntimeException beginFailure; + private RuntimeException commitFailure; private int commitAttempts; private int commits; private int rollbacks; @@ -234,6 +355,9 @@ class SpringTransactionTest { public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException { definitions.add(definition); + if (beginFailure != null) { + throw beginFailure; + } lifecycle.add("begin"); return new SimpleTransactionStatus(true); } @@ -245,6 +369,10 @@ class SpringTransactionTest { lifecycle.add("commit-failed"); throw new TransactionSystemException("commit failed"); } + if (commitFailure != null) { + lifecycle.add("commit-failed"); + throw commitFailure; + } lifecycle.add("commit"); commits++; } diff --git a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 index e32cb6f7..31f20b17 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 +++ b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 @@ -11,6 +11,7 @@ 2ba4214941a5563613b0dcc4f7cbf5f1278e342b900268721466e4bdeaa2fef2 jpa/idempotency/V1__expand_owner_safe_v2.sql 95be788589f01e32c9179acc80817e227e81805f8d518e8a9ac36e1c31b51da7 jpa/idempotency/V2__request_hash_varchar.sql 4379872989af0c97b937ff48527c788a2ba0216218d4df9435eba8c6e053ad8d jpa/notification-platform/V10__variables_payload_envelope_guard.sql +fb1eee652330995e2f761dd0c0cb9ca137b1c50dd99253aa9958c3ec130cf74b jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql 1ac7cc1c2509868eb0ce202e1917bb36846f98f17ad4922abe3fac0ef128199b jpa/notification-platform/V1__notification_platform_core.sql 0add67aa23580e51712f84fabe9b09e08401ef708cfa1b3292b120fdb5c12fa2 jpa/notification-platform/V2__notification_platform_contact_template_policy.sql f5b98598a59cc4376f5d233b410f8a5ae9f3cd94156291ebdf2d0da5a66f34ef jpa/notification-platform/V3__notification_platform_inbox_admin.sql diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRules.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRules.java index 0efad192..42c1f5ae 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRules.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRules.java @@ -5,7 +5,9 @@ import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; import com.tngtech.archunit.lang.ArchRule; +import jakarta.persistence.Embeddable; import jakarta.persistence.Entity; +import jakarta.persistence.MappedSuperclass; /** * The reusable ArchUnit rules that keep JPA mapping and exposure honest (design §7.3, §10.4). @@ -22,6 +24,8 @@ import jakarta.persistence.Entity; *

  • A {@code final} entity cannot be proxied, so every lazy reference to it is loaded eagerly. *
  • A missing no-arg constructor makes the provider fail at bootstrap, but only for entities on * a code path that was exercised. + *
  • A bidirectional association ({@code mappedBy}) is two fields for one foreign key; only the + * owning one is written, so forgetting the other leaves rows unlinked with no error. *
  • {@code org.hibernate} imports in a domain package make the domain depend on the ORM, which * is the boundary this whole template exists to hold. * @@ -116,4 +120,28 @@ public final class JpaArchitectureRules { // the production suite before any rule runs. .allowEmptyShould(true); } + + /** + * No mapped type declares the inverse ({@code mappedBy}) side of an association. + * + *

    A bidirectional pair stores one foreign key in two Java fields. Only the owning side is + * written, so the pair is correct only while every caller remembers to update both — a rule that + * lives in a developer's memory and fails silently. One side only keeps that risk visible: the + * reference is where the column is, and a collection is a query someone wrote on purpose. + */ + public static ArchRule associationsAreMappedFromOneSideOnly() { + return classes() + .that() + .areAnnotatedWith(Entity.class) + .or() + .areAnnotatedWith(MappedSuperclass.class) + .or() + .areAnnotatedWith(Embeddable.class) + .should(new SingleSidedAssociationCondition()) + .as("JPA associations are mapped from one side only") + .because( + "a bidirectional pair stays consistent only while every caller updates both sides;" + + " use a unidirectional @ManyToOne or an ID reference, and a repository query for" + + " the collection"); + } } diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java new file mode 100644 index 00000000..0456c877 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java @@ -0,0 +1,70 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch; + +import com.tngtech.archunit.core.domain.JavaAnnotation; +import com.tngtech.archunit.core.domain.JavaClass; +import com.tngtech.archunit.core.domain.JavaMember; +import com.tngtech.archunit.lang.ArchCondition; +import com.tngtech.archunit.lang.ConditionEvents; +import com.tngtech.archunit.lang.SimpleConditionEvent; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.OneToMany; +import jakarta.persistence.OneToOne; +import java.util.List; +import java.util.stream.Stream; + +/** + * Reports every association declared with {@code mappedBy} — the inverse half of a bidirectional + * pair. + * + *

    {@code mappedBy} is the one attribute that says "this field is a second copy of a link the + * other side owns". JPA writes only the owning side, so the inverse copy is correct only while + * application code remembers to update both — and nothing fails when it forgets: the row is left + * unlinked, or the in-memory graph disagrees with the database until the next load. Checking the + * attribute rather than the annotation keeps a unidirectional {@code @OneToMany} with its own + * {@code @JoinColumn}, which has nothing to keep in step, out of the report. + * + *

    Fields and methods are both inspected, because property access puts the mapping on the getter. + */ +public final class SingleSidedAssociationCondition extends ArchCondition { + + private static final List> INVERSE_CAPABLE = + List.of(OneToMany.class, OneToOne.class, ManyToMany.class); + + public SingleSidedAssociationCondition() { + super("map each association from one side only (no mappedBy)"); + } + + @Override + public void check(JavaClass mappedType, ConditionEvents events) { + Stream.concat(mappedType.getFields().stream(), mappedType.getMethods().stream()) + .forEach(member -> reportInverseSide(mappedType, member, events)); + } + + private static void reportInverseSide( + JavaClass mappedType, JavaMember member, ConditionEvents events) { + for (Class type : INVERSE_CAPABLE) { + if (!member.isAnnotatedWith(type)) { + continue; + } + JavaAnnotation annotation = member.getAnnotationOfType(type.getName()); + String mappedBy = String.valueOf(annotation.get("mappedBy").orElse("")); + if (mappedBy.isEmpty()) { + continue; + } + events.add( + SimpleConditionEvent.violated( + mappedType, + mappedType.getSimpleName() + + "." + + member.getName() + + " is @" + + type.getSimpleName() + + "(mappedBy = \"" + + mappedBy + + "\"), the inverse side of a bidirectional association. Map each association" + + " from one side only: keep the owning @ManyToOne (LAZY) or hold the other" + + " aggregate's ID, and load the collection with a repository query" + + " (docs/jpa/entity-mapping-guide.md, Associations)")); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/fetch/PagedChild.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/fetch/PagedChild.java index 81192dd4..b46d6065 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/fetch/PagedChild.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/fetch/PagedChild.java @@ -2,21 +2,17 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.fetch; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.ManyToOne; import jakarta.persistence.SequenceGenerator; import jakarta.persistence.Table; /** * The child side of the collection-fetch pagination fixture (design §26). * - *

    The {@code @ManyToOne} is {@code LAZY}. JPA's default for a to-one association is {@code - * EAGER}, which means every query that loads a child also issues a query for its parent — the - * single most common accidental N+1 in a JPA application (design §13.1). + *

    It holds no reference to its parent. {@link PagedParent}'s collection owns the {@code + * parent_id} column, so the association is mapped from one side only. */ @Entity @Table(name = "jpa_paged_child") @@ -33,10 +29,6 @@ public class PagedChild { @Column(name = "label", nullable = false, length = 64) private String label; - @ManyToOne(fetch = FetchType.LAZY, optional = false) - @JoinColumn(name = "parent_id", nullable = false) - private PagedParent parent; - protected PagedChild() { // required by the persistence provider } @@ -54,14 +46,4 @@ public class PagedChild { public String label() { return label; } - - /** The owning parent. */ - public PagedParent parent() { - return parent; - } - - /** Sets the owning side; called by {@link PagedParent#addChild}. */ - void assignParent(PagedParent owner) { - this.parent = owner; - } } diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/fetch/PagedParent.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/fetch/PagedParent.java index 97385d2f..51a27900 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/fetch/PagedParent.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/fetch/PagedParent.java @@ -7,6 +7,7 @@ import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.SequenceGenerator; import jakarta.persistence.Table; @@ -20,6 +21,10 @@ import java.util.List; * what happens when a query explicitly joins and pages it, not what happens when the mapping * fetches it eagerly for every query in the application. * + *

    The association is mapped from this side only: the collection owns the {@code parent_id} join + * column and the child has no reference back. There is no second field to keep in step, which is + * the one-side rule {@code JpaArchitectureRules.associationsAreMappedFromOneSideOnly} enforces. + * *

    Identifiers come from a sequence with an {@code allocationSize} the migration's sequence * increment must match, so the fixture can also be batched (design §28.2). */ @@ -38,11 +43,8 @@ public class PagedParent { @Column(name = "label", nullable = false, length = 64) private String label; - @OneToMany( - mappedBy = "parent", - cascade = CascadeType.ALL, - orphanRemoval = true, - fetch = FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) + @JoinColumn(name = "parent_id", nullable = false) private List children = new ArrayList<>(); protected PagedParent() { @@ -68,14 +70,8 @@ public class PagedParent { return List.copyOf(children); } - /** - * Adds a child and sets the owning side. - * - *

    Only the child holds the foreign key, so adding to this list alone would leave the row - * unlinked — the association helper is what keeps both sides consistent (design §13.4). - */ + /** Adds a child; the collection writes its {@code parent_id} on flush. */ public void addChild(PagedChild child) { children.add(child); - child.assignParent(this); } } diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/lifecycle/LifecycleChild.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/lifecycle/LifecycleChild.java index d3320a52..db172d1c 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/lifecycle/LifecycleChild.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/lifecycle/LifecycleChild.java @@ -2,21 +2,18 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.lifecycle; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.ManyToOne; import jakarta.persistence.SequenceGenerator; import jakarta.persistence.Table; /** * The owned child of the lifecycle fixture (design §13.4). * - *

    This side holds the foreign key, which makes it the owning side: an update to {@code parent} - * is what changes the {@code parent_id} column. Adding a child to the parent's list without setting - * this field leaves the row unlinked, which is why the parent's helper does both. + *

    {@link LifecycleParent}'s collection owns the {@code parent_id} column. This side exposes it + * as a read-only ID ({@code insertable = false, updatable = false}) so a query can filter by parent + * without a second, writable copy of the association. */ @Entity @Table(name = "jpa_lifecycle_child") @@ -33,9 +30,8 @@ public class LifecycleChild { @Column(name = "label", nullable = false, length = 64) private String label; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "parent_id") - private LifecycleParent parent; + @Column(name = "parent_id", insertable = false, updatable = false) + private Long parentId; protected LifecycleChild() { // required by the persistence provider @@ -55,13 +51,8 @@ public class LifecycleChild { return label; } - /** The owning parent, or {@code null} once orphaned. */ - public LifecycleParent parent() { - return parent; - } - - /** Sets the owning side; called by the parent's association helpers. */ - void assignParent(LifecycleParent owner) { - this.parent = owner; + /** The parent's identifier as last read from the database, or {@code null} before that. */ + public Long parentId() { + return parentId; } } diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/lifecycle/LifecycleParent.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/lifecycle/LifecycleParent.java index 33c0d020..ec89ad20 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/lifecycle/LifecycleParent.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/lifecycle/LifecycleParent.java @@ -7,6 +7,7 @@ import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.SequenceGenerator; import jakarta.persistence.Table; @@ -22,6 +23,10 @@ import java.util.List; * collection means the child ceases to exist. Applied to an association between two independent * aggregates, the same setting deletes rows another part of the system still owns. * + *

    The association is mapped from this side only: the collection owns the {@code parent_id} join + * column and the child keeps a read-only copy of that ID, not a reference back. Adding or removing + * through this list is the only way to change the link, so there is no second field to forget. + * *

    {@code @Version} makes the fixture usable by the optimistic-conflict contracts as well. */ @Entity @@ -43,11 +48,8 @@ public class LifecycleParent { @Column(name = "version", nullable = false) private long version; - @OneToMany( - mappedBy = "parent", - cascade = CascadeType.ALL, - orphanRemoval = true, - fetch = FetchType.LAZY) + @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) + @JoinColumn(name = "parent_id") private List children = new ArrayList<>(); protected LifecycleParent() { @@ -83,15 +85,13 @@ public class LifecycleParent { this.label = newLabel; } - /** Adds a child and sets the owning side. */ + /** Adds a child; the collection writes its {@code parent_id} on flush. */ public void addChild(LifecycleChild child) { children.add(child); - child.assignParent(this); } /** Removes a child; orphan removal deletes the row on flush. */ public void removeChild(LifecycleChild child) { children.remove(child); - child.assignParent(null); } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java index d2e7dae3..444b180a 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java @@ -6,7 +6,9 @@ import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJ import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort; import java.sql.Timestamp; import java.time.Clock; +import java.time.Duration; import java.time.Instant; +import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -23,8 +25,19 @@ import org.springframework.jdbc.core.RowMapper; * has one moves its due time rather than adding a second row, so a delivery that records AMBIGUOUS * repeatedly cannot accumulate a backlog of identical questions. * - *

    Claiming is {@code FOR UPDATE SKIP LOCKED} inside the select, for the same reason the delivery - * queue is: two workers polling the same table must not both take the same job. + *

    A claim is a lease written to the row, not a row lock. The statement picks due, unleased rows + * with {@code FOR UPDATE SKIP LOCKED} — so two claims running at the same instant skip each other — + * and in the same statement stamps {@code claimed_until} and advances {@code claim_fence}. The + * stamp is what keeps the job owned after the statement commits: a bare {@code SELECT ... FOR + * UPDATE SKIP LOCKED} on an autocommit connection releases its lock when the select ends, and every + * instance polling the table then takes the same jobs. + * + *

    No method here joins a caller transaction, unlike this leaf's other stores, and that is the + * design rather than an omission: each method is one statement, and the worker asks a provider + * between the claim and the write that follows it. Holding a transaction — and a pooled connection + * — open across that call is exactly what the lease exists to avoid. {@link #reschedule} and {@link + * #complete} match on the fence the job was claimed with, so a holder that outlived its lease + * changes nothing once somebody else has claimed the job. */ public final class JdbcReconciliationJobStore implements ReconciliationJobStorePort { @@ -37,18 +50,25 @@ public final class JdbcReconciliationJobStore implements ReconciliationJobStoreP SET next_check_at = LEAST(notification_reconciliation_job.next_check_at, EXCLUDED.next_check_at), updated_at = EXCLUDED.updated_at RETURNING id, attempt_id, provider_profile_id, next_check_at, attempts, last_result, - created_at, updated_at + created_at, updated_at, claim_fence """; private static final String CLAIM_DUE = """ - SELECT id, attempt_id, provider_profile_id, next_check_at, attempts, last_result, - created_at, updated_at - FROM notification_reconciliation_job - WHERE next_check_at <= ? - ORDER BY next_check_at, id - LIMIT ? - FOR UPDATE SKIP LOCKED + WITH claimable AS ( + SELECT id FROM notification_reconciliation_job + WHERE next_check_at <= ? + AND (claimed_until IS NULL OR claimed_until <= ?) + ORDER BY next_check_at, id + LIMIT ? + FOR UPDATE SKIP LOCKED) + UPDATE notification_reconciliation_job AS job + SET claimed_until = ?, + claim_fence = job.claim_fence + 1 + FROM claimable + WHERE job.id = claimable.id + RETURNING job.id, job.attempt_id, job.provider_profile_id, job.next_check_at, job.attempts, + job.last_result, job.created_at, job.updated_at, job.claim_fence """; private static final String RESCHEDULE = @@ -57,11 +77,14 @@ public final class JdbcReconciliationJobStore implements ReconciliationJobStoreP SET attempts = attempts + 1, last_result = ?, next_check_at = ?, + claimed_until = NULL, updated_at = ? WHERE id = ? + AND claim_fence = ? """; - private static final String COMPLETE = "DELETE FROM notification_reconciliation_job WHERE id = ?"; + private static final String COMPLETE = + "DELETE FROM notification_reconciliation_job WHERE id = ? AND claim_fence = ?"; private static final RowMapper MAPPER = (rows, rowNumber) -> @@ -73,7 +96,8 @@ public final class JdbcReconciliationJobStore implements ReconciliationJobStoreP rows.getInt("attempts"), Optional.ofNullable(rows.getString("last_result")), rows.getTimestamp("created_at").toInstant(), - rows.getTimestamp("updated_at").toInstant()); + rows.getTimestamp("updated_at").toInstant(), + rows.getLong("claim_fence")); private final JdbcOperations jdbc; private final Clock clock; @@ -114,12 +138,24 @@ public final class JdbcReconciliationJobStore implements ReconciliationJobStoreP } @Override - public List claimDue(int limit, Instant now) { + public List claimDue(int limit, Instant now, Duration lease) { Objects.requireNonNull(now, "now"); + Objects.requireNonNull(lease, "lease"); if (limit < 1) { throw new IllegalArgumentException("limit"); } - return jdbc.query(CLAIM_DUE, MAPPER, Timestamp.from(now), limit); + if (lease.isNegative() || lease.isZero()) { + throw new IllegalArgumentException("lease must be positive"); + } + Timestamp at = Timestamp.from(now); + List claimed = + jdbc.query(CLAIM_DUE, MAPPER, at, at, limit, Timestamp.from(now.plus(lease))); + // UPDATE ... RETURNING does not keep the CTE's order. + return claimed.stream() + .sorted( + Comparator.comparing(ReconciliationJob::nextCheckAt) + .thenComparing(ReconciliationJob::id)) + .toList(); } @Override @@ -133,12 +169,13 @@ public final class JdbcReconciliationJobStore implements ReconciliationJobStoreP result == null ? null : result.substring(0, Math.min(result.length(), 40)), Timestamp.from(nextCheckAt), Timestamp.from(clock.instant()), - job.id()); + job.id(), + job.claimFence()); } @Override public void complete(ReconciliationJob job) { Objects.requireNonNull(job, "job"); - jdbc.update(COMPLETE, job.id()); + jdbc.update(COMPLETE, job.id(), job.claimFence()); } } diff --git a/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql new file mode 100644 index 00000000..2b1dc5dd --- /dev/null +++ b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql @@ -0,0 +1,26 @@ +-- 04-02 — the reconciliation job claim held nothing. +-- +-- The claim was SELECT ... FOR UPDATE SKIP LOCKED run on an autocommit connection, so the row lock +-- ended with the statement that took it. A second instance polling a moment later read the same due +-- rows, both asked the provider, and both advanced attempts — a job reached its attempt limit twice +-- as fast for every instance that held it. +-- +-- Ownership is now durable rather than a lock: the claim stamps claimed_until (until when the holder +-- owns the job) and advances claim_fence. Another instance takes the row only after claimed_until +-- has passed, and every write after the claim names the fence it was claimed with, so a holder that +-- outlived its lease cannot reschedule or delete a job somebody else now holds. The provider call +-- stays outside any transaction, which is the reason for a lease rather than a long-held row lock. + +ALTER TABLE notification_reconciliation_job + ADD COLUMN IF NOT EXISTS claimed_until timestamptz, + ADD COLUMN IF NOT EXISTS claim_fence bigint NOT NULL DEFAULT 0; + +ALTER TABLE notification_reconciliation_job + ADD CONSTRAINT ck_notification_reconciliation_claim_fence CHECK (claim_fence >= 0); + +COMMENT ON COLUMN notification_reconciliation_job.claimed_until IS + 'Until when the instance that last claimed this job owns it. NULL or past means claimable once ' + 'next_check_at is due.'; +COMMENT ON COLUMN notification_reconciliation_job.claim_fence IS + 'Advanced by every claim. Reschedule and complete match on it, so a superseded holder changes ' + 'nothing.'; diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java index 666de82a..e3d5bdcf 100644 --- a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java +++ b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java @@ -141,6 +141,9 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand if (source.contains("'ACQUIRED'")) { return done(idempotencyClaim(rendered, arguments)); } + if (source.contains("'renewedFromRev'")) { + return done(idempotencyRenew(rendered, arguments)); + } if (source.contains("'state', ARGV[5], 'rev', rev + 1")) { return done(idempotencyTransition(rendered, arguments)); } @@ -278,6 +281,46 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand return reply("APPLIED", attempt, rev + 1, owner, "", ""); } + private List idempotencyRenew(String rendered, List arguments) { + String ownerToken = text(arguments.get(0)); + String handleRevision = text(arguments.get(1)); + String operationId = text(arguments.get(2)); + String leaseMillis = text(arguments.get(3)); + String state = field(rendered, "state"); + if (state == null) { + return reply("ABSENT", 0, 0, "", "", ""); + } + long attempt = Long.parseLong(field(rendered, "attempt")); + long rev = Long.parseLong(field(rendered, "rev")); + String owner = field(rendered, "owner"); + if (!ownerToken.equals(owner)) { + return reply("NOT_OWNER", attempt, rev, owner, "", ""); + } + if (!operationId.equals(field(rendered, "op"))) { + return reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); + } + long expectedRev = Long.parseLong(handleRevision); + if (rev != expectedRev) { + // A lost renewal reply: the record moved on by exactly the renewal this handle asked for. + if ("EXECUTING".equals(state) + && rev == expectedRev + 1 + && handleRevision.equals(field(rendered, "renewedFromRev"))) { + return leaseMillis.equals(field(rendered, "renewedLease")) + ? reply("ALREADY", attempt, rev, owner, "", "") + : reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); + } + return reply("NOT_OWNER", attempt, rev, owner, "", ""); + } + if (!"EXECUTING".equals(state)) { + return reply("WRONG_STATE", attempt, rev, owner, state, ""); + } + setField(rendered, "leaseUntil", Long.toString(now() + Long.parseLong(leaseMillis))); + setField(rendered, "rev", Long.toString(rev + 1)); + setField(rendered, "renewedFromRev", handleRevision); + setField(rendered, "renewedLease", leaseMillis); + return reply("APPLIED", attempt, rev + 1, owner, "", ""); + } + private List idempotencyRelease(String rendered, List arguments) { String ownerToken = text(arguments.get(0)); String operationId = text(arguments.get(2)); @@ -484,6 +527,9 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand if (source.contains("redis.sha1hex(current)")) { return done(replaceIfObserved(text(key), arguments)); } + if (source.contains("strictlyNewer")) { + return done(replaceIfRevisionNewer(text(key), arguments)); + } if (source.contains("redis.call('TIME')") && source.contains("return {1}")) { return done(1L); } @@ -514,6 +560,49 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand return 1L; } + /** + * The cache's revision-ordered replacement: applies when nothing is stored, when the stored entry + * is from an older region generation, or when the caller's decimal revision is strictly greater + * than the stored one at the same generation and schema version. + */ + private long replaceIfRevisionNewer(String rendered, List arguments) { + Entry current = live(rendered); + if (current != null) { + // digest(64) | version | revision | generation | ... + String stored = current.text(); + if (stored.length() <= 65 || stored.charAt(64) != '|') { + return 0L; + } + String[] header = stored.substring(65).split("\\|", 4); + if (header.length < 4 || !header[0].equals(text(arguments.get(3)))) { + return 0L; + } + long storedGeneration; + try { + storedGeneration = Long.parseLong(header[2]); + } catch (NumberFormatException corrupt) { + return 0L; + } + long writerGeneration = Long.parseLong(text(arguments.get(4))); + if (storedGeneration > writerGeneration) { + return 0L; + } + if (storedGeneration == writerGeneration) { + String storedRevision = header[1]; + String candidate = text(arguments.get(0)); + if (!storedRevision.matches("0|[1-9][0-9]*") + || new java.math.BigInteger(candidate) + .compareTo(new java.math.BigInteger(storedRevision)) + <= 0) { + return 0L; + } + } + } + long ttlMillis = Long.parseLong(text(arguments.get(2))); + entries.put(rendered, new Entry(arguments.get(1), now() + ttlMillis)); + return 1L; + } + /** Returns the live fields of a hash. */ private Map hash(String rendered) { return hashes.computeIfAbsent(rendered, unusedKey -> new LinkedHashMap<>()); diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java index 19c671e1..ce6087ea 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java @@ -7,11 +7,13 @@ import org.springframework.core.env.Environment; * One fail-fast startup rule over the resolved environment. * *

    A rule only finds violations; it never throws and never decides when it runs. The {@link - * StartupRuleRunner} runs every rule a module contributed — each is an ordinary bean — once, after - * all singletons exist, and raises the violations of a rule as the typed startup failure of its - * {@link #phase()}. Before this, sixteen validators across the composition root and the JPA module - * each implemented {@code SmartInitializingSingleton}, opened their own validation context and - * chose their own way to throw; the rule a module adds is now a list of messages and nothing else. + * StartupRuleRunner} runs every rule a module contributed — each is a bean — once, before any other + * singleton is created, and raises the violations of a rule as the typed startup failure of its + * {@link #phase()}. Declare a rule with a {@code static} {@code @Bean} method and no parameters, so + * running it early pulls nothing else forward. Before this, sixteen validators across the + * composition root and the JPA module each implemented {@code SmartInitializingSingleton}, opened + * their own validation context and chose their own way to throw; the rule a module adds is now a + * list of messages and nothing else. * *

    A check that needs a bean other than the environment — a secret source, the datasource, the * bean factory — is not a rule and stays a bean of its own. diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleAutoConfiguration.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleAutoConfiguration.java index 372e5645..40bfcd09 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleAutoConfiguration.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleAutoConfiguration.java @@ -1,6 +1,5 @@ package dev.caskeleton.adapter.outbound.support.startup; -import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; @@ -13,15 +12,14 @@ import org.springframework.core.env.Environment; public class StartupRuleAutoConfiguration { /** - * The runner over every contributed rule. + * The runner over every contributed rule. Static, as a bean-factory post-processor must be, so + * creating it does not create this configuration class before the bean factory is ready. * * @param environment the resolved environment - * @param rules the rules modules contributed * @return the runner */ @Bean - public StartupRuleRunner startupRuleRunner( - Environment environment, ObjectProvider rules) { - return new StartupRuleRunner(environment, rules.orderedStream().toList()); + public static StartupRuleRunner startupRuleRunner(Environment environment) { + return new StartupRuleRunner(environment); } } diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java index ec1d8903..55934d0e 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java @@ -1,43 +1,74 @@ package dev.caskeleton.adapter.outbound.support.startup; +import java.util.ArrayList; import java.util.List; import java.util.Objects; -import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.core.env.Environment; /** - * Runs every {@link StartupRule} the context holds, once, after all singletons are instantiated and - * before the context finishes refreshing. + * Runs every {@link StartupRule} the context holds, once, after the bean definitions are known and + * before any ordinary singleton — a datasource, a Flyway migration, a broker client — is created. * *

    The one place a rule's violations become a failure: a {@link StartupValidationContext} opened * for the rule's phase, so the exit code, the {@code error.code} field and the {@code * startup.phase} log field follow from the rule's declaration. Rules run in bean order and the * first rule with violations stops the boot, reporting all of that rule's violations at once. + * + *

    Why a bean-factory post-processor

    + * + *

    The rules exist to refuse a configuration before it reaches an external system: a prod + * datasource without {@code sslmode=verify-full} must not send its password in plain text, and a + * forbidden Flyway option must not have migrated the schema by the time it is reported. The runner + * used to be a {@code SmartInitializingSingleton}, which is called after every singleton exists — + * after the datasource opened its connection and Flyway ran (07-02). A {@link + * BeanFactoryPostProcessor} runs once configuration classes and conditions are resolved, so every + * contributed rule is a known bean definition, and before the bean factory creates anything else. + * + *

    The cost is that the rule beans are created that early, before any {@code BeanPostProcessor} + * is registered. That is why a rule reads only the {@link Environment} and is declared by a {@code + * static} {@code @Bean} method: it then pulls neither another bean nor its configuration class + * forward. Rules are found without eager initialization, so no {@code FactoryBean} — an entity + * manager factory, say — is created to learn its type. */ -public final class StartupRuleRunner implements SmartInitializingSingleton { +public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordered { private final Environment environment; - private final List rules; - /** * Creates the runner. * * @param environment the resolved environment - * @param rules every rule the context holds */ - public StartupRuleRunner(Environment environment, List rules) { + public StartupRuleRunner(Environment environment) { this.environment = Objects.requireNonNull(environment, "environment must be non-null"); - this.rules = List.copyOf(Objects.requireNonNull(rules, "rules must be non-null")); } @Override - public void afterSingletonsInstantiated() { - for (StartupRule rule : rules) { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { + for (StartupRule rule : rules(beanFactory)) { enforce(rule, environment); } } + /** First among the ordinary post-processors: nothing they do should precede a refused boot. */ + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + + private static List rules(ConfigurableListableBeanFactory beanFactory) { + List rules = new ArrayList<>(); + for (String name : beanFactory.getBeanNamesForType(StartupRule.class, true, false)) { + rules.add(beanFactory.getBean(name, StartupRule.class)); + } + AnnotationAwareOrderComparator.sort(rules); + return rules; + } + /** * Runs one rule and raises its violations as its phase's typed failure. * diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java index 1d4567b2..c35b885f 100644 --- a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -32,6 +33,35 @@ class StartupRuleRunnerTest { .isEqualTo(StartupErrorCode.PROFILE_MISMATCH)); } + @Test + @DisplayName("규칙 위반이 있으면 다른 빈이 하나도 만들어지기 전에 기동이 실패한다") + void aViolatedRuleFailsTheBootBeforeAnyOtherBeanIsCreated() { + // given + AtomicInteger connectionsCreated = new AtomicInteger(); + + // when + runner + .withBean( + StartupRule.class, + () -> rule(StartupPhase.PROFILE_CHECK, "prod forbids these", List.of("a=1"))) + .withBean( + "connectionLikeBean", + Object.class, + () -> { + connectionsCreated.incrementAndGet(); + return new Object(); + }) + .run( + context -> { + // then + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .extracting(failure -> ((StartupFailureException) failure).errorCode()) + .isEqualTo(StartupErrorCode.PROFILE_MISMATCH); + assertThat(connectionsCreated).hasValue(0); + }); + } + @Test void aContextWhoseRulesFindNothingStarts() { runner diff --git a/src/app-bootstrap/CLAUDE.md b/src/app-bootstrap/CLAUDE.md index f821acf5..99057767 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`, `WebSecurityAutoConfiguration`) and support + covers `dev.caskeleton.bootstrap` only; web (`WebAdapterAutoConfiguration`, `WebSecurityAutoConfiguration`, `WebMethodSecurityAutoConfiguration`) 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: `operation` (the durable operation use cases and their `/operations` endpoints, on only when the operation store and the @@ -83,7 +83,8 @@ configurations, Redis as one 376-line class. `ReadinessGroup`, `RuntimeWarnings`), so capability modules fail the same way without depending on this leaf. `runtime/startup/` keeps only `StartupFailureExceptionReporter`. - **An environment-only guard is a `StartupRule` bean** (`support.startup`): it returns violations, - and the one `StartupRuleRunner` raises them. A guard that needs another bean stays a bean. A + and the one `StartupRuleRunner` raises them before any other singleton exists (declare it with a + parameterless `static` `@Bean` method). A guard that needs another bean stays a bean. A capability's production secrets are the capability's: its module contributes a `RequiredProductionSecrets` bean, and `SecretSourceValidator` checks the names without knowing which roles exist. diff --git a/src/app-bootstrap/README.md b/src/app-bootstrap/README.md index 1720500b..62be2607 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`·`WebSecurityAutoConfiguration`)과 support(`OutboundSupportConfig`)도 +`dev.caskeleton.bootstrap`만 보고, web(`WebAdapterAutoConfiguration`·`WebSecurityAutoConfiguration`·`WebMethodSecurityAutoConfiguration`)과 support(`OutboundSupportConfig`)도 자기 auto-configuration으로 들어온다. - 줄마다 필요한 env와 끄는 키: [src/README.md](../README.md)의 "기능 추가 = 한 줄 + env" 표. @@ -156,8 +156,10 @@ README의 "startup" 절에 있다. 환경만 읽는 검사(`RuntimeNumericBoundsValidator`, `ErrorDetailExposureSafetyValidator`와 persistence-jpa의 datasource·Flyway·OSIV·TLS·vendor·Hikari 검사)는 `StartupRule`이다: 위반 목록만 -돌려주고, `adapter:outbound:support`의 `StartupRuleRunner` 하나가 모든 싱글톤 생성 후 규칙마다 그 -phase의 종료 코드로 실패시킨다. 다른 bean이 필요한 검사(`SecretSourceValidator`의 `SecretSourcePort`, +돌려주고, `adapter:outbound:support`의 `StartupRuleRunner` 하나가 다른 싱글톤을 만들기 전에(bean factory +post-processor 단계) 규칙마다 그 phase의 종료 코드로 실패시킨다. 그래서 prod 금지 값은 DataSource가 +연결을 열거나 Flyway가 마이그레이션하기 전에 거부된다. 규칙은 그만큼 일찍 만들어지므로 매개변수 없는 +`static` `@Bean` 메서드로 선언한다. 다른 bean이 필요한 검사(`SecretSourceValidator`의 `SecretSourcePort`, `StartupSafetyValidator`의 bean factory, persistence-jpa의 datasource 검사)는 계속 bean이고, 부팅 전에 돌아야 하는 profile 규칙(`RuntimeEnvironmentProfileValidator`)은 `EnvironmentPostProcessor`로 남는다. diff --git a/src/app-bootstrap/build.gradle b/src/app-bootstrap/build.gradle index 9b8dca31..2a0a7309 100644 --- a/src/app-bootstrap/build.gradle +++ b/src/app-bootstrap/build.gradle @@ -218,9 +218,9 @@ dependencies { // Micrometer core for the bootstrap meters (no-op without a MeterRegistry). See README. implementation 'io.micrometer:micrometer-core' - // OTel/Micrometer tracer runtime (exporter stays off until an OTLP endpoint is set). See README. + // The Micrometer Tracing API the tracing contract tests name. The tracer runtime itself — Boot's + // tracing auto-configuration and the OTLP exporter — is composition:service-runtime's. implementation 'io.micrometer:micrometer-tracing-bridge-otel' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp' // Actuator + Prometheus registry (health/info/prometheus/loggers endpoints). implementation 'org.springframework.boot:spring-boot-starter-actuator' diff --git a/src/app-bootstrap/gradle.lockfile b/src/app-bootstrap/gradle.lockfile index f4d9d3fb..6a5c4975 100644 --- a/src/app-bootstrap/gradle.lockfile +++ b/src/app-bootstrap/gradle.lockfile @@ -133,7 +133,7 @@ io.opentelemetry:opentelemetry-common:1.55.0=architectureTestCompileClasspath,ar io.opentelemetry:opentelemetry-context:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-exporter-common:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-exporter-otlp-common:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-exporter-sender-okhttp:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-sdk-common:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -297,7 +297,10 @@ org.springframework.boot:spring-boot-jpa:4.0.8=architectureTestCompileClasspath, org.springframework.boot:spring-boot-mail:4.0.8=architectureTestRuntimeClasspath,qualificationRuntimeClasspath org.springframework.boot:spring-boot-micrometer-metrics:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-micrometer-observation:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-tracing-opentelemetry:4.0.8=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-tracing:4.0.8=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-mongodb:4.0.8=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot-opentelemetry:4.0.8=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-persistence:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-reactor:4.0.8=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath org.springframework.boot:spring-boot-resttestclient:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java index 94363b8a..fc1097dc 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java @@ -95,6 +95,11 @@ class JpaProductionArchitectureTest { JpaArchitectureRules.noGenericRepository().check(productionClasses); } + @Test + void everyProductionAssociationIsMappedFromOneSideOnly() { + JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(productionClasses); + } + @Test @DisplayName("no entity uses two audit mechanisms at once") void noEntityUsesTwoAuditMechanismsAtOnce() { diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java index bf99b5dc..380a76c9 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java @@ -20,12 +20,12 @@ public class RuntimeSafetyConfig { } @Bean - RuntimeNumericBoundsValidator runtimeNumericBoundsValidator() { + static RuntimeNumericBoundsValidator runtimeNumericBoundsValidator() { return new RuntimeNumericBoundsValidator(); } @Bean - ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator() { + static ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator() { return new ErrorDetailExposureSafetyValidator(); } } diff --git a/src/app-bootstrap/src/main/resources/application.yml b/src/app-bootstrap/src/main/resources/application.yml index f4e5bd11..be55f13f 100644 --- a/src/app-bootstrap/src/main/resources/application.yml +++ b/src/app-bootstrap/src/main/resources/application.yml @@ -42,7 +42,8 @@ spring: # OIDC issuer (e.g., Keycloak realm URL). Spring Boot resolves JWKS from # /.well-known/openid-configuration at this URI. issuer-uri: ${APP_SECURITY_JWT_ISSUER} - # validated against the JWT `aud` claim; blank disables the check + # Spring's own decoder is replaced by JwtDecoderConfig, which validates `aud` against + # app.security.audience (required in jwt mode; blank refuses startup) audiences: ${APP_SECURITY_JWT_AUDIENCE} main: # off | console | log diff --git a/src/app-bootstrap/src/main/resources/config/observability.yml b/src/app-bootstrap/src/main/resources/config/observability.yml index 15ca1726..5b5b6d1a 100644 --- a/src/app-bootstrap/src/main/resources/config/observability.yml +++ b/src/app-bootstrap/src/main/resources/config/observability.yml @@ -151,11 +151,11 @@ app: # sentinel; prod MUST supply a real secret-manager value. pseudonymization-salt: ${APP_PRIVACY_PSEUDONYMIZATION_SALT:} # feature-distributed-tracing-contract D1/D4/D6 — tracing seam settings. - # The OTel/Micrometer tracer runtime is active in this repo (Plan A — seam activated): - # micrometer-tracing-bridge-otel + opentelemetry-exporter-otlp are wired in - # app-bootstrap/build.gradle. The exporter remains off while OTEL_EXPORTER_OTLP_ENDPOINT - # is blank (url_or_empty default). A fork can supply the endpoint via env or override - # SpanErrorRecorder with its own bean. + # The tracer is Spring Boot's (spring-boot-micrometer-tracing-opentelemetry, carried by + # composition:service-runtime): each HTTP request is a span. TracingEnvironmentPostProcessor + # translates these keys into Boot's: OTEL_EXPORTER_OTLP_ENDPOINT is the OTLP base address and + # spans go to /v1/traces over HTTP; blank = no exporter bean at all. + # enabled=false removes Boot's tracing auto-configuration (no Tracer bean). # D4 disabled-fallback: even when enabled=false, WebMvcRequestIdFilter always # generates a W3C traceparent so meta.traceId and log trace_id are never null. # D6 per-runtime defaults: prod=0.01 / dev·local=1.0 (RuntimeEnvironment SSOT). diff --git a/src/app-bootstrap/src/main/resources/config/security.yml b/src/app-bootstrap/src/main/resources/config/security.yml index e08e190f..f0919642 100644 --- a/src/app-bootstrap/src/main/resources/config/security.yml +++ b/src/app-bootstrap/src/main/resources/config/security.yml @@ -8,7 +8,8 @@ app: auth-mode: ${APP_SECURITY_AUTH_MODE:jwt} # Required only in jwt mode. issuer-uri: ${APP_SECURITY_JWT_ISSUER} - # blank to skip audience check + # Required in jwt mode; blank refuses startup. Comma-separated client ids: a token passes when + # its `aud` names any of them, and only these clients' resource_access roles are read. audience: ${APP_SECURITY_JWT_AUDIENCE} # comma-separated list (Spring binds to List) # diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/TracingExportSystemTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/TracingExportSystemTest.java new file mode 100644 index 00000000..dec8507d --- /dev/null +++ b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/TracingExportSystemTest.java @@ -0,0 +1,162 @@ +package dev.caskeleton.bootstrap.composition; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.WebApplicationType; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * The shipped composition exports the spans of an HTTP request to the OTLP endpoint an operator + * names, and exports nothing when none is named. + * + *

    The receiver is a plain HTTP server in this JVM standing in for an OpenTelemetry collector. It + * records what arrives at the OTLP/HTTP trace path; the request's trace id is looked for in those + * bytes, because OTLP/protobuf carries a trace id as its 16 raw bytes. Finding it proves three + * things at once: a span was made, it was exported to the configured address, and it belongs to the + * trace the response and the access log name. + */ +class TracingExportSystemTest { + + private static final String TRACES_PATH = "/v1/traces"; + + private static final Pattern META_TRACE_ID = + Pattern.compile("\"traceId\"\\s*:\\s*\"([0-9a-f]{32})\""); + + private final List receivedTraceExports = new CopyOnWriteArrayList<>(); + private HttpServer collector; + + @BeforeEach + void startCollector() throws IOException { + collector = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + collector.createContext( + TRACES_PATH, + exchange -> { + try (InputStream body = exchange.getRequestBody()) { + receivedTraceExports.add(body.readAllBytes()); + } + exchange.sendResponseHeaders(200, -1); + exchange.close(); + }); + collector.start(); + } + + @AfterEach + void stopCollector() { + collector.stop(0); + } + + @Test + @DisplayName("OTLP endpoint를 주면 HTTP 요청의 span이 그 주소로 나가고 trace id가 응답 meta와 같다") + void aRequestSpanIsExportedToTheConfiguredEndpointUnderTheResponseTraceId() throws Exception { + // given + String endpoint = "http://127.0.0.1:" + collector.getAddress().getPort(); + String metaTraceId; + String traceparent; + try (ConfigurableApplicationContext context = + start("--OTEL_EXPORTER_OTLP_ENDPOINT=" + endpoint)) { + + // when + HttpResponse response = get(context, "/api/tracing-probe"); + metaTraceId = metaTraceId(response.body()); + traceparent = response.headers().firstValue("traceparent").orElseThrow(); + assertThat(beanNamesOfType(context, "io.opentelemetry.sdk.trace.export.SpanExporter")) + .isNotEmpty(); + } // closing the context shuts the tracer provider down, which flushes the batch + + // then + assertThat(traceparent).contains(metaTraceId); + byte[] traceIdBytes = HexFormat.of().parseHex(metaTraceId); + assertThat(receivedTraceExports) + .as("an OTLP trace export reached %s%s", endpoint, TRACES_PATH) + .isNotEmpty() + .anySatisfy(body -> assertThat(indexOf(body, traceIdBytes)).isNotNegative()); + } + + @Test + @DisplayName("OTLP endpoint가 비어 있으면 span exporter 없이 기동하고 아무것도 내보내지 않는다") + void withoutAnEndpointNothingIsExported() throws Exception { + // given + try (ConfigurableApplicationContext context = start("--OTEL_EXPORTER_OTLP_ENDPOINT=")) { + + // when + get(context, "/api/tracing-probe"); + + // then + assertThat(beanNamesOfType(context, "io.opentelemetry.sdk.trace.export.SpanExporter")) + .isEmpty(); + } + assertThat(receivedTraceExports).isEmpty(); + } + + private static ConfigurableApplicationContext start(String... extra) { + String[] arguments = + Stream.of( + ShippedCompositionHarness.requiredOperatorInputs(), + ShippedCompositionHarness.allOffExcept("--app.tracing.enabled=true"), + new String[] {"--server.port=0", "--management.server.port=0"}, + extra) + .flatMap(Arrays::stream) + .toArray(String[]::new); + return ShippedCompositionHarness.shippedComposition("local") + .web(WebApplicationType.SERVLET) + .run(arguments); + } + + private static HttpResponse get(ConfigurableApplicationContext context, String path) + throws IOException, InterruptedException { + String port = context.getEnvironment().getRequiredProperty("local.server.port"); + try (HttpClient client = HttpClient.newHttpClient()) { + return client.send( + HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + path)).GET().build(), + HttpResponse.BodyHandlers.ofString()); + } + } + + private static String metaTraceId(String body) { + Matcher matcher = META_TRACE_ID.matcher(body); + assertThat(matcher.find()).as("response envelope carries meta.traceId: %s", body).isTrue(); + return matcher.group(1); + } + + private static List beanNamesOfType(ConfigurableApplicationContext context, String type) { + ClassLoader loader = context.getClassLoader(); + try { + return List.of(context.getBeanNamesForType(Class.forName(type, false, loader))); + } catch (ClassNotFoundException absent) { + return List.of(); + } + } + + private static int indexOf(byte[] haystack, byte[] needle) { + outer: + for (int i = 0; i + needle.length <= haystack.length; i++) { + for (int j = 0; j < needle.length; j++) { + if (haystack[i + j] != needle[j]) { + continue outer; + } + } + return i; + } + return -1; + } +} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/TracingActivationContextTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/TracingActivationContextTest.java index 9dc1fbb1..14632ba2 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/TracingActivationContextTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/TracingActivationContextTest.java @@ -44,8 +44,6 @@ import org.springframework.context.annotation.Import; "app.tracing.enabled=true", "app.tracing.sample-rate=", "app.tracing.exporter.otlp-endpoint=", - // Spring Boot management.tracing: enable for this slice - "management.tracing.enabled=true", "spring.application.name=tracing-test" }) class TracingActivationContextTest { @@ -62,7 +60,7 @@ class TracingActivationContextTest { @Test void tracerBeanIsPresent() { - // Tracer bean provided by micrometer-tracing-bridge-otel autoconfiguration + // Tracer bean provided by Boot's OpenTelemetry tracing auto-configuration assertThat(context.getBean(Tracer.class)) .as("Tracer bean must be present after adding micrometer-tracing-bridge-otel") .isNotNull(); @@ -83,7 +81,7 @@ class TracingActivationContextTest { @Test void contextLoadsWithBlankExporterEndpoint() { // Validates that blank OTEL_EXPORTER_OTLP_ENDPOINT does not cause startup failure. - // The OTel exporter autoconfiguration silently disables the exporter when endpoint is blank. + // A blank endpoint never reaches Boot's exporter key, so no exporter is created. assertThat(context).isNotNull(); } diff --git a/src/application-core/README.md b/src/application-core/README.md index c2213f46..c3118af6 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -292,8 +292,8 @@ application 계층이 claim·replay·복구 **정책** 을 소유하고, 저장 - 모두 **프레임워크-free, application 소유**(`AuthorizationDeniedException` 선례). web adapter 가 경계에서 HTTP 코드로 매핑한다. 진단 메시지는 scope digest 만 **로그용으로** 담고, 클라이언트에는 핸들러가 고정 client-safe 메시지로 대체한다(fingerprint 자체는 노출 안 함). -- retryable: mismatch / in-flight 모두 `false`. 클라이언트는 body 를 고치거나 결과를 polling 해야지 - 단순 재시도를 하면 안 된다. recovery-required 는 재생도 재실행도 안전하지 않다 — 비즈니스 +- retryable: mismatch 는 `false`(body 를 고쳐야 한다). in-flight 는 `true`: 결과 불명. 같은 + `Idempotency-Key`로 `Retry-After` 뒤 재전송. 새 키 금지(`docs/web/http-contract.md` §2). recovery-required 는 재생도 재실행도 안전하지 않다 — 비즈니스 데이터로만 판단할 수 있다. --- @@ -364,9 +364,20 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. 2. `occurred_at` 오름차순으로 방어적 정렬(claim 쿼리도 정렬하지만, adapter 가 안 해도 relay 가 FIFO 를 강제한다). 3. 각 이벤트를 **트랜잭션 밖에서** 발행하고 결과로 상태 머신을 구동한다: - - 발행 성공 → `inWrite { markPublished }` → `PUBLISHED`. - - 발행 실패(`RuntimeException`): `attemptCount >= maxAttempts` 면 `markDead`, 아니면 - `markFailed(nextAttemptAt)`를 먼저 성공시킨 뒤 해당 typed failure report를 보낸다. + - 발행 성공(`CONFIRMED`) → `inWrite { markPublished }` → `PUBLISHED`. + - 확정 거부(`REJECTED_BEFORE_SEND`·`REJECTED_AFTER_BROKER`) → 시도 예산과 무관하게 바로 `markDead`. + - 일시적 실패(`AMBIGUOUS`·`REJECTED_RETRYABLE`, 즉 `OutboxPublishOutcome.retryable()`) → + 시도 예산을 쓰지 않고 항상 `markFailed(nextAttemptAt)`. broker 정지·종료 중·permit 부족· + credential 교체는 모든 행을 같은 방식으로 실패시키고 저절로 끝나므로, 예산을 쓰게 하면 몇 분 + 장애가 aggregate 머리마다 DEAD 행을 남긴다(2026-11-01 리뷰 06-01·06-03). + - 발행 예외(`RuntimeException`, adapter가 분류하지 못한 실패): `attemptCount >= maxAttempts` 면 + `markDead`, 아니면 `markFailed(nextAttemptAt)`. 예산은 이 경우에만 쓴다 — payload 자체 결함일 + 수 있는 실패가 aggregate를 영원히 막지 않게 하는 장치다. `attemptCount`는 일시적 실패의 claim도 + 센다. 그래서 장애를 오래 기다린 행은 그 뒤 첫 발행 예외에서 바로 DEAD가 된다(알려진 한계). + - 전이를 먼저 성공시킨 뒤 해당 typed failure report를 보낸다. + - `nextAttemptAt` 의 기준 시각은 **그 행이 실패한 시각**(`clock.instant()`)이다. 회차 시작 + 시각을 쓰면 broker가 멈춘 동안 publish 하나가 deadline(약 5초)을 다 쓰므로 배치 뒤쪽 행은 + 표시되는 순간 이미 재시도 시각이 지나 있어 지연이 사라진다. - **발행 실패는 절대 삼키지 않는다**: relay 는 각 발행 예외를 잡아 FAILED/DEAD 상태 머신을 구동하고, 성공한 전이만 `OutboxRelayFailureReportPort`로 보고한 뒤 rethrow 하지 않는다 (스케줄러 루프가 다음 이벤트로 계속 가야 하므로). 상태 전이가 실패하면 예외가 전파되고 report는 @@ -399,10 +410,17 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. - relay 재시도 스케줄링 정책(I10). 이름과 달리 "full jitter" 가 아니다 — full jitter 는 0 을 고를 수 있고, relay 재시도가 실패한 그 순간에 다시 due 가 되면 안 된다. -- 공식: `base = 30s`, `maxAttempts = 3`, `delay = ceiling(attemptCount) + U[0, base]`, - `nextAttemptAt = now + delay`. `ceiling` 은 shared-contract `Backoff` 의 - `base × 2^(attemptCount-1)` 이고 마지막 시도 값(120s)에서 멈춘다. `attemptCount` 는 방금 실패한 - 시도의 1-based 번호다. +- 공식: `base = 30s`, `maxDelay = 5m`, `maxAttempts = 3`, `delay = ceiling(attemptCount) + U[0, base]`, + `nextAttemptAt = failedAt + delay`. `ceiling` 은 shared-contract `Backoff` 의 + `base × 2^(attemptCount-1)` 이고 `maxDelay`(5분)에서 멈춘다. `attemptCount` 는 방금 실패한 + 시도의 1-based 번호다. 예산 안(1·2회차)의 값은 30s·60s 그대로라 registry·runbook 숫자가 유지된다. +- `maxAttempts` 는 발행 예외(분류되지 않은 실패)에만 적용된다. 일시적 결과(`retryable()`)는 예산 없이 + `maxDelay` 간격까지 늘어나며 계속 재시도된다. 그래서 broker가 돌아오면 늦어도 약 5분 30초 안에 + 적체가 저절로 빠진다. +- 버린 대안: `MAX_ATTEMPTS` 만 늘리기(장애 길이에 비례해 계속 키워야 하고 진짜 poison 행이 늦게 + 격리된다), 예산을 설정 키로 외부화(I10 — registry·runbook과 어긋난다; 일시적 실패가 예산을 쓰지 + 않으므로 장애 길이에 맞춰 예산을 조정할 이유도 사라졌다), 일시적 실패 시 `attempt_count` 되돌리기 + (store 포트·SQL·계약 테스트를 넓히고, 지수 간격을 키울 근거가 사라진다). - 더하는 spread 는 한 base 짜리 full jitter(`Backoff#fullJitter`, `[0, base]` 균등)이며 주입된 `RandomGenerator` 로 뽑는다. 0 을 반환하는 generator 를 주면 테스트가 결정적이 된다(I10). - **상수는 고정이다(I10)**: `BASE_DELAY`·`MAX_ATTEMPTS`·jitter 범위는 설정 프로퍼티가 아니다. diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java index 0843aa98..802cce5b 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java @@ -6,8 +6,9 @@ import dev.caskeleton.shared.error.OperationalError; /** * Raised when another attempt still holds the same {@link IdempotencyScopeDigest}. Framework-free, - * application-owned; every transport maps it to a {@code IDEMPOTENT_IN_FLIGHT} 409 (retryable=false - * — the client polls). The message carries only the opaque scope digest, for logs. + * application-owned; every transport maps it to a {@code IDEMPOTENT_IN_FLIGHT} 409 (retryable=true + * — the result is unknown and the client resends with the same key, never a new one; {@code + * docs/web/http-contract.md}). The message carries only the opaque scope digest, for logs. */ public class IdempotencyInFlightException extends RuntimeException implements ApiErrorCarrier { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxBackoffPolicy.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxBackoffPolicy.java index 616f7190..a072ca32 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxBackoffPolicy.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxBackoffPolicy.java @@ -9,8 +9,15 @@ import java.util.random.RandomGenerator; /** * Retry scheduling for the outbox relay: {@code delay = ceiling(attemptCount) + U[0, base]}, where * the ceiling is the shared {@link Backoff} exponential {@code base × 2^(attemptCount-1)} capped at - * the last attempt's value, {@code base = 30s} and {@code maxAttempts = 3}; {@code attemptCount} is - * the 1-based just-failed attempt. + * {@link #MAX_DELAY}, {@code base = 30s}; {@code attemptCount} is the 1-based just-failed attempt. + * + *

    The attempt budget {@link #MAX_ATTEMPTS} applies only to a failure that may be the message's + * own fault — one the publish adapter could not classify and threw. A failure that says the broker + * or the publisher is unavailable for now ({@link OutboxPublishOutcome#retryable()}) does not spend + * it: it is retried for as long as it lasts, at most {@link #MAX_DELAY} apart, so an outage ends + * with the backlog draining on its own instead of with a DEAD row at the head of every aggregate + * that produced an event during it. Within the budget the schedule is what it always was (30s, + * 60s), so the registry and runbook numbers still hold. * *

    This is not "full jitter", although it used to be called that: full jitter ({@link * Backoff#fullJitter}) may choose zero, and a relay retry must never be due at the instant it @@ -23,12 +30,20 @@ public final class OutboxBackoffPolicy { /** Base retry delay (registry SSOT: retry_after_seconds=30). */ public static final Duration BASE_DELAY = Duration.ofSeconds(30); - /** Maximum delivery attempts before a row is DEAD-lettered. */ + /** + * The longest wait between two attempts: how late, at most, a backlog starts draining after the + * broker comes back. + */ + public static final Duration MAX_DELAY = Duration.ofMinutes(5); + + /** + * Maximum delivery attempts before a row whose publish threw is DEAD-lettered. A transient + * outcome ({@link OutboxPublishOutcome#retryable()}) is never dead-lettered by this budget. + */ public static final int MAX_ATTEMPTS = 3; - /** The exponential part, capped where the last attempt already is. */ - private static final Backoff SCHEDULE = - new Backoff(BASE_DELAY, BASE_DELAY.multipliedBy(1L << (MAX_ATTEMPTS - 1))); + /** The exponential part, capped at {@link #MAX_DELAY}. */ + private static final Backoff SCHEDULE = new Backoff(BASE_DELAY, MAX_DELAY); /** The spread: a full jitter of one base. */ private static final Backoff SPREAD = new Backoff(BASE_DELAY, BASE_DELAY); @@ -46,7 +61,8 @@ public final class OutboxBackoffPolicy { } /** - * Returns the maximum number of delivery attempts before an event is dead-lettered. + * Returns the maximum number of delivery attempts before an event whose publish threw is + * dead-lettered. * * @return {@value #MAX_ATTEMPTS} */ @@ -59,7 +75,8 @@ public final class OutboxBackoffPolicy { * * @param attemptCount the 1-based attempt number that just failed (e.g. {@code 1} for the first * failure) - * @param now the current wall-clock instant + * @param now the instant the attempt failed — not the instant its relay cycle started, which on a + * stalled broker is long enough ago that the retry would already be due * @return the earliest instant at which the event may be re-claimed * @throws IllegalArgumentException if {@code attemptCount < 1} */ diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishOutcome.java index 67242668..d895ef23 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishOutcome.java @@ -8,8 +8,8 @@ package dev.caskeleton.application.outbox; * retrying it may lose. Collapsing that into an exception forces the relay to choose one of those * two wrong answers, and it chooses the same one every time. * - *

    Four values, because two of them are the ones that matter operationally and the naming trap - * between the two outbox models is real: + *

    Two of the values are the ones that matter operationally, because the naming trap between the + * two outbox models is real: * *

      *
    • the legacy {@code OutboxEventStatus.FAILED} is retryable and {@code DEAD} is @@ -21,6 +21,10 @@ package dev.caskeleton.application.outbox; *

      Mapping those by name inverts both meanings: a definitely-rejected message would be retried * forever and an unknown one would be parked. This type exists so no bridge is ever tempted to map * enum names. + * + *

      A refusal is definite about the broker not holding the message, but not always about the + * message being at fault: {@link #REJECTED_RETRYABLE} is the refusal whose cause clears on its own, + * and it is retried like {@link #AMBIGUOUS} instead of being parked like the two definite ones. */ public enum OutboxPublishOutcome { @@ -50,11 +54,25 @@ public enum OutboxPublishOutcome { * broker, so an operator investigating looks at broker-side policy — quota, ACL, message size — * rather than at this application's routing. */ - REJECTED_AFTER_BROKER; + REJECTED_AFTER_BROKER, + + /** + * Refused for a reason that belongs to the moment, not to the message. + * + *

      The publisher is shutting down, its permits are exhausted, its transport is closed, or the + * broker refused this producer's credentials while they are being rotated. The broker does not + * hold the message, and the same payload may well be accepted a little later. Dead-lettering it + * would park a committed business event, and every later event of its aggregate behind it, for a + * cause that clears on its own. + * + *

      Whether bytes left the process is not asserted: the refusal says only that the broker did + * not store the message. + */ + REJECTED_RETRYABLE; /** True when the relay may claim this row again. */ public boolean retryable() { - return this == AMBIGUOUS; + return this == AMBIGUOUS || this == REJECTED_RETRYABLE; } /** True when nothing was transmitted, so no duplicate can exist. */ diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishRefusedException.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishRefusedException.java index 81bfe1ca..0bf9f8c6 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishRefusedException.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishRefusedException.java @@ -3,11 +3,12 @@ package dev.caskeleton.application.outbox; /** * What the relay reports when a publish was refused without throwing. * - *

      An adapter that returns {@link OutboxPublishOutcome#REJECTED_BEFORE_SEND} or {@link - * OutboxPublishOutcome#REJECTED_AFTER_BROKER} has already decided the attempt is over and has no - * exception to hand up. The failure report needs a cause, and inventing a generic one would put a - * stack trace from this class in an operator's hands with nothing in it about the refusal — so the - * refusal itself is the cause, and it says which of the two it was. + *

      An adapter that returns {@link OutboxPublishOutcome#REJECTED_BEFORE_SEND}, {@link + * OutboxPublishOutcome#REJECTED_AFTER_BROKER} or {@link OutboxPublishOutcome#REJECTED_RETRYABLE} + * has already decided the attempt is over and has no exception to hand up. The failure report needs + * a cause, and inventing a generic one would put a stack trace from this class in an operator's + * hands with nothing in it about the refusal — so the refusal itself is the cause, and it says + * which refusal it was. * *

      Never thrown across the port. It exists only to carry a returned outcome into a report. */ @@ -23,15 +24,26 @@ public final class OutboxPublishRefusedException extends RuntimeException { * @param outcome the refusal the adapter reported */ public OutboxPublishRefusedException(OutboxPublishOutcome outcome) { - super( - outcome == OutboxPublishOutcome.REJECTED_BEFORE_SEND - ? "the broker adapter refused this event before transmitting it, so nothing was stored" - + " anywhere and the same payload will be refused again" - : "the broker received this event and refused it; the cause is broker-side policy" - + " rather than this application's routing"); + super(describe(outcome)); this.outcome = outcome; } + private static String describe(OutboxPublishOutcome outcome) { + return switch (outcome) { + case REJECTED_BEFORE_SEND -> + "the broker adapter refused this event before transmitting it, so nothing was stored" + + " anywhere and the same payload will be refused again"; + case REJECTED_AFTER_BROKER -> + "the broker received this event and refused it; the cause is broker-side policy" + + " rather than this application's routing"; + case REJECTED_RETRYABLE -> + "the publisher refused this event for now (shutting down, saturated, transport closed or" + + " credentials refused); the broker does not hold it and it will be retried"; + case CONFIRMED, AMBIGUOUS -> + throw new IllegalArgumentException(outcome + " is not a refusal"); + }; + } + /** * The refusal this cause carries. * diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java index 6115ea33..799d4685 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java @@ -114,7 +114,7 @@ public class PublishPendingOutboxEventsUseCase // Step 3: Publish each event outside any transaction; drive status machine per result. List outcomes = new ArrayList<>(sorted.size()); for (OutboxLease lease : sorted) { - OutboxRelayResult.Outcome outcome = publishOne(lease, now); + OutboxRelayResult.Outcome outcome = publishOne(lease); outcomes.add( new OutboxRelayResult.EventOutcome(lease.eventId(), lease.event().eventType(), outcome)); } @@ -127,24 +127,38 @@ public class PublishPendingOutboxEventsUseCase * publish failure is caught here and never rethrown; a {@code markPublished} failure after a * successful publish is NOT caught — it propagates so the row is recovered via the in-flight * timeout. See README for both failure modes. + * + *

      A retry is scheduled from the instant the publish failed, read from the clock after it + * returned. The cycle's start is the wrong origin: against a stalled broker each publish spends + * its whole deadline, so the last rows of a batch fail long after the cycle began and a delay + * measured from its start is already over when they are marked — they are retried at once, and + * the delay the policy promised never happens. */ - private OutboxRelayResult.Outcome publishOne(OutboxLease lease, Instant now) { + private OutboxRelayResult.Outcome publishOne(OutboxLease lease) { ClaimedOutboxEvent event = lease.event(); OutboxPublishOutcome achieved; try { - // The four-valued call, not the throwing one. An adapter that cannot tell an ambiguous + // The outcome-valued call, not the throwing one. An adapter that cannot tell an ambiguous // publish apart still throws and is handled below exactly as before; one that can no longer // has to pretend a message it may have stored was definitely not stored. achieved = publishPort.publishForOutcome(event); } catch (RuntimeException publishEx) { // Publish failure: drive FAILED/DEAD state machine + typed report; do NOT rethrow. - return handlePublishFailure(lease, now, publishEx); + return handlePublishFailure(lease, clock.instant(), publishEx); } if (achieved == OutboxPublishOutcome.AMBIGUOUS) { // The message left this process and no acknowledgement arrived, so it may be stored. Treated // as retryable and reported as such: the duplicate risk is the caller's to bound with an // idempotency key, and the alternative — parking it — loses a message that was delivered. - return handlePublishFailure(lease, now, new OutboxPublishAmbiguousException()); + // It does not spend the attempt budget: a broker that stopped answering fails every row this + // way, and parking them after three tries is what turned a short outage into DEAD rows. + return retryLater(lease, clock.instant(), new OutboxPublishAmbiguousException()); + } + if (achieved == OutboxPublishOutcome.REJECTED_RETRYABLE) { + // Refused for a reason that is about the moment — shutdown, saturation, a closed transport, + // a credential being rotated — not about the message. Retried like an ambiguous outcome and + // for the same reason; the cause says it was a refusal, so no duplicate is suspected. + return retryLater(lease, clock.instant(), new OutboxPublishRefusedException(achieved)); } if (achieved != OutboxPublishOutcome.CONFIRMED) { // Definite refusal. Retrying the same payload fails the same way, so the attempt budget is @@ -160,35 +174,48 @@ public class PublishPendingOutboxEventsUseCase } /** - * Drives the FAILED/DEAD state transition and reports it only after persistence succeeds. A - * transition failure remains authoritative and propagates without a report. A diagnostic adapter - * failure is contained and cannot change the persisted outcome. See README. + * Drives the FAILED/DEAD state transition for a publish that threw, and reports it only after + * persistence succeeds. A transition failure remains authoritative and propagates without a + * report. A diagnostic adapter failure is contained and cannot change the persisted outcome. See + * README. + * + *

      The attempt budget is spent here and only here: a thrown failure is one the adapter could + * not classify, so it may be the message's own fault, and the budget is what keeps such a row + * from blocking its aggregate forever. {@code attemptCount} counts every claim, transient ones + * included, so a row that has already waited out an outage is dead-lettered by the first thrown + * failure after it. */ private OutboxRelayResult.Outcome handlePublishFailure( - OutboxLease lease, Instant now, RuntimeException cause) { - ClaimedOutboxEvent event = lease.event(); - - if (event.attemptCount() >= backoffPolicy.maxAttempts()) { + OutboxLease lease, Instant failedAt, RuntimeException cause) { + if (lease.event().attemptCount() >= backoffPolicy.maxAttempts()) { // All attempts exhausted — DEAD-letter the event. return deadLetter(lease, cause); - } else { - // Transient failure — schedule retry with exponential backoff. - Instant nextAttemptAt = backoffPolicy.nextAttemptAt(event.attemptCount(), now); - if (tx.inWrite(() -> store.markFailed(lease, nextAttemptAt)) == OutboxCompletion.STALE) { - return stale(lease, OutboxRelayResult.Outcome.FAILED); - } - reportFailure( - () -> - OutboxRelayFailureReport.retryableFailure( - event.eventId(), - event.eventType(), - event.aggregateId(), - event.correlationId(), - event.attemptCount(), - nextAttemptAt, - cause)); - return OutboxRelayResult.Outcome.FAILED; } + return retryLater(lease, failedAt, cause); + } + + /** + * Marks the row FAILED with its next attempt time and reports it. Never dead-letters: the caller + * has decided this failure is worth another attempt. + */ + private OutboxRelayResult.Outcome retryLater( + OutboxLease lease, Instant failedAt, RuntimeException cause) { + ClaimedOutboxEvent event = lease.event(); + Instant nextAttemptAt = backoffPolicy.nextAttemptAt(event.attemptCount(), failedAt); + if (tx.inWrite(() -> store.markFailed(lease, nextAttemptAt)) == OutboxCompletion.STALE) { + return stale(lease, OutboxRelayResult.Outcome.FAILED); + } + reportFailure( + () -> + OutboxRelayFailureReport.retryableFailure( + event.eventId(), + event.eventType(), + event.aggregateId(), + event.correlationId(), + event.attemptCount(), + nextAttemptAt, + cause)); + return OutboxRelayResult.Outcome.FAILED; } private OutboxRelayResult.Outcome deadLetter(OutboxLease lease, RuntimeException cause) { diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPublishOutcomeTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPublishOutcomeTest.java index dd4efdf4..a64468b8 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPublishOutcomeTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPublishOutcomeTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.application.outbox; import static org.assertj.core.api.Assertions.assertThat; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -17,14 +18,19 @@ import org.junit.jupiter.api.Test; class OutboxPublishOutcomeTest { @Test - @DisplayName("only an ambiguous outcome is retryable") - void onlyAmbiguousIsRetryable() { - assertThat(OutboxPublishOutcome.AMBIGUOUS.retryable()).isTrue(); - assertThat(OutboxPublishOutcome.CONFIRMED.retryable()).isFalse(); - assertThat(OutboxPublishOutcome.REJECTED_BEFORE_SEND.retryable()) - .as("a definite rejection retried forever is a queue that never drains") - .isFalse(); - assertThat(OutboxPublishOutcome.REJECTED_AFTER_BROKER.retryable()).isFalse(); + @DisplayName("모를 결과와 지금만 거부된 결과만 다시 시도할 수 있다") + void onlyAnAmbiguousOrARetryableRefusalIsRetryable() { + // given + List outcomes = List.of(OutboxPublishOutcome.values()); + + // when + List retryable = + outcomes.stream().filter(OutboxPublishOutcome::retryable).toList(); + + // then: a definite rejection retried forever is a queue that never drains + assertThat(retryable) + .containsExactlyInAnyOrder( + OutboxPublishOutcome.AMBIGUOUS, OutboxPublishOutcome.REJECTED_RETRYABLE); } @Test @@ -37,6 +43,9 @@ class OutboxPublishOutcomeTest { assertThat(OutboxPublishOutcome.AMBIGUOUS.nothingTransmitted()) .as("the whole point of AMBIGUOUS is that this cannot be asserted") .isFalse(); + assertThat(OutboxPublishOutcome.REJECTED_RETRYABLE.nothingTransmitted()) + .as("a retryable refusal says the broker did not store it, not where the bytes went") + .isFalse(); } @Test diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java new file mode 100644 index 00000000..ca9db730 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java @@ -0,0 +1,207 @@ +package dev.caskeleton.application.outbox; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCaseTest.MutableClock; +import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCaseTest.ZeroRandom; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What the relay does with a failure that says nothing about the message. + * + *

      A broker that is down, a publisher that is shutting down, a credential being rotated: each one + * fails every row the same way for as long as it lasts and then stops. Spending the attempt budget + * on them turned a five-minute broker outage into a DEAD row at the head of every aggregate that + * produced an event during it, and nothing restarted them once the broker came back. + */ +class TransientPublishFailureRelayTest { + + private static final Instant START = Instant.parse("2026-11-01T09:00:00Z"); + + private static final Duration IN_FLIGHT_TIMEOUT = Duration.ofMinutes(15); + + /** What one publish against a stopped broker costs before it gives up. */ + private static final Duration PUBLISH_DEADLINE = Duration.ofSeconds(5); + + private InMemoryOutboxStore store; + + private MutableClock clock; + + private ScriptedPort port; + + private List reports; + + private PublishPendingOutboxEventsUseCase relay; + + @BeforeEach + void setUp() { + store = new InMemoryOutboxStore(); + clock = new MutableClock(START, ZoneOffset.UTC); + port = new ScriptedPort(); + reports = new ArrayList<>(); + relay = + new PublishPendingOutboxEventsUseCase( + store, + port, + reports::add, + new DirectTransactionPort(), + new OutboxBackoffPolicy(new ZeroRandom()), + clock, + 20, + IN_FLIGHT_TIMEOUT, + "relay-under-test"); + } + + @Test + @DisplayName("다시 시도하면 될 거부는 DEAD가 아니라 FAILED로 남아 재시도 시각을 받는다") + void aRetryableRefusalIsScheduledForRetryInsteadOfDeadLettered() { + // given: the platform refused the publish because it is shutting down + store.addClaimable(OutboxEvents.claimed("evt-shutdown", START.minusSeconds(1), 1)); + port.answer = OutboxPublishOutcome.REJECTED_RETRYABLE; + + // when + OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then: the row waits for the next attempt and is not parked + assertThat(result.outcomes()) + .extracting(OutboxRelayResult.EventOutcome::outcome) + .containsExactly(OutboxRelayResult.Outcome.FAILED); + assertThat(store.dead()).isEmpty(); + assertThat(store.status("evt-shutdown")).isEqualTo(OutboxEventStatus.FAILED); + assertThat(reports) + .singleElement() + .extracting(OutboxRelayFailureReport::nextAttemptAt) + .isNotNull(); + } + + @Test + @DisplayName("일시적 실패는 시도 예산을 다 쓴 행도 DEAD로 보내지 않는다") + void aTransientFailureNeverDeadLettersEvenPastTheAttemptBudget() { + // given: two rows already at the last budgeted attempt, one refused for now, one ambiguous + int lastBudgetedAttempt = OutboxBackoffPolicy.MAX_ATTEMPTS; + store.addClaimable( + OutboxEvents.claimed("evt-refused", START.minusSeconds(2), lastBudgetedAttempt)); + store.addClaimable( + OutboxEvents.claimed("evt-ambiguous", START.minusSeconds(1), lastBudgetedAttempt)); + port.script("evt-refused", OutboxPublishOutcome.REJECTED_RETRYABLE); + port.script("evt-ambiguous", OutboxPublishOutcome.AMBIGUOUS); + + // when + relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then: the budget isolates a payload the adapter could not classify, not a broker outage + assertThat(store.dead()).isEmpty(); + assertThat(store.failed()).containsOnlyKeys("evt-refused", "evt-ambiguous"); + } + + @Test + @DisplayName("재시도 시각은 회차 시작이 아니라 그 행이 실패한 시각부터 잰다") + void theRetryIsScheduledFromWhenThePublishFailedNotFromWhenTheCycleStarted() { + // given: each publish against the stopped broker takes the whole deadline + store.addClaimable(OutboxEvents.claimed("evt-first", START.minusSeconds(3), 1)); + store.addClaimable(OutboxEvents.claimed("evt-last", START.minusSeconds(2), 1)); + port.answer = OutboxPublishOutcome.AMBIGUOUS; + port.costPerPublish = PUBLISH_DEADLINE; + + // when + relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then: the second row failed ten seconds into the cycle and waits a full delay from there + Duration firstDelay = OutboxBackoffPolicy.BASE_DELAY; + assertThat(store.nextAttemptAt("evt-first")) + .isEqualTo(START.plus(PUBLISH_DEADLINE).plus(firstDelay)); + assertThat(store.nextAttemptAt("evt-last")) + .isEqualTo(START.plus(PUBLISH_DEADLINE.multipliedBy(2)).plus(firstDelay)); + } + + @Test + @DisplayName("broker가 10분 멈췄다가 돌아오면 운영자 개입 없이 모든 행이 PUBLISHED가 된다") + void aTenMinuteBrokerOutageDrainsOnItsOwnOnceTheBrokerReturns() { + // given: twenty events committed while the broker is down for ten minutes + for (int i = 0; i < 20; i++) { + store.addClaimable(OutboxEvents.claimed("evt-" + i, START.minusSeconds(60 - i), 1)); + } + Instant brokerBack = START.plus(Duration.ofMinutes(10)); + port.answerUntil(brokerBack, OutboxPublishOutcome.AMBIGUOUS); + port.costPerPublish = PUBLISH_DEADLINE; + + // when: the scheduler keeps polling every five seconds for half an hour + runRelayEvery(Duration.ofSeconds(5), START.plus(Duration.ofMinutes(30))); + + // then + assertThat(store.dead()).as("nothing waits for the dead-letter runbook").isEmpty(); + assertThat(store.published()).hasSize(20); + } + + @Test + @DisplayName("일시적 실패가 이어지면 재시도 간격이 늘어나되 상한을 넘지 않는다") + void repeatedTransientFailuresBackOffUpToTheCeiling() { + // given: a row that has already been tried many times during a long outage + store.addClaimable(OutboxEvents.claimed("evt-long-outage", START.minusSeconds(1), 12)); + port.answer = OutboxPublishOutcome.AMBIGUOUS; + + // when + relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then + assertThat(store.status("evt-long-outage")).isEqualTo(OutboxEventStatus.FAILED); + assertThat(store.nextAttemptAt("evt-long-outage")) + .isEqualTo(START.plus(OutboxBackoffPolicy.MAX_DELAY)); + } + + private void runRelayEvery(Duration pollInterval, Instant until) { + while (clock.instant().isBefore(until)) { + relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + clock.advance(pollInterval); + } + } + + /** Answers per event, or until a moment on the relay's clock, and spends time doing it. */ + private final class ScriptedPort implements OutboxMessagePublishPort { + + private final Map scripted = new HashMap<>(); + + private OutboxPublishOutcome answer = OutboxPublishOutcome.CONFIRMED; + + private Instant answerUntil = Instant.MAX; + + private Duration costPerPublish = Duration.ZERO; + + void script(String eventId, OutboxPublishOutcome outcome) { + scripted.put(eventId, outcome); + } + + void answerUntil(Instant until, OutboxPublishOutcome outcome) { + this.answer = outcome; + this.answerUntil = until; + } + + @Override + public void publish(ClaimedOutboxEvent event) { + throw new UnsupportedOperationException("the relay asks for an outcome"); + } + + @Override + public OutboxPublishOutcome publishForOutcome(ClaimedOutboxEvent event) { + Instant calledAt = clock.instant(); + clock.advance(costPerPublish); + OutboxPublishOutcome outcome = scripted.get(event.eventId()); + if (outcome != null) { + return outcome; + } + return calledAt.isBefore(answerUntil) ? answer : OutboxPublishOutcome.CONFIRMED; + } + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java index 71bf38fa..db60ce18 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java @@ -7,10 +7,13 @@ import dev.caskeleton.application.fileserver.api.FileId; import dev.caskeleton.application.fileserver.api.FileState; import dev.caskeleton.application.fileserver.api.content.StoredContent; import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; import dev.caskeleton.application.fileserver.api.metadata.FileRecord; import dev.caskeleton.application.fileserver.api.metadata.FileRecordDraft; import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.metadata.QuotaReservation; +import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; import dev.caskeleton.application.fileserver.api.security.FileOperation; import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy; @@ -18,8 +21,12 @@ import dev.caskeleton.application.fileserver.api.security.RequestContext; import dev.caskeleton.application.fileserver.api.security.SanitizedFilename; import dev.caskeleton.application.fileserver.port.in.CopyFileCommand; import dev.caskeleton.application.fileserver.port.in.CopyFileUseCase; +import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; +import dev.caskeleton.application.fileserver.quota.TransferPermit; import dev.caskeleton.application.fileserver.upload.FileView; import dev.caskeleton.application.fileserver.upload.UploadIdentifierPort; +import dev.caskeleton.application.fileserver.upload.UploadPolicies; +import dev.caskeleton.application.fileserver.upload.UploadPolicy; import dev.caskeleton.application.security.RequiresPermission; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; @@ -27,7 +34,13 @@ import java.time.Clock; import java.util.Objects; import java.util.Optional; -/** Copies a readable file into a new file the caller owns. */ +/** + * Copies a readable file into a new file the caller owns. + * + *

      A copy writes new bytes, so it passes the same capacity checks an upload does: {@link + * TransferAdmissionController} refuses it at the hard high-water mark, and the target namespace's + * quota is reserved before the bytes move and committed with the record's publication. + */ @RequiresPermission("file:copy") @UseCaseCapability( transactionMode = TransactionMode.WRITE, @@ -40,8 +53,11 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase { private final FileMetadataPort metadataStore; private final CopyContentPort copyGateway; + private final FileQuotaPort quotaService; + private final TransferAdmissionController admissionController; private final FileAccessPolicyPort accessPolicy; private final OriginalFilenamePolicy filenamePolicy; + private final UploadPolicy uploadPolicy; private final UploadIdentifierPort identifierFactory; private final TransactionPort transactions; private final Clock clock; @@ -49,15 +65,19 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase { public CopyFileApplicationUseCase( FileMetadataPort metadataStore, CopyContentPort copyGateway, - FileAccessPolicyPort accessPolicy, - OriginalFilenamePolicy filenamePolicy, + UploadPolicies policies, + FileQuotaPort quotaService, + TransferAdmissionController admissionController, UploadIdentifierPort identifierFactory, TransactionPort transactions, Clock clock) { this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore"); this.copyGateway = Objects.requireNonNull(copyGateway, "copyGateway"); - this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); - this.filenamePolicy = Objects.requireNonNull(filenamePolicy, "filenamePolicy"); + this.quotaService = Objects.requireNonNull(quotaService, "quotaService"); + this.admissionController = Objects.requireNonNull(admissionController, "admissionController"); + this.accessPolicy = policies.access(); + this.filenamePolicy = policies.filenames(); + this.uploadPolicy = policies.upload(); this.identifierFactory = Objects.requireNonNull(identifierFactory, "identifierFactory"); this.transactions = Objects.requireNonNull(transactions, "transactions"); this.clock = Objects.requireNonNull(clock, "clock"); @@ -74,40 +94,68 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase { SanitizedFilename filename = filenamePolicy.sanitize(command.targetFilename().orElse(source.originalName())); - FileId targetId = identifierFactory.newFileId(); - FileRecord target = - transactions.inWrite( - () -> - metadataStore.insert( - new FileRecordDraft( - targetId, - command.targetNamespace(), - filename.value(), - source.verifiedMediaType().or(source::claimedMediaType), - source.actualSize(), - // The copy belongs to whoever made it, not to the source's owner. - context.subject().asOwner()))); + long bytes = source.actualSize().orElseThrow(CopyFileApplicationUseCase::readyWithoutSize); + QuotaScope scope = QuotaScope.ofNamespace(command.targetNamespace().value()); - StoredContent copied; - try { - copied = - copyGateway.copyCreateOnly( - source.contentKey().orElseThrow(CopyFileApplicationUseCase::readyWithoutKey), - command.targetNamespace()); - } catch (RuntimeException failure) { - // The target may exist as a partial object; no rollback is promised, so it is queued for the - // cleanup worker instead of being left for an orphan scan to find much later. - failRecord(target, "COPY_FAILED"); - throw failure; + // A copy adds as many bytes to the pool as an upload of the same file, so it is admitted the + // same way: the hard high-water mark and the caller's concurrency, held for the whole transfer. + try (TransferPermit permit = + admissionController.acquireUpload( + TransferAdmissionController.callerScope(context), bytes)) { + FileId targetId = identifierFactory.newFileId(); + CopyTarget target = + transactions.inWrite( + () -> + new CopyTarget( + quotaService.reserve(scope, bytes, uploadPolicy.reservationTtl()), + metadataStore.insert( + new FileRecordDraft( + targetId, + command.targetNamespace(), + filename.value(), + source.verifiedMediaType().or(source::claimedMediaType), + source.actualSize(), + // The copy belongs to whoever made it, not to the source's owner. + context.subject().asOwner())))); + + StoredContent copied; + try { + copied = + copyGateway.copyCreateOnly( + source.contentKey().orElseThrow(CopyFileApplicationUseCase::readyWithoutKey), + command.targetNamespace()); + } catch (RuntimeException failure) { + // The target may exist as a partial object; no rollback is promised, so it is queued for + // the cleanup worker instead of being left for an orphan scan to find much later. + try { + transactions.inWrite( + () -> { + failRecord(target.record(), "COPY_FAILED"); + quotaService.release(target.reservation()); + }); + } catch (RuntimeException compensationFailure) { + failure.addSuppressed(compensationFailure); + } + throw failure; + } + return FileView.of(publish(target, copied).toDescriptor()); } - return FileView.of(publish(target, copied).toDescriptor()); } + /** The reservation and the record one copy opens, so a single boundary can return both. */ + private record CopyTarget(QuotaReservation reservation, FileRecord record) {} + /** Walks the copied target to READY through the same edges an upload would take. */ - private FileRecord publish(FileRecord target, StoredContent copied) { - // Four hops, one boundary. The intermediate states exist to satisfy the transition table, not - // to be observable; a copy that stalled on one of them would look like a stuck upload. - return transactions.inWrite(() -> publishSteps(target, copied)); + private FileRecord publish(CopyTarget target, StoredContent copied) { + // Four hops and the quota commit, one boundary. The intermediate states exist to satisfy the + // transition table, not to be observable; a copy that stalled on one of them would look like a + // stuck upload. + return transactions.inWrite( + () -> { + FileRecord ready = publishSteps(target.record(), copied); + quotaService.commit(target.reservation(), copied.size()); + return ready; + }); } private FileRecord publishSteps(FileRecord target, StoredContent copied) { @@ -148,25 +196,26 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase { * one path it permits, through UPLOADING. */ private void failRecord(FileRecord record, String reasonCode) { - transactions.inWrite( - () -> { - FileRecord uploading = - metadataStore.transition( - record.fileId(), - record.version(), - FileState.CREATED, - FileState.UPLOADING, - FileRecordMutation.none()); - metadataStore.transition( - uploading.fileId(), - uploading.version(), - FileState.UPLOADING, - FileState.FAILED, - FileRecordMutation.failure(reasonCode)); - }); + FileRecord uploading = + metadataStore.transition( + record.fileId(), + record.version(), + FileState.CREATED, + FileState.UPLOADING, + FileRecordMutation.none()); + metadataStore.transition( + uploading.fileId(), + uploading.version(), + FileState.UPLOADING, + FileState.FAILED, + FileRecordMutation.failure(reasonCode)); } private static IllegalStateException readyWithoutKey() { return new IllegalStateException("READY record has no content key"); } + + private static IllegalStateException readyWithoutSize() { + return new IllegalStateException("READY record has no size"); + } } diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java index e8f21e08..d9969dba 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/TransferAdmissionController.java @@ -4,6 +4,7 @@ import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverException; import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; +import dev.caskeleton.application.fileserver.api.security.RequestContext; import java.util.HashMap; import java.util.Map; import java.util.OptionalDouble; @@ -43,6 +44,17 @@ public final class TransferAdmissionController { this.overflowScopeUploads = new Semaphore(properties.scopeUploadPermits()); } + /** + * The scope a caller's transfers are admitted under: the caller, not the namespace. + * + *

      Counting it per namespace put every caller of a deployment — which uploads into one default + * namespace — behind the same handful of permits, so one busy client refused everyone else. Every + * write that adds bytes to the pool (upload create, append, copy) takes its permit here. + */ + public static QuotaScope callerScope(RequestContext context) { + return QuotaScope.ofPrincipal(context.subject().principalId()); + } + public TransferPermit acquireUpload(QuotaScope scope, long requestedBytes) { requireWithinFileSizePolicy(requestedBytes); requireBelowHardHighWater(); diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java index c9635a9e..bf5a15aa 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java @@ -96,7 +96,8 @@ public class AppendUploadApplicationUseCase implements AppendUploadUseCase { try (TransferPermit permit = admissionController.acquireUpload( - UploadSessions.admissionScope(context), Math.max(command.contentLength(), 0))) { + TransferAdmissionController.callerScope(context), + Math.max(command.contentLength(), 0))) { WriterLease lease = leaseCoordinator.acquire(uploadId, context.instanceId()); // The fence is what carries the lease through the transfer. It renews on its own heartbeat // and refuses the next write the moment renewal is denied, so a transfer that outlives its diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java index 1e85864e..7bc88f21 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java @@ -104,7 +104,7 @@ public class CreateUploadApplicationUseCase implements CreateUploadUseCase { try (TransferPermit permit = admissionController.acquireUpload( - UploadSessions.admissionScope(context), reservationBytes)) { + TransferAdmissionController.callerScope(context), reservationBytes)) { FileId fileId = identifierFactory.newFileId(); UploadId uploadId = identifierFactory.newUploadId(); diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java index cf7adf77..9133db82 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java @@ -5,10 +5,8 @@ import dev.caskeleton.application.fileserver.api.error.FileNotFoundException; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverException; import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; -import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; import dev.caskeleton.application.fileserver.api.metadata.UploadSession; import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; -import dev.caskeleton.application.fileserver.api.security.RequestContext; import java.time.Instant; import java.util.OptionalLong; @@ -52,16 +50,6 @@ final class UploadSessions { return session; } - /** - * Transfer concurrency is counted per caller. - * - *

      Counting it per namespace put every caller of a deployment — which uploads into one default - * namespace — behind the same handful of permits, so one busy client refused everyone else. - */ - static QuotaScope admissionScope(RequestContext context) { - return QuotaScope.ofPrincipal(context.subject().principalId()); - } - static long effectiveMaximum(UploadPolicy policy, OptionalLong expectedLength) { return expectedLength.isPresent() ? Math.min(policy.maximumFileSize(), Math.max(expectedLength.getAsLong(), 1)) diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadUseCasesTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadUseCasesTest.java index 52728bb6..bea18987 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadUseCasesTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadUseCasesTest.java @@ -2,13 +2,17 @@ package dev.caskeleton.application.fileserver.download; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.fileserver.api.ByteRange; import dev.caskeleton.application.fileserver.api.FileId; import dev.caskeleton.application.fileserver.api.error.FileNotFoundException; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverException; import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.security.FileAccessSubject; import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.api.security.RequestContext; import dev.caskeleton.application.fileserver.port.in.DescribeFileQuery; import dev.caskeleton.application.fileserver.port.in.OpenDownloadContentQuery; import dev.caskeleton.application.fileserver.port.in.PrepareDownloadQuery; @@ -20,7 +24,9 @@ import dev.caskeleton.application.fileserver.testkit.InMemoryFileMetadataStore; import dev.caskeleton.application.fileserver.testkit.ReadyFileFixture; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; +import java.util.Set; import java.util.UUID; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class DownloadUseCasesTest { @@ -66,6 +72,25 @@ class DownloadUseCasesTest { assertThat(content.neverOpened()).isTrue(); } + @Test + @DisplayName("다른 사용자가 만든 파일은 다운로드를 준비할 수 없다") + void preparingADownloadOfAFileAnotherCallerOwnsIsRefused() { + // given + FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + RequestContext stranger = + new RequestContext(FileAccessSubject.of("user-2", Set.of("uploader")), "trace-2", "node-a"); + + // when + Throwable failure = + catchThrowable(() -> prepare.handle(new PrepareDownloadQuery(ready.fileId(), stranger))); + + // then + assertThat(failure) + .isInstanceOfSatisfying( + FileserverException.class, + refused -> assertThat(refused.code()).isEqualTo(FileserverErrorCode.ACCESS_DENIED)); + } + @Test void nonReadyFileIsRejectedAndNeverOpened() { FileRecord verifying = ReadyFileFixture.verifying(metadata, SIZE, DIGEST); diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java index 95d09261..f8062a71 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java @@ -2,24 +2,33 @@ package dev.caskeleton.application.fileserver.lifecycle; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.application.fileserver.api.FileId; import dev.caskeleton.application.fileserver.api.FileState; import dev.caskeleton.application.fileserver.api.StorageNamespace; import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverException; import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft; +import dev.caskeleton.application.fileserver.api.security.FileAccessSubject; import dev.caskeleton.application.fileserver.api.security.FileOperation; import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy; +import dev.caskeleton.application.fileserver.api.security.RequestContext; import dev.caskeleton.application.fileserver.api.transfer.UploadMode; import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; import dev.caskeleton.application.fileserver.cleanup.CleanupType; import dev.caskeleton.application.fileserver.port.in.CopyFileCommand; import dev.caskeleton.application.fileserver.port.in.DeleteFileCommand; import dev.caskeleton.application.fileserver.port.in.MoveFileCommand; +import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; +import dev.caskeleton.application.fileserver.quota.TransferAdmissionProperties; import dev.caskeleton.application.fileserver.testkit.DirectTransactions; import dev.caskeleton.application.fileserver.testkit.FakeCopyContentGateway; import dev.caskeleton.application.fileserver.testkit.FakeFileAccessPolicy; +import dev.caskeleton.application.fileserver.testkit.FakeFileQuotaService; import dev.caskeleton.application.fileserver.testkit.FileserverFixtures; import dev.caskeleton.application.fileserver.testkit.InMemoryCleanupQueue; import dev.caskeleton.application.fileserver.testkit.InMemoryFileMetadataStore; @@ -27,18 +36,25 @@ import dev.caskeleton.application.fileserver.testkit.InMemoryUploadSessionStore; import dev.caskeleton.application.fileserver.testkit.ReadyFileFixture; import dev.caskeleton.application.fileserver.testkit.SequentialUploadIdentifierFactory; import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.fileserver.upload.UploadPolicies; +import dev.caskeleton.application.fileserver.upload.UploadPolicy; import java.time.Clock; import java.time.ZoneOffset; import java.util.List; import java.util.Optional; +import java.util.OptionalDouble; import java.util.OptionalLong; +import java.util.Set; import java.util.UUID; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class FileLifecycleUseCasesTest { private static final String DIGEST = "f".repeat(64); private static final long SIZE = 10; + private static final long MAX_FILE = 1024; + private static final StorageNamespace TARGET = StorageNamespace.of("tenant-b"); private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore(); private final FakeCopyContentGateway copyGateway = new FakeCopyContentGateway(); @@ -52,12 +68,22 @@ class FileLifecycleUseCasesTest { new DeleteFileApplicationUseCase( metadata, accessPolicy, cleanup, sessions, sessions, transactions); + private final FakeFileQuotaService quota = new FakeFileQuotaService(); + + /** How full the pool reads; the standard profile refuses writes from 0.85. */ + private OptionalDouble storageUsed = OptionalDouble.empty(); + private final CopyFileApplicationUseCase copy = new CopyFileApplicationUseCase( metadata, copyGateway, - accessPolicy, - OriginalFilenamePolicy.standard(), + new UploadPolicies( + accessPolicy, + OriginalFilenamePolicy.standard(), + UploadPolicy.standard(FileserverFixtures.NAMESPACE)), + quota, + new TransferAdmissionController( + TransferAdmissionProperties.standard(), () -> storageUsed, MAX_FILE), new SequentialUploadIdentifierFactory(), transactions, Clock.fixed(FileserverFixtures.NOW, ZoneOffset.UTC)); @@ -229,6 +255,96 @@ class FileLifecycleUseCasesTest { assertThat(copyGateway.copies()).isEmpty(); } + @Test + @DisplayName("저장소가 hard high-water를 넘으면 복사는 레코드도 바이트도 만들지 않고 STORAGE_FULL로 거절된다") + void copyAtTheHardHighWaterMarkIsRefusedBeforeAnyRecordOrByteIsWritten() { + // given + FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + copyGateway.copiesContentOf(SIZE, DIGEST); + storageUsed = OptionalDouble.of(0.90); + + // when + Throwable failure = catchThrowable(() -> copy.handle(copyOf(source))); + + // then + assertThat(failure) + .isInstanceOfSatisfying( + FileserverException.class, + refused -> assertThat(refused.code()).isEqualTo(FileserverErrorCode.STORAGE_FULL)); + assertThat( + List.of( + copyGateway.copies(), + metadata.find(nextCopyId()).isPresent(), + quota.reservationCount())) + .containsExactly(List.of(), false, 0); + } + + @Test + @DisplayName("복사는 대상 namespace에 쿼터를 예약하고 복사된 크기로 확정한다") + void copyReservesQuotaInTheTargetNamespaceAndCommitsTheCopiedSize() { + // given + FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + copyGateway.copiesContentOf(SIZE, DIGEST); + + // when + copy.handle(copyOf(source)); + + // then + assertThat(List.of(quota.reservedScopes(), quota.committedBytes(), quota.anyReleased())) + .containsExactly(List.of(QuotaScope.ofNamespace(TARGET.value())), List.of(SIZE), false); + } + + @Test + @DisplayName("복사가 실패하면 예약한 쿼터를 확정하지 않고 돌려준다") + void aFailedCopyReleasesItsQuotaReservationInsteadOfCommittingIt() { + // given + FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + copyGateway.failNextCopy(); + + // when + Throwable failure = catchThrowable(() -> copy.handle(copyOf(source))); + + // then + assertThat(failure).isInstanceOf(FileserverException.class); + assertThat(List.of(quota.reservationCount(), quota.anyReleased(), quota.committedBytes())) + .containsExactly(1, true, List.of()); + } + + @Test + @DisplayName("다른 사용자가 만든 파일은 file:copy 권한이 있어도 복사할 수 없다") + void copyingAFileAnotherCallerOwnsIsRefusedAndCopiesNothing() { + // given + FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + copyGateway.copiesContentOf(SIZE, DIGEST); + RequestContext stranger = + new RequestContext(FileAccessSubject.of("user-2", Set.of("uploader")), "trace-2", "node-a"); + + // when + Throwable failure = + catchThrowable( + () -> + copy.handle( + new CopyFileCommand( + source.fileId(), TARGET, Optional.empty(), Optional.empty(), stranger))); + + // then + assertThat(failure) + .isInstanceOfSatisfying( + FileserverException.class, + refused -> assertThat(refused.code()).isEqualTo(FileserverErrorCode.ACCESS_DENIED)); + assertThat(copyGateway.copies()).isEmpty(); + } + + private static CopyFileCommand copyOf(FileRecord source) { + return new CopyFileCommand( + source.fileId(), TARGET, Optional.empty(), Optional.empty(), FileserverFixtures.context()); + } + + /** The id the copy would give its target: the identifier factory's first file id. */ + private static FileId nextCopyId() { + return new SequentialUploadIdentifierFactory().newFileId(); + } + @Test void moveChangesOnlyTheNamespaceAndNeverTheContentKey() { FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java index 4d65c035..4c00435f 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java @@ -13,7 +13,13 @@ import java.util.List; import java.util.Optional; import java.util.Set; -/** Hand-rolled access policy that can deny a named operation and records what it was asked. */ +/** + * Hand-rolled access policy that can deny a named operation and records what it was asked. + * + *

      It keeps the one rule every production policy owes the port: an operation on an existing file + * is refused unless the caller created it, in the same tenant (owner decision 14). Without it a use + * case that stopped passing the file's descriptor would still pass every test. + */ public final class FakeFileAccessPolicy implements FileAccessPolicyPort { private final Set denied = EnumSet.noneOf(FileOperation.class); @@ -36,5 +42,11 @@ public final class FakeFileAccessPolicy implements FileAccessPolicyPort { "operation denied by policy", FileserverFailureContext.of(FileserverErrorCode.ACCESS_DENIED, false)); } + if (descriptor.isPresent() + && !descriptor.get().owner().equals(Optional.of(subject.asOwner()))) { + throw new FileserverException( + "subject does not own the file", + FileserverFailureContext.of(FileserverErrorCode.ACCESS_DENIED, false)); + } } } diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java index 590148cd..ceaaac82 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java @@ -48,6 +48,10 @@ public final class FakeFileQuotaService implements FileQuotaPort { released.add(reservation); } + public List reservedScopes() { + return reserved.stream().map(QuotaReservation::scope).toList(); + } + public int reservationCount() { return reserved.size(); } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFactory.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFactory.java index 47ed6af1..0061d787 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFactory.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFactory.java @@ -17,8 +17,9 @@ import java.util.Optional; * Builds the attempt row that is committed before the provider call. * *

      That ordering is the whole recovery story: after a crash the row is either absent, in which - * case nothing was sent, or present in {@code DISPATCHING}, in which case reconciliation has - * something to ask about. + * case nothing was sent, or present in {@code DISPATCHING} and unfinished, in which case + * reconciliation has something to ask about. The row therefore records that whether the call + * started is unknown: it stays the stored state for the whole call. */ public final class DeliveryAttemptFactory { @@ -51,9 +52,12 @@ public final class DeliveryAttemptFactory { profile.providerId(), profile.profileId(), Optional.empty(), - // A row that exists before any call: nothing started, and that is a proven fact rather than - // an unknown one. - ProviderExecutionEvidence.notStarted(), + // Not notStarted(): that is true when the row is inserted and false the moment the call + // begins, yet nothing rewrites the row until the outcome is recorded. A worker killed + // during the call would leave "proven never started", and recovery would requeue — a + // second send. Proven not-started is written only by closedBeforeSubmission and by the + // outcome of an adapter that raised ProviderCallNotStartedException; both complete the row. + ProviderExecutionEvidence.undetermined(), SubmissionOutcome.NOT_SUBMITTED, DeliveryOutcome.UNKNOWN, AttemptConfirmation.AMBIGUOUS, diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryService.java index 9f9b4a57..bb5f12fd 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryService.java @@ -138,7 +138,9 @@ public final class LeaseRecoveryService { // is nothing for a provider to tell us, so asking costs a round trip to learn what is // already written down. This branch only became possible once the certainty survived // persistence: before, "proven not started" and "unknown whether started" read back - // identically, so every abandoned attempt had to be reconciled. + // identically, so every abandoned attempt had to be reconciled. The pre-call row the + // dispatcher writes never lands here: it records the start as unknown, because it is + // still the stored state while the provider call runs. requeue(recipientDeliveryId); } else { // Outside any transaction: reconciliation asks the provider over the network and opens diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJob.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJob.java index 6728d04a..c8545b62 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJob.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJob.java @@ -20,6 +20,10 @@ import java.util.UUID; * duplicate questions: re-scheduling one that already exists moves its due time rather than adding * a second row. * + *

      {@code claimFence} is which claim this copy was handed out under. Every claim advances it, and + * the store's writes after the claim match on it, so an instance that held the job past its lease + * cannot reschedule or remove it once another instance has claimed it since. + * * @param id the job identity * @param attemptId the attempt whose outcome is unknown * @param providerProfileId the profile that must answer, since capability is per profile @@ -28,6 +32,7 @@ import java.util.UUID; * @param lastResult the previous answer, for operators reading the table directly * @param createdAt when the job was first scheduled * @param updatedAt when it last changed + * @param claimFence the claim this copy belongs to; {@code 0} for a job nobody has claimed yet */ public record ReconciliationJob( UUID id, @@ -37,7 +42,8 @@ public record ReconciliationJob( int attempts, Optional lastResult, Instant createdAt, - Instant updatedAt) { + Instant updatedAt, + long claimFence) { /** Validates the job. */ public ReconciliationJob { @@ -51,5 +57,8 @@ public record ReconciliationJob( if (attempts < 0) { throw new IllegalArgumentException("attempts must not be negative"); } + if (claimFence < 0) { + throw new IllegalArgumentException("claimFence must not be negative"); + } } } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJobStorePort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJobStorePort.java index c5e0cfe2..5c3929bd 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJobStorePort.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJobStorePort.java @@ -2,6 +2,7 @@ package dev.caskeleton.application.notification.platform.dispatch; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import java.time.Duration; import java.time.Instant; import java.util.List; @@ -29,18 +30,28 @@ public interface ReconciliationJobStorePort { DeliveryAttemptId attemptId, ProviderProfileId providerProfileId, Instant dueAt); /** - * Claims due jobs for one worker pass. + * Claims due jobs for one worker pass, for {@code lease}. + * + *

      The claim is ownership that outlives the statement that took it: until {@code now + lease} + * no other caller is handed the same job, whether or not a transaction is open. That is what lets + * the caller ask a provider about each job with no database transaction held across the call. A + * job whose lease has passed is claimable again, so the lease must cover the whole pass. * * @param limit how many to take * @param now the current instant - * @return the due jobs, oldest first + * @param lease how long the caller owns the claimed jobs + * @return the due jobs, oldest first, each carrying the fence of this claim */ - List claimDue(int limit, Instant now); + List claimDue(int limit, Instant now, Duration lease); /** * Records that a job was asked and answered inconclusively, and when to ask again. * - * @param job the job + *

      Fenced: when another caller has claimed the job since {@code job} was handed out, nothing + * changes, because the new holder's answer is the one that counts. The claim is released so the + * job becomes due again at {@code nextCheckAt} rather than at the end of the lease. + * + * @param job the job, as claimed * @param result a bounded description of the answer * @param nextCheckAt when to ask next */ @@ -49,7 +60,9 @@ public interface ReconciliationJobStorePort { /** * Removes a job whose attempt now has a final outcome. * - * @param job the job + *

      Fenced like {@link #reschedule}: a job claimed by another caller since is left alone. + * + * @param job the job, as claimed */ void complete(ReconciliationJob job); } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/ProviderExecutionEvidence.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/ProviderExecutionEvidence.java index 2889af6a..8794b2ee 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/ProviderExecutionEvidence.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/ProviderExecutionEvidence.java @@ -25,6 +25,17 @@ public record ProviderExecutionEvidence( EvidenceFact.provenAbsent()); } + /** + * Nothing is known yet, including whether a request began. + * + *

      The state of a row written before a call and still stored while the call runs: at any later + * moment the call may have started, so the row must not claim it did not. + */ + public static ProviderExecutionEvidence undetermined() { + return new ProviderExecutionEvidence( + EvidenceFact.UNKNOWN, EvidenceFact.UNKNOWN, EvidenceFact.UNKNOWN, EvidenceFact.UNKNOWN); + } + /** A complete response was read and understood. */ public static ProviderExecutionEvidence completed(boolean accepted) { return new ProviderExecutionEvidence( diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFactoryTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFactoryTest.java index 3f910a8c..ff2ed965 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFactoryTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFactoryTest.java @@ -1,115 +1,55 @@ package dev.caskeleton.application.notification.platform.dispatch; +import static dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFixtures.NOW; +import static dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFixtures.profile; +import static dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFixtures.recipient; +import static dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFixtures.rendered; +import static dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFixtures.route; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.application.notification.platform.api.ContactPointId; -import dev.caskeleton.application.notification.platform.api.NotificationId; -import dev.caskeleton.application.notification.platform.api.ProviderId; -import dev.caskeleton.application.notification.platform.api.ProviderProfileId; -import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; -import dev.caskeleton.application.notification.platform.api.TemplateSelection; -import dev.caskeleton.application.notification.platform.api.TenantId; -import dev.caskeleton.application.notification.platform.api.content.EmailContent; -import dev.caskeleton.application.notification.platform.api.content.EmailOptions; import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; -import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; -import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.policy.RouteCandidate; -import dev.caskeleton.application.notification.platform.provider.ProviderCapabilities; +import dev.caskeleton.application.notification.platform.provider.EvidenceCertainty; import dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence; import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot; -import dev.caskeleton.application.notification.platform.template.RenderedNotificationContent; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; import java.util.UUID; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class DeliveryAttemptFactoryTest { - private static final Instant NOW = Instant.parse("2026-09-20T00:00:00Z"); private static final UUID ATTEMPT_ID = UUID.fromString("00000000-0000-7000-8000-000000000010"); @Test - void createsAProvenNotStartedRowBeforeTheProviderCall() { + @DisplayName("provider 호출 전에 만드는 attempt 행은 요청 시작 여부를 불명으로 적는다") + void createsARowThatDoesNotClaimTheCallNeverStarted() { + // given RouteCandidate route = route(); ProviderProfileSnapshot profile = profile(); DeliveryAttemptFactory factory = new DeliveryAttemptFactory(() -> ATTEMPT_ID); + // when DeliveryAttemptRecord attempt = factory.create(recipient(route), route, profile, rendered(), 2, NOW); + // then assertThat(attempt.id().value()).isEqualTo(ATTEMPT_ID); assertThat(attempt.attemptNo()).isEqualTo(2); assertThat(attempt.submissionOutcome()).isEqualTo(SubmissionOutcome.NOT_SUBMITTED); assertThat(attempt.deliveryOutcome()).isEqualTo(DeliveryOutcome.UNKNOWN); assertThat(attempt.confirmation()).isEqualTo(AttemptConfirmation.AMBIGUOUS); assertThat(attempt.evidenceLevel()).isEqualTo(EvidenceLevel.PLATFORM_QUEUED); - assertThat(attempt.executionEvidence()).isEqualTo(ProviderExecutionEvidence.notStarted()); + assertThat(attempt.executionEvidence().requestStarted().certainty()) + .as( + "this row outlives the moment it was written: it is still the stored state while the" + + " provider call runs, so it must not say the call provably never started") + .isEqualTo(EvidenceCertainty.UNKNOWN); + assertThat(attempt.executionEvidence()).isEqualTo(ProviderExecutionEvidence.undetermined()); assertThat(attempt.providerRequestId()).isEmpty(); assertThat(attempt.credentialGeneration()).isEqualTo(7L); assertThat(attempt.renderedContentDigest()).isEqualTo("d".repeat(64)); } - - private static RouteCandidate route() { - return new RouteCandidate( - 0, - Channel.EMAIL, - new ContactPointId(UUID.fromString("00000000-0000-7000-8000-000000000011")), - new ProviderProfileId("ses-primary"), - true, - true); - } - - private static ProviderProfileSnapshot profile() { - return new ProviderProfileSnapshot( - new ProviderProfileId("ses-primary"), - new ProviderId("ses"), - Channel.EMAIL, - "prod", - 7L, - new ProviderCapabilities( - false, true, true, true, true, false, false, false, 1, 10_000L, Duration.ofHours(1)), - Map.of()); - } - - private static RenderedNotificationContent rendered() { - return new RenderedNotificationContent( - new EmailContent("subject", "body", Optional.empty(), List.of(), EmailOptions.DEFAULT), - "d".repeat(64), - new TemplateSelection("receipt", 1L, Locale.KOREAN), - Locale.KOREAN); - } - - private static RecipientDeliveryRecord recipient(RouteCandidate route) { - return new RecipientDeliveryRecord( - new RecipientDeliveryId(UUID.fromString("00000000-0000-7000-8000-000000000012")), - new NotificationId(UUID.fromString("00000000-0000-7000-8000-000000000013")), - new TenantId("tenant-a"), - "user-1", - Optional.of(Locale.KOREAN), - Optional.empty(), - List.of(route), - 0, - RecipientDeliveryState.READY_TO_DISPATCH, - SubmissionOutcome.NOT_SUBMITTED, - DeliveryOutcome.UNKNOWN, - EvidenceLevel.NONE, - false, - false, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - 0, - Optional.empty(), - NOW, - NOW); - } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFixtures.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFixtures.java new file mode 100644 index 00000000..383590e4 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFixtures.java @@ -0,0 +1,101 @@ +package dev.caskeleton.application.notification.platform.dispatch; + +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.NotificationId; +import dev.caskeleton.application.notification.platform.api.ProviderId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.TemplateSelection; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.api.content.EmailContent; +import dev.caskeleton.application.notification.platform.api.content.EmailOptions; +import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; +import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; +import dev.caskeleton.application.notification.platform.api.routing.Channel; +import dev.caskeleton.application.notification.platform.policy.RouteCandidate; +import dev.caskeleton.application.notification.platform.provider.ProviderCapabilities; +import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot; +import dev.caskeleton.application.notification.platform.template.RenderedNotificationContent; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +/** + * The inputs the dispatcher hands {@link DeliveryAttemptFactory}, shared by every test that needs a + * row exactly as the factory writes it rather than one assembled by hand. + */ +final class DeliveryAttemptFixtures { + + static final Instant NOW = Instant.parse("2026-09-20T00:00:00Z"); + + private DeliveryAttemptFixtures() {} + + static RouteCandidate route() { + return new RouteCandidate( + 0, + Channel.EMAIL, + new ContactPointId(UUID.fromString("00000000-0000-7000-8000-000000000011")), + new ProviderProfileId("ses-primary"), + true, + true); + } + + static ProviderProfileSnapshot profile() { + return new ProviderProfileSnapshot( + new ProviderProfileId("ses-primary"), + new ProviderId("ses"), + Channel.EMAIL, + "prod", + 7L, + new ProviderCapabilities( + false, true, true, true, true, false, false, false, 1, 10_000L, Duration.ofHours(1)), + Map.of()); + } + + static RenderedNotificationContent rendered() { + return new RenderedNotificationContent( + new EmailContent("subject", "body", Optional.empty(), List.of(), EmailOptions.DEFAULT), + "d".repeat(64), + new TemplateSelection("receipt", 1L, Locale.KOREAN), + Locale.KOREAN); + } + + static RecipientDeliveryRecord recipient(RouteCandidate route) { + return new RecipientDeliveryRecord( + new RecipientDeliveryId(UUID.fromString("00000000-0000-7000-8000-000000000012")), + new NotificationId(UUID.fromString("00000000-0000-7000-8000-000000000013")), + new TenantId("tenant-a"), + "user-1", + Optional.of(Locale.KOREAN), + Optional.empty(), + List.of(route), + 0, + RecipientDeliveryState.READY_TO_DISPATCH, + SubmissionOutcome.NOT_SUBMITTED, + DeliveryOutcome.UNKNOWN, + EvidenceLevel.NONE, + false, + false, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + 0, + Optional.empty(), + NOW, + NOW); + } + + /** The attempt row the dispatcher commits immediately before the provider call. */ + static DeliveryAttemptRecord attemptAsTheDispatcherWritesIt(UUID attemptId) { + RouteCandidate route = route(); + return new DeliveryAttemptFactory(() -> attemptId) + .create(recipient(route), route, profile(), rendered(), 1, NOW); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java index 7903c15f..ad270c1c 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java @@ -496,11 +496,12 @@ class DispatchOutcomeRecorderTest { 0, Optional.empty(), COMPLETED, - COMPLETED); + COMPLETED, + 0); } @Override - public List claimDue(int limit, Instant now) { + public List claimDue(int limit, Instant now, Duration lease) { return List.of(); } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryServiceTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryServiceTest.java index 566e0f4c..0f73e442 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryServiceTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryServiceTest.java @@ -109,6 +109,31 @@ class LeaseRecoveryServiceTest { assertThat(deliveries.transitions).isEmpty(); } + @Test + @DisplayName("provider 호출 중에 워커가 죽어 factory가 쓴 attempt 행만 남으면 다시 큐에 넣지 않고 정산한다") + void anAttemptLeftAsTheFactoryWroteItIsReconciledNotRequeued() { + // given + // The row the dispatcher commits before the call is, unchanged, the row a worker killed during + // the SES/SMTP call leaves behind: nothing writes it again until the outcome is recorded. + RecipientDeliveryId id = new RecipientDeliveryId(UUID.randomUUID()); + DeliveryAttemptId attemptId = new DeliveryAttemptId(UUID.randomUUID()); + leases.abandoned.add(id); + attempts.byDelivery.put( + id, List.of(DeliveryAttemptFixtures.attemptAsTheDispatcherWritesIt(attemptId.value()))); + + // when + int handled = recovery.recoverOnce(); + + // then + assertThat(handled).isEqualTo(1); + assertThat(reconciled) + .as("the provider may already have the message; only the provider can say whether it does") + .containsExactly(attemptId); + assertThat(deliveries.transitions) + .as("a requeue here hands the same notification to another worker, which sends it again") + .isEmpty(); + } + @Test @DisplayName("attempt가 모두 끝난 DISPATCHING 수신자는 다시 꺼낼 수 있게 되돌린다") void aDispatchingDeliveryWhoseAttemptsAllCompletedIsRequeued() { diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java index 567c5275..39f1dcd2 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java @@ -82,7 +82,8 @@ public final class NotificationPlatformNoops { } @Override - public List claimDue(int limit, java.time.Instant now) { + public List claimDue( + int limit, java.time.Instant now, java.time.Duration lease) { return List.of(); } diff --git a/src/build-logic/README.md b/src/build-logic/README.md index 0039365e..e4e20312 100644 --- a/src/build-logic/README.md +++ b/src/build-logic/README.md @@ -16,6 +16,7 @@ capability, and the files it reads are declared as that test task's inputs. | `ca.java-library` / `ca.spring-library` / `ca.spring-config` | leaf-level composition of the Java/quality conventions for plain and Spring libraries | | `ca.platform-module` / `ca.grpc-platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library`, plus the gRPC BOM for the leaves that had it | | `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason. Extra test source sets are Gradle `jvm-test-suite` suites declared in the leaf (`testing { suites { … } }`); a lane named after its suite makes the suite's own `Test` task strict, and `ca.java-conventions` gives every suite the BOM's JUnit | +| `ca.strict-lane-stages` (root) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow (a `--dry-run` or `-p ` command does not count). The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01) | | `ca.redis-topology-lane` | the Redis topology lane (mode selection, `-P` property validation, per-mode required classes) the redis-sdk-topology workflow drives | | `ca.api-surface` | read-only public API surface verification with a separate update task, wired into the leaf's `check` (owner decision 20); optionally holds other leaves' imports to a reviewed adopter subset (`adopterBaseline`) | | `ca.config-contract` | app-bootstrap's `verifyEnvKeys` (moved from the deleted build-tools included build; owner decision 4 keeps the task in app-bootstrap) | diff --git a/src/build-logic/build.gradle b/src/build-logic/build.gradle index 82dec59e..95409eb2 100644 --- a/src/build-logic/build.gradle +++ b/src/build-logic/build.gradle @@ -59,6 +59,10 @@ gradlePlugin { id = 'ca.strict-test-lane' implementationClass = 'dev.caskeleton.buildlogic.strictlane.StrictTestLanePlugin' } + strictLaneStages { + id = 'ca.strict-lane-stages' + implementationClass = 'dev.caskeleton.buildlogic.strictlane.StrictLaneStagesPlugin' + } redisTopologyLane { id = 'ca.redis-topology-lane' implementationClass = 'dev.caskeleton.buildlogic.redis.RedisTopologyLanePlugin' diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java new file mode 100644 index 00000000..771f8d07 --- /dev/null +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java @@ -0,0 +1,21 @@ +package dev.caskeleton.buildlogic.strictlane; + +import org.gradle.api.file.DirectoryProperty; +import org.gradle.api.provider.ListProperty; + +/** + * The stages a strict lane may belong to, and where the workflows that run them live. + * + *

      A stage is a task path a workflow executes ({@code :ci}, {@code :mainCheck}, ...). Every strict + * lane that is not {@code explicitOnly} must be in the plan of at least one stage, and every stage + * must be executed — not merely planned with {@code --dry-run} — by at least one workflow. + */ +public abstract class StrictLaneStagesExtension { + public abstract ListProperty getStages(); + + public abstract DirectoryProperty getWorkflowDirectory(); + + public void stage(String... taskPaths) { + getStages().addAll(taskPaths); + } +} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java new file mode 100644 index 00000000..2824a052 --- /dev/null +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java @@ -0,0 +1,188 @@ +package dev.caskeleton.buildlogic.strictlane; + +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Deque; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.gradle.api.GradleException; +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.gradle.api.Task; +import org.gradle.api.execution.TaskExecutionGraph; + +/** + * Fails when a strict lane belongs to no stage a workflow executes. + * + *

      A strict lane fails closed when it runs, but nothing makes it run: a lane that no workflow + * reaches is a file that looks like coverage (review 2026-11-01 08-01 found fourteen). The rule is + * stated once, here, instead of as one workflow line per lane: + * + *

        + *
      1. every strict lane that is not {@code explicitOnly} is in the task plan of a declared stage; + *
      2. every declared stage is executed by a workflow — a {@code --dry-run} or a {@code -p + * other-build} command does not count. + *
      + * + *

      The task plan is Gradle's own: {@code verifyStrictLaneStages} depends on the stages, so a + * {@code --dry-run} of it builds the real plan, and the check reads it when the graph is ready. It + * refuses to run without {@code --dry-run}, which would execute every stage. + */ +public final class StrictLaneStagesPlugin implements Plugin { + public static final String TASK_NAME = "verifyStrictLaneStages"; + + @Override + public void apply(Project project) { + if (project != project.getRootProject()) { + throw new GradleException("ca.strict-lane-stages is applied to the root project only."); + } + StrictLaneStagesExtension extension = + project.getExtensions().create("strictLaneStages", StrictLaneStagesExtension.class); + var verify = + project + .getTasks() + .register( + TASK_NAME, + task -> { + task.setGroup("verification"); + task.setDescription( + "Fails when a strict lane is in no stage a workflow executes. Run with --dry-run."); + task.notCompatibleWithConfigurationCache( + "the check reads the task graph itself, which a cached entry does not rebuild"); + }); + project.afterEvaluate( + ignored -> verify.configure(task -> task.dependsOn(extension.getStages().get().toArray()))); + project + .getGradle() + .getTaskGraph() + .whenReady( + graph -> { + Task task = verify.get(); + if (!graph.hasTask(task)) { + return; + } + if (!project.getGradle().getStartParameter().isDryRun()) { + throw new GradleException( + TASK_NAME + + " checks the plan of " + + extension.getStages().get() + + " and would execute all of them; run it with --dry-run."); + } + List problems = + problems( + project, + graph, + extension.getStages().get(), + extension.getWorkflowDirectory().get().getAsFile()); + if (!problems.isEmpty()) { + throw new GradleException( + TASK_NAME + + ": " + + problems.size() + + " problem(s). A lane no executed stage reaches runs nowhere; put it in a" + + " stage, or declare explicitOnly(\"reason\") if it needs an input no stage" + + " has.\n - " + + String.join("\n - ", problems)); + } + project + .getLogger() + .lifecycle( + TASK_NAME + ": every strict lane is in an executed stage."); + }); + } + + private static List problems( + Project root, TaskExecutionGraph graph, List stages, File workflowDirectory) { + List problems = new ArrayList<>(); + List invocations = invocations(workflowDirectory); + List executedStages = new ArrayList<>(); + for (String stage : stages) { + if (invocations.stream().anyMatch(invocation -> invocation.executesInStartBuild(stage))) { + executedStages.add(stage); + } else { + problems.add( + "stage " + + stage + + " is executed by no workflow in " + + workflowDirectory.getName() + + " (a --dry-run or -p command does not count)"); + } + } + + // Only an executed stage covers a lane: a stage no workflow runs is the same gap one level up. + Map> plans = new LinkedHashMap<>(); + for (String stage : executedStages) { + Task stageTask = root.getTasks().findByPath(stage); + plans.put(stage, stageTask == null ? Set.of() : plan(graph, stageTask)); + } + List lanes = new ArrayList<>(); + root.getAllprojects().stream() + .sorted(Comparator.comparing(Project::getPath)) + .forEach( + project -> { + StrictTestLaneExtension lanesOf = + project.getExtensions().findByType(StrictTestLaneExtension.class); + if (lanesOf == null) { + return; + } + lanesOf.getLanes().stream() + .filter(lane -> lane.getExplicitOnlyReason() == null) + .map(lane -> taskPath(project, lane.getName())) + .sorted() + .forEach(lanes::add); + }); + for (String lane : lanes) { + if (plans.values().stream().noneMatch(plan -> plan.contains(lane))) { + problems.add("strict lane " + lane + " is in no executed stage of " + stages); + } + } + return problems; + } + + private static Set plan(TaskExecutionGraph graph, Task stage) { + Set seen = new HashSet<>(); + Deque pending = new ArrayDeque<>(List.of(stage)); + while (!pending.isEmpty()) { + Task task = pending.pop(); + if (seen.add(task.getPath())) { + pending.addAll(graph.getDependencies(task)); + } + } + return seen; + } + + private static List invocations(File workflowDirectory) { + File[] files = + workflowDirectory.listFiles( + file -> file.getName().endsWith(".yml") || file.getName().endsWith(".yaml")); + if (files == null || files.length == 0) { + throw new GradleException( + TASK_NAME + ": no workflow files in " + workflowDirectory + "; nothing could run a stage."); + } + List invocations = new ArrayList<>(); + Arrays.sort(files); + for (File file : files) { + try { + invocations.addAll( + WorkflowGradleInvocations.read(Files.readString(file.toPath(), StandardCharsets.UTF_8))); + } catch (IOException exception) { + throw new UncheckedIOException("failed to read " + file, exception); + } + } + return invocations; + } + + private static String taskPath(Project project, String name) { + return project == project.getRootProject() ? ":" + name : project.getPath() + ":" + name; + } +} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java new file mode 100644 index 00000000..7e681592 --- /dev/null +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java @@ -0,0 +1,217 @@ +package dev.caskeleton.buildlogic.strictlane; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * The {@code ./gradlew} commands a GitHub Actions workflow file runs, read from its {@code run:} + * steps. + * + *

      Not a YAML parser: it reads the two shapes the workflows use — a one-line {@code run:} and a + * {@code |} or {@code >} block — and applies YAML's folding rule to the second, because a blank line + * inside a folded block ends the command (the rest becomes a separate shell command). Comments are + * dropped before anything is matched, so a task named only in a comment is not "run". + */ +public final class WorkflowGradleInvocations { + private static final Pattern RUN_KEY = Pattern.compile("^(\\s*)(?:-\\s+)?run:(.*)$"); + private static final Pattern BLOCK_HEADER = Pattern.compile("^([|>])[-+]?\\d*\\s*(#.*)?$"); + private static final Set OPTIONS_WITH_VALUE = + Set.of( + "-p", + "--project-dir", + "-x", + "--exclude-task", + "--tests", + "-I", + "--init-script", + "--warning-mode", + "--console", + "--max-workers", + "-g", + "--gradle-user-home", + "-c", + "--settings-file", + "-b", + "--build-file", + "--include-build", + "--priority"); + + /** + * One Gradle command. + * + * @param projectDir the {@code -p} directory, or {@code null} for the build in the step's working + * directory + * @param tasks the task selectors it requests, in order + * @param dryRun whether it only plans ({@code --dry-run} or {@code -m}) instead of executing + */ + public record Invocation(String projectDir, List tasks, boolean dryRun) { + public Invocation { + tasks = List.copyOf(tasks); + } + + /** + * Whether this command executes the task at {@code taskPath} (for example {@code :ci}) in the + * build its step starts in. {@code ci} and {@code :ci} name the same root task. + */ + public boolean executesInStartBuild(String taskPath) { + String wanted = absolute(taskPath); + return projectDir == null + && !dryRun + && tasks.stream().map(Invocation::absolute).anyMatch(wanted::equals); + } + + private static String absolute(String selector) { + return selector.startsWith(":") ? selector : ":" + selector; + } + } + + private WorkflowGradleInvocations() {} + + public static List read(String workflow) { + List invocations = new ArrayList<>(); + for (String script : runScripts(workflow)) { + for (String command : shellCommands(script)) { + Invocation invocation = gradleInvocation(command); + if (invocation != null) { + invocations.add(invocation); + } + } + } + return List.copyOf(invocations); + } + + static List runScripts(String workflow) { + List lines = workflow.lines().toList(); + List scripts = new ArrayList<>(); + for (int index = 0; index < lines.size(); index++) { + Matcher run = RUN_KEY.matcher(lines.get(index)); + if (!run.matches()) { + continue; + } + int keyIndent = run.group(1).length(); + String value = run.group(2).trim(); + Matcher header = BLOCK_HEADER.matcher(value); + if (!header.matches()) { + scripts.add(stripScalarComment(value)); + continue; + } + List block = new ArrayList<>(); + int next = index + 1; + while (next < lines.size() + && (lines.get(next).isBlank() || indentOf(lines.get(next)) > keyIndent)) { + block.add(lines.get(next)); + next++; + } + index = next - 1; + int blockIndent = + block.stream().filter(line -> !line.isBlank()).mapToInt(WorkflowGradleInvocations::indentOf).min().orElse(0); + List content = + block.stream().map(line -> line.isBlank() ? "" : line.substring(blockIndent)).toList(); + scripts.add(header.group(1).equals("|") ? String.join("\n", content) : fold(content)); + } + return scripts; + } + + /** YAML folding: adjacent lines join with a space, and each blank line is a line break. */ + private static String fold(List content) { + StringBuilder folded = new StringBuilder(); + boolean previousWasText = false; + for (String line : content) { + if (line.isEmpty()) { + folded.append('\n'); + previousWasText = false; + } else { + if (previousWasText) { + folded.append(' '); + } + folded.append(line); + previousWasText = true; + } + } + return folded.toString(); + } + + private static String stripScalarComment(String value) { + int comment = value.indexOf(" #"); + String plain = comment < 0 ? value : value.substring(0, comment); + plain = plain.trim(); + if (plain.length() >= 2 + && (plain.startsWith("'") && plain.endsWith("'") + || plain.startsWith("\"") && plain.endsWith("\""))) { + plain = plain.substring(1, plain.length() - 1); + } + return plain; + } + + private static List shellCommands(String script) { + String joined = script.replace("\\\n", " "); + List commands = new ArrayList<>(); + for (String line : joined.split("\n", -1)) { + for (String command : line.split(";|&&|\\|\\||\\|")) { + commands.add(command); + } + } + return commands; + } + + private static Invocation gradleInvocation(String command) { + List tokens = new ArrayList<>(); + for (String token : command.trim().split("\\s+")) { + if (token.startsWith("#")) { + break; + } + if (!token.isEmpty()) { + tokens.add(unquote(token)); + } + } + int start = -1; + for (int index = 0; index < tokens.size(); index++) { + if (tokens.get(index).equals("gradlew") || tokens.get(index).endsWith("/gradlew")) { + start = index; + break; + } + } + if (start < 0) { + return null; + } + String projectDir = null; + boolean dryRun = false; + List tasks = new ArrayList<>(); + for (int index = start + 1; index < tokens.size(); index++) { + String token = tokens.get(index); + if (token.equals("--dry-run") || token.equals("-m")) { + dryRun = true; + } else if (token.equals("-p") || token.equals("--project-dir")) { + projectDir = index + 1 < tokens.size() ? tokens.get(index + 1) : ""; + index++; + } else if (token.startsWith("--project-dir=")) { + projectDir = token.substring("--project-dir=".length()); + } else if (OPTIONS_WITH_VALUE.contains(token)) { + index++; + } else if (!token.startsWith("-")) { + tasks.add(token); + } + } + return new Invocation(projectDir, tasks, dryRun); + } + + private static String unquote(String token) { + if (token.length() >= 2 + && (token.startsWith("'") && token.endsWith("'") + || token.startsWith("\"") && token.endsWith("\""))) { + return token.substring(1, token.length() - 1); + } + return token; + } + + private static int indentOf(String line) { + int indent = 0; + while (indent < line.length() && line.charAt(indent) == ' ') { + indent++; + } + return indent; + } +} diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java new file mode 100644 index 00000000..4d542339 --- /dev/null +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java @@ -0,0 +1,188 @@ +package dev.caskeleton.buildlogic.strictlane; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.file.Files; +import java.nio.file.Path; +import org.gradle.testkit.runner.BuildResult; +import org.gradle.testkit.runner.GradleRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * A two-project build: a root that declares stages, and a leaf with strict lanes. The workflows + * live where the real repository keeps them, one directory above the Gradle root. + */ +class StrictLaneStagesFunctionalTest { + private static final String EXECUTING_WORKFLOW = + """ + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :ci --stacktrace + - working-directory: src + run: ./gradlew :integrationCheck --continue --stacktrace + """; + + @TempDir Path repository; + private Path gradleRoot; + + @BeforeEach + void setUp() throws Exception { + gradleRoot = repository.resolve("src"); + Files.createDirectories(gradleRoot.resolve("leaf/src/test/java")); + Files.createDirectories(repository.resolve(".github/workflows")); + Files.writeString( + gradleRoot.resolve("settings.gradle"), "rootProject.name = 'fixture'\ninclude 'leaf'\n"); + Files.writeString( + gradleRoot.resolve("build.gradle"), + """ + plugins { id 'ca.strict-lane-stages' } + tasks.register('ci') { dependsOn ':leaf:check' } + tasks.register('integrationCheck') { dependsOn ':leaf:integrationTestLaneCheck' } + strictLaneStages { + stage ':ci', ':integrationCheck' + workflowDirectory = layout.projectDirectory.dir('../.github/workflows') + } + """); + Files.writeString( + gradleRoot.resolve("leaf/src/test/java/LaneTest.java"), + """ + class LaneTest {} + """); + } + + @Test + @DisplayName("모든 lane이 workflow가 실행하는 단계에 들어 있으면 통과한다") + void passesWhenEveryLaneIsInAnExecutedStage() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + """); + workflow(EXECUTING_WORKFLOW); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").build(); + + // then + assertThat(result.getOutput()).contains("every strict lane is in an executed stage"); + } + + @Test + @DisplayName("어느 단계 집계에도 들지 않는 lane이 있으면 그 lane 이름으로 실패한다") + void failsNamingALaneThatNoStageReaches() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + lane('loadLane') { performance(); tag = 'load'; description = 'Load and shutdown.' } + """); + workflow(EXECUTING_WORKFLOW); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("strict lane :leaf:loadLane is in no executed stage") + .doesNotContain("strict lane :leaf:databaseLane"); + } + + @Test + @DisplayName("단계를 workflow가 --dry-run으로만 부르면 그 단계와 그 단계에만 있는 lane을 함께 보고하고 실패한다") + void failsWhenAStageIsOnlyDryRun() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + """); + workflow( + """ + jobs: + main: + steps: + - run: ./gradlew :ci --stacktrace + - run: | + for gate in ci integrationCheck; do + ./gradlew "${gate}" --dry-run + done + ./gradlew integrationCheck --dry-run + """); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("stage :integrationCheck is executed by no workflow") + .contains("strict lane :leaf:databaseLane is in no executed stage"); + } + + @Test + @DisplayName("explicitOnly lane은 이유가 코드에 있으므로 단계 밖에 있어도 통과한다") + void explicitOnlyLaneIsExempt() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + lane('sandboxLane') { + integration(); tag = 'sandbox'; description = 'Protected sandbox.' + explicitOnly 'it needs the protected sandbox credentials' + } + """); + workflow(EXECUTING_WORKFLOW); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").build(); + + // then + assertThat(result.getOutput()).contains("every strict lane is in an executed stage"); + } + + @Test + @DisplayName("--dry-run 없이 부르면 모든 단계를 실행하게 되므로 시작 전에 거절한다") + void refusesToRunWithoutDryRun() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + """); + workflow(EXECUTING_WORKFLOW); + + // when + BuildResult result = runner(":verifyStrictLaneStages").buildAndFail(); + + // then + assertThat(result.getOutput()).contains("run it with --dry-run"); + } + + private void leafLanes(String lanes) throws Exception { + Files.writeString( + gradleRoot.resolve("leaf/build.gradle"), + """ + plugins { + id 'java' + id 'ca.strict-test-lane' + } + strictTestLanes { + %s + } + """ + .formatted(lanes)); + } + + private void workflow(String content) throws Exception { + Files.writeString(repository.resolve(".github/workflows/main.yml"), content); + } + + private GradleRunner runner(String... args) { + return GradleRunner.create() + .withProjectDir(gradleRoot.toFile()) + .withPluginClasspath() + .withArguments(args); + } +} diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java new file mode 100644 index 00000000..9430954f --- /dev/null +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java @@ -0,0 +1,148 @@ +package dev.caskeleton.buildlogic.strictlane; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.buildlogic.strictlane.WorkflowGradleInvocations.Invocation; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class WorkflowGradleInvocationsTest { + + @Test + @DisplayName("한 줄 run 단계의 gradlew 명령은 그 태스크를 실행하는 것으로 읽는다") + void oneLineRunStepExecutesItsTasks() { + // given + String workflow = + """ + jobs: + gate: + steps: + - name: Run + working-directory: src + run: ./gradlew :mainCheck --continue --warning-mode=fail --stacktrace + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).singleElement().satisfies( + invocation -> { + assertThat(invocation.tasks()).containsExactly(":mainCheck"); + assertThat(invocation.executesInStartBuild(":mainCheck")).isTrue(); + }); + } + + @Test + @DisplayName("--dry-run 명령은 태스크를 계획만 하므로 실행으로 세지 않는다") + void dryRunPlansButDoesNotExecute() { + // given + String workflow = + """ + - run: | + for gate in ci integrationCheck; do + ./gradlew "${gate}" --dry-run --configuration-cache + done + ./gradlew integrationCheck -m + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations) + .isNotEmpty() + .noneMatch(invocation -> invocation.executesInStartBuild(":integrationCheck")); + } + + @Test + @DisplayName("주석에만 적힌 태스크는 실행으로 세지 않는다") + void taskNamedOnlyInACommentIsNotExecuted() { + // given + String workflow = + """ + # ./gradlew :integrationCheck runs every lane + job: + steps: + - run: ./gradlew :ci --stacktrace # then ./gradlew :integrationCheck + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations) + .noneMatch(invocation -> invocation.executesInStartBuild(":integrationCheck")) + .anyMatch(invocation -> invocation.executesInStartBuild(":ci")); + } + + @Test + @DisplayName("-p로 다른 빌드를 실행하는 명령은 시작 빌드의 같은 이름 태스크로 세지 않는다") + void otherBuildDoesNotCountForTheStartBuild() { + // given + String workflow = + """ + - run: ./gradlew -p optional-platforms integrationCheck --stacktrace + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).singleElement().satisfies( + invocation -> { + assertThat(invocation.projectDir()).isEqualTo("optional-platforms"); + assertThat(invocation.executesInStartBuild(":integrationCheck")).isFalse(); + }); + } + + @Test + @DisplayName("접힌 블록은 줄을 공백으로 잇고, 빈 줄 뒤는 별개의 셸 명령이 된다") + void foldedBlockJoinsLinesAndBreaksOnABlankLine() { + // given + String workflow = + """ + - name: Lanes + run: >- + ./gradlew + :adapter:inbound:web:performanceTest + :adapter:inbound:web:webJettyPerformanceTest + + ./gradlew --version + - name: Next + run: echo done + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).hasSize(2); + assertThat(invocations.get(0).tasks()) + .containsExactly( + ":adapter:inbound:web:performanceTest", ":adapter:inbound:web:webJettyPerformanceTest"); + assertThat(invocations.get(1).tasks()).isEmpty(); + } + + @Test + @DisplayName("루트 태스크는 콜론을 붙여도 빼도 같은 태스크로 읽는다") + void rootTaskWithOrWithoutLeadingColonIsTheSameTask() { + // given + String workflow = + """ + - run: ./gradlew integrationCheck sample-portfolio:check --tests '*Contract*' + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).singleElement().satisfies( + invocation -> { + assertThat(invocation.executesInStartBuild(":integrationCheck")).isTrue(); + assertThat(invocation.executesInStartBuild(":sample-portfolio:check")).isTrue(); + assertThat(invocation.tasks()).doesNotContain("*Contract*"); + }); + } +} diff --git a/src/build.gradle b/src/build.gradle index 47114ede..d4a51439 100644 --- a/src/build.gradle +++ b/src/build.gradle @@ -18,6 +18,8 @@ plugins { // and archive hygiene is gone with the revision it cleaned out of every leaf's jar name (review // 2026-09-24 BUILD-O3-5). id 'ca.architecture' + // Every strict lane belongs to a stage a workflow executes (review 2026-11-01 08-01). + id 'ca.strict-lane-stages' } group = 'dev.caskeleton' @@ -70,6 +72,8 @@ tasks.register('verifyDependencyLocks') { // sample web contract, public-path baseline, transport and messaging // qualification lanes, and each leaf's document-contract lanes // integrationCheck the declared strict integration lanes (several need a container runtime) +// performanceCheck the declared strict performance lanes (load, shutdown, pool and resource +// bounds; real servers and containers) // releaseCheck the tag-only checks: release provenance + public path snapshot (not `ci` // again — a tag is cut from a main commit the PR and main stages ran on) // @@ -104,6 +108,14 @@ tasks.register('integrationCheck') { dependsOn ':sample-portfolio:integrationTestLaneCheck' } +// Performance lanes are not the pull request's or the main stage's: their bounds need a machine that +// is not compiling something else. integration-main.yml runs this aggregate on main and nightly. +tasks.register('performanceCheck') { + group = 'verification' + description = "Runs every production CI leaf's performance-category test lanes. Several need a container runtime." + dependsOn leafPaths.collect { "${it}:performanceTestLaneCheck" } +} + tasks.named('architectureCheck') { dependsOn leafPaths.collect { "${it}:architectureTestLaneCheck" } } @@ -160,12 +172,26 @@ tasks.register('mainCheck') { dependsOn tasks.named('configContractCheck') dependsOn tasks.named('qualificationCheck') dependsOn tasks.named('sampleWebContractCheck') + // The standalone sample booted whole against real PostgreSQL. The sample is outside `leafPaths`, + // so systemTestCheck does not reach it, and no stage ran it (review 2026-11-01 08-01). + dependsOn ':sample-portfolio:systemTest' dependsOn tasks.named('verifyPublicPathSnapshot') dependsOn tasks.named('conditionalTransportQualification') dependsOn tasks.named('verifyMessagingContracts') dependsOn ':adapter:inbound:graphql:graphqlStableTest' } +// The stages a strict lane may belong to. `verifyStrictLaneStages --dry-run` (pull-request gate) +// fails when a strict lane that is not `explicitOnly` is in the plan of none of these, or when a +// stage is executed by no workflow — the gap that left fourteen lanes running nowhere while each +// one failed closed (review 2026-11-01 08-01). A new lane joins a stage through its category +// aggregate; no workflow line names it. +strictLaneStages { + stage ':ci', ':sample-portfolio:check', ':mainCheck', ':integrationCheck', ':performanceCheck', + ':releaseCheck' + workflowDirectory = layout.projectDirectory.dir('../.github/workflows') +} + // The deny-by-default public path baseline: app-bootstrap's approval-test lane under its old name. // `-PapprovePublicPathChange` rewrites the baseline after review. tasks.register('verifyPublicPathSnapshot') { diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java index 37a2e54a..ca9222d4 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java @@ -2,9 +2,9 @@ package dev.caskeleton.composition.fileserver; import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.FileserverMetricsSupport; import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; -import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy; import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; import dev.caskeleton.application.fileserver.download.DescribeFileApplicationUseCase; import dev.caskeleton.application.fileserver.download.DownloadContentPort; @@ -24,8 +24,10 @@ import dev.caskeleton.application.fileserver.port.in.MoveFileUseCase; import dev.caskeleton.application.fileserver.port.in.OpenDownloadContentUseCase; import dev.caskeleton.application.fileserver.port.in.PrepareDownloadUseCase; import dev.caskeleton.application.fileserver.port.in.TransferDownloadContentUseCase; +import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort; import dev.caskeleton.application.fileserver.upload.UploadIdentifierPort; +import dev.caskeleton.application.fileserver.upload.UploadPolicies; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.util.Optional; @@ -94,16 +96,18 @@ class FileserverFileUseCaseConfiguration { CopyFileUseCase fileserverCopyFile( FileMetadataPort metadataStore, CopyContentPort copyGateway, - FileAccessPolicyPort accessPolicy, - OriginalFilenamePolicy filenamePolicy, + UploadPolicies policies, + FileQuotaPort quotaService, + TransferAdmissionController admissionController, UploadIdentifierPort identifierFactory, TransactionPort transactions, Clock clock) { return new CopyFileApplicationUseCase( metadataStore, copyGateway, - accessPolicy, - filenamePolicy, + policies, + quotaService, + admissionController, identifierFactory, transactions, clock); diff --git a/src/composition/outbox-relay/README.md b/src/composition/outbox-relay/README.md index db52e264..1c76f915 100644 --- a/src/composition/outbox-relay/README.md +++ b/src/composition/outbox-relay/README.md @@ -15,7 +15,8 @@ composition:outbox-relay └─ OutboxRelayAutoConfiguration app.outbox.enabled=true + OutboxStorePort 가 있을 때만 ├─ OutboxSettings app.outbox.* strict 바인딩(오타는 기동 실패) ├─ OutboxRelayScheduler relay-enabled=true + OutboxMessagePublishPort 가 있을 때만, - │ PublishPendingOutboxEventsUseCase 를 fixed-delay 로 구동 + │ PublishPendingOutboxEventsUseCase 를 fixed-delay 로 구동, + │ 종료 때 platform보다 먼저 멈춤(SmartLifecycle) ├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag / published.total └─ OutboxLeaderElectionToken SKIP LOCKED 가 리더 선출이라는 표시(로직 없음) ``` @@ -126,6 +127,20 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a - **스케줄링은 `OutboxRelayAutoConfiguration`가 직접 켜고(`@EnableScheduling`) fixed-delay 를 쓴다.** 예전에는 JDBC idempotency 설정만 스케줄링을 켰기 때문에 다른 provider 를 고르면 릴레이가 조립만 되고 돌지 않았다. fixed-delay 는 릴레이 실행 시간과 무관하게 사이클이 겹치지 않도록(non-overlapping) 보장한다. +- **종료 때는 platform보다 먼저 멈추고 진행 중 회차를 끝낸다(SmartLifecycle, phase + `Integer.MAX_VALUE`).** relay 회차는 messaging platform을 거쳐 발행한다. platform은 자기 종료 + phase(`MessagingShutdownLifecycle`, `Integer.MAX_VALUE - 1024`)에서 발행 admission을 닫고, 그 뒤 + 발행은 `SHUTTING_DOWN`으로 거부된다. `@Scheduled`만으로는 이 순서에 들어가지 못한다(Spring은 + `ContextClosedEvent`에서 다음 tick만 취소하고 실행 중 회차는 그대로 둔다). 그래서 스케줄러가 + SmartLifecycle로 platform 위 phase(platform 자체 relay `MessagingOutboxRelayLifecycle`와 같은 값)에 + 서고, `stop`에서 새 회차를 막고 실행 중 회차가 결과를 기록할 때까지 종료를 붙잡는다. 기다리는 한도는 + Spring의 `spring.lifecycle.timeout-per-shutdown-phase`다. 한도를 넘긴 회차의 남은 row는 거부되지만 + 재시도 대상(FAILED)이고, 프로세스가 강제 종료되면 IN_FLIGHT row는 lease 만료(`in-flight-timeout`) + 뒤 다시 claim된다. 이 leaf는 messaging 타입을 이름으로 부를 수 없어 phase를 값으로 맞췄고, + `OutboxRelayShutdownOrderTest`가 같은 phase의 대역으로 순서를 고정한다. + - 버린 대안: scheduler executor phase 올리기(전역 설정이라 다른 `@Scheduled` 작업까지 바뀐다), + relay 루프를 전용 스레드로 직접 소유하기(`@Scheduled`·fixed-delay 정책과 `@EnableScheduling` + 결정까지 다시 열어야 해서 이번 범위보다 크다). ### OutboxSettings - **튜닝 값(poll 주기·batch·timeout·보존)은 코드 리터럴 기본값을 쓰고 env placeholder 를 두지 않는다.** 신규 env key 를 diff --git a/src/composition/outbox-relay/build.gradle b/src/composition/outbox-relay/build.gradle index 5c227e88..9cc10118 100644 --- a/src/composition/outbox-relay/build.gradle +++ b/src/composition/outbox-relay/build.gradle @@ -29,6 +29,8 @@ dependencies { implementation libs.logstash.logback.encoder testImplementation 'org.springframework.boot:spring-boot-starter-test' + // The shutdown-order test runs the real relay over the port owner's shared fake store. + testImplementation testFixtures(project(':application-core')) testImplementation 'org.mockito:mockito-core' testImplementation 'ch.qos.logback:logback-classic' testRuntimeOnly 'org.yaml:snakeyaml' diff --git a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayScheduler.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayScheduler.java index 315a29a7..f98b1c06 100644 --- a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayScheduler.java +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayScheduler.java @@ -8,13 +8,28 @@ import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase; import java.time.Clock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.context.SmartLifecycle; import org.springframework.scheduling.annotation.Scheduled; /** - * Thin bootstrap scheduler that drives the outbox relay use case on a fixed-delay polling loop. - * Registered by {@code OutboxConfig}. See README for the design rationale. + * Thin scheduler that drives the outbox relay use case on a fixed-delay polling loop, and stops + * ahead of the messaging platform on shutdown. Registered by {@link OutboxRelayAutoConfiguration}. + * See README for the design rationale. + * + *

      A cycle publishes through the platform. The platform closes publish admission when its own + * shutdown phase runs ({@code MessagingShutdownLifecycle}, phase {@code Integer.MAX_VALUE - 1024}), + * and every publish after that is refused. So this scheduler is a {@link SmartLifecycle} in a + * higher phase: on stop it refuses new cycles and holds the shutdown until the running cycle has + * written its outcomes, and only then lets the lower phases close admission and the transports. */ -public class OutboxRelayScheduler { +public class OutboxRelayScheduler implements SmartLifecycle { + + /** + * Stops first, in the same phase as the platform's own outbox relay ({@code + * MessagingOutboxRelayLifecycle}): above the platform's admission gate, which this leaf cannot + * name. + */ + static final int PHASE = Integer.MAX_VALUE; private static final Logger log = LoggerFactory.getLogger(OutboxRelayScheduler.class); @@ -22,6 +37,11 @@ public class OutboxRelayScheduler { private final OutboxMetrics metrics; private final Clock clock; + private final Object monitor = new Object(); + private boolean running; + private boolean cycleInProgress; + private Runnable stopCallback; + public OutboxRelayScheduler( PublishPendingOutboxEventsUseCase relayUseCase, OutboxMetrics metrics, Clock clock) { this.relayUseCase = relayUseCase; @@ -30,11 +50,33 @@ public class OutboxRelayScheduler { } /** - * Unexpected exceptions are caught (not propagated) so the scheduler thread stays alive for the - * next tick. + * Runs one relay cycle unless the scheduler is stopped. Unexpected exceptions are caught (not + * propagated) so the scheduler thread stays alive for the next tick. */ @Scheduled(fixedDelayString = "${app.outbox.poll-interval:PT5S}") public void relay() { + synchronized (monitor) { + if (!running) { + return; + } + cycleInProgress = true; + } + try { + runCycle(); + } finally { + Runnable pendingStop; + synchronized (monitor) { + cycleInProgress = false; + pendingStop = stopCallback; + stopCallback = null; + } + if (pendingStop != null) { + pendingStop.run(); + } + } + } + + private void runCycle() { try { OutboxRelayResult result = relayUseCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -58,4 +100,48 @@ public class OutboxRelayScheduler { ex); } } + + @Override + public void start() { + synchronized (monitor) { + running = true; + } + } + + /** Refuses new cycles; does not wait. Context shutdown uses {@link #stop(Runnable)}. */ + @Override + public void stop() { + synchronized (monitor) { + running = false; + } + } + + /** + * Refuses new cycles and reports stopped once the running cycle, if any, has finished. Spring + * waits for the callback up to {@code spring.lifecycle.timeout-per-shutdown-phase}; a cycle still + * running then meets a closed admission gate and its rows are retried, not lost. + */ + @Override + public void stop(Runnable callback) { + synchronized (monitor) { + running = false; + if (cycleInProgress) { + stopCallback = callback; + return; + } + } + callback.run(); + } + + @Override + public boolean isRunning() { + synchronized (monitor) { + return running; + } + } + + @Override + public int getPhase() { + return PHASE; + } } diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerLoggingTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerLoggingTest.java index 26de8226..99482c17 100644 --- a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerLoggingTest.java +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerLoggingTest.java @@ -28,7 +28,9 @@ class OutboxRelaySchedulerLoggingTest { .thenThrow(new IllegalStateException("unexpected")); try (CapturedLogger captured = capture(OutboxRelayScheduler.class)) { - new OutboxRelayScheduler(relay, metrics, Clock.systemUTC()).relay(); + OutboxRelayScheduler scheduler = new OutboxRelayScheduler(relay, metrics, Clock.systemUTC()); + scheduler.start(); + scheduler.relay(); ILoggingEvent event = captured.singleEvent(); assertThat(event.getLevel()).isEqualTo(Level.ERROR); diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java new file mode 100644 index 00000000..8c556e1b --- /dev/null +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java @@ -0,0 +1,197 @@ +package dev.caskeleton.composition.outbox; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import dev.caskeleton.application.outbox.ClaimedOutboxEvent; +import dev.caskeleton.application.outbox.OutboxCompletion; +import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxLease; +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort; +import dev.caskeleton.application.outbox.OutboxStorePort; +import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import java.time.Clock; +import java.time.Instant; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.SmartLifecycle; + +/** + * The messaging platform closes publish admission at phase {@code Integer.MAX_VALUE - 1024} ({@code + * MessagingShutdownLifecycle}). A relay cycle still publishing after that is refused with {@code + * SHUTTING_DOWN} and spends an attempt. The relay must stop first and finish its cycle. + */ +class OutboxRelayShutdownOrderTest { + + /** {@code MessagingShutdownLifecycle#getPhase()}; this leaf may not name the messaging type. */ + private static final int PLATFORM_ADMISSION_PHASE = Integer.MAX_VALUE - 1024; + + private static final String EVENT_ID = "evt-shutdown-1"; + + @Test + @DisplayName("종료 시 relay가 진행 중 회차를 끝내고 멈춘 뒤에 platform이 admission을 닫는다") + void relayFinishesItsRunningCycleBeforeThePlatformClosesAdmission() throws Exception { + // given + RecordingStore store = new RecordingStore(); + store.addClaimable(OutboxEvents.claimed(EVENT_ID, Instant.now().minusSeconds(60), 1)); + BlockingPublishPort publishPort = new BlockingPublishPort(); + PlatformAdmissionStandIn platform = new PlatformAdmissionStandIn(store); + ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) + .withBean(OutboxStorePort.class, () -> store) + .withBean(OutboxMessagePublishPort.class, () -> publishPort) + .withBean(OutboxRelayFailureReportPort.class, () -> report -> {}) + .withBean(TransactionPort.class, DirectTransactionPort::new) + .withBean(Clock.class, Clock::systemUTC) + .withBean(PlatformAdmissionStandIn.class, () -> platform) + .withPropertyValues( + "app.outbox.enabled=true", + "app.outbox.relay-enabled=true", + "app.outbox.poll-interval=PT1H"); + AtomicReference> closing = new AtomicReference<>(); + + runner.run( + context -> { + assertThat(publishPort.entered.await(10, TimeUnit.SECONDS)) + .as("the first relay tick claims the row and starts publishing it") + .isTrue(); + + // when + closing.set(CompletableFuture.runAsync(context::close)); + + // The relay holds the shutdown while its cycle runs; release the publish either way so + // a wrong order fails the assertions below instead of hanging. + platform.stopped.await(300, TimeUnit.MILLISECONDS); + publishPort.release.countDown(); + closing.get().get(20, TimeUnit.SECONDS); + }); + + // then + assertThat(platform.stopped.getCount()).as("the platform stand-in was stopped").isZero(); + assertThat(platform.rowCompletedWhenStopped.get()) + .as("the relay cycle wrote its outcome before the platform closed admission") + .isTrue(); + assertThat(store.status(EVENT_ID)).isEqualTo(OutboxEventStatus.PUBLISHED); + } + + @Test + @DisplayName("멈춘 relay는 다음 tick이 와도 새 회차를 시작하지 않는다") + void aStoppedRelayStartsNoNewCycle() { + // given + PublishPendingOutboxEventsUseCase relayUseCase = mock(PublishPendingOutboxEventsUseCase.class); + OutboxRelayScheduler scheduler = + new OutboxRelayScheduler(relayUseCase, mock(OutboxMetrics.class), Clock.systemUTC()); + scheduler.start(); + AtomicBoolean reportedStopped = new AtomicBoolean(); + scheduler.stop(() -> reportedStopped.set(true)); + + // when + scheduler.relay(); + + // then + verifyNoInteractions(relayUseCase); + assertThat(reportedStopped).as("no cycle was running, so stop reported at once").isTrue(); + assertThat(scheduler.isRunning()).isFalse(); + } + + /** Records when the relay writes the row's completion. */ + private static final class RecordingStore extends InMemoryOutboxStore { + + private final AtomicBoolean completed = new AtomicBoolean(); + + @Override + public synchronized OutboxCompletion markPublished(OutboxLease lease) { + OutboxCompletion completion = super.markPublished(lease); + completed.set(true); + return completion; + } + + @Override + public synchronized OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { + OutboxCompletion completion = super.markFailed(lease, nextAttemptAt); + completed.set(true); + return completion; + } + + @Override + public synchronized OutboxCompletion markDead(OutboxLease lease) { + OutboxCompletion completion = super.markDead(lease); + completed.set(true); + return completion; + } + + @Override + public synchronized OutboxEventStatus status(String eventId) { + return super.status(eventId); + } + } + + /** A publish that blocks until the test releases it, like a slow broker. */ + private static final class BlockingPublishPort implements OutboxMessagePublishPort { + + private final CountDownLatch entered = new CountDownLatch(1); + private final CountDownLatch release = new CountDownLatch(1); + + @Override + public void publish(ClaimedOutboxEvent event) { + entered.countDown(); + try { + if (!release.await(20, TimeUnit.SECONDS)) { + throw new IllegalStateException("publish was never released"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("publish interrupted", interrupted); + } + } + } + + /** Stands in for the platform's admission gate: same phase, records what it found on stop. */ + private static final class PlatformAdmissionStandIn implements SmartLifecycle { + + private final RecordingStore store; + private final CountDownLatch stopped = new CountDownLatch(1); + private final AtomicBoolean rowCompletedWhenStopped = new AtomicBoolean(); + private volatile boolean running; + + PlatformAdmissionStandIn(RecordingStore store) { + this.store = store; + } + + @Override + public void start() { + running = true; + } + + @Override + public void stop() { + running = false; + rowCompletedWhenStopped.set(store.completed.get()); + stopped.countDown(); + } + + @Override + public boolean isRunning() { + return running; + } + + @Override + public int getPhase() { + return PLATFORM_ADMISSION_PHASE; + } + } +} diff --git a/src/composition/service-runtime/README.md b/src/composition/service-runtime/README.md index fbfec221..95ae5f23 100644 --- a/src/composition/service-runtime/README.md +++ b/src/composition/service-runtime/README.md @@ -12,16 +12,21 @@ runtime 배선이다. 예전에는 app-bootstrap에 있었고 sample이 그 복 ``` composition:service-runtime - ├─ tracing/ TracingConfig(+ Tracer·SpanErrorRecorder·sampling gauge), TracingSettings, - │ TracingSampleRateResolver, TracingSamplingEnvironmentPostProcessor + ├─ tracing/ TracingConfig(SpanErrorRecorder·ActiveTrace·sampling gauge), TracingSettings, + │ TracingSampleRateResolver, TracingEnvironmentPostProcessor(app.tracing.* → + │ Boot 키), TracingSwitchImportFilter(enabled=false면 Boot tracing 제외) ├─ metrics/ MetricsContractConfig(cardinality deny-list + SLO 분포 filter) ├─ context/ DomainContextConfig ├─ logging/ PseudonymizationConfig, PrivacySettings (user_principal HMAC 가명화) └─ management/security/ ManagementSecurityConfig (actuator chain) ``` -- 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(sampling bridge는 `spring.factories`의 - `EnvironmentPostProcessor`). 구성 루트의 component scan에 기대지 않는다. +- 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(설정 브리지와 tracing 스위치는 + `spring.factories`의 `EnvironmentPostProcessor`·`AutoConfigurationImportFilter`). 구성 루트의 + component scan에 기대지 않는다. +- Tracer·span processor·OTLP exporter는 이 모듈이 만들지 않는다. Spring Boot 4의 + `spring-boot-micrometer-tracing-opentelemetry`(+ `opentelemetry-exporter-otlp`)가 만들고, 이 모듈은 + `app.tracing.*` 값을 Boot 키로 옮기고 끄는 스위치만 둔다(아래 "tracing" 절). - 설정 키는 옮기지 않았다: `app.tracing.*`, `app.privacy.*`. 값은 각 구성 루트의 `application.yml`/`config/observability.yml`에 있다. - actuator chain은 servlet 웹 애플리케이션에서만 만들어지고, 구성 루트가 같은 이름 `actuatorSecurityFilterChain`의 bean을 두면 물러난다. sample-portfolio는 공개 데모라 그렇게 @@ -57,9 +62,26 @@ runtimeOnly project(':composition:service-runtime') ### tracing — 분산 트레이싱 wiring과 샘플링 정책 +#### Boot tracing으로 바꾼 이유 (리뷰 07-01, 2026-11-01) +- **예전에는 `TracingConfig`가 `Tracer`를 직접 만들었다.** `SdkTracerProvider`에 sampler만 있고 span + processor·exporter가 없었고, Boot tracing 자동 설정은 classpath에 없었다. 그래서 HTTP 요청이 span을 + 만들지 않았고 `OTEL_EXPORTER_OTLP_ENDPOINT`를 넣어도 아무것도 나가지 않았다. +- **고른 방법:** 직접 조립을 지우고 Boot 4의 `spring-boot-micrometer-tracing-opentelemetry`를 쓴다. + Boot가 SDK, `BatchSpanProcessor`, observation→span 핸들러, propagator, 그리고 + `management.opentelemetry.tracing.export.otlp.endpoint`가 있을 때만 OTLP exporter를 만든다. + `spring-boot-starter-opentelemetry`는 쓰지 않는다 — OTLP 메트릭 push(`micrometer-registry-otlp`)까지 + 켜서 이 템플릿의 Prometheus scrape 계약 밖의 전송이 생긴다. +- **버린 대안:** (1) 직접 만든 `SdkTracerProvider`에 processor·exporter를 붙이기 — observation→span 연결과 + propagator까지 다시 짜야 한다. (2) tracing을 빼고 로그 상관만 제공 — 소유자가 관측 기본 제공을 정했다. +- **trace id 하나로 맞추기:** Boot의 서버 observation(`HIGHEST_PRECEDENCE + 1`)이 span을 연 뒤에 + `WebMvcRequestIdFilter`(`+ 10`)가 돈다. 필터는 `ActiveTrace`로 그 span의 id를 받아 `meta.traceId`, + 로그 `trace_id`·`span_id`, 응답 `traceparent`에 쓴다. tracer가 없으면 예전처럼 들어온 + `traceparent`를 쓰거나 새로 만든다. + #### TracingConfig -- **컴포지션 루트에서 트레이싱을 조립한다.** 두 가지를 한다: (1) 시작 시 `tracing.sampling.rate` - 게이지 등록, (2) `SpanErrorRecorder` 빈 등록. +- **컴포지션 루트의 트레이싱 부속을 등록한다.** 세 가지를 한다: (1) 시작 시 `tracing.sampling.rate` + 게이지 등록, (2) `SpanErrorRecorder` 빈 등록, (3) `ActiveTrace` 빈 등록(`Tracer`가 없으면 `NONE`). + Boot의 `OpenTelemetryTracingAutoConfiguration` 뒤에 돈다. - **`SpanErrorRecorder` 빈은 `@ConditionalOnBean(Tracer.class)`가 아니라 `ObjectProvider`로 런타임 존재 여부를 직접 조회한다.** 이유: `@ConditionalOnBean`은 사용자 정의 `@Configuration`에서 autoconfiguration 이 만드는 빈(여기서는 `Tracer`)을 조건으로 쓸 때 빈 등록 순서가 보장되지 않아 @@ -69,10 +91,14 @@ runtimeOnly project(':composition:service-runtime') `SpanErrorRecorder` 빈을 이미 등록한 경우 이 빈은 backoff 한다.** adapter-web 의 `GlobalExceptionHandler`는 `ObjectProvider`로 `SpanErrorRecorder`를 조회하므로, 자기 자신의 NOOP self-default 에서 여기서 등록한 실제 구현으로 자동 교체된다. -- **OTel/Micrometer tracer 런타임은 이 repo 에서 seam 이 활성 상태다.** `micrometer-tracing-bridge-otel` - + `opentelemetry-exporter-otlp`가 `app-bootstrap/build.gradle`에 실제로 wiring 되어 있다. 단, span - exporter 는 `OTEL_EXPORTER_OTLP_ENDPOINT`가 비어 있는 동안 꺼져 있고, 엔드포인트를 설정하면 - export 가 시작된다. +- **span export는 `OTEL_EXPORTER_OTLP_ENDPOINT`가 정한다.** 비어 있으면 Boot exporter 키가 생기지 + 않아 exporter bean이 없다(기본 주소로 보내지도 않는다). 값이 있으면 OTLP/HTTP로 `<값>/v1/traces`에 + 보낸다. `TracingExportSystemTest`가 로컬 수신기로 이것을 확인한다. +- **`APP_TRACING_ENABLED=false`면 `Tracer` bean이 없다.** `TracingSwitchImportFilter`가 + `org.springframework.boot.micrometer.tracing.` 아래 자동 설정을 모두 뺀다. Boot의 + `management.tracing.export.enabled=false`는 export만 끄고 tracer와 span은 그대로 만들기 때문에 쓰지 + 않았다. `spring.autoconfigure.exclude`에 넣는 방법은 운영자가 쓴 exclude 목록과 덮어쓰기 경쟁을 + 해서 버렸다. - **게이지 등록 시 active profile 은 `Environment.getActiveProfiles()`의 첫 번째 값을 쓴다.** 멀티 프로파일 배포에서는 맨 앞에 나열된 프로파일이 권위 있는 배포 환경이라는 규약이다. `MeterRegistry`가 classpath 에 없으면(Actuator 미탑재) 게이지 등록은 조용히 no-op 이 된다. @@ -87,7 +113,7 @@ runtimeOnly project(':composition:service-runtime') - **`sampleRate`가 blank 이면 숫자 검증을 건너뛴다.** blank 는 "값이 잘못됐다"가 아니라 "프로파일별 기본값에 위임하라"는 신호이기 때문이다. 실제 런타임별 기본값(prod=0.01, dev/local=1.0)은 `TracingSampleRateResolver`가 적용하고, profile vocabulary 자체는 `RuntimeEnvironment`가 소유한다. resolved 된 값은 - `TracingSamplingEnvironmentPostProcessor`가 Spring Boot 네이티브 + `TracingEnvironmentPostProcessor`가 Spring Boot 네이티브 `management.tracing.sampling.probability`로 브리지한다. - **검증은 시작 시 fail-fast 다.** `sampleRate`가 non-blank 인데 [0.0, 1.0] float 이 아니면 시작이 실패하고, `otlpEndpoint`가 non-empty 인데 scheme 없는 잘못된 URL 이면 시작이 실패한다. `enabled`는 @@ -114,11 +140,16 @@ runtimeOnly project(':composition:service-runtime') - **`MeterRegistry`를 `ObjectProvider`로 조회하며, Actuator 미탑재로 빈이 없으면 등록을 조용히 건너뛴다.** 이는 `BackgroundJobMetrics` / `OutboxMetrics`의 선례를 그대로 따른다. -#### TracingSamplingEnvironmentPostProcessor -- **resolved 된 유효 샘플 비율을 Spring Boot 네이티브 키 `management.tracing.sampling.probability`로 - 단일화(브리지)하는 `EnvironmentPostProcessor`다.** 이를 통해 "프로파일별 기본값 + env override"라는 +#### TracingEnvironmentPostProcessor +- **`app.tracing.*`을 Boot tracing 키로 옮기는 `EnvironmentPostProcessor`다.** (1) resolved 된 유효 샘플 + 비율 → `management.tracing.sampling.probability`, (2) `app.tracing.exporter.otlp-endpoint`(= + `OTEL_EXPORTER_OTLP_ENDPOINT`) → `management.opentelemetry.tracing.export.otlp.endpoint`. (2)는 + OpenTelemetry 규약대로 기준 주소에 `/v1/traces`를 붙인다(끝의 `/`는 하나로 정리). gRPC 전송이나 다른 + 경로가 필요하면 Boot 키(`management.opentelemetry.tracing.export.otlp.*`)를 직접 주며, 직접 준 값은 + 덮어쓰지 않는다. 예전 이름은 `TracingSamplingEnvironmentPostProcessor`다(순서 상수는 + `StartupOrder.TRACING_SAMPLING` 그대로). 이를 통해 "프로파일별 기본값 + env override"라는 우리 규약을 Spring Boot 의 기본 샘플링 메커니즘에 그대로 연결한다. -- **브리지 우선순위.** (1) 사용자가 `management.tracing.sampling.probability`를 이미 명시했으면 +- **샘플링 브리지 우선순위.** (1) 사용자가 `management.tracing.sampling.probability`를 이미 명시했으면 덮어쓰지 않고 그대로 둔다, (2) `app.tracing.sample-rate`가 non-blank 면 그 값 사용, (3) blank 면 `TracingSampleRateResolver.defaultRateForProfile(...)`로 active profile 기본값 적용. - **`META-INF/spring.factories`에 `org.springframework.boot.EnvironmentPostProcessor` 키로 등록된다.** diff --git a/src/composition/service-runtime/build.gradle b/src/composition/service-runtime/build.gradle index cadce8d5..7c5bedaa 100644 --- a/src/composition/service-runtime/build.gradle +++ b/src/composition/service-runtime/build.gradle @@ -30,8 +30,14 @@ dependencies { // MeterRegistryCustomizer, EndpointRequest and the actuator types the chains match on. implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'io.micrometer:micrometer-core' + // Distributed tracing is Boot's: its auto-configuration builds the OTel SDK, the span processor, + // the observation handlers that turn each HTTP observation into a span, and — only once + // management.opentelemetry.tracing.export.otlp.endpoint is set — the OTLP exporter. This module + // translates the app.tracing.* keys into those (TracingEnvironmentPostProcessor) and + // switches the whole of it off for app.tracing.enabled=false (TracingSwitchImportFilter). implementation 'io.micrometer:micrometer-tracing-bridge-otel' - implementation 'io.opentelemetry:opentelemetry-sdk' + implementation 'org.springframework.boot:spring-boot-micrometer-tracing-opentelemetry' + implementation 'io.opentelemetry:opentelemetry-exporter-otlp' // The actuator security chain. implementation 'org.springframework.boot:spring-boot-starter-security' diff --git a/src/composition/service-runtime/gradle.lockfile b/src/composition/service-runtime/gradle.lockfile index 82aa5297..2c16687f 100644 --- a/src/composition/service-runtime/gradle.lockfile +++ b/src/composition/service-runtime/gradle.lockfile @@ -36,6 +36,10 @@ com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProce com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle +com.squareup.okhttp3:okhttp-jvm:5.2.1=runtimeClasspath,testRuntimeClasspath +com.squareup.okhttp3:okhttp:5.2.1=runtimeClasspath,testRuntimeClasspath +com.squareup.okio:okio-jvm:3.16.1=runtimeClasspath,testRuntimeClasspath +com.squareup.okio:okio:3.16.1=runtimeClasspath,testRuntimeClasspath com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-collections:commons-collections:3.2.2=checkstyle @@ -55,8 +59,13 @@ io.opentelemetry.semconv:opentelemetry-semconv:1.37.0=compileClasspath,runtimeCl io.opentelemetry:opentelemetry-api:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-common:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-context:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-common:1.55.0=runtimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-otlp-common:1.55.0=runtimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-sender-okhttp:1.55.0=runtimeClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-sdk-common:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.55.0=runtimeClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-sdk-logs:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-sdk-metrics:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-sdk-trace:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -101,6 +110,8 @@ org.dom4j:dom4j:2.2.0=spotbugs org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle +org.jetbrains.kotlin:kotlin-stdlib:2.2.21=runtimeClasspath,testRuntimeClasspath +org.jetbrains:annotations:13.0=runtimeClasspath,testRuntimeClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath @@ -142,6 +153,9 @@ org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,t org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-micrometer-metrics:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-micrometer-observation:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-tracing-opentelemetry:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-tracing:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-opentelemetry:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-security:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath diff --git a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/MicrometerActiveTrace.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/MicrometerActiveTrace.java new file mode 100644 index 00000000..9b781ad6 --- /dev/null +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/MicrometerActiveTrace.java @@ -0,0 +1,35 @@ +package dev.caskeleton.composition.runtime.tracing; + +import dev.caskeleton.shared.tracing.ActiveTrace; +import dev.caskeleton.shared.tracing.TraceParent; +import io.micrometer.tracing.Span; +import io.micrometer.tracing.TraceContext; +import io.micrometer.tracing.Tracer; +import java.util.Optional; + +/** Micrometer-backed {@link ActiveTrace}: the context of {@link Tracer#currentSpan()}. */ +public final class MicrometerActiveTrace implements ActiveTrace { + + private final Tracer tracer; + + public MicrometerActiveTrace(Tracer tracer) { + this.tracer = tracer; + } + + @Override + public Optional current() { + Span span = tracer.currentSpan(); + if (span == null) { + return Optional.empty(); + } + TraceContext context = span.context(); + // An invalid (all-zero) context is what a no-op span reports; it names no trace. + if (!TraceParent.isValidTraceId(context.traceId()) + || !TraceParent.isValidSpanId(context.spanId())) { + return Optional.empty(); + } + return Optional.of( + TraceParent.of( + context.traceId(), context.spanId(), Boolean.TRUE.equals(context.sampled()))); + } +} diff --git a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingConfig.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingConfig.java index 1e59ee93..d46cc21f 100644 --- a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingConfig.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingConfig.java @@ -2,25 +2,27 @@ package dev.caskeleton.composition.runtime.tracing; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; import dev.caskeleton.shared.runtime.RuntimeEnvironment; +import dev.caskeleton.shared.tracing.ActiveTrace; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.tracing.Tracer; -import io.micrometer.tracing.otel.bridge.OtelBaggageManager; -import io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext; -import io.micrometer.tracing.otel.bridge.OtelTracer; -import io.opentelemetry.sdk.OpenTelemetrySdk; -import io.opentelemetry.sdk.trace.SdkTracerProvider; -import io.opentelemetry.sdk.trace.samplers.Sampler; import java.util.List; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; -/** Composition-root wiring for distributed tracing. See README for the design rationale. */ -@AutoConfiguration +/** + * Composition-root wiring for distributed tracing: the sampling-rate gauge and the {@link + * SpanErrorRecorder}. The {@link Tracer} itself, the span processor and the OTLP exporter are + * Spring Boot's tracing auto-configuration; this class runs after it so the recorder sees the + * tracer it built. See README for the design rationale. + */ +@AutoConfiguration( + afterName = + "org.springframework.boot.micrometer.tracing.opentelemetry.autoconfigure" + + ".OpenTelemetryTracingAutoConfiguration") public class TracingConfig { /** @@ -64,32 +66,6 @@ public class TracingConfig { effectiveRate); } - @Bean - @ConditionalOnMissingBean(Tracer.class) - @ConditionalOnProperty( - prefix = "app.tracing", - name = "enabled", - havingValue = "true", - matchIfMissing = true) - Tracer micrometerTracer() { - double sampleRate = - new TracingSampleRateResolver() - .resolve( - RuntimeProfileSnapshot.from(environment).activeProfiles(), properties.sampleRate()); - SdkTracerProvider tracerProvider = - SdkTracerProvider.builder() - .setSampler(Sampler.parentBased(Sampler.traceIdRatioBased(sampleRate))) - .build(); - OpenTelemetrySdk openTelemetry = - OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).build(); - OtelCurrentTraceContext currentTraceContext = new OtelCurrentTraceContext(); - return new OtelTracer( - openTelemetry.getTracer("dev.caskeleton"), - currentTraceContext, - event -> {}, - new OtelBaggageManager(currentTraceContext, List.of(), List.of())); - } - /** * {@link ObjectProvider}, not {@code @ConditionalOnBean(Tracer.class)}: a missing {@link Tracer} * yields {@link SpanErrorRecorder#NOOP} rather than no bean, so downstream injection points never @@ -105,6 +81,21 @@ public class TracingConfig { return new MicrometerSpanErrorRecorder(tracer); } + /** + * The tracer's active span for the inbound adapters that name a request's trace id. Same {@link + * ObjectProvider} reasoning as {@link #micrometerSpanErrorRecorder}: without a {@link Tracer} it + * is {@link ActiveTrace#NONE}, and the web filter falls back to the inbound {@code traceparent}. + */ + @Bean + @ConditionalOnMissingBean(ActiveTrace.class) + ActiveTrace micrometerActiveTrace(ObjectProvider tracerProvider) { + Tracer tracer = tracerProvider.getIfAvailable(); + if (tracer == null) { + return ActiveTrace.NONE; + } + return new MicrometerActiveTrace(tracer); + } + /** Exists so tests can inspect what was registered without a live MeterRegistry. */ public record TracingSamplingRateGaugeRegistrar( String activeProfile, double effectiveSampleRate) {} diff --git a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessor.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessor.java new file mode 100644 index 00000000..a128b388 --- /dev/null +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessor.java @@ -0,0 +1,74 @@ +package dev.caskeleton.composition.runtime.tracing; + +import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; +import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.springframework.boot.EnvironmentPostProcessor; +import org.springframework.boot.SpringApplication; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; + +/** + * Translates this template's {@code app.tracing.*} keys into the Spring Boot keys its tracing + * auto-configuration reads: the resolved sample rate into {@code + * management.tracing.sampling.probability}, and the OTLP endpoint into {@code + * management.opentelemetry.tracing.export.otlp.endpoint}. Boot creates the span exporter only when + * that second key is set, so a blank endpoint means no exporter rather than an exporter aimed at a + * default address. Registered via {@code META-INF/spring.factories}. See README for the design + * rationale. + */ +public class TracingEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + + static final String SAMPLING_KEY = "management.tracing.sampling.probability"; + static final String OTLP_ENDPOINT_KEY = "management.opentelemetry.tracing.export.otlp.endpoint"; + + private static final String CA_SAMPLE_RATE_KEY = "app.tracing.sample-rate"; + private static final String CA_OTLP_ENDPOINT_KEY = "app.tracing.exporter.otlp-endpoint"; + + /** + * The OTLP/HTTP trace signal path. {@code OTEL_EXPORTER_OTLP_ENDPOINT} is, by the OpenTelemetry + * specification, the base address shared by every signal, and the exporter appends the signal's + * path to it; Boot's key is the full trace URL. Translating one into the other is this suffix. + */ + private static final String OTLP_HTTP_TRACES_PATH = "/v1/traces"; + + private final TracingSampleRateResolver resolver = new TracingSampleRateResolver(); + + @Override + public void postProcessEnvironment( + ConfigurableEnvironment environment, SpringApplication application) { + // A value the operator set on Boot's own key takes precedence over the translation. + Map bridged = new LinkedHashMap<>(); + if (!environment.containsProperty(SAMPLING_KEY)) { + List activeProfiles = RuntimeProfileSnapshot.from(environment).activeProfiles(); + String configured = environment.getProperty(CA_SAMPLE_RATE_KEY); + bridged.put(SAMPLING_KEY, String.valueOf(resolver.resolve(activeProfiles, configured))); + } + String endpoint = environment.getProperty(CA_OTLP_ENDPOINT_KEY, "").trim(); + if (!endpoint.isEmpty() && !environment.containsProperty(OTLP_ENDPOINT_KEY)) { + bridged.put(OTLP_ENDPOINT_KEY, tracesUrl(endpoint)); + } + if (!bridged.isEmpty()) { + environment.getPropertySources().addLast(new MapPropertySource("tracingBridge", bridged)); + } + } + + private static String tracesUrl(String baseEndpoint) { + String base = + baseEndpoint.endsWith("/") + ? baseEndpoint.substring(0, baseEndpoint.length() - 1) + : baseEndpoint; + return base + OTLP_HTTP_TRACES_PATH; + } + + @Override + public int getOrder() { + // Declared rather than inherited. Implementing EnvironmentPostProcessor without Ordered means + // LOWEST_PRECEDENCE by default, which is the same value three other post-processors returned + // explicitly — four things claiming the same position, none of them saying so (BOOT-005). + return StartupOrder.TRACING_SAMPLING; + } +} diff --git a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessor.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessor.java deleted file mode 100644 index 1baafb7e..00000000 --- a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessor.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.composition.runtime.tracing; - -import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; -import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; -import java.util.List; -import java.util.Map; -import org.springframework.boot.EnvironmentPostProcessor; -import org.springframework.boot.SpringApplication; -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.MapPropertySource; - -/** - * Bridges the resolved tracing sample rate into Spring Boot's native {@code - * management.tracing.sampling.probability}. Registered via {@code META-INF/spring.factories}. See - * README for the design rationale. - */ -public class TracingSamplingEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { - - private static final String NATIVE_KEY = "management.tracing.sampling.probability"; - private static final String CA_SAMPLE_RATE_KEY = "app.tracing.sample-rate"; - - private final TracingSampleRateResolver resolver = new TracingSampleRateResolver(); - - @Override - public void postProcessEnvironment( - ConfigurableEnvironment environment, SpringApplication application) { - // A user-supplied value takes precedence. - if (environment.containsProperty(NATIVE_KEY)) { - return; - } - List activeProfiles = RuntimeProfileSnapshot.from(environment).activeProfiles(); - String configured = environment.getProperty(CA_SAMPLE_RATE_KEY); - double rate = resolver.resolve(activeProfiles, configured); - environment - .getPropertySources() - .addLast( - new MapPropertySource( - "tracingSamplingBridge", Map.of(NATIVE_KEY, String.valueOf(rate)))); - } - - @Override - public int getOrder() { - // Declared rather than inherited. Implementing EnvironmentPostProcessor without Ordered means - // LOWEST_PRECEDENCE by default, which is the same value three other post-processors returned - // explicitly — four things claiming the same position, none of them saying so (BOOT-005). - return StartupOrder.TRACING_SAMPLING; - } -} diff --git a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSwitchImportFilter.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSwitchImportFilter.java new file mode 100644 index 00000000..b73d9ebe --- /dev/null +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingSwitchImportFilter.java @@ -0,0 +1,45 @@ +package dev.caskeleton.composition.runtime.tracing; + +import org.springframework.boot.autoconfigure.AutoConfigurationImportFilter; +import org.springframework.boot.autoconfigure.AutoConfigurationMetadata; +import org.springframework.context.EnvironmentAware; +import org.springframework.core.env.Environment; + +/** + * Leaves Spring Boot's tracing auto-configuration out of the context when {@code + * app.tracing.enabled=false}, so "tracing off" means no {@code Tracer} bean at all — not Boot's + * no-op tracer, and not a real one that merely exports nothing. + * + *

      Boot has no property for that: {@code management.tracing.export.enabled=false} stops export + * but still builds the tracer and opens a span per observation. An import filter is Boot's own + * extension point for dropping auto-configurations by condition, and unlike {@code + * spring.autoconfigure.exclude} it does not compete with an exclusion list the operator writes. + * + *

      Every tracing auto-configuration Boot ships lives under one package, so the filter names that + * package rather than a list of classes that would go stale when Boot adds one. Registered via + * {@code META-INF/spring.factories}. + */ +public final class TracingSwitchImportFilter + implements AutoConfigurationImportFilter, EnvironmentAware { + + static final String BOOT_TRACING_PACKAGE = "org.springframework.boot.micrometer.tracing."; + + private boolean tracingEnabled = true; + + @Override + public void setEnvironment(Environment environment) { + this.tracingEnabled = environment.getProperty("app.tracing.enabled", Boolean.class, true); + } + + @Override + public boolean[] match( + String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) { + boolean[] matches = new boolean[autoConfigurationClasses.length]; + for (int i = 0; i < autoConfigurationClasses.length; i++) { + String candidate = autoConfigurationClasses[i]; + matches[i] = + tracingEnabled || candidate == null || !candidate.startsWith(BOOT_TRACING_PACKAGE); + } + return matches; + } +} diff --git a/src/composition/service-runtime/src/main/resources/META-INF/spring.factories b/src/composition/service-runtime/src/main/resources/META-INF/spring.factories index 9f256287..67efecaa 100644 --- a/src/composition/service-runtime/src/main/resources/META-INF/spring.factories +++ b/src/composition/service-runtime/src/main/resources/META-INF/spring.factories @@ -1,2 +1,5 @@ org.springframework.boot.EnvironmentPostProcessor=\ -dev.caskeleton.composition.runtime.tracing.TracingSamplingEnvironmentPostProcessor +dev.caskeleton.composition.runtime.tracing.TracingEnvironmentPostProcessor + +org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\ +dev.caskeleton.composition.runtime.tracing.TracingSwitchImportFilter diff --git a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java index 64c7fcc9..6e4b35d9 100644 --- a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java @@ -9,7 +9,8 @@ import dev.caskeleton.composition.runtime.logging.PseudonymizationConfig; import dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig; import dev.caskeleton.composition.runtime.metrics.MetricsContractConfig; import dev.caskeleton.composition.runtime.tracing.TracingConfig; -import dev.caskeleton.composition.runtime.tracing.TracingSamplingEnvironmentPostProcessor; +import dev.caskeleton.composition.runtime.tracing.TracingEnvironmentPostProcessor; +import dev.caskeleton.composition.runtime.tracing.TracingSwitchImportFilter; import dev.caskeleton.shared.concurrency.DomainContextPropagator; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import java.io.IOException; @@ -60,13 +61,29 @@ class ServiceRuntimeRegistrationTest { // then assertThat(registrations.getProperty("org.springframework.boot.EnvironmentPostProcessor")) - .contains(TracingSamplingEnvironmentPostProcessor.class.getName()); + .contains(TracingEnvironmentPostProcessor.class.getName()); + } + + @Test + @DisplayName("tracing 스위치는 auto-configuration import filter로 등록된다") + void theTracingSwitchIsRegisteredAsAnImportFilter() throws IOException { + // given + ClassPathResource factories = new ClassPathResource("META-INF/spring.factories"); + + // when + Properties registrations = PropertiesLoaderUtils.loadProperties(factories); + + // then + assertThat( + registrations.getProperty( + "org.springframework.boot.autoconfigure.AutoConfigurationImportFilter")) + .contains(TracingSwitchImportFilter.class.getName()); } @Test void theSamplingBridgeTakesItsCentralStartupOrderPosition() { // given - TracingSamplingEnvironmentPostProcessor bridge = new TracingSamplingEnvironmentPostProcessor(); + TracingEnvironmentPostProcessor bridge = new TracingEnvironmentPostProcessor(); // when int order = bridge.getOrder(); diff --git a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/MicrometerActiveTraceTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/MicrometerActiveTraceTest.java new file mode 100644 index 00000000..b71f35f5 --- /dev/null +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/MicrometerActiveTraceTest.java @@ -0,0 +1,68 @@ +package dev.caskeleton.composition.runtime.tracing; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import dev.caskeleton.shared.tracing.TraceParent; +import io.micrometer.tracing.Span; +import io.micrometer.tracing.TraceContext; +import io.micrometer.tracing.Tracer; +import java.util.Optional; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class MicrometerActiveTraceTest { + + private final Tracer tracer = mock(Tracer.class); + + @Test + @DisplayName("열린 span이 있으면 그 span의 trace id·span id·sampled를 W3C 값으로 돌려준다") + void theCurrentSpanIsReturnedAsATraceParent() { + // given + givenCurrentSpan("4bf92f3577b34da6a3ce929d0e0e4736", "00f067aa0ba902b7", true); + + // when + Optional active = new MicrometerActiveTrace(tracer).current(); + + // then + assertThat(active) + .contains(TraceParent.of("4bf92f3577b34da6a3ce929d0e0e4736", "00f067aa0ba902b7", true)); + } + + @Test + @DisplayName("열린 span이 없으면 비어 있다") + void noCurrentSpanIsEmpty() { + // given + when(tracer.currentSpan()).thenReturn(null); + + // when + Optional active = new MicrometerActiveTrace(tracer).current(); + + // then + assertThat(active).isEmpty(); + } + + @Test + @DisplayName("no-op span의 0 값 context는 trace로 치지 않는다") + void anInvalidContextIsEmpty() { + // given + givenCurrentSpan("00000000000000000000000000000000", "0000000000000000", false); + + // when + Optional active = new MicrometerActiveTrace(tracer).current(); + + // then + assertThat(active).isEmpty(); + } + + private void givenCurrentSpan(String traceId, String spanId, boolean sampled) { + Span span = mock(Span.class); + TraceContext context = mock(TraceContext.class); + when(tracer.currentSpan()).thenReturn(span); + when(span.context()).thenReturn(context); + when(context.traceId()).thenReturn(traceId); + when(context.spanId()).thenReturn(spanId); + when(context.sampled()).thenReturn(sampled); + } +} diff --git a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessorTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessorTest.java new file mode 100644 index 00000000..d85dbc6e --- /dev/null +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessorTest.java @@ -0,0 +1,107 @@ +package dev.caskeleton.composition.runtime.tracing; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.SpringApplication; +import org.springframework.mock.env.MockEnvironment; + +/** + * D-1 (ISSUE-1 해소): {@link TracingEnvironmentPostProcessor}가 유효 샘플링 비율을 {@code + * management.tracing.sampling.probability}로 브리지하는지 검증. + */ +class TracingEnvironmentPostProcessorTest { + + private final TracingEnvironmentPostProcessor epp = new TracingEnvironmentPostProcessor(); + + @Test + void prodProfileBlankRateResolvesToOnePercent() { + MockEnvironment env = new MockEnvironment(); + env.setActiveProfiles("prod"); + // APP_TRACING_SAMPLE_RATE 미설정(blank) — per-profile 기본값이 적용돼야 한다. + + epp.postProcessEnvironment(env, new SpringApplication()); + + assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.01"); + } + + @Test + void profilelessContextDoesNotInventALocalRuntimeButUsesTheSafeNonProductionRate() { + MockEnvironment env = new MockEnvironment(); + + epp.postProcessEnvironment(env, new SpringApplication()); + + assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("1.0"); + } + + @Test + void explicitRateWins() { + MockEnvironment env = new MockEnvironment(); + env.setActiveProfiles("prod"); + env.setProperty("app.tracing.sample-rate", "0.25"); + + epp.postProcessEnvironment(env, new SpringApplication()); + + assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.25"); + } + + @Test + void doesNotOverrideExplicitProbability() { + MockEnvironment env = new MockEnvironment(); + env.setActiveProfiles("prod"); + env.setProperty("management.tracing.sampling.probability", "0.5"); + + epp.postProcessEnvironment(env, new SpringApplication()); + + assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.5"); + } + + @ParameterizedTest + @ValueSource(strings = {"http://collector:4318", "http://collector:4318/"}) + @DisplayName("OTEL_EXPORTER_OTLP_ENDPOINT 기준 주소에 trace 경로를 붙여 Boot의 exporter 키로 넘긴다") + void theOtlpBaseEndpointBecomesBootsTraceExportUrl(String baseEndpoint) { + // given + MockEnvironment env = new MockEnvironment(); + env.setProperty("app.tracing.exporter.otlp-endpoint", baseEndpoint); + + // when + epp.postProcessEnvironment(env, new SpringApplication()); + + // then + assertThat(env.getProperty(TracingEnvironmentPostProcessor.OTLP_ENDPOINT_KEY)) + .isEqualTo("http://collector:4318/v1/traces"); + } + + @Test + @DisplayName("endpoint가 비어 있으면 Boot exporter 키를 만들지 않아 exporter가 생기지 않는다") + void aBlankEndpointLeavesBootsExporterKeyUnset() { + // given + MockEnvironment env = new MockEnvironment(); + env.setProperty("app.tracing.exporter.otlp-endpoint", " "); + + // when + epp.postProcessEnvironment(env, new SpringApplication()); + + // then + assertThat(env.containsProperty(TracingEnvironmentPostProcessor.OTLP_ENDPOINT_KEY)).isFalse(); + } + + @Test + @DisplayName("운영자가 Boot exporter 키를 직접 주면 그 값을 덮어쓰지 않는다") + void anExplicitBootEndpointWins() { + // given + MockEnvironment env = new MockEnvironment(); + env.setProperty("app.tracing.exporter.otlp-endpoint", "http://collector:4318"); + env.setProperty(TracingEnvironmentPostProcessor.OTLP_ENDPOINT_KEY, "http://other:4318/x"); + + // when + epp.postProcessEnvironment(env, new SpringApplication()); + + // then + assertThat(env.getProperty(TracingEnvironmentPostProcessor.OTLP_ENDPOINT_KEY)) + .isEqualTo("http://other:4318/x"); + } +} diff --git a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessorTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessorTest.java deleted file mode 100644 index 5b3cfcda..00000000 --- a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSamplingEnvironmentPostProcessorTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.composition.runtime.tracing; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.SpringApplication; -import org.springframework.mock.env.MockEnvironment; - -/** - * D-1 (ISSUE-1 해소): {@link TracingSamplingEnvironmentPostProcessor}가 유효 샘플링 비율을 {@code - * management.tracing.sampling.probability}로 브리지하는지 검증. - */ -class TracingSamplingEnvironmentPostProcessorTest { - - private final TracingSamplingEnvironmentPostProcessor epp = - new TracingSamplingEnvironmentPostProcessor(); - - @Test - void prodProfileBlankRateResolvesToOnePercent() { - MockEnvironment env = new MockEnvironment(); - env.setActiveProfiles("prod"); - // APP_TRACING_SAMPLE_RATE 미설정(blank) — per-profile 기본값이 적용돼야 한다. - - epp.postProcessEnvironment(env, new SpringApplication()); - - assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.01"); - } - - @Test - void profilelessContextDoesNotInventALocalRuntimeButUsesTheSafeNonProductionRate() { - MockEnvironment env = new MockEnvironment(); - - epp.postProcessEnvironment(env, new SpringApplication()); - - assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("1.0"); - } - - @Test - void explicitRateWins() { - MockEnvironment env = new MockEnvironment(); - env.setActiveProfiles("prod"); - env.setProperty("app.tracing.sample-rate", "0.25"); - - epp.postProcessEnvironment(env, new SpringApplication()); - - assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.25"); - } - - @Test - void doesNotOverrideExplicitProbability() { - MockEnvironment env = new MockEnvironment(); - env.setActiveProfiles("prod"); - env.setProperty("management.tracing.sampling.probability", "0.5"); - - epp.postProcessEnvironment(env, new SpringApplication()); - - assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.5"); - } -} diff --git a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSwitchImportFilterTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSwitchImportFilterTest.java new file mode 100644 index 00000000..f42c3bfc --- /dev/null +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/tracing/TracingSwitchImportFilterTest.java @@ -0,0 +1,54 @@ +package dev.caskeleton.composition.runtime.tracing; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.mock.env.MockEnvironment; + +class TracingSwitchImportFilterTest { + + private static final String[] CANDIDATES = { + "org.springframework.boot.micrometer.tracing.opentelemetry.autoconfigure" + + ".OpenTelemetryTracingAutoConfiguration", + "org.springframework.boot.micrometer.tracing.autoconfigure.NoopTracerAutoConfiguration", + "org.springframework.boot.micrometer.observation.autoconfigure.ObservationAutoConfiguration", + "dev.caskeleton.composition.runtime.tracing.TracingConfig" + }; + + @Test + @DisplayName("app.tracing.enabled=false면 Boot tracing 자동 설정만 빠지고 나머지는 남는다") + void disabledTracingDropsOnlyBootsTracingAutoConfigurations() { + // given + TracingSwitchImportFilter filter = filterWith("false"); + + // when + boolean[] matches = filter.match(CANDIDATES, null); + + // then + assertThat(matches).containsExactly(false, false, true, true); + } + + @Test + @DisplayName("app.tracing.enabled가 없거나 true면 아무것도 빼지 않는다") + void enabledTracingKeepsEverything() { + // given + TracingSwitchImportFilter filter = filterWith(null); + + // when + boolean[] matches = filter.match(CANDIDATES, null); + + // then + assertThat(matches).containsExactly(true, true, true, true); + } + + private static TracingSwitchImportFilter filterWith(String enabled) { + MockEnvironment environment = new MockEnvironment(); + if (enabled != null) { + environment.setProperty("app.tracing.enabled", enabled); + } + TracingSwitchImportFilter filter = new TracingSwitchImportFilter(); + filter.setEnvironment(environment); + return filter; + } +} diff --git a/src/config/jpa/readiness-cards.yaml b/src/config/jpa/readiness-cards.yaml index 20c36f63..5991ac87 100644 --- a/src/config/jpa/readiness-cards.yaml +++ b/src/config/jpa/readiness-cards.yaml @@ -132,7 +132,7 @@ "covers": ["concurrency", "fault"] }, { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried", + "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried", "covers": ["fault"] } ], diff --git a/src/grpc/CLAUDE.md b/src/grpc/CLAUDE.md index 7bb05da0..f056c0ab 100644 --- a/src/grpc/CLAUDE.md +++ b/src/grpc/CLAUDE.md @@ -134,3 +134,9 @@ the repository's `.seconds` / `.total` unit naming and the corresponding validat durable operation idempotency adds `:grpc:grpc-operation-ledger-jpa` explicitly, enables the ledger configuration, and includes that adapter's Flyway location `db/migration/grpc`. A deployment that does not adopt the ledger therefore pays no Spring Data JPA classpath cost. + +An `IN_PROGRESS` claim expires after the claim TTL (`GrpcIdempotencyInterceptor`'s `claimTtl` +argument; no configuration key while the starter does not assemble the interceptor). A retry of the +same request then takes it over through `GrpcOperationLedger.reclaimStale`. The adopter must record +the commit in the mutation's transaction and choose a TTL longer than the slowest keyed method; both +reasons are in ADR-GRPC-004. diff --git a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java index 4342bde7..7a4ee67c 100644 --- a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java +++ b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java @@ -52,6 +52,36 @@ public interface GrpcOperationLedger { */ boolean reclaimFailed(GrpcOperationIdentity identity, String requestFingerprint, Instant now); + /** + * Takes over an {@code IN_PROGRESS} claim whose owner is presumed dead, for a new attempt of the + * same request. + * + *

      A claim made before {@code claimedBefore} has outlived the time its owner could still be + * working (the claim TTL), so its owner is treated as gone. Without this, a process that dies + * between claim and commit leaves its key blocked forever: every retry waits on, or is refused + * by, a claim nobody will finish. + * + *

      A compare-and-set like {@link #reclaimFailed}: the record becomes a fresh {@code + * IN_PROGRESS} claim at {@code now}, and of two concurrent takeovers exactly one returns true — + * the winner's new claim moment is no longer before the cutoff, so the loser's condition fails. + * That is why {@code claimedBefore} after {@code now} is refused: the new claim would itself be + * stale and a second takeover would win too. A record in any other state, claimed at or after the + * cutoff, or made for a different request, is left untouched. + * + *

      Safe only because the commit is recorded in the same transaction as the mutation (see {@link + * #markCommitted}): then a claim still {@code IN_PROGRESS} means the mutation never committed. + * When an adopter commits them separately, the abandoned attempt's outcome is unknown and a + * takeover can run the mutation twice. + * + * @return true when this call now owns the record as a fresh attempt claimed at {@code now} + * @throws IllegalArgumentException when {@code claimedBefore} is after {@code now} + */ + boolean reclaimStale( + GrpcOperationIdentity identity, + String requestFingerprint, + Instant claimedBefore, + Instant now); + /** * Releases a claim that will never complete, so the caller may try again. * diff --git a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java index 1ff769cc..b2839d63 100644 --- a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java +++ b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.grpc.core.GrpcMethodName; +import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Optional; @@ -12,6 +13,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** @@ -34,6 +36,10 @@ public abstract class GrpcOperationLedgerContract { "sha256:1122334455667788990011223344556677889900112233445566778899001122"; private static final String OUTCOME = "outcome://document/42"; private static final Instant NOW = Instant.parse("2026-09-25T10:00:00Z"); + private static final Duration CLAIM_TTL = Duration.ofMinutes(5); + // A retry arriving after the TTL: its cutoff (LATER - TTL) is past the original claim at NOW. + private static final Instant LATER = NOW.plus(CLAIM_TTL).plusSeconds(1); + private static final Instant CUTOFF = LATER.minus(CLAIM_TTL); /** The ledger under test, holding no records when a test starts. */ protected abstract GrpcOperationLedger ledger(); @@ -237,6 +243,160 @@ public abstract class GrpcOperationLedgerContract { assertThat(reclaimed).containsExactlyInAnyOrder(true, false); } + @Test + @DisplayName("TTL이 지난 IN_PROGRESS claim은 같은 요청의 재시도가 넘겨받는다") + void aStaleInProgressClaimIsTakenOverByARetryOfTheSameRequest() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + boolean reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + + // then + assertThat(reclaimed).isTrue(); + } + + @Test + @DisplayName("넘겨받은 stale claim은 넘겨받은 시각부터 진행 중인 새 시도다") + void aTakenOverStaleClaimIsANewAttemptInProgressSinceTheTakeover() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + + // then + assertThat(ledger().find(ID)) + .get() + .extracting( + GrpcOperationLedgerRecord::state, + GrpcOperationLedgerRecord::claimedAt, + GrpcOperationLedgerRecord::completedAt) + .containsExactly(GrpcOperationLedgerState.IN_PROGRESS, LATER, Optional.empty()); + } + + @Test + @DisplayName("넘겨받은 stale claim은 commit할 수 있다") + void aTakenOverStaleClaimCanBeCommitted() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + + // when + ledger().markCommitted(ID, OUTCOME, LATER.plusSeconds(1)); + + // then + assertThat(ledger().find(ID)) + .get() + .extracting(GrpcOperationLedgerRecord::state, GrpcOperationLedgerRecord::outcomeReference) + .containsExactly(GrpcOperationLedgerState.COMMITTED, Optional.of(OUTCOME)); + } + + @Test + @DisplayName("TTL 안의 IN_PROGRESS claim은 넘겨받지 않는다") + void anInProgressClaimWithinTheTtlIsNotTakenOver() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + boolean reclaimed = ledger().reclaimStale(ID, FINGERPRINT, NOW, NOW.plus(CLAIM_TTL)); + + // then + assertThat(reclaimed).isFalse(); + } + + @Test + @DisplayName("다른 요청은 TTL이 지난 claim도 넘겨받지 못한다") + void aStaleClaimIsNotTakenOverForADifferentRequest() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + boolean reclaimed = ledger().reclaimStale(ID, OTHER_FINGERPRINT, CUTOFF, LATER); + + // then + assertThat(reclaimed).isFalse(); + } + + @Test + @DisplayName("commit된 claim은 오래되어도 stale로 넘겨받지 않는다") + void aCommittedClaimIsNotTakenOverAsStale() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(1)); + + // when + boolean reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + + // then + assertThat(reclaimed).isFalse(); + } + + @Test + @DisplayName("실패한 claim은 stale 회수가 아니라 실패 재claim으로만 다시 연다") + void aFailedClaimIsNotTakenOverAsStale() { + // given + failedClaim(); + + // when + boolean reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + + // then + assertThat(reclaimed).isFalse(); + } + + @Test + @DisplayName("claim이 없으면 stale 회수는 아무것도 만들지 않는다") + void takingOverAMissingClaimCreatesNothing() { + // when + boolean reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + + // then + assertThat(reclaimed).isFalse(); + assertThat(ledger().find(ID)).isEmpty(); + } + + @Test + @DisplayName("한 번 넘겨받은 claim은 같은 cutoff로 다시 넘겨받지 못한다") + void aTakenOverClaimIsNotTakenOverAgainWithTheSameCutoff() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + + // when + boolean again = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + + // then + assertThat(again).isFalse(); + } + + @Test + @DisplayName("TTL이 지난 claim을 동시에 넘겨받으려 하면 승자는 하나다") + void concurrentTakeoversOfAStaleClaimHaveExactlyOneWinner() throws Exception { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + List reclaimed = + concurrently(() -> ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER)); + + // then + assertThat(reclaimed).containsExactlyInAnyOrder(true, false); + } + + @Test + @DisplayName("cutoff가 현재 시각보다 뒤면 거부한다 — 새 claim이 곧바로 stale이 되기 때문이다") + void aCutoffAfterNowIsRefused() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + Throwable refused = catchThrowable(() -> ledger().reclaimStale(ID, FINGERPRINT, LATER, CUTOFF)); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("cutoff"); + } + private void failedClaim() { ledger().claim(ID, FINGERPRINT, NOW); ledger().markFailed(ID, NOW.plusSeconds(1)); diff --git a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java index f08ddacf..207971b5 100644 --- a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java +++ b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java @@ -10,9 +10,9 @@ import java.util.concurrent.ConcurrentMap; * *

      {@code putIfAbsent} on a concurrent map is the in-memory equivalent of the unique constraint * the real adapter relies on, and {@code replace(key, expected, next)} of its conditional update, - * so claim and re-claim are atomic here for the same reason they are there. The transitions match - * the JPA adapter's because {@link GrpcOperationLedgerContract} runs against both; a fake that - * allowed more would let the policy tests pass for code the database refuses. + * so claim, re-claim and stale takeover are atomic here for the same reason they are there. The + * transitions match the JPA adapter's because {@link GrpcOperationLedgerContract} runs against + * both; a fake that allowed more would let the policy tests pass for code the database refuses. */ public final class InMemoryOperationLedger implements GrpcOperationLedger { @@ -81,6 +81,27 @@ public final class InMemoryOperationLedger implements GrpcOperationLedger { GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now)); } + @Override + public boolean reclaimStale( + GrpcOperationIdentity identity, + String requestFingerprint, + Instant claimedBefore, + Instant now) { + if (claimedBefore.isAfter(now)) { + throw new IllegalArgumentException( + "a stale-claim cutoff after now would leave the new claim stale as well"); + } + GrpcOperationLedgerRecord current = records.get(identity.storageKey()); + return current != null + && current.state() == GrpcOperationLedgerState.IN_PROGRESS + && current.claimedAt().isBefore(claimedBefore) + && current.sameRequestAs(requestFingerprint) + && records.replace( + identity.storageKey(), + current, + GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now)); + } + @Override public void release(GrpcOperationIdentity identity) { records.remove(identity.storageKey()); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java index 2d1e6b20..701b31b5 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java @@ -22,6 +22,7 @@ import java.util.Optional; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.data.jpa.repository.support.JpaRepositoryFactory; import org.springframework.orm.jpa.JpaTransactionManager; @@ -120,6 +121,44 @@ class JpaGrpcOperationLedgerContractIT extends GrpcOperationLedgerContract { .containsExactly(GrpcOperationLedgerState.COMMITTED, Optional.of("outcome://document/42")); } + /** + * The takeover's conditional update clears the persistence context for the same reason the failed + * re-claim does: the claim's read-on-conflict loaded the stale row, and a commit reading that + * copy would keep the abandoned claim moment. + */ + @Test + @DisplayName("stale claim을 넘겨받아 같은 트랜잭션에서 commit하면 commit된다") + void aRetryThatTakesOverAStaleClaimAndCommitsInOneTransactionCommits() { + // given + GrpcOperationIdentity id = + new GrpcOperationIdentity( + "tenant-1.actor-1", + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"), + "sha256:aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"); + String fingerprint = "sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"; + Instant abandonedAt = Instant.parse("2026-09-25T10:00:00Z"); + Instant retryAt = abandonedAt.plusSeconds(301); + ledger.claim(id, fingerprint, abandonedAt); + + // when + transactions.executeWithoutResult( + status -> { + adapter.claim(id, fingerprint, retryAt); + adapter.reclaimStale(id, fingerprint, retryAt.minusSeconds(300), retryAt); + adapter.markCommitted(id, "outcome://document/42", retryAt.plusSeconds(1)); + }); + + // then + assertThat(ledger.find(id)) + .get() + .extracting( + GrpcOperationLedgerRecord::state, + GrpcOperationLedgerRecord::claimedAt, + GrpcOperationLedgerRecord::outcomeReference) + .containsExactly( + GrpcOperationLedgerState.COMMITTED, retryAt, Optional.of("outcome://document/42")); + } + private static void execute(String sql) throws SQLException { try (Connection connection = DriverManager.getConnection( @@ -177,6 +216,17 @@ class JpaGrpcOperationLedgerContractIT extends GrpcOperationLedgerContract { status -> delegate.reclaimFailed(identity, requestFingerprint, now))); } + @Override + public boolean reclaimStale( + GrpcOperationIdentity identity, + String requestFingerprint, + Instant claimedBefore, + Instant now) { + return Boolean.TRUE.equals( + transactions.execute( + status -> delegate.reclaimStale(identity, requestFingerprint, claimedBefore, now))); + } + @Override public void release(GrpcOperationIdentity identity) { transactions.executeWithoutResult(status -> delegate.release(identity)); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java index f1823b8b..32d14c01 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java @@ -92,6 +92,36 @@ public interface GrpcOperationLedgerRepository @Param("requestFingerprint") String requestFingerprint, @Param("claimedAt") Instant claimedAt); + /** + * Takes over an {@code IN_PROGRESS} row claimed before {@code claimedBefore}, for the same + * request. + * + *

      Same shape as {@link #tryReclaimFailed}: one conditional update decided by PostgreSQL's row + * lock. A concurrent second takeover waits for the winner, re-evaluates the condition against the + * winner's row — whose {@code claimed_at} is now {@code :claimedAt}, not before the cutoff — and + * updates nothing. It clears the persistence context for the same reason. + * + * @return one when this caller took the row over, zero otherwise + */ + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Transactional + @Query( + value = + """ + UPDATE grpc_operation_ledger + SET claimed_at = :claimedAt + WHERE storage_key = :storageKey + AND state = 'IN_PROGRESS' + AND request_fingerprint = :requestFingerprint + AND claimed_at < :claimedBefore + """, + nativeQuery = true) + int tryReclaimStale( + @Param("storageKey") String storageKey, + @Param("requestFingerprint") String requestFingerprint, + @Param("claimedBefore") Instant claimedBefore, + @Param("claimedAt") Instant claimedAt); + /** Updates an existing claim after it has been loaded. */ GrpcOperationLedgerEntity save(GrpcOperationLedgerEntity entity); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java index 7cd1afc2..d81fd669 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java @@ -107,6 +107,21 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { return repository.tryReclaimFailed(identity.storageKey(), requestFingerprint, now) == 1; } + @Override + public boolean reclaimStale( + GrpcOperationIdentity identity, + String requestFingerprint, + Instant claimedBefore, + Instant now) { + requireIdentity(identity); + if (claimedBefore.isAfter(now)) { + throw new IllegalArgumentException( + "a stale-claim cutoff after now would leave the new claim stale as well"); + } + return repository.tryReclaimStale(identity.storageKey(), requestFingerprint, claimedBefore, now) + == 1; + } + @Override public void release(GrpcOperationIdentity identity) { requireIdentity(identity); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java b/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java index 8da7c640..9b7fcb49 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java @@ -66,6 +66,13 @@ class GrpcOperationLedgerRepositoryTest { "the re-claim is certified against PostgreSQL by JpaGrpcOperationLedgerContractIT"); } + @Override + public int tryReclaimStale( + String storageKey, String requestFingerprint, Instant claimedBefore, Instant claimedAt) { + throw new UnsupportedOperationException( + "the stale takeover is certified against PostgreSQL by JpaGrpcOperationLedgerContractIT"); + } + @Override public GrpcOperationLedgerEntity save(GrpcOperationLedgerEntity entity) { rows.put(entity.getStorageKey(), entity); diff --git a/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java b/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java index e2326699..b48d9a65 100644 --- a/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java +++ b/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java @@ -19,6 +19,10 @@ import java.util.Optional; * client takes the same one before deciding whether a retry is safe. An interceptor that owns the * logic leaves the client re-deriving it. * + *

      A claim does not block its key forever. One still {@code IN_PROGRESS} after the claim TTL is + * treated as abandoned by a dead owner and taken over by the next retry of the same request — one + * winner, like the re-claim of a terminal failure. + * *

      The ordering matters and is easy to get subtly wrong. The claim is attempted first, * atomically; only then is the existing record examined. Reading first and claiming second leaves a * window in which two attempts both read nothing. @@ -29,18 +33,24 @@ public final class GrpcIdempotencyInterceptor { private final GrpcMethodPolicyCatalog catalog; private final Duration inProgressPollInterval; private final boolean waitForInProgress; + private final Duration claimTtl; /** * @param inProgressPollInterval how long a duplicate is told to wait before asking again * @param waitForInProgress whether a duplicate of a running operation waits or is refused. A * method whose caller is a user-facing request usually wants to be refused quickly; a worker * usually wants to wait. + * @param claimTtl how long an {@code IN_PROGRESS} claim is trusted to have a live owner. After + * it, a retry of the same request takes the claim over. It must be longer than every keyed + * method's deadline, and longer than the slowest such method can actually run: a claim taken + * over from an owner that is merely slow runs the mutation twice. */ public GrpcIdempotencyInterceptor( GrpcOperationLedger ledger, GrpcMethodPolicyCatalog catalog, Duration inProgressPollInterval, - boolean waitForInProgress) { + boolean waitForInProgress, + Duration claimTtl) { if (ledger == null || catalog == null) { throw new IllegalArgumentException("an idempotency interceptor needs a ledger and a catalog"); } @@ -54,6 +64,32 @@ public final class GrpcIdempotencyInterceptor { this.catalog = catalog; this.inProgressPollInterval = inProgressPollInterval; this.waitForInProgress = waitForInProgress; + this.claimTtl = requireClaimTtlOutlivesKeyedDeadlines(claimTtl, catalog); + } + + // A TTL inside a keyed method's deadline lets a retry take over a claim whose owner is still + // within its budget. The deadline is the only per-method bound on owner lifetime the catalog + // knows; it does not bound a server that keeps working after the deadline fires. + private static Duration requireClaimTtlOutlivesKeyedDeadlines( + Duration claimTtl, GrpcMethodPolicyCatalog catalog) { + if (claimTtl == null || claimTtl.isZero() || claimTtl.isNegative()) { + throw new IllegalArgumentException("a claim TTL must be present and positive"); + } + for (GrpcMethodName method : catalog.methods()) { + GrpcMethodPolicy policy = catalog.require(method); + if (policy.idempotency().idempotencyKeyRequired() + && claimTtl.compareTo(policy.deadline().total()) <= 0) { + throw new IllegalArgumentException( + "claim TTL " + + claimTtl + + " is not longer than the " + + policy.deadline().total() + + " deadline of keyed method '" + + method.canonical() + + "'; a retry would take over a claim whose owner is still running"); + } + } + return claimTtl; } /** @@ -115,7 +151,22 @@ public final class GrpcIdempotencyInterceptor { return GrpcIdempotencyDecision.proceed( "the previous attempt failed terminally; this caller re-claimed it for a new attempt"); } - // Running, or a failed attempt another retry re-claimed first. + if (record.state() == GrpcOperationLedgerState.IN_PROGRESS) { + Instant cutoff = now.minus(claimTtl); + if (record.claimedAt().isBefore(cutoff) + && ledger.reclaimStale(identity, requestFingerprint, cutoff, now)) { + // The owner outlived the TTL without committing or failing, so it is presumed dead. Its + // mutation did not commit if the commit was recorded in the mutation's own transaction, + // which the ledger contract requires; when an adopter commits them separately, the + // abandoned attempt's outcome is unknown and this re-run can duplicate it. + return GrpcIdempotencyDecision.proceed( + "the previous claim was abandoned (older than the " + + claimTtl + + " claim TTL); this caller took it over for a new attempt"); + } + } + // Running, a failed attempt another retry re-claimed first, or an abandoned claim another + // retry took over first. return waitForInProgress ? GrpcIdempotencyDecision.waitAndPoll(inProgressPollInterval) : GrpcIdempotencyDecision.rejectInProgress(); diff --git a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java index 972630e5..90c34214 100644 --- a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java +++ b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java @@ -2,8 +2,10 @@ package dev.caskeleton.grpc.idempotency; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; import dev.caskeleton.grpc.api.ledger.InMemoryOperationLedger; import dev.caskeleton.grpc.core.GrpcMethodName; +import java.time.Duration; import java.time.Instant; import java.util.Optional; import org.junit.jupiter.api.DisplayName; @@ -29,6 +31,28 @@ class GrpcCompletionReconcilerTest { NOW); } + @Test + @DisplayName("버려진 claim으로 대기열에 오른 건은 넘겨받은 재시도가 commit하면 다음 회차에 COMMITTED로 풀린다") + void anAbandonedClaimStaysPendingUntilATakeoverCommits() { + // given + GrpcOperationIdentity identity = + new GrpcOperationIdentity(CALLER, CREATE, GrpcRequestFingerprint.hashIdempotencyKey(KEY)); + String fingerprint = GrpcRequestFingerprint.of("body"); + Instant afterTtl = NOW.plus(Duration.ofMinutes(5)).plusSeconds(1); + GrpcCompletionReconciler reconciler = new GrpcCompletionReconciler(query); + claim(); + reconciler.reconcile(CREATE, CALLER, KEY, null); + ledger.reclaimStale(identity, fingerprint, afterTtl.minus(Duration.ofMinutes(5)), afterTtl); + ledger.markCommitted(identity, "outcome://document/42", afterTtl.plusSeconds(1)); + + // when + GrpcCompletionResolution nextPass = reconciler.reconcile(CREATE, CALLER, KEY, null); + + // then + assertThat(nextPass.status()).isEqualTo(GrpcOperationStatus.COMMITTED); + assertThat(nextPass.outcomeReference()).contains("outcome://document/42"); + } + @Test @DisplayName("a status query returns the five documented answers") void theQueryReturnsTheFiveDocumentedAnswers() { @@ -141,6 +165,5 @@ class GrpcCompletionReconcilerTest { GrpcCompletionResolution resolution = reconciler.reconcile(CREATE, CALLER, KEY, null); assertThat(resolution.status()).isEqualTo(GrpcOperationStatus.IN_PROGRESS); - assertThat(reconciler.pendingCases()).hasSize(1); } } diff --git a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java index 6ed3d16b..df26ea21 100644 --- a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java +++ b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.grpc.idempotency; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile; import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; @@ -36,6 +37,8 @@ class GrpcIdempotencyInterceptorTest { private static final Instant NOW = Instant.parse("2026-08-30T10:00:00Z"); private static final String CALLER = "tenant-1|actor-1"; private static final String KEY = "order-2026-0001"; + private static final Duration CLAIM_TTL = Duration.ofMinutes(5); + private static final Instant AFTER_TTL = NOW.plus(CLAIM_TTL).plusSeconds(1); private final InMemoryOperationLedger ledger = new InMemoryOperationLedger(); @@ -57,7 +60,7 @@ class GrpcIdempotencyInterceptorTest { private GrpcIdempotencyInterceptor interceptor(boolean waitForInProgress) { return new GrpcIdempotencyInterceptor( - ledger, catalog(), Duration.ofMillis(250), waitForInProgress); + ledger, catalog(), Duration.ofMillis(250), waitForInProgress, CLAIM_TTL); } @Test @@ -194,6 +197,107 @@ class GrpcIdempotencyInterceptorTest { GrpcIdempotencyDecision.Outcome.REJECT_IN_PROGRESS); } + @Test + @DisplayName("소유자가 죽어 TTL이 지난 claim은 같은 요청의 재시도가 넘겨받아 진행한다") + void aRetryAfterTheClaimTtlTakesOverAnAbandonedClaimAndProceeds() { + // given + GrpcIdempotencyInterceptor interceptor = interceptor(false); + String fingerprint = GrpcRequestFingerprint.of("body"); + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); + + // when + GrpcIdempotencyDecision decision = + interceptor.decide(CREATE, CALLER, KEY, fingerprint, AFTER_TTL); + + // then + assertThat(decision.outcome()).isEqualTo(GrpcIdempotencyDecision.Outcome.PROCEED); + assertThat(decision.reason()).contains("abandoned"); + } + + @Test + @DisplayName("넘겨받은 claim은 재시도 시각에 다시 잡힌 진행 중 claim이다") + void aTakenOverClaimIsHeldInProgressFromTheRetry() { + // given + GrpcIdempotencyInterceptor interceptor = interceptor(false); + String fingerprint = GrpcRequestFingerprint.of("body"); + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); + + // when + interceptor.decide(CREATE, CALLER, KEY, fingerprint, AFTER_TTL); + + // then + assertThat( + ledger + .find( + new GrpcOperationIdentity( + CALLER, CREATE, GrpcRequestFingerprint.hashIdempotencyKey(KEY))) + .map(GrpcOperationLedgerRecord::claimedAt)) + .contains(AFTER_TTL); + } + + @Test + @DisplayName("TTL이 지나기 직전의 중복 요청은 여전히 대기하거나 거부된다") + void aDuplicateAtTheTtlBoundaryIsStillTreatedAsRunning() { + // given + GrpcIdempotencyInterceptor interceptor = interceptor(false); + String fingerprint = GrpcRequestFingerprint.of("body"); + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); + + // when + GrpcIdempotencyDecision decision = + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW.plus(CLAIM_TTL)); + + // then + assertThat(decision.outcome()).isEqualTo(GrpcIdempotencyDecision.Outcome.REJECT_IN_PROGRESS); + } + + @Test + @DisplayName("버려진 claim에 동시에 온 재시도 중 하나만 진행한다") + void concurrentRetriesOfAnAbandonedClaimProceedOnlyOnce() throws Exception { + // given + GrpcIdempotencyInterceptor interceptor = interceptor(false); + String fingerprint = GrpcRequestFingerprint.of("body"); + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); + CountDownLatch start = new CountDownLatch(1); + Callable retry = + () -> { + start.await(); + return interceptor.decide(CREATE, CALLER, KEY, fingerprint, AFTER_TTL).outcome(); + }; + + // when + List outcomes; + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(retry); + Future second = executor.submit(retry); + start.countDown(); + outcomes = List.of(first.get(), second.get()); + } + + // then + assertThat(outcomes) + .containsExactlyInAnyOrder( + GrpcIdempotencyDecision.Outcome.PROCEED, + GrpcIdempotencyDecision.Outcome.REJECT_IN_PROGRESS); + } + + @Test + @DisplayName("claim TTL이 key 필수 method의 deadline보다 짧으면 생성 시 거부한다") + void aClaimTtlNoLongerThanAKeyedMethodsDeadlineIsRefused() { + // when + Throwable refused = + catchThrowable( + () -> + new GrpcIdempotencyInterceptor( + ledger, catalog(), Duration.ofMillis(250), false, Duration.ofSeconds(10))); + + // then + assertThat(refused) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(CREATE.canonical()) + .hasMessageContaining("claim TTL"); + } + @Test @DisplayName("one caller's key does not suppress another caller's write") void oneCallersKeyDoesNotSuppressAnother() { diff --git a/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaMessagingTransport.java b/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaMessagingTransport.java index e80cff40..ce84b544 100644 --- a/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaMessagingTransport.java +++ b/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaMessagingTransport.java @@ -119,7 +119,16 @@ public final class KafkaMessagingTransport implements MessagingTransport { Objects.requireNonNull(request, "request must not be null"); if (closed.get()) { - return completed(rejectedLocally("KAFKA_TRANSPORT_CLOSED", "the transport is shutting down")); + // Not the message's fault: the next instance, or this one after a restart, will take it. A + // caller that trusts the retryable flag must not park it. + return completed( + new TransportPublishResult( + PublishResult.rejected( + Duration.ZERO, + FailureDescriptor.of( + FailureCategory.TRANSIENT_INFRASTRUCTURE, + "KAFKA_TRANSPORT_CLOSED", + "the transport is shutting down")))); } int size = request.envelope().payload().size(); int limit = request.profile().payload().maxBytes(); diff --git a/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifier.java b/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifier.java index 3436871d..0eea955a 100644 --- a/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifier.java +++ b/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifier.java @@ -19,8 +19,10 @@ import org.apache.kafka.common.errors.UnsupportedVersionException; *

      The split is between failures that prove the record was not stored and failures that prove * nothing. Serialization, an invalid topic, authentication, authorization, fencing, and an * over-large record are all rejections: the broker never took the record, so abandoning the attempt - * is safe. Everything else — a delivery timeout above all — is ambiguous, because the record may - * already be replicated and only the acknowledgement was lost. + * is safe. Of those, authentication and authorization are marked retryable, because they clear on + * their own once a credential or an ACL is in place. Everything else — a delivery timeout above all + * — is ambiguous, because the record may already be replicated and only the acknowledgement was + * lost. * *

      The default is deliberately ambiguous rather than rejected. Guessing "rejected" on an unknown * error is what turns one lost confirmation into two orders. @@ -37,7 +39,8 @@ public final class KafkaPublishFailureClassifier { public PublishResult classify(Throwable error, Duration elapsed) { Throwable cause = unwrap(error); if (isDefinitiveRejection(cause)) { - return PublishResult.rejected(elapsed, descriptor(cause, rejectionCategory(cause), false)); + return PublishResult.rejected( + elapsed, descriptor(cause, rejectionCategory(cause), mayPassOnRetry(cause))); } return PublishResult.ambiguous(elapsed, descriptor(cause, FailureCategory.AMBIGUOUS, false)); } @@ -58,6 +61,21 @@ public final class KafkaPublishFailureClassifier { || cause instanceof UnsupportedVersionException; } + /** + * Reports whether a definitive rejection may pass if the same record is sent again later. + * + *

      Authentication and authorization prove the broker did not store the record, but not that it + * will refuse it again: a credential being rotated, or an ACL deployed after the application, + * fails every publish this way for a few minutes and then stops. Marked not retryable, a + * publisher that trusts the flag — the application's outbox relay does — parks every record sent + * in those minutes. A credential that is simply wrong is retried too, and the outbox then holds + * its rows FAILED with an alert every retry — recoverable once the credential is fixed, where + * DEAD rows needed a manual reset each. + */ + private static boolean mayPassOnRetry(Throwable cause) { + return cause instanceof AuthenticationException || cause instanceof AuthorizationException; + } + private static FailureCategory rejectionCategory(Throwable cause) { if (cause instanceof AuthenticationException) { return FailureCategory.AUTHENTICATION; diff --git a/src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaMessagingTransportTest.java b/src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaMessagingTransportTest.java new file mode 100644 index 00000000..d50ce603 --- /dev/null +++ b/src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaMessagingTransportTest.java @@ -0,0 +1,43 @@ +package dev.caskeleton.messaging.kafka; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.messaging.api.error.FailureDescriptor; +import dev.caskeleton.messaging.api.publish.PublishCompletion; +import dev.caskeleton.messaging.api.publish.PublishOptions; +import dev.caskeleton.messaging.api.publish.PublishResult; +import dev.caskeleton.messaging.transport.TransportPublishRequest; +import org.apache.kafka.clients.producer.MockProducer; +import org.apache.kafka.clients.producer.Partitioner; +import org.apache.kafka.common.serialization.ByteArraySerializer; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** What a closed Kafka transport answers a publish that arrives during shutdown. */ +class KafkaMessagingTransportTest { + + @Test + @DisplayName("닫힌 transport의 거부는 다음 인스턴스가 받을 수 있으므로 다시 시도할 수 있다고 표시한다") + void aPublishToAClosedTransportIsARefusalThatMayBeRetried() { + // given: the transport closed while a relay cycle was still publishing + KafkaMessagingTransport transport = + new KafkaMessagingTransport( + "kafka-primary", + 1, + new MockProducer<>( + false, (Partitioner) null, new ByteArraySerializer(), new ByteArraySerializer())); + transport.close(); + TransportPublishRequest request = + new TransportPublishRequest( + KafkaContractHarness.profile(), + KafkaFixtures.orderCreatedEnvelope(), + PublishOptions.defaults()); + + // when + PublishResult result = transport.publish(request).toCompletableFuture().join().result(); + + // then + assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); + assertThat(result.failure()).get().extracting(FailureDescriptor::retryable).isEqualTo(true); + } +} diff --git a/src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifierTest.java b/src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifierTest.java new file mode 100644 index 00000000..cdbae5a2 --- /dev/null +++ b/src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifierTest.java @@ -0,0 +1,69 @@ +package dev.caskeleton.messaging.kafka; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.messaging.api.error.FailureDescriptor; +import dev.caskeleton.messaging.api.publish.PublishCompletion; +import dev.caskeleton.messaging.api.publish.PublishResult; +import java.time.Duration; +import org.apache.kafka.common.errors.AuthenticationException; +import org.apache.kafka.common.errors.AuthorizationException; +import org.apache.kafka.common.errors.InvalidTopicException; +import org.apache.kafka.common.errors.TopicAuthorizationException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Which producer failures a publisher may retry. + * + *

      Authentication and authorization failures prove the broker did not store the record, so they + * are rejections. They are not proof the record will be refused again: a credential being rotated + * or an ACL deployed after the application fails this way for a few minutes and then stops. + */ +class KafkaPublishFailureClassifierTest { + + private final KafkaPublishFailureClassifier classifier = new KafkaPublishFailureClassifier(); + + @Test + @DisplayName("인증 실패는 저장되지 않은 거부지만 다시 시도할 수 있다고 표시한다") + void anAuthenticationFailureIsARejectionThatMayBeRetried() { + // given + AuthenticationException rotatingCredential = + new AuthenticationException("SASL authentication failed"); + + // when + PublishResult result = classifier.classify(rotatingCredential, Duration.ZERO); + + // then + assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); + assertThat(result.failure()).get().extracting(FailureDescriptor::retryable).isEqualTo(true); + } + + @Test + @DisplayName("인가 실패는 저장되지 않은 거부지만 다시 시도할 수 있다고 표시한다") + void anAuthorizationFailureIsARejectionThatMayBeRetried() { + // given + AuthorizationException aclNotYetDeployed = new TopicAuthorizationException("orders"); + + // when + PublishResult result = classifier.classify(aclNotYetDeployed, Duration.ZERO); + + // then + assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); + assertThat(result.failure()).get().extracting(FailureDescriptor::retryable).isEqualTo(true); + } + + @Test + @DisplayName("존재하지 않는 topic은 다시 시도해도 같으므로 다시 시도할 수 없다고 표시한다") + void anInvalidTopicIsARejectionThatMayNotBeRetried() { + // given + InvalidTopicException noSuchTopic = new InvalidTopicException("no such topic"); + + // when + PublishResult result = classifier.classify(noSuchTopic, Duration.ZERO); + + // then + assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); + assertThat(result.failure()).get().extracting(FailureDescriptor::retryable).isEqualTo(false); + } +} diff --git a/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java b/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java index 0f6d9e29..a51f9fef 100644 --- a/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java +++ b/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java @@ -263,7 +263,17 @@ public final class DefaultMessagePublisher implements MessagePublisher, EncodedM lease.close(); } admission.complete(destination.name().value()); - return rejected("PUBLISH_RUNTIME_UNAVAILABLE", sanitized(beforeTheSend), startedAt); + // No runtime to send through — the registry closed during shutdown, or none is installed + // yet. Nothing about the message was wrong, so the refusal is marked retryable: a caller that + // trusts the flag, as the application's outbox relay does, retries it instead of parking it. + return refused( + new FailureDescriptor( + FailureCategory.TRANSIENT_INFRASTRUCTURE, + "PUBLISH_RUNTIME_UNAVAILABLE", + true, + sanitized(beforeTheSend), + Optional.empty()), + startedAt); } } diff --git a/src/messaging/messaging-runtime-core/src/test/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisherTest.java b/src/messaging/messaging-runtime-core/src/test/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisherTest.java index 4ac4854b..5a9b7504 100644 --- a/src/messaging/messaging-runtime-core/src/test/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisherTest.java +++ b/src/messaging/messaging-runtime-core/src/test/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisherTest.java @@ -420,6 +420,37 @@ class DefaultMessagePublisherTest { assertThat(admission.inFlight()).isZero(); } + @Test + @DisplayName("runtime이 없어서 생긴 거부는 다시 시도할 수 있다고 표시한다") + void aRefusalForAnUnavailableRuntimeMayBeRetried() { + // given: the runtime registry closed during shutdown, before this publish acquired it + DefaultMessagePublisher publisher = + new DefaultMessagePublisher( + registry(), + allowOrders(), + new SingleCodecRegistry(), + admission, + new FailingRuntimeRegistry(), + transport); + + // when + PublishResult result = + publisher + .publish( + new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class), + envelope(), + PublishOptions.defaults()) + .toCompletableFuture() + .join(); + + // then: nothing about the message was wrong, so a later attempt may succeed + assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); + assertThat(result.failure()) + .get() + .extracting(FailureDescriptor::code, FailureDescriptor::retryable) + .containsExactly("PUBLISH_RUNTIME_UNAVAILABLE", true); + } + @Test @DisplayName("an unregistered destination names itself") void anUnregisteredDestinationNamesItself() { diff --git a/src/sample-portfolio/README.md b/src/sample-portfolio/README.md index aedf9f78..84124b88 100644 --- a/src/sample-portfolio/README.md +++ b/src/sample-portfolio/README.md @@ -8,7 +8,7 @@ ## 도메인: WorkLog (엔지니어링 작업 기록 게시판) -메인 화면 = `GET /work-logs` 목록. 각 항목은 직접 수행한 작업입니다. +메인 화면 = `GET /api/worklogs` 목록. 각 항목은 직접 수행한 작업입니다. | 필드 | 설명 | | --- | --- | @@ -21,20 +21,35 @@ ## 엔드포인트 -| Method | Path | 설명 | 시연 계약 | +| Method | Path | 설명 | 필요 권한 | 시연 계약 | +| --- | --- | --- | --- | --- | +| GET | /api/worklogs | 목록 (메인) | 없음(공개) | Envelope wrap | +| GET | /api/worklogs/{id} | 상세 | 없음(공개) | 도메인 예외→404 envelope | +| POST | /api/worklogs | 생성 | `worklog:write` | Bean Validation @GroupSequence (B4), unknown-field 거부 (B1), mapper 실패→MAPPING_FAILED (B3) | +| PATCH | /api/worklogs/{id} | 부분수정 | `worklog:write` | JsonNullable 3-state (B2) | +| DELETE | /api/worklogs/{id} | 삭제 | `worklog:close` | 204 | +| POST | /api/worklogs:batchCreate | 일괄 등록 | `worklog:write` | 동기 = 원자적(한 항목 실패 → 전체 롤백, 단일 4xx) | + +## 데모 계정과 권한 + +읽기(GET)는 인증 없이 열려 있고, 나머지 메서드는 아래 데모 계정 중 하나로 HTTP Basic 인증을 해야 +합니다. 인증 없이 쓰면 401 envelope입니다. 계정이 그 작업을 해도 되는지는 이 체인이 아니라 유스케이스의 +`@RequiresPermission`이 정하고, 역할→권한 표는 `application.yml`의 `app.authz.role-permissions`입니다. +운영 경로(JWT)와 같은 advisor·같은 표를 씁니다. + +| 계정 | 비밀번호 | 역할 | 할 수 있는 것 | | --- | --- | --- | --- | -| GET | /work-logs | 목록 (메인) | Envelope wrap | -| GET | /work-logs/{id} | 상세 | 도메인 예외→404 envelope | -| POST | /work-logs | 생성 | Bean Validation @GroupSequence (B4), unknown-field 거부 (B1), mapper 실패→MAPPING_FAILED (B3) | -| PATCH | /work-logs/{id} | 부분수정 | JsonNullable 3-state (B2) | -| DELETE | /work-logs/{id} | 삭제 | 204 | -| POST | /work-logs/import | 일괄 등록 | BulkEnvelope 부분실패 (B8) | +| `demo-user` | `demo-user` | `user` | 읽기, 생성, 수정. 삭제는 403 | +| `demo-admin` | `demo-admin` | `admin` | 위 전부 + 삭제 | + +비밀번호가 문서에 적혀 있는 공개 데모 계정입니다. 비밀이 아니며, 실제 서비스는 이 방식을 쓰지 않고 +`adapter:inbound:web`의 JWT 체인으로 인증합니다. ## 샘플 데이터 (curl 예시) ```bash # 1) 인프라 인증·인가 위임 (Keycloak + k3s + Vault) -curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ +curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type: application/json' -d '{ "title": "Keycloak + k3s + Vault 기반 인증·인가 위임", "category": "INFRASTRUCTURE", "summary": "인증/인가를 Keycloak으로 위임, k3s + Vault로 시크릿·구성 관리", @@ -45,7 +60,7 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ }' # 2) DB 쿼리 튜닝 -curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ +curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type: application/json' -d '{ "title": "DB 쿼리 튜닝", "category": "DATABASE", "summary": "slow query 분석 및 인덱스/실행계획 개선", @@ -334,6 +349,23 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ - UPDATE(버전 non-null): 기존 행의 created 값을 읽어 그대로 이어가고(같은 트랜잭션에서 유스케이스가 이미 로드해둔 JPA 1차 캐시에서 served), updated 만 갱신합니다. +### PosterRepositoryAdapter — 중복 규칙은 DB 제약 + 충돌 변환 +- 포스터 제목은 대소문자를 무시하고 유일합니다. 이 규칙은 **DB 유일 인덱스가 지킵니다** + (`uq_poster_title_ci ON poster (upper(title))`, 샘플 마이그레이션 V8.1). +- `CreatePosterUseCase` 의 `existsByTitle` 사전 조회는 흔한 경우에 일찍 409 를 주는 용도일 뿐입니다. + READ COMMITTED 에서 동시 요청 둘은 모두 "없음"을 보고 둘 다 insert 하므로, 조회만으로는 규칙이 + 깨집니다(리뷰 09-02: 동시 16요청에 10행). +- `save()` 는 `saveAndFlush` 로 insert 를 그 자리에서 실행하고, `uq_poster_title_ci` 위반을 사전 + 조회와 같은 `PosterTitleAlreadyExistsException`(409 `POSTER_ALREADY_EXISTS`)으로 바꿉니다. flush 를 + 미루면 위반이 커밋 시점에 일반 `DB_UNIQUE_VIOLATION` 으로 나와 도메인 오류 코드를 잃습니다. +- 버린 대안: 비관적 락·`SERIALIZABLE` 격리(더 비싸고 재시도가 필요함), 사전 조회만 유지(동시성에서 깨짐). +- 인덱스 키가 `upper(title)` 인 이유: 사전 조회(`existsByTitleIgnoreCase`)를 Hibernate 가 + `upper(title) = upper(?)` 로 만들기 때문입니다. 같은 식이라 그 조회도 순차 스캔 대신 이 인덱스를 + 씁니다. 제목 정렬용 `ix_poster_title` 은 그대로 둡니다. +- 버전이 9 가 아니라 8.1 인 이유: 일부 샘플 테스트는 프로덕션 위치와 샘플 위치를 한 Flyway 로 합쳐 + 돌리고, 프로덕션이 9 이상 정수 버전을 이미 씁니다. 소수 버전은 겹치지 않습니다. 마이그레이션은 + 이미 중복 제목이 있으면 그 제목을 이름으로 대며 멈춥니다. + ### WorkLogJpaRepository - `findByCategory`: 계약이 허용하는 유일한 필터 구문인 **평면 동등 필터**를 데이터 계층 안에 둔 파생 쿼리입니다. @@ -406,10 +438,18 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ classpath 의) `SamplePortfolioTestApplication` **둘 다** 찾으면 "multiple @SpringBootConfiguration" 오류를 냅니다. `@Configuration`(= `@SpringBootConfiguration` 아님)을 쓰면 finder 에 숨으면서도, `@SpringBootTest(classes = SamplePortfolioApplication.class)` 로 부팅하는 데는 문제가 없습니다. -- **`@EnableAutoConfiguration(exclude = WebSecurityAutoConfiguration.class)`**: web leaf의 보안 root - (JWT 필터 체인·메서드 보안·권한 port)만 뺀다 — 공개 데모 앱이라 IdP나 메서드 보안 principal 없이 - URL에 접근해야 하고, 그 자리는 `SamplePublicAccessSecurityConfig`가 채운다. 에러 envelope·필터· - health·rate limit은 `WebAdapterAutoConfiguration`으로 프로덕션과 같게 들어온다. +- **`@EnableAutoConfiguration(exclude = WebSecurityAutoConfiguration.class)`**: web leaf의 인증 체인 + (JWT 필터 체인)만 뺀다 — IdP 없이 띄우는 데모라 그 자리는 `SampleDemoSecurityConfig`(읽기 공개, + 나머지는 데모 계정 HTTP Basic)가 채운다. **메서드 보안은 빼지 않는다**: `@RequiresPermission` advisor와 + 권한 port는 `WebMethodSecurityAutoConfiguration`으로 프로덕션과 같게 들어와서, 데모 계정의 역할도 + `app.authz` 표로 검사된다. 에러 envelope·필터·health·rate limit은 `WebAdapterAutoConfiguration`으로 + 프로덕션과 같게 들어온다. + - 예전에는 체인과 메서드 보안이 한 root에 있어서, 체인을 빼면 권한 검사도 같이 꺼졌다. 실행 중인 + 샘플에서 누구나 삭제할 수 있었고, 인증 주체가 없어 owner가 null이라 생성은 항상 500이었다(리뷰 + 07-03·09-03). `SampleWorkLogAuthorizationSystemTest`가 실제 서버로 이 동작을 지킨다. + - 버린 대안: 공개 체인을 두고 README에 경고만 적기(위험이 코드에 드러나지 않는다), 샘플에서 + `@RequiresPermission`을 지우기(인가 위치를 보여 주는 예시가 사라진다), `X-Demo-Role` 같은 헤더를 + 그대로 믿는 필터(호출자가 역할을 스스로 주장하는 패턴이 복제될 위험). - 데이터 계층을 빼고 뜨는 테스트 슬라이스(`DataSourceAutoConfiguration` 제외)는 `app.persistence-jpa.enabled=false`도 함께 준다. 모듈은 classpath에 있으면 켜지기 때문이다. diff --git a/src/sample-portfolio/build.gradle b/src/sample-portfolio/build.gradle index 86fbe3df..deab916d 100644 --- a/src/sample-portfolio/build.gradle +++ b/src/sample-portfolio/build.gradle @@ -97,7 +97,6 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'io.micrometer:micrometer-registry-prometheus' implementation 'io.micrometer:micrometer-tracing-bridge-otel' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp' // Spring dotenv: picks up src/.env when bootRun workingDir = src/ (same as app-bootstrap). implementation libs.spring.dotenv // Boot 4 Flyway API/autoconfiguration needed by sample-local persistence configuration. @@ -110,6 +109,9 @@ dependencies { // Property-based testing for @ValueObject invariants (registers its own JUnit Platform engine). testImplementation libs.jqwik testImplementation libs.archunit.junit5 + // The JPA rule pack (one-side associations) checks the sample's entities, which the composition + // root's production architecture suite cannot import. + testImplementation testFixtures(project(':adapter:outbound:persistence-jpa')) // The Poster image workflow drives the real executor over the port owner's shared fake store. testImplementation testFixtures(project(':application-core')) diff --git a/src/sample-portfolio/gradle.lockfile b/src/sample-portfolio/gradle.lockfile index 2b9febd1..9aafaf59 100644 --- a/src/sample-portfolio/gradle.lockfile +++ b/src/sample-portfolio/gradle.lockfile @@ -13,9 +13,9 @@ com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=integrationTestRun com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath com.fasterxml:classmate:1.7.3=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,integrationTestAnnotationProcessor,posterImageMigrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,webSystemTestAnnotationProcessor -com.github.docker-java:docker-java-api:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath -com.github.docker-java:docker-java-transport-zerodep:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath -com.github.docker-java:docker-java-transport:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath +com.github.docker-java:docker-java-api:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +com.github.docker-java:docker-java-transport-zerodep:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +com.github.docker-java:docker-java-transport:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath com.github.f4b6a3:uuid-creator:6.1.1=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,integrationTestAnnotationProcessor,posterImageMigrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,webSystemTestAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs @@ -25,10 +25,10 @@ com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,integ com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,integrationTestAnnotationProcessor,posterImageMigrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,webSystemTestAnnotationProcessor com.google.auto:auto-common:1.2.2=annotationProcessor,integrationTestAnnotationProcessor,posterImageMigrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,webSystemTestAnnotationProcessor com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs -com.google.code.gson:gson:2.13.2=spotbugs +com.google.code.gson:gson:2.13.2=integrationTestRuntimeClasspath,spotbugs,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,posterImageMigrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,webSystemTestAnnotationProcessor com.google.errorprone:error_prone_annotations:2.38.0=compileClasspath,integrationTestCompileClasspath,posterImageMigrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,webSystemTestCompileClasspath -com.google.errorprone:error_prone_annotations:2.41.0=spotbugs +com.google.errorprone:error_prone_annotations:2.41.0=integrationTestRuntimeClasspath,spotbugs,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath com.google.errorprone:error_prone_annotations:2.47.0=checkstyle com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,posterImageMigrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,webSystemTestAnnotationProcessor com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,posterImageMigrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,webSystemTestAnnotationProcessor @@ -60,9 +60,10 @@ com.zaxxer:HikariCP:7.0.2=compileClasspath,integrationTestCompileClasspath,integ commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-codec:commons-codec:1.19.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle -commons-io:commons-io:2.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath +commons-io:commons-io:2.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath commons-io:commons-io:2.21.0=spotbugs commons-logging:commons-logging:1.3.6=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +eu.rekawek.toxiproxy:toxiproxy-java:2.1.11=integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath info.picocli:picocli:4.7.7=checkstyle io.github.cdimascio:dotenv-java:3.0.0=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integrationTestAnnotationProcessor,posterImageMigrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,webSystemTestAnnotationProcessor @@ -95,7 +96,7 @@ io.opentelemetry:opentelemetry-common:1.55.0=compileClasspath,integrationTestCom io.opentelemetry:opentelemetry-context:1.55.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath io.opentelemetry:opentelemetry-exporter-common:1.55.0=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath io.opentelemetry:opentelemetry-exporter-otlp-common:1.55.0=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath -io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath io.opentelemetry:opentelemetry-exporter-sender-okhttp:1.55.0=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath io.opentelemetry:opentelemetry-sdk-common:1.55.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath @@ -111,6 +112,7 @@ io.prometheus:prometheus-metrics-exposition-formats:1.4.3=integrationTestRuntime io.prometheus:prometheus-metrics-exposition-textformats:1.4.3=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath io.prometheus:prometheus-metrics-model:1.4.3=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath io.prometheus:prometheus-metrics-tracer-common:1.4.3=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +io.smallrye:jandex:3.3.2=integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath io.swagger.core.v3:swagger-core-jakarta:2.2.38=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath io.swagger.core.v3:swagger-models-jakarta:2.2.38=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath @@ -126,7 +128,7 @@ jaxen:jaxen:2.0.6=spotbugs me.paulschwarz:spring-dotenv:4.0.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath net.bytebuddy:byte-buddy-agent:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath -net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath +net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath net.jqwik:jqwik-api:1.9.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath net.jqwik:jqwik-engine:1.9.1=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath net.jqwik:jqwik-time:1.9.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath @@ -138,7 +140,7 @@ net.minidev:json-smart:2.6.0=integrationTestCompileClasspath,integrationTestRunt net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-compress:1.28.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath +org.apache.commons:commons-compress:1.28.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.apache.commons:commons-lang3:3.20.0=checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,spotbugs,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle @@ -175,12 +177,13 @@ org.hamcrest:hamcrest:3.0=integrationTestCompileClasspath,integrationTestRuntime org.hdrhistogram:HdrHistogram:2.2.2=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.hibernate.models:hibernate-models:1.0.1=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.hibernate.orm:hibernate-core:7.2.24.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +org.hibernate.orm:hibernate-envers:7.2.24.Final=integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.hibernate.validator:hibernate-validator:9.0.1.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle org.jboss.logging:jboss-logging:3.6.3.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.jetbrains.kotlin:kotlin-stdlib:2.2.21=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath -org.jetbrains:annotations:13.0=productionRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath -org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath +org.jetbrains:annotations:13.0=productionRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath +org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestAnnotationProcessor,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestAnnotationProcessor,systemTestCompileClasspath,systemTestRuntimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestAnnotationProcessor,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath @@ -211,7 +214,7 @@ org.pcollections:pcollections:4.0.1=annotationProcessor,integrationTestAnnotatio org.postgresql:postgresql:42.7.13=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.reactivestreams:reactive-streams:1.0.4=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle -org.rnorth.duct-tape:duct-tape:1.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath +org.rnorth.duct-tape:duct-tape:1.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.skyscreamer:jsonassert:1.5.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.slf4j:slf4j-api:2.0.18=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath @@ -238,6 +241,9 @@ org.springframework.boot:spring-boot-jpa-test:4.0.8=integrationTestCompileClassp org.springframework.boot:spring-boot-jpa:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.springframework.boot:spring-boot-micrometer-metrics:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.springframework.boot:spring-boot-micrometer-observation:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-tracing-opentelemetry:4.0.8=integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-tracing:4.0.8=integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +org.springframework.boot:spring-boot-opentelemetry:4.0.8=integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.springframework.boot:spring-boot-persistence:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.springframework.boot:spring-boot-restclient:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.springframework.boot:spring-boot-resttestclient:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath @@ -300,11 +306,12 @@ org.springframework:spring-tx:7.0.9=compileClasspath,integrationTestCompileClass org.springframework:spring-web:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.springframework:spring-webflux:7.0.9=posterImageMigrationTestRuntimeClasspath org.springframework:spring-webmvc:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath -org.testcontainers:testcontainers-database-commons:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath -org.testcontainers:testcontainers-jdbc:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath -org.testcontainers:testcontainers-junit-jupiter:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath -org.testcontainers:testcontainers-postgresql:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath -org.testcontainers:testcontainers:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath +org.testcontainers:testcontainers-database-commons:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +org.testcontainers:testcontainers-jdbc:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +org.testcontainers:testcontainers-junit-jupiter:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +org.testcontainers:testcontainers-postgresql:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +org.testcontainers:testcontainers-toxiproxy:2.0.5=integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +org.testcontainers:testcontainers:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.yaml:snakeyaml:2.5=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath 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 2e2f5903..43f523bc 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 @@ -1,9 +1,11 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.persistence.audit.AuditContextPort; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.config.JpaConfig; +import dev.caskeleton.sample.portfolio.application.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.domain.poster.Poster; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterImageReference; @@ -177,6 +179,23 @@ class PosterRepositoryAdapterIntegrationTest { assertThat(exists).isEqualTo(expected); } + /** The store holds the rule even when the caller skipped or lost the existsByTitle check. */ + @Test + void savingATitleThatDiffersOnlyByCaseIsRejectedAsATitleConflict() { + // given + saveAndDetach(Poster.create(ID, "여름 세일 Banner", "7월 한정")); + Poster sameTitle = + Poster.create(PosterId.of("0190bd6e-7c3e-7abc-8def-0123456789ac"), "여름 세일 BANNER", null); + + // when + Throwable failure = catchThrowable(() -> adapter.save(sameTitle)); + + // then + assertThat(failure) + .isInstanceOf(PosterTitleAlreadyExistsException.class) + .hasMessage("Poster title already in use: 여름 세일 BANNER"); + } + @Test void aPreV8RawKeyRowReadsBackWithoutAnImage() { // given diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java new file mode 100644 index 00000000..bf1dadcc --- /dev/null +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java @@ -0,0 +1,182 @@ +package dev.caskeleton.sample.portfolio.application.poster; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.audit.AuditContextPort; +import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.UuidPosterIdFactory; +import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.config.JpaConfig; +import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository.PosterRepositoryAdapter; +import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; +import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; +import java.time.Clock; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.Function; +import java.util.stream.Collectors; +import javax.sql.DataSource; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.TestPropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * The duplicate-title rule under concurrent requests, against real PostgreSQL. + * + *

      The use case's {@code existsByTitle} pre-check cannot hold the rule on its own: under READ + * COMMITTED two transactions both see "no such title" and both insert. The rule is held by the + * {@code uq_poster_title_ci} unique index (sample migration V8.1), and the repository adapter turns + * its violation into the same {@link PosterTitleAlreadyExistsException} the pre-check throws. The + * test is not transactional so each request commits on its own connection, as it does in the + * running service. + */ +@DataJpaTest +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +@Transactional(propagation = Propagation.NOT_SUPPORTED) +@Testcontainers(disabledWithoutDocker = true) +@Import({ + JpaConfig.class, + PosterRepositoryAdapter.class, + CreatePosterConcurrencyIntegrationTest.TestAuditConfig.class +}) +@TestPropertySource( + properties = { + "spring.flyway.enabled=true", + "spring.flyway.locations=classpath:db/migration/postgresql,classpath:db/sample-migration", + "spring.jpa.hibernate.ddl-auto=validate" + }) +class CreatePosterConcurrencyIntegrationTest { + + private static final int REQUESTS = 16; + + @Container @ServiceConnection + static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); + + @Autowired PosterRepositoryAdapter repository; + @Autowired PlatformTransactionManager transactionManager; + @Autowired DataSource dataSource; + + private final InMemoryOutboxStore outbox = new InMemoryOutboxStore(); + + @Test + void concurrentCreatesOfOneTitleKeepOneRowAndRejectTheRestAsTitleConflicts() throws Exception { + // given + String title = "race-" + UUID.randomUUID(); + List sameTitleInMixedCase = new ArrayList<>(); + for (int i = 0; i < REQUESTS; i++) { + sameTitleInMixedCase.add(i % 2 == 0 ? title : title.toUpperCase(Locale.ROOT)); + } + + // when + Map outcomes = createConcurrently(sameTitleInMixedCase); + + // then + assertThat(List.of(outcomes, storedRowsWithTitle(title), outbox.appended().size())) + .containsExactly( + Map.of("created", 1L, PosterTitleAlreadyExistsException.class.getSimpleName(), 15L), + 1L, + 1); + } + + /** Releases every request at once and counts how each one ended. */ + private Map createConcurrently(List titles) throws Exception { + CreatePosterUseCase useCase = useCase(); + CountDownLatch start = new CountDownLatch(1); + ExecutorService pool = Executors.newFixedThreadPool(titles.size()); + try { + List> results = new ArrayList<>(); + for (String title : titles) { + Callable request = + () -> { + start.await(); + try { + useCase.handle(new CreatePosterCommand(title, null)); + return "created"; + } catch (RuntimeException failure) { + return failure.getClass().getSimpleName(); + } + }; + results.add(pool.submit(request)); + } + start.countDown(); + List outcomes = new ArrayList<>(); + for (Future result : results) { + outcomes.add(result.get()); + } + return outcomes.stream() + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + } finally { + pool.shutdownNow(); + } + } + + private CreatePosterUseCase useCase() { + FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(); + // The in-memory fakes are single-threaded; the requests reach them one at a time. + PortfolioEventOutbox events = + new PortfolioEventOutbox( + event -> { + synchronized (outbox) { + outbox.append(event); + } + }, + draft -> { + synchronized (encoder) { + return encoder.encode(draft); + } + }, + () -> UUID.randomUUID().toString(), + Optional::empty, + Clock.systemUTC()); + return new CreatePosterUseCase( + repository, + new UuidPosterIdFactory(), + new PosterEventPublisher(events), + new SpringTransaction(transactionManager)); + } + + private long storedRowsWithTitle(String title) { + Long rows = + new JdbcTemplate(dataSource) + .queryForObject( + "select count(*) from poster where upper(title) = upper(?)", Long.class, title); + return rows == null ? 0 : rows; + } + + @TestConfiguration + static class TestAuditConfig { + + @Bean + Clock clock() { + return Clock.systemUTC(); + } + + @Bean + AuditContextPort auditContext() { + return () -> "it-actor"; + } + } +} diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationStreamIsolationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationStreamIsolationTest.java index 7843beae..ad29e306 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationStreamIsolationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationStreamIsolationTest.java @@ -44,7 +44,7 @@ class SampleMigrationStreamIsolationTest { // then assertThat(successfulVersions("flyway_schema_history")) .contains("1", "3", "13") - .doesNotContain("2", "7", "8"); + .doesNotContain("2", "7", "8", "8.1"); } @Test @@ -53,7 +53,7 @@ class SampleMigrationStreamIsolationTest { SamplePostgreSqlPersistenceConfig.sampleMigrationStrategy().migrate(productionFlyway); // then - assertThat(successfulVersions("flyway_sample_schema_history")).contains("2", "7", "8"); + assertThat(successfulVersions("flyway_sample_schema_history")).contains("2", "7", "8", "8.1"); } @Test diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterTitleUniqueMigrationQualificationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterTitleUniqueMigrationQualificationTest.java new file mode 100644 index 00000000..d81ab7fd --- /dev/null +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterTitleUniqueMigrationQualificationTest.java @@ -0,0 +1,113 @@ +package dev.caskeleton.sample.portfolio.qualification; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.OffsetDateTime; +import java.util.UUID; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.FlywayException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** Sample migration V8.1: the case-insensitive unique index that holds the poster title rule. */ +@Testcontainers +class PosterTitleUniqueMigrationQualificationTest { + + @Container static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); + + private static final OffsetDateTime NOW = OffsetDateTime.parse("2026-11-01T00:00:00Z"); + + @BeforeEach + void cleanDatabase() { + flyway(null).clean(); + } + + @Test + void existingTitlesThatDifferOnlyByCaseStopTheMigrationAndAreNamed() throws SQLException { + // given + flyway("8").migrate(); + insertPoster("Summer Sale"); + insertPoster("SUMMER SALE"); + + // when + Throwable failure = catchThrowable(() -> flyway(null).migrate()); + + // then + assertThat(failure) + .isInstanceOf(FlywayException.class) + .hasMessageContaining( + "poster has titles that differ only by case or repeat: 'SUMMER SALE'"); + } + + /** The planner is told to avoid a sequential scan, so a usable index is the only way left. */ + @Test + void theCaseInsensitiveTitleLookupCanUseTheUniqueIndex() throws SQLException { + // given + flyway(null).migrate(); + + // when + String plan = planOf("select 1 from poster where upper(title) = upper('Summer Sale')"); + + // then + assertThat(plan).contains("uq_poster_title_ci"); + } + + private static Flyway flyway(String target) { + var configuration = + Flyway.configure() + .dataSource(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()) + .locations("classpath:db/migration/postgresql", "classpath:db/sample-migration") + .cleanDisabled(false); + if (target != null) { + configuration.target(target); + } + return configuration.load(); + } + + private static Connection connection() throws SQLException { + return DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + } + + private static String planOf(String query) throws SQLException { + try (Connection connection = connection(); + Statement statement = connection.createStatement()) { + statement.execute("set enable_seqscan = off"); + StringBuilder plan = new StringBuilder(); + try (ResultSet rows = statement.executeQuery("explain " + query)) { + while (rows.next()) { + plan.append(rows.getString(1)).append('\n'); + } + } + return plan.toString(); + } + } + + private static void insertPoster(String title) throws SQLException { + try (Connection connection = connection(); + PreparedStatement statement = + connection.prepareStatement( + """ + insert into poster ( + id, title, status, version, created_at, updated_at, created_by, updated_by + ) values (?, ?, 'DRAFT', 0, ?, ?, 'it', 'it') + """)) { + statement.setObject(1, UUID.randomUUID()); + statement.setString(2, title); + statement.setObject(3, NOW); + statement.setObject(4, NOW); + assertThat(statement.executeUpdate()).isEqualTo(1); + } + } +} 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 152936c4..7a35460e 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 @@ -18,11 +18,12 @@ import org.springframework.context.annotation.Configuration; * scan of the web leaf once registered the durable operation endpoint here, with none of the store * it needs). * - *

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

      The one exclusion is the web leaf's JWT chain: the sample authenticates its published demo + * accounts instead ({@code SampleDemoSecurityConfig}), so it runs without a configured IdP. Only + * the way a caller is authenticated is replaced. Method security ({@code + * WebMethodSecurityAutoConfiguration}) is not excluded, so every {@code @RequiresPermission} is + * enforced as in production, and 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. 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 281b3857..2b42d19c 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 @@ -3,6 +3,7 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; import dev.caskeleton.adapter.outbound.persistence.audit.AuditContextPort; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.entity.PosterEntity; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.mapper.PosterPersistenceMapper; +import dev.caskeleton.sample.portfolio.application.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.domain.poster.Poster; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterPage; @@ -13,6 +14,8 @@ import java.time.Clock; import java.time.Instant; import java.util.List; import java.util.Optional; +import org.hibernate.exception.ConstraintViolationException; +import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; @@ -21,6 +24,8 @@ import org.springframework.stereotype.Repository; @Repository public class PosterRepositoryAdapter implements PosterRepository { + private static final String TITLE_UNIQUE_INDEX = "uq_poster_title_ci"; + private final PosterJpaRepository jpa; // Audit metadata (time/actor) is stamped here in the persistence adapter; the domain Poster // carries no audit fields. Mirrors WorkLogRepositoryAdapter. @@ -54,7 +59,35 @@ public class PosterRepositoryAdapter implements PosterRepository { entity.carryCreation(existing.getCreatedAt(), existing.getCreatedBy()); entity.applyModification(now, actor); } - return PosterPersistenceMapper.toDomain(jpa.save(entity)); + return PosterPersistenceMapper.toDomain(saveHoldingTheTitleRule(entity, poster.title())); + } + + /** + * The unique index {@value #TITLE_UNIQUE_INDEX} (sample migration V8.1) is what keeps poster + * titles unique; the use case's {@code existsByTitle} check only gives the common case an early + * answer and loses races. Flushing here makes a violation surface inside this call, where it is + * turned into the same {@link PosterTitleAlreadyExistsException} the check throws, instead of at + * commit as a generic unique-violation failure. + */ + private PosterEntity saveHoldingTheTitleRule(PosterEntity entity, String title) { + try { + return jpa.saveAndFlush(entity); + } catch (DataIntegrityViolationException failure) { + if (violated(failure, TITLE_UNIQUE_INDEX)) { + throw new PosterTitleAlreadyExistsException(title); + } + throw failure; + } + } + + private static boolean violated(Throwable failure, String constraint) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof ConstraintViolationException violation + && constraint.equalsIgnoreCase(violation.getConstraintName())) { + return true; + } + } + return false; } @Override diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterUseCase.java index 99edd093..9fd982cb 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterUseCase.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterUseCase.java @@ -16,6 +16,11 @@ import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; * Creates a new {@link Poster} (server-assigned id via {@link PosterIdFactory}) and appends a * {@code poster.created} outbox event in the same write transaction. Rejects a duplicate title. * Mirrors {@code CreateWorkLogUseCase}. + * + *

      Duplicate rule pattern: the database holds the rule, the use case only asks first. The {@code + * existsByTitle} check cannot hold it alone (two concurrent requests both see "absent"); {@link + * PosterRepository#save} is backed by a unique index and reports a lost race as the same {@link + * PosterTitleAlreadyExistsException}, so both paths answer 409 {@code POSTER_ALREADY_EXISTS}. */ @RequiresPermission("poster:write") @UseCaseCapability( @@ -44,6 +49,7 @@ public class CreatePosterUseCase implements CommandUseCase { + // Early answer for the common case; save() enforces the rule when requests race. if (repository.existsByTitle(cmd.title())) { throw new PosterTitleAlreadyExistsException(cmd.title()); } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccounts.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccounts.java new file mode 100644 index 00000000..3a54feff --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccounts.java @@ -0,0 +1,53 @@ +package dev.caskeleton.sample.portfolio.bootstrap.security; + +import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; + +/** + * Two published demo accounts, one per role the sample's {@code app.authz} policy names. + * + *

      These are not secrets: the password of each account is its own name, and the sample README + * prints both. They exist so a reader of the demo can watch {@code @RequiresPermission} allow one + * caller and refuse another — {@code demo-user} (role {@code user}) may create and update but not + * delete, {@code demo-admin} (role {@code admin}) may also delete. A real service authenticates + * through the JWT chain the sample excludes; nothing here belongs in one. + * + *

      The authenticated principal is the same {@link AuthenticatedPrincipal} the JWT chain produces, + * so the controller stamps the account name as the owner and the authorization manager reads its + * roles without knowing which chain made it. + */ +public final class SampleDemoAccounts implements AuthenticationProvider { + + private static final Map> ROLES_BY_ACCOUNT = + Map.of("demo-user", Set.of("user"), "demo-admin", Set.of("admin")); + + @Override + public Authentication authenticate(Authentication authentication) { + String account = authentication.getName(); + Set roles = ROLES_BY_ACCOUNT.get(account); + Object presented = authentication.getCredentials(); + if (roles == null || !(presented instanceof String password) || !matches(password, account)) { + throw new BadCredentialsException("not a demo account"); + } + return UsernamePasswordAuthenticationToken.authenticated( + new AuthenticatedPrincipal(account, null, roles), null, List.of()); + } + + @Override + public boolean supports(Class authentication) { + return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); + } + + private static boolean matches(String presented, String expected) { + return MessageDigest.isEqual( + presented.getBytes(StandardCharsets.UTF_8), expected.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java new file mode 100644 index 00000000..a9b99884 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java @@ -0,0 +1,69 @@ +package dev.caskeleton.sample.portfolio.bootstrap.security; + +import dev.caskeleton.adapter.inbound.web.auth.EnvelopeAuthenticationEntryPoint; +import dev.caskeleton.adapter.inbound.web.auth.SecurityErrorClassifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.SecurityFilterChain; +import tools.jackson.databind.ObjectMapper; + +/** + * The sample's request authentication, standing in for the JWT chain it excludes. + * + *

      Reading is open, so the demo can be browsed without an IdP. Every other method needs one of + * the {@link SampleDemoAccounts} over HTTP Basic, and an anonymous write is answered 401 by the + * same envelope entry point production uses. Whether that account may run the use case is not + * decided here: method security stays on ({@code WebMethodSecurityAutoConfiguration}), so each + * {@code @RequiresPermission} is checked against {@code app.authz} exactly as it is for a JWT + * caller. This chain only answers who the caller is. + */ +@Configuration +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) +public class SampleDemoSecurityConfig { + + /** + * The demo accounts, as the only {@link AuthenticationProvider}. + * + *

      A bean rather than a provider set on the chain: its presence is what makes Spring Boot's + * {@code UserDetailsServiceAutoConfiguration} back off. Without it Boot would add a generated + * {@code user} account whose principal is not an {@code AuthenticatedPrincipal}, and a write made + * with it would carry no owner. + * + * @return the demo accounts + */ + @Bean + public SampleDemoAccounts sampleDemoAccounts() { + return new SampleDemoAccounts(); + } + + @Bean + @Order(-100) + public SecurityFilterChain sampleDemoSecurityFilterChain(HttpSecurity http, ObjectMapper json) + throws Exception { + AuthenticationEntryPoint unauthenticated = + new EnvelopeAuthenticationEntryPoint(new SecurityErrorClassifier(), json); + http.securityMatcher("/**") + .csrf(csrf -> csrf.disable()) + .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .httpBasic(basic -> basic.authenticationEntryPoint(unauthenticated)) + .exceptionHandling(ex -> ex.authenticationEntryPoint(unauthenticated)) + .authorizeHttpRequests( + auth -> + auth.requestMatchers(HttpMethod.GET) + .permitAll() + .requestMatchers(HttpMethod.HEAD) + .permitAll() + .requestMatchers(HttpMethod.OPTIONS) + .permitAll() + .anyRequest() + .authenticated()); + return http.build(); + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfig.java deleted file mode 100644 index e15af510..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.security; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.Order; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.web.SecurityFilterChain; - -/** - * Sample-only HTTP security posture. The WorkLog sample has no login surface, so every demo URL is - * reachable without an Authorization header while production modules continue to use adapter-web's - * JWT and method-security configuration. - */ -@Configuration -@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) -public class SamplePublicAccessSecurityConfig { - - @Bean - @Order(-100) - public SecurityFilterChain samplePublicAccessSecurityFilterChain(HttpSecurity http) - throws Exception { - http.securityMatcher("/**") - .csrf(csrf -> csrf.disable()) - .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - .authorizeHttpRequests(auth -> auth.anyRequest().permitAll()); - return http.build(); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterRepository.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterRepository.java index ec9ff4a9..420f08f5 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterRepository.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterRepository.java @@ -4,6 +4,12 @@ import java.util.Optional; /** Outbound port for Poster persistence. Implemented in adapter-persistence. */ public interface PosterRepository { + + /** + * Stores the poster. Titles are unique ignoring case, and the store enforces it: a save that + * would duplicate a stored title fails with the application's {@code + * PosterTitleAlreadyExistsException}, even when {@link #existsByTitle} said the title was free. + */ Poster save(Poster poster); Optional findById(PosterId id); @@ -18,6 +24,7 @@ public interface PosterRepository { boolean existsById(PosterId id); + /** Case-insensitive. Advisory only — a concurrent save can take the title right after. */ boolean existsByTitle(String title); void deleteById(PosterId id); diff --git a/src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql b/src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql new file mode 100644 index 00000000..7ff4d46b --- /dev/null +++ b/src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql @@ -0,0 +1,31 @@ +-- The duplicate-title rule is held by the database, not by the check before the insert. +-- +-- CreatePosterUseCase checks existsByTitle and then inserts. Under READ COMMITTED two requests +-- with the same title both see "no such title" and both insert, so the check alone cannot keep the +-- rule. This unique index can. PosterRepositoryAdapter turns a violation of it into the same +-- PosterTitleAlreadyExistsException (409 POSTER_ALREADY_EXISTS) the check throws. +-- +-- The index key is upper(title) because the rule is case-insensitive: the check is Spring Data's +-- existsByTitleIgnoreCase, which Hibernate renders as upper(title) = upper(?). The same +-- expression lets that check use this index instead of scanning the table. ix_poster_title stays: +-- it serves ORDER BY title for the title sort. +-- +-- Numbered 8.1, not 9. Some sample tests merge db/migration/postgresql and db/sample-migration into +-- one Flyway location list, and the production stream already owns the integer versions from 9 +-- up; a fractional version cannot collide with them. The sample's own history table +-- (flyway_sample_schema_history) orders it right after V8. + +DO $$ +DECLARE + duplicated text; +BEGIN + SELECT string_agg(quote_literal(key), ', ' ORDER BY key) + INTO duplicated + FROM (SELECT upper(title) AS key FROM poster GROUP BY upper(title) HAVING count(*) > 1) d; + IF duplicated IS NOT NULL THEN + RAISE EXCEPTION 'poster has titles that differ only by case or repeat: %', duplicated + USING HINT = 'Rename or remove the duplicates, then rerun the migration.'; + END IF; +END $$; + +CREATE UNIQUE INDEX uq_poster_title_ci ON poster (upper(title)); diff --git a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java new file mode 100644 index 00000000..3cfc6904 --- /dev/null +++ b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java @@ -0,0 +1,165 @@ +package dev.caskeleton.sample.portfolio.bootstrap.security; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.sample.portfolio.SamplePortfolioApplication; +import dev.caskeleton.sample.portfolio.domain.worklog.Period; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; +import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.test.context.ActiveProfiles; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * The running sample enforces the permissions its use cases declare. + * + *

      Boots the whole {@link SamplePortfolioApplication} composition on a real port over a real + * PostgreSQL, with nothing switched off, so a {@code @RequiresPermission} that the composition + * leaves without an advisor shows up here as a delete anyone can make. The demo accounts are the + * sample's published HTTP Basic credentials; their roles resolve through {@code app.authz} exactly + * as a JWT's roles would. + */ +@SpringBootTest( + classes = SamplePortfolioApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +@Testcontainers(disabledWithoutDocker = true) +class SampleWorkLogAuthorizationSystemTest { + + @Container @ServiceConnection + static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); + + private static final String CREATE_BODY = + "{\"title\":\"demo\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}"; + + private final HttpClient http = HttpClient.newHttpClient(); + + @LocalServerPort int port; + + @Autowired WorkLogRepository repository; + + @Autowired TransactionPort transactions; + + @Test + void anonymousDeleteIsRefusedAsUnauthenticated() throws Exception { + // given + WorkLogId id = storedWorkLog(); + + // when + HttpResponse response = send(delete(id), null); + + // then + assertThat(response.statusCode()).isEqualTo(401); + } + + @Test + void deleteByAnAccountWithoutWorklogCloseIsForbiddenAndKeepsTheRecord() throws Exception { + // given + WorkLogId id = storedWorkLog(); + + // when + HttpResponse response = send(delete(id), "demo-user"); + + // then + assertThat(List.of(response.statusCode(), exists(id))).containsExactly(403, true); + } + + @Test + void deleteByAnAccountWithWorklogCloseRemovesTheRecord() throws Exception { + // given + WorkLogId id = storedWorkLog(); + + // when + HttpResponse response = send(delete(id), "demo-admin"); + + // then + assertThat(List.of(response.statusCode(), exists(id))).containsExactly(204, false); + } + + @Test + void createByAnAccountWithWorklogWriteSucceeds() throws Exception { + // when + HttpResponse response = send(create(), "demo-user"); + + // then + assertThat(response.statusCode()).isEqualTo(200); + } + + @Test + void anonymousCreateIsRefusedAsUnauthenticatedRatherThanFailingOnTheMissingOwner() + throws Exception { + // when + HttpResponse response = send(create(), null); + + // then + assertThat(response.statusCode()).isEqualTo(401); + } + + private WorkLogId storedWorkLog() { + WorkLogId id = WorkLogId.of(UUID.randomUUID().toString()); + transactions.inWrite( + () -> + repository.save( + WorkLog.create( + id, + "stored", + WorkCategory.DATABASE, + "summary", + "content", + List.of(), + List.of(), + new Period(LocalDate.of(2025, 1, 1), null)))); + return id; + } + + private boolean exists(WorkLogId id) { + return transactions.inRead(() -> repository.existsById(id)); + } + + private HttpRequest.Builder delete(WorkLogId id) { + return HttpRequest.newBuilder(uri("/api/worklogs/" + id.value())).DELETE(); + } + + private HttpRequest.Builder create() { + return HttpRequest.newBuilder(uri("/api/worklogs")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(CREATE_BODY)); + } + + private HttpResponse send(HttpRequest.Builder request, String demoAccount) + throws IOException, InterruptedException { + if (demoAccount != null) { + // The demo accounts publish their own name as the password; see SampleDemoSecurityConfig. + String credentials = demoAccount + ":" + demoAccount; + request.header( + "Authorization", + "Basic " + + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8))); + } + return http.send(request.build(), HttpResponse.BodyHandlers.ofString()); + } + + private URI uri(String path) { + return URI.create("http://localhost:" + port + path); + } +} diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/architecture/SampleArchitectureTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/architecture/SampleArchitectureTest.java index 4e66ceb1..5c30b803 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/architecture/SampleArchitectureTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/architecture/SampleArchitectureTest.java @@ -7,6 +7,7 @@ import static org.assertj.core.api.Assertions.assertThat; import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.core.importer.ImportOption; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.JpaArchitectureRules; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -23,6 +24,16 @@ class SampleArchitectureTest { assertThat(sample).isNotEmpty(); } + /** + * The sample is the code adopters copy first, and the composition root's production suite cannot + * see it (app-bootstrap does not depend on the sample), so the one-side association rule runs + * here as well. + */ + @Test + void sampleAssociationsAreMappedFromOneSideOnly() { + JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(sample); + } + @Test void applicationLayerIsFrameworkFree() { noClasses() 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/SampleDemoSecurityConfigTest.java similarity index 77% rename from src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java rename to src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfigTest.java index de7d751a..98067db3 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/SampleDemoSecurityConfigTest.java @@ -3,6 +3,8 @@ package dev.caskeleton.sample.portfolio.bootstrap.security; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -47,17 +49,20 @@ import org.springframework.test.web.servlet.ResultActions; // The slice excludes the data layer; persistence-jpa is on while present, so it is switched off. @SpringBootTest( - classes = SamplePublicAccessSecurityConfigTest.TestBootstrap.class, + classes = SampleDemoSecurityConfigTest.TestBootstrap.class, properties = { "app.persistence-jpa.enabled=false", // The PostgreSQL idempotency store needs the relational module this test leaves off. "app.capabilities.idempotency.provider=disabled" }) @AutoConfigureMockMvc -class SamplePublicAccessSecurityConfigTest { +class SampleDemoSecurityConfigTest { private static final String ID = "0190bd6e-7c3e-7abc-8def-0123456789ab"; + private static final String CREATE_BODY = + "{\"title\":\"demo\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}"; + @Autowired MockMvc mvc; @MockitoBean CreateWorkLogUseCase createUseCase; @@ -69,18 +74,53 @@ class SamplePublicAccessSecurityConfigTest { @MockitoBean GetRepoStatsUseCase repoStatsUseCase; @Test - void sampleWorklogWriteEndpointIsReachableWithoutAuthorizationHeader() throws Exception { + void anonymousWorklogWriteIsRefusedAsUnauthenticated() throws Exception { + // when + ResultActions result = + mvc.perform(post("/worklogs").contentType(MediaType.APPLICATION_JSON).content(CREATE_BODY)); + + // then + result.andExpect(status().isUnauthorized()); + } + + @Test + void worklogWriteByADemoAccountReachesTheUseCase() throws Exception { // given - when(createUseCase.handle(any())).thenReturn(sample("public demo")); + when(createUseCase.handle(any())).thenReturn(sample("demo")); // when ResultActions result = mvc.perform( post("/worklogs") + .with(httpBasic("demo-user", "demo-user")) .contentType(MediaType.APPLICATION_JSON) - .content( - "{\"title\":\"public" - + " demo\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}")); + .content(CREATE_BODY)); + + // then + result.andExpect(status().isOk()); + } + + @Test + void worklogWriteWithAWrongDemoPasswordIsRefusedAsUnauthenticated() throws Exception { + // when + ResultActions result = + mvc.perform( + post("/worklogs") + .with(httpBasic("demo-admin", "not-the-password")) + .contentType(MediaType.APPLICATION_JSON) + .content(CREATE_BODY)); + + // then + result.andExpect(status().isUnauthorized()); + } + + @Test + void worklogReadIsOpenWithoutAuthorizationHeader() throws Exception { + // given + when(getUseCase.handle(any())).thenReturn(sample("demo")); + + // when + ResultActions result = mvc.perform(get("/worklogs/" + ID)); // then result.andExpect(status().isOk()); @@ -140,14 +180,14 @@ class SamplePublicAccessSecurityConfigTest { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class, - // The web roots are imported piecewise below; the security root is the JWT and method - // security this sample leaves out. + // The web roots are imported piecewise below; the security root is the JWT chain this + // sample replaces with its demo accounts. WebAdapterAutoConfiguration.class, WebSecurityAutoConfiguration.class }) @Import({ WorkLogController.class, - SamplePublicAccessSecurityConfig.class, + SampleDemoSecurityConfig.class, GlobalExceptionHandler.class, DomainExceptionHandler.class, EnvelopeBodyAdvice.class, diff --git a/src/shared-contract/README.md b/src/shared-contract/README.md index 47ea2e75..32855e7f 100644 --- a/src/shared-contract/README.md +++ b/src/shared-contract/README.md @@ -116,8 +116,10 @@ Spring/Lettuce 타입을 노출하지 않는다. **rate-limit / idempotency** - `RATE_LIMIT_EXCEEDED` 는 `retryable=true` 이며 Retry-After 헤더와 짝을 이룬다. -- `IDEMPOTENT_IN_FLIGHT`/`IDEMPOTENT_REQUEST_MISMATCH` 는 결정적인 클라이언트 결과(다시 - poll 하거나 본문을 고쳐야 함)라 `retryable=false`. +- `IDEMPOTENT_IN_FLIGHT` 는 `retryable=true`(Retry-After 2s): 결과 불명. 같은 `Idempotency-Key`로 + `Retry-After` 뒤 재전송. 새 키 금지. 같은 키 재전송은 서버가 재생·처리 중·불일치로 판정하므로 안전하다. +- `IDEMPOTENT_REQUEST_MISMATCH` 는 본문을 고쳐야 하는 클라이언트 버그라 `retryable=false`. + 두 코드의 클라이언트 행동은 `docs/web/http-contract.md` §2 가 정본이다. **ADAPTER_DISABLED — 어댑터 런타임 fail-fast** - 비활성(`app...enabled=false`, 기본값) 상태인 선택적 어댑터(Kafka/Redis/Slack/ @@ -246,6 +248,9 @@ Spring/Lettuce 타입을 노출하지 않는다. - **스켈레톤 공통 단일 아이템 응답 envelope.** 성공과 실패가 한 모양을 공유한다: 최상위 `success` 플래그, `data`(성공) 또는 `error`(실패) 필드, 그리고 request/trace/correlation id 를 담는 `meta`. `data`/`error` 중 정확히 하나만 non-null 이다. +- **wire 에서는 null 필드를 키째 생략한다**(`Envelope`·`BulkEnvelope`·`ApiError`·`ResponseMeta`). + 이 모듈은 Jackson 에 의존하지 않으므로 규칙은 web 어댑터의 `EnvelopeWireFormatConfig` mix-in 에 있다. + 키 목록은 `docs/web/http-contract.md` §1 이 정본이다. - **RFC 7807 ProblemDetail 을 대체한다**(boundary D5/D6). `meta` 객체는 예전의 평평한 `traceId` 필드를 대체하며, success/error 대칭은 유지하면서 요청 진단 정보를 더 풍부하게 담는다. @@ -430,6 +435,13 @@ Spring/Lettuce 타입을 노출하지 않는다. 으로 전파하기 전에 제거한다 — W3C Baggage spec §4.1 의 trust-boundary 규칙과 OTel Baggage API 의 "untrusted process" 제거 의무(D2)에 따른 것. +### ActiveTrace +- **tracer 가 지금 스레드에서 열어 둔 span 의 trace context 를 W3C 값(`TraceParent`)으로 돌려주는 seam.** + adapter-web 의 `WebMvcRequestIdFilter` 가 `meta.traceId`·로그 `trace_id` 를 정할 때 tracer 가 있으면 + 그 span 의 id 를 쓰게 하려고 둔다. 이게 없으면 필터가 자기 id 를 따로 만들어, export 된 span 과 + 응답·로그의 trace id 가 서로 다른 값이 된다(리뷰 07-01). +- **`NONE` 기본값:** tracer 가 없는 조립. 구현은 `composition:service-runtime` 의 `MicrometerActiveTrace`. + ### SpanErrorRecorder - **tracer 라이브러리에 결합하지 않고 span error 를 기록하기 위한 D12 seam.** adapter-web (`GlobalExceptionHandler`)·adapter-outbound 가 컴파일타임 tracer 의존 없이 span error 를 일관되게 diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java index b6c359d3..5bd8e8c6 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java @@ -44,7 +44,7 @@ public enum OperationalError implements ApiErrorCode { ROUTE_NOT_FOUND(Category.NOT_FOUND, 404, false), // rate-limit / idempotency RATE_LIMIT_EXCEEDED(Category.RATE_LIMIT, 429, true), - IDEMPOTENT_IN_FLIGHT(Category.CONFLICT, 409, false), + IDEMPOTENT_IN_FLIGHT(Category.CONFLICT, 409, true), IDEMPOTENT_REQUEST_MISMATCH(Category.VALIDATION, 422, false), IDEMPOTENCY_UNAVAILABLE(Category.TRANSIENT_DEPENDENCY, 503, true), IDEMPOTENCY_RECOVERY_REQUIRED(Category.DATA_INTEGRITY, 500, false), diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/Envelope.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/Envelope.java index fdd1bced..aab4595e 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/response/Envelope.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/response/Envelope.java @@ -4,7 +4,8 @@ package dev.caskeleton.shared.response; * Skeleton-wide single-item response envelope. Success and failure share one shape: a top-level * {@code success} flag, a {@code data} field (success) or an {@code error} field (failure), and a * {@code meta} object carrying request / trace / correlation ids. Exactly one of {@code data} / - * {@code error} is non-null. + * {@code error} is non-null, and the HTTP adapter leaves the {@code null} one off the wire ({@code + * docs/web/http-contract.md}). * *

      See the module README for why this replaces RFC 7807 ProblemDetail and how {@code meta} * replaced the earlier flat {@code traceId} field. diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/tracing/ActiveTrace.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/tracing/ActiveTrace.java new file mode 100644 index 00000000..a7c2444f --- /dev/null +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/tracing/ActiveTrace.java @@ -0,0 +1,25 @@ +package dev.caskeleton.shared.tracing; + +import java.util.Optional; + +/** + * The trace context of the span the tracer has active on the calling thread, as a W3C value. + * + *

      Exists so an inbound adapter that names a request's trace id (the web filter that writes + * {@code meta.traceId} and the {@code trace_id} log field) uses the tracer's id when there is a + * tracer, rather than minting a second one the exported spans never carry. Java standard library + * only; {@link #NONE} is what a composition without a tracer gets. + */ +@FunctionalInterface +public interface ActiveTrace { + + /** + * Returns the active span's trace context. + * + * @return the context, or empty when no tracer is wired or no span is active + */ + Optional current(); + + /** No tracer: there is never an active span. */ + ActiveTrace NONE = Optional::empty; +} diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/error/OperationalErrorTest.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/error/OperationalErrorTest.java index a1c15667..3de1a863 100644 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/error/OperationalErrorTest.java +++ b/src/shared-contract/src/test/java/dev/caskeleton/shared/error/OperationalErrorTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.shared.error; import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class OperationalErrorTest { @@ -228,13 +229,14 @@ class OperationalErrorTest { } @Test - void idempotentInFlightIs409ConflictNotRetryable() { - // D7 / error-codes.yaml#IDEMPOTENT_IN_FLIGHT — client polls for the in-flight result, not - // retries. + @DisplayName("처리 중 409는 같은 키로 다시 보내면 되므로 retryable이다") + void idempotentInFlightIs409ConflictRetryableWithTheSameKey() { + // docs/web/http-contract.md — the result is unknown and a resend with the same key is judged + // by the server (replay / in-flight / mismatch), so the resend is safe. assertThat(OperationalError.IDEMPOTENT_IN_FLIGHT.code()).isEqualTo("IDEMPOTENT_IN_FLIGHT"); assertThat(OperationalError.IDEMPOTENT_IN_FLIGHT.httpStatus()).isEqualTo(409); assertThat(OperationalError.IDEMPOTENT_IN_FLIGHT.category()).isEqualTo(Category.CONFLICT); - assertThat(OperationalError.IDEMPOTENT_IN_FLIGHT.retryable()).isFalse(); + assertThat(OperationalError.IDEMPOTENT_IN_FLIGHT.retryable()).isTrue(); } @Test From 1400dc15060ebe5f4675c592bce4c885e6e5cee1 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 19:52:06 +0900 Subject: [PATCH 02/17] =?UTF-8?q?feat!:=20=EB=82=A8=EC=9D=80=20=EB=A6=AC?= =?UTF-8?q?=EB=B7=B0=20=EB=B0=9C=EA=B2=AC=EC=9D=84=20=EA=B3=A0=EC=B9=98?= =?UTF-8?q?=EA=B3=A0=20=EA=B0=9C=EB=B0=9C=20=EB=A7=A4=EB=89=B4=EC=96=BC?= =?UTF-8?q?=EA=B3=BC=20=EA=B8=B0=EB=8A=A5=20=EC=83=9D=EC=84=B1=20=EB=AA=85?= =?UTF-8?q?=EB=A0=B9=EC=9D=84=20=EB=8D=94=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: High·P1을 고친 뒤에도 P2·P3 약 90건이 남았다. 연결·구독·메시지 크기 상한이 없는 전송(WebSocket·gRPC·GraphQL deadline), 낙관적 충돌의 500, upsert 경쟁, Mongo 무제한 timeout, 샘플 목록 N+1, 갈라진 복사본 (TenantId 3벌, 이벤트 ID 문법 5곳, SQLState 표 2벌), 문서를 읽는 PR 테스트와 캐시를 막는 lane 설정 등이다. 새 기능을 어디에 어떤 순서로 만드는지 알려 주는 문서와 도구가 없었다. MinIO 공식 이미지가 사라져 객체 저장소 lane이 돌지 않았다. 방법: 영역별 묶음으로 실패 테스트를 먼저 쓰고 고쳤다. 고치는 중에 찾은 결함도 함께 고쳤다(durable operation id가 UUIDv4라 이벤트가 전부 DEAD, S3 어댑터 생성·작은 chunk 읽기 실패, Redis 조건부 기록의 EVALSHA 권한). MinIO는 pgsty/minio를 digest로 고정했다(Chainguard는 태그·실행 사용자· mc 이미지 문제로 버림). docs/manual/에 작업 순서와 판단 지점을 쓰고, scripts/new-feature.sh가 5개 leaf에 뼈대를 만든다. 생성→빌드→통과 왕복을 verifyFeatureScaffold가 mainCheck에서 본다. 묶음별 결과와 결정은 리뷰 README 14절에 있다. 위험·한계: 파생 서비스 동작이 바뀐다. JDBC batch 50 기본, 운영 jar에서 H2 제거, 트랜잭션 30초 제한, 격리 수준을 Hikari에서 고정, gRPC· WebSocket·GraphQL 새 한도, correlation ID 규칙 밖이면 서버가 교체, 샘플 키 오류 코드 IDEMPOTENCY_KEY_INVALID. 새 leaf 두 개 (composition:durable-operation, adapter:inbound:messaging)와 새 마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1, grpc-ledger V002)이 생긴다. V21 유일 인덱스는 기존 중복이 있으면 실패한다(runbook에 확인 쿼리). 검증: ci, mainCheck(생성 명령 왕복 포함), integrationCheck(MinIO 포함 전 컨테이너 lane), -p optional-platforms ci integrationCheck 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 14절 BREAKING CHANGE: JDBC batch 기본 켜짐, H2 운영 의존 제거, 트랜잭션 기본 제한 30초, gRPC·WebSocket·GraphQL 서버 한도 기본값 추가, 샘플 Idempotency-Key 오류 코드 변경. --- .github/workflows/fileserver-nightly.yml | 4 - .github/workflows/fileserver-pr.yml | 5 - .github/workflows/integration-main.yml | 10 + .github/workflows/jpa-nightly.yml | 4 - .github/workflows/pr-adapters.yml | 7 - .github/workflows/release.yml | 2 - AGENTS.md | 28 +- CLAUDE.md | 23 +- docker-compose.dev.yml | 2 +- docker-compose.infra.yml | 24 +- docker-compose.local.yml | 2 +- docker-compose.prod-smoke.yml | 1 - docker-compose.yml | 20 +- docs/README.md | 1 + ...retry-ownership-and-durable-idempotency.md | 19 +- docs/architecture/graphql-api-surface.txt | 4 +- docs/architecture/jpa-api-surface.txt | 3 +- docs/httpclient/configuration-reference.md | 60 +++- docs/httpclient/env-fields.yaml | 22 +- docs/httpclient/retry-and-ambiguity.md | 36 +- docs/jpa/transaction-guide.md | 16 +- docs/manual/01-generator.md | 95 +++++ docs/manual/02-new-feature.md | 143 ++++++++ docs/manual/03-placement.md | 73 ++++ docs/manual/04-persistence.md | 126 +++++++ docs/manual/05-idempotency.md | 79 ++++ docs/manual/06-errors.md | 67 ++++ docs/manual/07-authorization.md | 74 ++++ docs/manual/08-testing.md | 80 +++++ docs/manual/09-outbox-events.md | 73 ++++ docs/manual/10-capabilities.md | 65 ++++ docs/manual/11-checklist.md | 67 ++++ docs/manual/README.md | 82 +++++ docs/manual/appendix-common-principles.md | 20 ++ docs/messaging/outbox-inbox.md | 5 + docs/mongodb/consumer-leaf-guide.md | 144 ++++++++ docs/registries/env-keys.yaml | 113 +++++- .../2026-11-01-maturity-review/README.md | 88 ++++- docs/runbooks/grpc-platform-operations.md | 30 +- docs/web/http-contract.md | 62 +++- docs/web/repository-adaptation.md | 5 +- docs/web/runbook.md | 6 + infra/minio/smoke/object-storage-smoke.sh | 5 +- .../Create__Feature__HttpRequest.java.tmpl | 12 + .../__Feature__Controller.java.tmpl | 69 ++++ .../__Feature__HttpResponse.java.tmpl | 17 + .../__Feature__ControllerTest.java.tmpl | 98 +++++ .../Uuid__Feature__IdFactory.java.tmpl | 20 ++ .../Uuid__Feature__IdFactoryTest.java.tmpl | 24 ++ .../__feature__/__Feature__Config.java.tmpl | 56 +++ .../__Feature__ConfigTest.java.tmpl | 52 +++ .../Create__Feature__Command.java.tmpl | 10 + .../Create__Feature__UseCase.java.tmpl | 63 ++++ .../__feature__/Get__Feature__Query.java.tmpl | 17 + .../Get__Feature__UseCase.java.tmpl | 45 +++ .../__Feature__ErrorCode.java.tmpl | 42 +++ .../__Feature__NotFoundException.java.tmpl | 25 ++ .../__Feature__RejectedException.java.tmpl | 29 ++ .../__feature__/__Feature__View.java.tmpl | 17 + .../Create__Feature__UseCaseTest.java.tmpl | 47 +++ .../Get__Feature__UseCaseTest.java.tmpl | 43 +++ .../domain/__feature__/__Feature__.java.tmpl | 68 ++++ .../__feature__/__Feature__Id.java.tmpl | 38 ++ .../__Feature__IdFactory.java.tmpl | 9 + .../__Feature__InvariantException.java.tmpl | 33 ++ .../__Feature__Repository.java.tmpl | 30 ++ .../__feature__/__Feature__IdTest.java.tmpl | 31 ++ .../__feature__/__Feature__Test.java.tmpl | 53 +++ ..._Feature__RepositoryContractTest.java.tmpl | 13 + .../InMemory__Feature__Repository.java.tmpl | 29 ++ .../Sequential__Feature__IdFactory.java.tmpl | 29 ++ .../__Feature__RepositoryContract.java.tmpl | 56 +++ scripts/new-feature.sh | 157 ++++++++ scripts/verify-feature-scaffold.sh | 88 +++++ scripts/verify-httpclient-docs.py | 5 +- src/.env.example | 13 +- src/Dockerfile | 6 +- src/Dockerfile.sample | 14 +- src/adapter/inbound/graphql/CLAUDE.md | 2 + src/adapter/inbound/graphql/README.md | 80 ++++- src/adapter/inbound/graphql/build.gradle | 2 - .../GraphQlExecutionChainConfiguration.java | 31 ++ .../GraphQlPlatformSettings.java | 10 +- .../GraphQlPlatformStartupValidator.java | 3 + .../graphql/context/GraphQlDeadline.java | 22 +- .../dataloader/GraphQlDataLoaderFactory.java | 12 +- .../GraphQlDataLoaderRequestRegistry.java | 64 ---- .../GraphQlRequestCancelledException.java | 9 +- .../execution/GraphQlTimeoutPolicy.java | 38 -- .../observation/GraphQlObservationNames.java | 7 + .../runtime/GraphQlBatchLoaderRegistrar.java | 14 +- .../GraphQlDeadlineInstrumentation.java | 61 ++++ .../GraphQlPerParentFetchInstrumentation.java | 150 ++++++++ ...raphQlPlatformContextMissingException.java | 52 +++ .../GraphQlPlatformInstrumentation.java | 3 +- .../GraphQlPlatformWebInterceptor.java | 26 +- .../src/main/resources/config/graphql.yml | 3 + .../example/OrderCustomerBatchLoading.java | 79 ++++ .../runtime/GraphQlPerParentFetchTest.java | 191 ++++++++++ ...hQlRequestDeadlineOnRequestThreadTest.java | 93 +++++ .../runtime/GraphQlRequestDeadlineTest.java | 118 ++++++ .../runtime/RuntimeLimitsTestSupport.java | 146 ++++++++ .../runtime-limits.graphqls | 28 ++ .../GraphQlPlatformStartupValidatorTest.java | 3 +- ...java => GraphQlDataLoaderFactoryTest.java} | 28 +- .../error/GraphQlWireErrorMapperTest.java | 4 +- .../execution/GraphQlTimeoutPolicyTest.java | 43 --- .../GraphQlBatchLoaderRegistrationTest.java | 53 +++ src/adapter/inbound/grpc/CLAUDE.md | 16 +- src/adapter/inbound/grpc/README.md | 80 ++++- src/adapter/inbound/grpc/build.gradle | 1 - .../inbound/grpc/GrpcCallAdmission.java | 120 +++++++ .../grpc/GrpcServerDeadlineInterceptor.java | 145 ++++++++ .../inbound/grpc/GrpcServerRunner.java | 133 ++++++- .../inbound/grpc/GrpcServerSettings.java | 213 +++++++++++ .../inbound/grpc/GrpcP1BoundaryWireTest.java | 206 ++++++++++- .../inbound/grpc/GrpcSafeActivationTest.java | 63 ++++ .../grpc/GrpcServerRunnerBootTest.java | 51 +++ src/adapter/inbound/messaging/CLAUDE.md | 12 + src/adapter/inbound/messaging/README.md | 87 +++++ src/adapter/inbound/messaging/build.gradle | 35 ++ src/adapter/inbound/messaging/gradle.lockfile | 152 ++++++++ .../MessagingInboxAutoConfiguration.java | 65 ++++ ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../MessagingInboxAutoConfigurationTest.java | 212 +++++++++++ src/adapter/inbound/web-advanced/README.md | 28 ++ src/adapter/inbound/web-advanced/build.gradle | 8 +- .../RouteInventoryMismatchException.java | 15 +- .../web/advanced/error/WebAdvancedError.java | 80 +++++ .../patch/JsonPatchRejectedException.java | 12 +- .../patch/JsonPatchTestFailedException.java | 19 +- .../patch/PatchAuthorizationException.java | 19 +- .../UntrustedTenantInputException.java | 15 +- .../encoding/StreamItemTooLargeException.java | 14 +- .../replay/ReplayCursorExpiredException.java | 15 +- .../versioning/SunsetViolationException.java | 14 +- .../UnsupportedApiVersionException.java | 15 +- .../AdmissionRefusedException.java | 12 +- .../error/WebAdvancedErrorMappingTest.java | 140 ++++++++ .../FileserverHttpSurfaceConfiguration.java | 31 +- .../FileserverCorsExposedHeadersTest.java | 28 ++ src/adapter/inbound/web/README.md | 63 +++- src/adapter/inbound/web/build.gradle | 13 +- src/adapter/inbound/web/gradle.lockfile | 1 + .../web/auth/AuthErrorResponseWriter.java | 14 +- .../inbound/web/auth/CorsExposedHeaders.java | 54 +++ .../inbound/web/auth/SecurityConfig.java | 17 +- .../web/envelope/EnvelopeBodyAdvice.java | 41 ++- .../envelope/EnvelopeWireFormatConfig.java | 5 + .../web/error/ClientSafeErrorDetails.java | 15 + .../error/ClientSafeValidationDetails.java | 11 + .../web/error/EnvelopeResponseWriter.java | 42 +++ .../web/error/GlobalExceptionHandler.java | 71 +++- .../inbound/web/error/WebTransportError.java | 55 +++ .../web/http/IdempotencyKeyHeader.java | 51 +++ .../http/InvalidIdempotencyKeyException.java | 48 +++ .../WebAdapterAutoConfiguration.java | 20 +- .../WebMvcPlatformAutoConfiguration.java | 4 +- .../web/mvc/filter/JsonBodyLimitFilter.java | 13 +- .../web/mvc/filter/WebMvcRequestIdFilter.java | 21 +- .../web/observability/RetryAfterAdvisor.java | 3 + .../web/observability/RetryAfterHint.java | 14 + .../operation/DurableOperationController.java | 17 +- .../web/ratelimit/RateLimitInterceptor.java | 9 +- .../web/settings/SecuritySettings.java | 20 +- .../CorsSecurityFilterIntegrationTest.java | 70 ++++ .../web/envelope/EnvelopeBodyAdviceTest.java | 60 ++++ .../web/error/TransportErrorHandlingTest.java | 42 +++ .../web/http/IdempotencyKeyHeaderTest.java | 113 ++++++ .../WebMvcPlatformAutoConfigurationTest.java | 60 ++++ .../mvc/filter/JsonBodyLimitFilterTest.java | 61 ++++ .../mvc/filter/WebMvcRequestIdFilterTest.java | 50 ++- .../DurableOperationControllerTest.java | 67 +++- .../ratelimit/RateLimitInterceptorTest.java | 60 ++++ .../web/settings/SecuritySettingsTest.java | 38 ++ .../testkit/fault/FaultFixtureController.java | 5 +- src/adapter/inbound/websocket/CLAUDE.md | 5 + src/adapter/inbound/websocket/README.md | 34 +- src/adapter/inbound/websocket/build.gradle | 4 - .../outbound/SerializedOutboundWriter.java | 12 +- .../servlet/PlatformWebSocketHandler.java | 94 ++++- .../websocket/stomp/StompConnectionLimit.java | 106 ++++++ .../websocket/stomp/WebSocketConfig.java | 26 ++ ...SocketInboundAuthorizationInterceptor.java | 58 ++- .../websocket/stomp/WebSocketSettings.java | 90 +++++ .../proxy/NginxWebSocketHarness.java | 3 +- .../runtime/TomcatWebSocketAbuseIT.java | 9 +- .../runtime/TomcatWebSocketShutdownIT.java | 44 +++ .../WebSocketBoundaryQualificationTest.java | 83 ++++- .../SerializedOutboundWriterTest.java | 48 +++ .../servlet/PlatformWebSocketHandlerTest.java | 83 +++++ .../stomp/StompConnectionLimitTest.java | 65 ++++ .../stomp/WebSocketAutoConfigurationTest.java | 34 ++ .../WebSocketEnvironmentBindingTest.java | 28 +- ...etInboundAuthorizationInterceptorTest.java | 85 +++++ .../stomp/WebSocketSettingsTest.java | 31 +- .../runtime/WebSocketFixtureApplication.java | 7 + src/adapter/outbound/cache-redis/CLAUDE.md | 15 +- src/adapter/outbound/cache-redis/README.md | 61 +++- src/adapter/outbound/cache-redis/build.gradle | 4 +- .../cache/redis/SemanticRedisCall.java | 77 +++- .../cache/redis/cache/CacheScripts.java | 57 ++- .../redis/cache/RedisCacheRegionAdapter.java | 148 ++++++-- .../capability/RedisCapabilityConfig.java | 5 +- .../cache/redis/capability/RedisKeys.java | 52 ++- .../RedisSemanticScriptAclProbe.java | 54 ++- .../RateLimitEvaluationDedupPolicy.java | 4 + .../redis/ratelimit/RateLimitPolicy.java | 4 +- .../ratelimit/RedisEdgeRateLimitAdapter.java | 22 +- .../config/module-defaults/cache-redis.yml | 10 + .../cache/redis/SemanticRedisCallTest.java | 105 ++++++ .../LiveRedisCacheRegionContractTest.java | 53 +++ .../cache/RedisCacheRegionAdapterTest.java | 5 +- .../cache/RedisCacheRegionContractTest.java | 43 +++ .../cache/redis/capability/RedisKeysTest.java | 33 ++ .../RedisReadinessGroupPostProcessorTest.java | 24 ++ .../RedisSemanticScriptAclProbeTest.java | 86 +++++ .../RedisIdempotencyStoreAdapterTest.java | 39 +- .../RedisIdempotencyStoreContractTest.java | 37 ++ .../RedisDistributedLeaseAdapterTest.java | 39 +- .../redis/ratelimit/RateLimitPolicyTest.java | 14 + .../RedisEdgeRateLimitAdapterTest.java | 48 +++ src/adapter/outbound/httpclient/README.md | 13 +- src/adapter/outbound/httpclient/build.gradle | 44 +-- .../PoolSaturationPerformanceTest.java | 2 - .../FailureInjectionContractTest.java | 81 ++++- .../httpclient/testkit/ToxiproxyFixture.java | 17 +- .../ApacheBlockingTransportProvider.java | 6 + .../apache/ApacheClientFactory.java | 1 + .../apache/SignallingRequestExecutor.java | 38 ++ .../HttpClientPlatformSettings.java | 23 +- .../HttpClientPlatformSettingsBinder.java | 9 +- .../HttpClientProfileFactory.java | 24 +- .../autoconfigure/ListElementKeyGuard.java | 111 ++++++ .../http3/JettyHttp3TransportProvider.java | 33 +- .../profile/CircuitBreakerSettings.java | 48 +++ .../profile/ClientObservabilitySettings.java | 13 +- .../httpclient/profile/ClientProfile.java | 2 + .../profile/ClientProfileValidator.java | 81 +++++ .../httpclient/profile/PoolSettings.java | 9 +- .../httpclient/profile/ProxySettings.java | 9 +- .../httpclient/profile/TimeoutSettings.java | 11 +- .../DefaultRetryEligibilityEngine.java | 27 +- .../resilience/ResilienceRegistry.java | 27 +- .../restclient/BlockingAttemptExecutor.java | 92 ++++- .../restclient/BlockingClientRuntime.java | 8 + .../restclient/BlockingStreamingGateway.java | 16 +- .../restclient/DefaultGenericHttpGateway.java | 15 +- .../restclient/RestClientRuntimeFactory.java | 37 +- .../transport/BlockingTransportProvider.java | 9 + .../transport/RequestWriteSignal.java | 55 +++ .../apache/ApachePoolSaturationTest.java | 2 - .../HttpClientAutoConfigurationTest.java | 72 ++++ .../HttpClientPlatformSettingsTest.java | 3 +- .../http3/JettyAttemptDeadlineTest.java | 67 ++++ .../profile/ClientProfileValidatorTest.java | 138 +++++++ .../RetryEligibilityEngineTest.java | 42 +++ .../AttemptDeadlineEnforcementTest.java | 2 - .../BlockingStreamingLifecycleTest.java | 2 - .../CircuitBreakerStatusAccountingTest.java | 90 +++++ .../DefaultGenericHttpGatewayTest.java | 2 - .../ExecutionEvidenceGatewayTest.java | 304 ++++++++++++++++ .../restclient/RetryBudgetAssignmentTest.java | 58 +++ .../StreamingSetupDeadlineTest.java | 93 +++++ .../restclient/UnauthorizedRefreshTest.java | 108 ++++++ .../testkit/ForwardProxyContractTest.java | 2 - .../httpclient/testkit/ClientProfiles.java | 16 +- .../httpclient/testkit/MockHttpServer.java | 15 + .../testkit/ResourceLifecycleContract.java | 2 - src/adapter/outbound/identifier/CLAUDE.md | 20 +- src/adapter/outbound/identifier/README.md | 73 ++-- src/adapter/outbound/identifier/build.gradle | 5 + .../outbound/identifier/gradle.lockfile | 3 +- .../UuidV7DurableOperationIdFactory.java | 18 + .../outbound/identifier/package-info.java | 4 +- .../HmacUserPrincipalPseudonymizerTest.java | 34 ++ .../UuidV7DurableOperationIdFactoryTest.java | 28 ++ .../outbound/messaging-kafka/README.md | 19 + .../outbound/messaging-kafka/build.gradle | 45 +++ .../outbound/messaging-kafka/gradle.lockfile | 240 +++++++------ .../ApplicationRelayKafkaIntegrationTest.java | 336 ++++++++++++++++++ src/adapter/outbound/messaging/README.md | 8 + ...latformIntegrationEventPublishAdapter.java | 33 +- ...ormIntegrationEventPublishAdapterTest.java | 31 ++ src/adapter/outbound/objectstorage/README.md | 37 +- .../outbound/objectstorage/build.gradle | 16 +- .../MinioManagedObjectContractTest.java | 276 +++++++------- .../qualification/QualificationImages.java | 4 +- ...ioS3ManagedObjectProviderContractTest.java | 141 ++++++++ .../s3/SelfSignedServerCertificate.java | 115 ++++++ .../s3/S3AsyncClientFactory.java | 5 + .../s3/S3AsyncRequestBodyBridge.java | 30 +- .../s3/S3AsyncResponseBodyBridge.java | 13 +- .../S3ObjectStorageProviderContribution.java | 8 +- .../objectstorage/s3/S3ProviderBinding.java | 27 +- .../s3/S3ProviderErrorMapper.java | 6 +- .../objectstorage/s3/S3ProviderType.java | 37 +- .../objectstorage/s3/S3ProviderVersion.java | 4 +- .../ComposeMinioImageMatchesEvidenceTest.java | 40 +++ .../s3/S3AsyncRequestBodyBridgeTest.java | 75 ++++ .../s3/S3AsyncResponseBodyBridgeTest.java | 69 +++- .../s3/S3ProviderBindingTest.java | 67 ++++ .../s3/S3ProviderErrorMapperTest.java | 41 +++ .../minio-provider-evidence.json | 32 +- .../outbound/persistence-fileserver/CLAUDE.md | 47 +++ .../persistence-fileserver/build.gradle | 4 + .../persistence-fileserver/gradle.lockfile | 2 +- .../fileserver/JpaCleanupQueue.java | 135 ++++--- .../fileserver/entity/AssignedIdEntity.java | 42 +++ .../fileserver/entity/CleanupItemEntity.java | 7 +- .../fileserver/entity/FileEntity.java | 7 +- .../entity/QuotaReservationEntity.java | 7 +- .../fileserver/entity/RecoveryItemEntity.java | 7 +- .../entity/UploadSessionEntity.java | 7 +- .../entity/VerificationResultEntity.java | 7 +- .../repository/CleanupClaimSql.java | 56 +++ .../FileserverCleanupRepository.java | 44 +-- .../entity/AssignedIdEntityTest.java | 131 +++++++ .../outbound/persistence-jpa/CLAUDE.md | 37 +- .../outbound/persistence-jpa/README.md | 10 +- .../outbound/persistence-jpa/build.gradle | 25 +- .../outbound/persistence-jpa/gradle.lockfile | 2 +- .../api/error/FailureCategory.java | 43 ++- .../api/error/JpaPersistenceException.java | 24 +- .../autoconfigure/JpaAdapterBeansConfig.java | 14 +- .../database/TenantDataSourceRegistry.java | 2 +- .../rls/RlsTenantSessionBinder.java | 2 +- .../SchemaMultiTenantConnectionProvider.java | 2 +- .../SchemaTenantMigrationOrchestrator.java | 2 +- .../schema/SchemaTenantRegistry.java | 2 +- .../schema/TenantMigrationStatus.java | 2 +- .../experimental/tenant/TenantContext.java | 1 + .../experimental/tenant/TenantId.java | 29 -- .../PersistenceExceptionTranslator.java | 35 +- .../failure/StandardSqlStateErrorMapping.java | 7 + .../outbox/jpa/JpaOutboxStore.java | 53 ++- .../outbox/jpa/OutboxEventJpaRepository.java | 80 +++++ .../entity/OutboxAggregateSequenceEntity.java | 66 ++++ .../outbox/jpa/entity/OutboxEventEntity.java | 15 + .../PostgreSqlSqlStateErrorMapping.java | 84 ++++- .../postgresql/error/PostgreSqlState.java | 3 +- .../HikariPoolConstraintValidator.java | 19 + .../startup/JpaStartupAutoConfiguration.java | 47 ++- .../transaction/SpringTransaction.java | 83 ++++- .../module-defaults/persistence-jpa.yml | 31 +- ...0__outbox_event_deferred_attempt_count.sql | 17 + .../V21__outbox_aggregate_sequence.sql | 27 ++ .../notification/NotificationFixtures.java | 3 +- .../notification/NotificationJpaStack.java | 108 ++++++ ...PostgreSqlPreferenceStoreContractTest.java | 57 +++ ...ostgreSqlSuppressionStoreContractTest.java | 57 +++ .../SuppressionTargetUniqueMigrationTest.java | 108 ++++++ .../RecipientExpiryVersionContractTest.java | 103 ++++++ .../InboxBulkReadVersionContractTest.java | 99 ++++++ .../JpaLifecycleAssociationContractTest.java | 1 + .../experimental/RlsIsolationFailureTest.java | 2 +- .../SchemaTenantMigrationContractTest.java | 2 +- .../TenantColumnIsolationTest.java | 2 +- .../TenantPoolCapacityContractTest.java | 2 +- ...tgreSqlDistributedLockIntegrationTest.java | 34 ++ ...ileserverMetadataStoreIntegrationTest.java | 17 +- ...lFileserverReclamationIntegrationTest.java | 159 +++++---- .../PostgreSqlMigrationIntegrationTest.java | 2 +- .../PostgreSqlOptionalStreamLifecycle.java | 4 +- ...utboxAggregateSequenceIntegrationTest.java | 111 ++++++ .../readiness/PostgreSqlReadinessSupport.java | 3 +- .../PostgreSqlTransactionIntegrationTest.java | 170 +++++++++ .../JpaPersistenceExceptionCodeTest.java | 2 +- .../ExperimentalFailClosedTest.java | 2 +- .../PersistenceExceptionTranslatorTest.java | 33 ++ .../batch/ModuleDefaultJdbcBatchingTest.java | 44 +++ .../PostgreSqlSqlStateErrorMappingTest.java | 11 +- .../SqlStateClassificationParityTest.java | 68 ++++ .../HikariPoolConstraintValidatorTest.java | 34 ++ .../JpaStartupAutoConfigurationTest.java | 41 +++ .../JpaVersionedBulkUpdateRuleTest.java | 91 +++++ .../arch/JpaArchitectureRulesTest.java | 5 + .../postgresql/PostgreSqlVersionTest.java | 11 +- .../transaction/SpringTransactionTest.java | 147 ++++++-- .../resources/db/applied-migrations.sha256 | 3 + .../arch/JpaVersionedBulkUpdateRule.java | 182 ++++++++++ .../testkit/postgresql/PostgreSqlVersion.java | 32 +- .../outbound/persistence-mongo/CLAUDE.md | 8 +- .../outbound/persistence-mongo/README.md | 14 +- .../outbound/persistence-mongo/build.gradle | 43 ++- ...rofileClientSettingsAutoConfiguration.java | 35 ++ .../client/MongoUriOnlyClientDefaults.java | 64 ++++ .../SpringMongoTransactionSessionFactory.java | 13 +- .../MongoTransactionRetryCoordinator.java | 26 +- .../src/main/resources/config/mongo.yml | 10 +- ...MongoTransactionWriteConflictLaneTest.java | 126 +++++++ .../failover/MongoProxiedReplicaSetNode.java | 4 +- .../failover/MongoThreeNodeReplicaSet.java | 4 +- .../ToxiproxyMongoNetworkFaultController.java | 3 +- ...MongoAuthenticatedReplicaSetContainer.java | 4 +- .../rs/MongoSingleReplicaSetContainer.java | 5 +- .../rs/MongoTlsReplicaSetContainer.java | 3 +- ...leClientSettingsAutoConfigurationTest.java | 26 +- .../MongoUriOnlyClientDefaultsTest.java | 97 +++++ .../mongo/example/MongoNoteStore.java | 40 +++ .../example/MongoNoteStoreExampleTest.java | 133 +++++++ .../adapter/outbound/mongo/example/Note.java | 17 + .../outbound/mongo/example/NoteDocument.java | 23 ++ .../mongo/example/NoteDocumentMapper.java | 16 + .../mongo/example/NoteDocumentRepository.java | 74 ++++ .../outbound/mongo/example/NoteStore.java | 31 ++ .../outbound/mongo/example/package-info.java | 27 ++ ...oTransactionBodyTranslatedFailureTest.java | 97 +++++ .../MongoTransactionRetryCoordinatorTest.java | 38 ++ .../persistence-notification/CLAUDE.md | 40 +++ .../persistence-notification/gradle.lockfile | 1 - .../platform/JpaPolicyStores.java | 72 ++-- .../platform/JpaSuppressionStore.java | 79 ++-- .../platform/PreferenceJpaRepository.java | 32 ++ .../platform/RecipientClaimSql.java | 2 + .../RecipientDeliveryJpaRepository.java | 4 +- .../platform/SuppressionJpaRepository.java | 34 ++ .../inbox/InboxItemJpaRepository.java | 9 +- ...notification_suppression_target_unique.sql | 39 ++ .../config/RedisHealthContributor.java | 7 +- .../RedisLaneUnavailableException.java | 27 +- .../runtime/connection/RedisRuntimeOwner.java | 52 ++- .../config/RedisHealthContributorTest.java | 35 ++ .../connection/RedisRuntimeOwnerTest.java | 50 +++ .../InMemorySemanticRedisCommands.java | 53 ++- src/adapter/outbound/support/build.gradle | 1 + .../JsonIntegrationEventEncoder.java | 27 +- ...oduleDefaultsEnvironmentPostProcessor.java | 53 ++- .../support/startup/StartupOrder.java | 9 +- .../outbound/support/startup/StartupRule.java | 18 +- ...onIntegrationEventEncoderContractTest.java | 15 + .../JsonIntegrationEventEncoderTest.java | 35 +- ...eDefaultsEnvironmentPostProcessorTest.java | 60 ++++ src/app-bootstrap/CLAUDE.md | 17 +- src/app-bootstrap/README.md | 65 ++-- src/app-bootstrap/build.gradle | 111 +++++- src/app-bootstrap/gradle.lockfile | 12 +- .../ApplicationBoundaryArchitectureTest.java | 21 ++ .../ArchRuleDiscoveryContractTest.java | 1 + .../DomainFeatureOnboardingContractTest.java | 66 +++- .../ForbiddenApiArchitectureTest.java | 4 - .../JpaProductionArchitectureTest.java | 14 + .../architecture/NamingConventionTest.java | 14 +- .../RequiresPermissionProxyabilityTest.java | 86 +++-- .../integration/PostgreSqlTestContainer.java | 2 +- .../FileserverCompositionIntegrationTest.java | 14 +- ...leOperationCompositionIntegrationTest.java | 14 +- .../bootstrap/CaSkeletonApplication.java | 15 +- .../bootstrap/async/AsyncExecutorConfig.java | 18 +- .../async/AsyncExecutorSettings.java | 23 +- .../logging/LoggingConfigurationRule.java | 116 ++++++ .../RuntimeEnvironmentProfileValidator.java | 4 +- .../runtime/RuntimeSafetyConfig.java | 21 +- .../bootstrap/runtime/SecretSourceConfig.java | 28 +- .../runtime/SecretSourceFactory.java | 11 + .../runtime/SecretSourceSettings.java | 20 +- .../runtime/SecretSourceValidator.java | 92 +++-- .../runtime/StartupSafetyValidator.java | 61 ++-- .../bootstrap/settings/BootstrapSettings.java | 41 ++- .../settings/BootstrapSettingsConfig.java | 18 + .../bootstrap/settings/LoggingSettings.java | 84 ----- .../settings/RuntimeSafetySettings.java | 33 +- ...ot.autoconfigure.AutoConfiguration.imports | 1 - .../src/main/resources/application-local.yml | 35 +- .../src/main/resources/application-prod.yml | 2 +- .../src/main/resources/config/runtime.yml | 6 +- .../src/main/resources/config/security.yml | 37 +- .../src/main/resources/config/server.yml | 8 +- .../src/main/resources/logback-spring.xml | 41 ++- .../DefaultCompositionBootTest.java | 5 +- .../LoggingSettingsSourceSystemTest.java | 64 ++++ .../async/AsyncExecutorSettingsTest.java | 17 + .../jpa/LocalJpaVendorParityTest.java | 16 +- .../PortResolutionContractTest.java | 16 +- .../BackgroundJobErrorCodeContractTest.java | 2 + ...lityAutoConfigurationReachabilityTest.java | 4 +- .../BusinessRuleValidationContractTest.java | 19 +- .../CapabilityStatusDocumentTest.java | 14 +- .../ConfigurationNamespaceContractTest.java | 17 +- .../ContainerRuntimeOomContractTest.java | 15 +- .../ContractRegistrySchemaGovernanceTest.java | 2 + .../DeveloperExperienceContractTest.java | 160 ++++++++- .../DistributedTracingContractTest.java | 15 +- .../EnvProfileMatrixContractTest.java | 2 + .../ErrorCodeRegistryMappingTest.java | 2 + .../HeaderRegistryRuntimeAlignmentTest.java | 2 + ...tionTimeoutClassificationContractTest.java | 11 +- ...LockFailureClassificationContractTest.java | 7 +- ...anagementActuatorSecurityContractTest.java | 20 +- .../contract/MetricsAlertingContractTest.java | 51 ++- .../OperationalErrorRegistryContractTest.java | 14 +- ...PersistenceFailureMappingContractTest.java | 7 +- .../PiiTokenBodyForbiddenContractTest.java | 2 + .../ProfileSeparationContractTest.java | 16 +- ...epositoryAccessCapabilityRegistryTest.java | 7 +- .../contract/RunbookCoverageContractTest.java | 2 + .../SampleRuntimeDefaultsContractTest.java | 108 ++++++ .../SecretsClassificationRegistryTest.java | 2 + .../SqlLoggingForbiddenContractTest.java | 2 + .../StructuredLogFieldContractTest.java | 28 +- .../GraphQlResolverReachabilityTest.java | 16 +- .../MessagingAuthorityContractTest.java | 16 +- .../MessagingPublicSurfaceContractTest.java | 16 +- .../OutboxStatusRegistryContractTest.java | 2 + .../support/RepositoryContractResources.java | 15 +- .../RepositoryContractResourcesTest.java | 2 + .../logging/LoggingConfigurationRuleTest.java | 91 +++++ .../MongoRegistryPermissionParityTest.java | 17 +- .../ReleaseManifestTaskExistenceTest.java | 16 +- .../runtime/SecretSourceValidatorTest.java | 71 +++- .../runtime/StartupSafetyValidatorTest.java | 51 ++- .../startup/StartupOrderContractTest.java | 5 +- .../PublicHealthPathAgreementTest.java | 17 +- .../settings/BootstrapSettingsTest.java | 25 +- .../settings/LoggingSettingsTest.java | 132 ------- .../FeatureAggregateRepositoryAdapter.java | 4 +- .../port/FeatureAggregateWritePort.java | 8 - .../CreateFeatureAggregateUseCase.java | 12 +- .../domain/feature/FeatureAggregateId.java | 3 +- .../feature/FeatureAggregateIdFactory.java | 8 +- .../feature/FeatureAggregateRepository.java | 11 + src/application-core/CLAUDE.md | 35 +- src/application-core/README.md | 51 ++- src/application-core/build.gradle | 5 +- .../cache/CacheRecordMetadata.java | 18 +- .../application/cache/CacheRegionPort.java | 15 + .../cache/CacheSourceRevisionOrder.java | 69 ++++ .../messaging/event/AggregateIdentity.java | 5 +- .../messaging/event/AggregateOrder.java | 22 +- .../application/messaging/event/EventId.java | 13 +- .../event/IntegrationEventDraft.java | 12 +- .../event/IntegrationEventDrafts.java | 80 +++++ .../messaging/event/IntegrationIdentity.java | 57 +++ .../event/ValidatedIntegrationEvent.java | 7 +- .../operation/DurableOperationIdFactory.java | 21 ++ .../SubmitDurableOperationUseCase.java | 27 +- .../outbox/ClaimedOutboxEvent.java | 33 +- .../outbox/OutboxAggregateSequencePort.java | 39 ++ .../application/outbox/OutboxRelayResult.java | 17 +- .../application/outbox/OutboxStorePort.java | 32 +- .../PublishPendingOutboxEventsCommand.java | 24 +- .../PublishPendingOutboxEventsUseCase.java | 77 +++- .../application/security/SystemInvoked.java | 29 ++ .../application/tenant/TenantId.java | 8 +- .../cache/CacheSourceRevisionOrderTest.java | 77 ++++ ...ractTest.java => CacheValueTypesTest.java} | 2 +- .../InMemoryCacheRegionContractTest.java | 13 + ...st.java => IdempotencyValueTypesTest.java} | 2 +- .../InMemoryIdempotencyStoreContractTest.java | 13 + .../lock/DistributedLockPortContractTest.java | 65 +--- .../InMemoryDistributedLockContractTest.java | 19 + ...egrationEventContractContributionTest.java | 4 +- .../event/IntegrationEventDraftsTest.java | 110 ++++++ .../event/IntegrationIdentityTest.java | 90 +++++ ...keIntegrationEventEncoderContractTest.java | 14 + .../SubmitDurableOperationUseCaseTest.java | 3 +- .../StoppingRelayReleasesItsClaimsTest.java | 98 +++++ .../TransientPublishFailureRelayTest.java | 53 +++ ...ryOutboxAggregateSequenceContractTest.java | 20 ++ .../application/tenant/TenantIdTest.java | 17 +- .../cache/testkit/CacheRegionContract.java | 315 ++++++++++++++++ .../cache/testkit/InMemoryCacheRegion.java | 212 +++++++++++ .../testkit/IdempotencyStoreContract.java | 274 ++++++++++++++ .../testkit/InMemoryIdempotencyStore.java | 27 +- .../lock/testkit/DistributedLockContract.java | 82 +++++ .../lock/testkit/InMemoryDistributedLock.java | 65 ++++ .../testkit/EncoderContractKitContract.java | 95 +++++ .../testkit/FakeIntegrationEventEncoder.java | 52 ++- .../IntegrationEventEncoderContract.java | 146 ++++++++ .../InMemoryOutboxAggregateSequences.java | 17 + .../outbox/testkit/InMemoryOutboxStore.java | 41 ++- .../OutboxAggregateSequenceContract.java | 59 +++ .../testkit/OutboxLeaseFencingContract.java | 75 ++++ .../testkit.encoder-contract/v1.schema.json | 11 + src/application-fileserver/build.gradle | 9 + src/application-fileserver/gradle.lockfile | 54 +-- .../fileserver/cleanup/CleanupItem.java | 15 +- .../fileserver/cleanup/CleanupQueuePort.java | 38 +- .../cleanup/DefaultCleanupService.java | 43 ++- .../observability/SafeFileFingerprint.java | 21 +- .../admin/FileserverAdminUseCasesTest.java | 5 +- .../cleanup/CleanupServiceTest.java | 57 +++ .../lifecycle/FileLifecycleUseCasesTest.java | 5 +- .../SafeFileFingerprintTest.java | 29 ++ .../testkit/InMemoryCleanupQueue.java | 77 ---- .../InMemoryCleanupQueueContractTest.java | 19 + ...InMemoryFileMetadataStoreContractTest.java | 13 + .../upload/ResumableUploadUseCasesTest.java | 2 +- .../testkit/CleanupQueuePortContract.java | 241 +++++++++++++ .../testkit/FileMetadataPortContract.java | 157 ++++++++ .../testkit/InMemoryCleanupQueue.java | 191 ++++++++++ .../testkit/InMemoryFileMetadataStore.java | 8 +- src/application-notification/build.gradle | 7 + src/application-notification/gradle.lockfile | 54 +-- .../notification/platform/api/TenantId.java | 15 +- .../testkit/InMemoryPreferenceStoreTest.java | 26 ++ .../testkit/InMemorySuppressionStoreTest.java | 26 ++ .../testkit/InMemoryPreferenceStore.java | 35 ++ .../testkit/InMemorySuppressionStore.java | 77 ++++ .../policy/testkit/OverlappingWrites.java | 93 +++++ .../testkit/PreferenceStoreContract.java | 107 ++++++ .../testkit/SuppressionStoreContract.java | 190 ++++++++++ .../caskeleton/buildlogic/ModuleRegistry.java | 71 ++++ .../architecture/ArchitecturePlugin.java | 7 + ...rifyCleanArchitectureDependenciesTask.java | 17 + .../config/ConfigContractPlugin.java | 13 + .../config/EnvContractVerifier.java | 65 ++++ .../buildlogic/config/VerifyEnvKeysTask.java | 7 +- .../java/JavaConventionsPlugin.java | 64 +++- .../quality/QualityConventionsPlugin.java | 13 + .../strictlane/StrictLaneStagesPlugin.java | 27 +- .../strictlane/StrictTestLanePlugin.java | 46 ++- .../strictlane/WorkflowGradleInvocations.java | 47 +++ .../buildlogic/ModuleRegistryTest.java | 27 ++ ...ectureResolvedClasspathFunctionalTest.java | 17 + .../config/EnvContractVerifierTest.java | 79 ++++ .../PlatformModuleConventionTest.java | 4 + .../StrictLaneStagesFunctionalTest.java | 26 ++ .../StrictTestLaneConventionTest.java | 77 ++++ .../WorkflowGradleInvocationsTest.java | 52 +++ src/build.gradle | 22 +- src/composition/durable-operation/README.md | 26 ++ .../durable-operation/build.gradle | 22 ++ .../durable-operation/gradle.lockfile | 182 ++++++++++ .../DurableOperationAutoConfiguration.java} | 29 +- ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../module-defaults/durable-operation.yml | 10 + .../operation/DurableOperationModuleTest.java | 58 +++ .../fileserver-platform/build.gradle | 8 +- .../fileserver-platform/gradle.lockfile | 1 - .../config/module-defaults/fileserver.yml | 13 + src/composition/idempotency/gradle.lockfile | 1 - .../notification-platform/gradle.lockfile | 1 - .../config/module-defaults/notification.yml | 10 + src/composition/outbox-relay/README.md | 60 ++-- src/composition/outbox-relay/build.gradle | 6 + .../composition/outbox/OutboxMetrics.java | 29 +- .../outbox/OutboxRelayAutoConfiguration.java | 28 +- .../outbox/OutboxRelayOffWarning.java | 32 ++ .../outbox/OutboxRelayScheduler.java | 78 ++-- .../composition/outbox/OutboxMetricsTest.java | 165 +++++++++ .../outbox/OutboxRelaySchedulerDrainTest.java | 198 +++++++++++ .../OutboxRelaySchedulerLoggingTest.java | 6 +- .../outbox/OutboxRelayShutdownOrderTest.java | 91 ++++- src/composition/service-runtime/README.md | 15 +- src/composition/service-runtime/build.gradle | 8 +- .../service-runtime/gradle.lockfile | 9 +- .../PermissionEnforcementConfig.java | 25 ++ .../PermissionEnforcementGuard.java | 69 ++++ .../TracingEnvironmentPostProcessor.java | 2 +- ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../ServiceRuntimeRegistrationTest.java | 6 +- .../PermissionEnforcementGuardTest.java | 69 ++++ src/config/architecture/modules.json | 27 +- .../testing/container-images.properties | 41 +++ src/domain-core/build.gradle | 6 + src/domain-core/gradle.lockfile | 54 +-- src/gradle/libs.versions.toml | 10 +- src/grpc/CLAUDE.md | 59 ++- .../grpc/api/ledger/GrpcOperationLedger.java | 21 ++ .../ledger/GrpcOperationLedgerContract.java | 104 +++++- .../api/ledger/InMemoryOperationLedger.java | 29 +- .../ledger/GrpcOperationLedgerMigrations.java | 37 ++ .../ledger/GrpcOperationLedgerPostgresIT.java | 14 +- .../JpaGrpcOperationLedgerContractIT.java | 21 +- .../ledger/GrpcOperationLedgerRepository.java | 33 ++ .../grpc/ledger/JpaGrpcOperationLedger.java | 11 + ...ex_grpc_operation_ledger_finished_rows.sql | 16 + .../GrpcOperationLedgerRepositoryTest.java | 6 + .../GrpcOperationLedgerRetention.java | 80 +++++ .../GrpcOperationLedgerRetentionTest.java | 83 +++++ .../grpc-spring-boot-starter/build.gradle | 2 + .../boot/GrpcPlatformAutoConfiguration.java | 88 +++++ .../grpc/boot/GrpcPlatformProperties.java | 42 ++- .../boot/GrpcPlatformStartupValidator.java | 4 +- ...cPlatformAutoConfigurationContextTest.java | 187 +++++++++- src/messaging/messaging-kafka/build.gradle | 4 +- .../kafka/KafkaAmbiguityChaosIT.java | 4 +- .../kafka/KafkaBrokerCertificationIT.java | 5 +- .../messaging/kafka/KafkaBrokerIT.java | 4 +- .../kafka/KafkaContainerFixture.java | 2 +- .../messaging/inbox/InboxPostgresIT.java | 2 +- .../AdminOperationJournalPostgresIT.java | 2 +- .../messaging/outbox/OutboxPostgresIT.java | 2 +- ...essagingKafkaConsumeQualificationTest.java | 5 +- ...ssagingLiveRoundTripQualificationTest.java | 3 +- ...ssagingSecuredBrokerQualificationTest.java | 2 +- ...MessagingReliabilityAutoConfiguration.java | 22 ++ .../MessagingShutdownLifecycle.java | 19 +- .../MessagingInboxAssemblyTest.java | 68 ++++ src/optional-platforms/gradle.properties | 9 + src/optional-platforms/settings.gradle | 15 + src/sample-portfolio/README.md | 117 ++++-- src/sample-portfolio/build.gradle | 3 - src/sample-portfolio/gradle.lockfile | 16 +- ...osterRepositoryAdapterIntegrationTest.java | 36 ++ .../WorkLogRepositoryAdapterContractTest.java | 14 +- ...reatePosterConcurrencyIntegrationTest.java | 7 +- ...osterImageRetirementQualificationTest.java | 3 +- ...sterImageV8MigrationQualificationTest.java | 3 +- .../web/controller/OperationsController.java | 7 +- .../PosterImagePublicationController.java | 18 +- .../web/controller/WorkLogController.java | 18 +- .../web/error/DomainExceptionHandler.java | 21 +- .../inbound/web/error/PortfolioErrorCode.java | 5 +- .../inbound/web/mapper/WorkLogWebMapper.java | 9 +- .../inbound/web}/operation/Operation.java | 2 +- .../web}/operation/OperationStatus.java | 2 +- .../SampleOperationNotFoundException.java | 23 ++ .../web/operation/SampleOperationStore.java | 1 - .../identifier/UuidOutboxEventIdFactory.java | 8 +- .../persistence/entity/WorkLogEntity.java | 35 ++ .../mapper/WorkLogPersistenceMapper.java | 14 + .../repository/WorkLogJpaRepository.java | 29 +- .../repository/WorkLogRepositoryAdapter.java | 71 ++-- .../WorkLogSummaryQueryAdapter.java | 41 ++- .../repository/WorkLogSummaryRow.java | 16 +- .../event/OutboxEventIdFactory.java | 17 + .../event/PortfolioEventOutbox.java | 63 ++-- .../poster/UpdatePosterUseCase.java | 6 + .../worklog/ListWorkLogsUseCase.java | 18 +- .../worklog/UpdateWorkLogCommand.java | 3 + .../worklog/UpdateWorkLogUseCase.java | 14 + .../worklog/WorkLogNotOwnedException.java | 17 + .../WorkLogReservedContractContribution.java | 2 +- .../application/worklog/WorkLogSummary.java | 8 +- .../worklog/WorkLogSummaryPage.java | 14 + .../worklog/WorkLogSummaryQueryPort.java | 18 +- .../SampleApplicationUseCaseConfig.java | 12 +- .../domain/worklog/OutboxEventIdFactory.java | 16 - .../portfolio/domain/worklog/WorkLog.java | 5 + .../portfolio/domain/worklog/WorkLogPage.java | 14 - .../domain/worklog/WorkLogRepository.java | 14 +- .../src/main/resources/application.yml | 115 ++---- .../inbound/web/SampleApiDocsSystemTest.java | 57 +++ .../persistence/InsertRoundTripCounter.java | 119 +++++++ .../RecordingStatementInspector.java | 36 ++ .../WorkLogStatementCostSystemTest.java | 200 +++++++++++ .../SampleWorkLogAuthorizationSystemTest.java | 44 +++ .../OperationsControllerWireTest.java | 12 + .../controller/PosterControllerWireTest.java | 21 ++ ...terImagePublicationControllerWireTest.java | 39 +- .../controller/WorkLogControllerWireTest.java | 72 +++- .../web/error/DomainExceptionHandlerTest.java | 28 ++ .../inbound/web}/operation/OperationTest.java | 2 +- .../WorkLogRepositoryAdapterTest.java | 69 ++-- .../WorkLogSummaryQueryAdapterTest.java | 70 +++- .../CommandSelfValidationTest.java | 8 +- .../event/PortfolioEventOutboxTest.java | 52 ++- .../poster/PosterEventPublisherTest.java | 16 +- .../PosterImageAbortReconcileRaceTest.java | 8 +- .../PosterImagePublicationWorkflowTest.java | 8 +- .../worklog/CreateWorkLogOutboxTest.java | 7 +- ...ListRecentWorkLogSummariesUseCaseTest.java | 84 +++-- ...rkLogReservedContractContributionTest.java | 2 +- .../worklog/WorkLogUseCasesTest.java | 52 ++- .../WorkLogAuthorizationContractTest.java | 9 +- ...InMemoryWorkLogRepositoryContractTest.java | 8 + .../testkit/InMemoryWorkLogSummaryQuery.java | 72 ++++ .../testkit/InMemoryWorkLogRepository.java | 40 +-- .../testkit/WorkLogRepositoryContract.java | 86 +++-- .../testinfra/PostgreSqlTestContainer.java | 2 +- src/shared-contract/CLAUDE.md | 7 +- src/shared-contract/README.md | 22 +- src/shared-contract/build.gradle | 1 - .../dev/caskeleton/shared/annotation/.gitkeep | 1 - .../dev/caskeleton/shared/headers/.gitkeep | 1 - .../dev/caskeleton/shared/registry/.gitkeep | 1 - 768 files changed, 26982 insertions(+), 3348 deletions(-) create mode 100644 docs/manual/01-generator.md create mode 100644 docs/manual/02-new-feature.md create mode 100644 docs/manual/03-placement.md create mode 100644 docs/manual/04-persistence.md create mode 100644 docs/manual/05-idempotency.md create mode 100644 docs/manual/06-errors.md create mode 100644 docs/manual/07-authorization.md create mode 100644 docs/manual/08-testing.md create mode 100644 docs/manual/09-outbox-events.md create mode 100644 docs/manual/10-capabilities.md create mode 100644 docs/manual/11-checklist.md create mode 100644 docs/manual/README.md create mode 100644 docs/manual/appendix-common-principles.md create mode 100644 docs/mongodb/consumer-leaf-guide.md create mode 100644 scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/Create__Feature__HttpRequest.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__Controller.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__HttpResponse.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__ControllerTest.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactory.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactoryTest.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__Config.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__ConfigTest.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__Command.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__UseCase.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Get__Feature__Query.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Get__Feature__UseCase.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__ErrorCode.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__NotFoundException.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__RejectedException.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__View.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/application-core/src/test/java/dev/caskeleton/application/__feature__/Create__Feature__UseCaseTest.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/application-core/src/test/java/dev/caskeleton/application/__feature__/Get__Feature__UseCaseTest.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__Id.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__IdFactory.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__InvariantException.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__Repository.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/__Feature__IdTest.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/__Feature__Test.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/testkit/InMemory__Feature__RepositoryContractTest.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/InMemory__Feature__Repository.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/Sequential__Feature__IdFactory.java.tmpl create mode 100644 scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/__Feature__RepositoryContract.java.tmpl create mode 100755 scripts/new-feature.sh create mode 100755 scripts/verify-feature-scaffold.sh delete mode 100644 src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderRequestRegistry.java delete mode 100644 src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicy.java create mode 100644 src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDeadlineInstrumentation.java create mode 100644 src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPerParentFetchInstrumentation.java create mode 100644 src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformContextMissingException.java create mode 100644 src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/example/OrderCustomerBatchLoading.java create mode 100644 src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPerParentFetchTest.java create mode 100644 src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineOnRequestThreadTest.java create mode 100644 src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineTest.java create mode 100644 src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/RuntimeLimitsTestSupport.java create mode 100644 src/adapter/inbound/graphql/src/systemTest/resources/graphql-runtime-limits/runtime-limits.graphqls rename src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/dataloader/{GraphQlDataLoaderRequestRegistryTest.java => GraphQlDataLoaderFactoryTest.java} (80%) delete mode 100644 src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicyTest.java create mode 100644 src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java create mode 100644 src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerDeadlineInterceptor.java create mode 100644 src/adapter/inbound/messaging/CLAUDE.md create mode 100644 src/adapter/inbound/messaging/README.md create mode 100644 src/adapter/inbound/messaging/build.gradle create mode 100644 src/adapter/inbound/messaging/gradle.lockfile create mode 100644 src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java create mode 100644 src/adapter/inbound/messaging/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports create mode 100644 src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java create mode 100644 src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java create mode 100644 src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java create mode 100644 src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/CorsExposedHeaders.java create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeErrorDetails.java create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeResponseWriter.java create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebTransportError.java create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/IdempotencyKeyHeader.java create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/InvalidIdempotencyKeyException.java create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterHint.java create mode 100644 src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/IdempotencyKeyHeaderTest.java create mode 100644 src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompConnectionLimit.java create mode 100644 src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompConnectionLimitTest.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/SemanticRedisCallTest.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/LiveRedisCacheRegionContractTest.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionContractTest.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeysTest.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreContractTest.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/SignallingRequestExecutor.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/ListElementKeyGuard.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/CircuitBreakerSettings.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/RequestWriteSignal.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/http3/JettyAttemptDeadlineTest.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ExecutionEvidenceGatewayTest.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/RetryBudgetAssignmentTest.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingSetupDeadlineTest.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/UnauthorizedRefreshTest.java create mode 100644 src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactory.java create mode 100644 src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactoryTest.java create mode 100644 src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java create mode 100644 src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/s3/MinioS3ManagedObjectProviderContractTest.java create mode 100644 src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/s3/SelfSignedServerCertificate.java create mode 100644 src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/ComposeMinioImageMatchesEvidenceTest.java create mode 100644 src/adapter/outbound/persistence-fileserver/CLAUDE.md create mode 100644 src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/AssignedIdEntity.java create mode 100644 src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSql.java create mode 100644 src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/AssignedIdEntityTest.java delete mode 100644 src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/tenant/TenantId.java create mode 100644 src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxAggregateSequenceEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V20__outbox_event_deferred_attempt_count.sql create mode 100644 src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V21__outbox_aggregate_sequence.sql create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaStack.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlPreferenceStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlSuppressionStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/SuppressionTargetUniqueMigrationTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientExpiryVersionContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxBulkReadVersionContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAggregateSequenceIntegrationTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/ModuleDefaultJdbcBatchingTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/SqlStateClassificationParityTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaVersionedBulkUpdateRuleTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaVersionedBulkUpdateRule.java create mode 100644 src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoUriOnlyClientDefaults.java create mode 100644 src/adapter/outbound/persistence-mongo/src/mongoIntegrationTest/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionWriteConflictLaneTest.java create mode 100644 src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoUriOnlyClientDefaultsTest.java create mode 100644 src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/MongoNoteStore.java create mode 100644 src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/MongoNoteStoreExampleTest.java create mode 100644 src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/Note.java create mode 100644 src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocument.java create mode 100644 src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocumentMapper.java create mode 100644 src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocumentRepository.java create mode 100644 src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteStore.java create mode 100644 src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/package-info.java create mode 100644 src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionBodyTranslatedFailureTest.java create mode 100644 src/adapter/outbound/persistence-notification/CLAUDE.md create mode 100644 src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V12__notification_suppression_target_unique.sql create mode 100644 src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderContractTest.java create mode 100644 src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/logging/LoggingConfigurationRule.java create mode 100644 src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/BootstrapSettingsConfig.java delete mode 100644 src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/LoggingSettings.java create mode 100644 src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/logging/LoggingSettingsSourceSystemTest.java create mode 100644 src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SampleRuntimeDefaultsContractTest.java create mode 100644 src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/logging/LoggingConfigurationRuleTest.java delete mode 100644 src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/LoggingSettingsTest.java delete mode 100644 src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/application/port/FeatureAggregateWritePort.java create mode 100644 src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateRepository.java create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSourceRevisionOrder.java create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDrafts.java create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationIdFactory.java create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/cache/CacheSourceRevisionOrderTest.java rename src/application-core/src/test/java/dev/caskeleton/application/cache/{CacheRegionContractTest.java => CacheValueTypesTest.java} (99%) create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/cache/InMemoryCacheRegionContractTest.java rename src/application-core/src/test/java/dev/caskeleton/application/idempotency/{IdempotencyContractTest.java => IdempotencyValueTypesTest.java} (98%) create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/idempotency/InMemoryIdempotencyStoreContractTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/lock/testkit/InMemoryDistributedLockContractTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftsTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationIdentityTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoderContractTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/outbox/StoppingRelayReleasesItsClaimsTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequenceContractTest.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/CacheRegionContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/InMemoryCacheRegion.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/InMemoryDistributedLock.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/EncoderContractKitContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventEncoderContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequences.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAggregateSequenceContract.java create mode 100644 src/application-core/src/testFixtures/resources/contracts/messaging/testkit.encoder-contract/v1.schema.json create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/observability/SafeFileFingerprintTest.java delete mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueue.java create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueueContractTest.java create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStoreContractTest.java create mode 100644 src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/CleanupQueuePortContract.java create mode 100644 src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileMetadataPortContract.java create mode 100644 src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueue.java rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStore.java (93%) create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryPreferenceStoreTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemorySuppressionStoreTest.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryPreferenceStore.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemorySuppressionStore.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/OverlappingWrites.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/PreferenceStoreContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/SuppressionStoreContract.java create mode 100644 src/composition/durable-operation/README.md create mode 100644 src/composition/durable-operation/build.gradle create mode 100644 src/composition/durable-operation/gradle.lockfile rename src/{app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/operation/DurableOperationConfig.java => composition/durable-operation/src/main/java/dev/caskeleton/composition/operation/DurableOperationAutoConfiguration.java} (70%) create mode 100644 src/composition/durable-operation/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports create mode 100644 src/composition/durable-operation/src/main/resources/config/module-defaults/durable-operation.yml create mode 100644 src/composition/durable-operation/src/test/java/dev/caskeleton/composition/operation/DurableOperationModuleTest.java create mode 100644 src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayOffWarning.java create mode 100644 src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxMetricsTest.java create mode 100644 src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerDrainTest.java create mode 100644 src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementConfig.java create mode 100644 src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java create mode 100644 src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java create mode 100644 src/config/testing/container-images.properties create mode 100644 src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java create mode 100644 src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql create mode 100644 src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetention.java create mode 100644 src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetentionTest.java create mode 100644 src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingInboxAssemblyTest.java create mode 100644 src/optional-platforms/gradle.properties rename src/{shared-contract/src/main/java/dev/caskeleton/shared => sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web}/operation/Operation.java (96%) rename src/{shared-contract/src/main/java/dev/caskeleton/shared => sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web}/operation/OperationStatus.java (82%) create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/SampleOperationNotFoundException.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/OutboxEventIdFactory.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogNotOwnedException.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummaryPage.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/OutboxEventIdFactory.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogPage.java create mode 100644 src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/SampleApiDocsSystemTest.java create mode 100644 src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/InsertRoundTripCounter.java create mode 100644 src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/RecordingStatementInspector.java create mode 100644 src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/WorkLogStatementCostSystemTest.java rename src/{shared-contract/src/test/java/dev/caskeleton/shared => sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web}/operation/OperationTest.java (95%) create mode 100644 src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/application/worklog/testkit/InMemoryWorkLogSummaryQuery.java delete mode 100644 src/shared-contract/src/main/java/dev/caskeleton/shared/annotation/.gitkeep delete mode 100644 src/shared-contract/src/main/java/dev/caskeleton/shared/headers/.gitkeep delete mode 100644 src/shared-contract/src/main/java/dev/caskeleton/shared/registry/.gitkeep diff --git a/.github/workflows/fileserver-nightly.yml b/.github/workflows/fileserver-nightly.yml index 48179b0f..dc026c36 100644 --- a/.github/workflows/fileserver-nightly.yml +++ b/.github/workflows/fileserver-nightly.yml @@ -32,7 +32,6 @@ jobs: run: >- ./gradlew :adapter:outbound:fileserver:test --tests '*NfsAmbiguityIntegrationTest' - --stacktrace - name: Tear down the NFS environment if: always() @@ -51,7 +50,6 @@ jobs: :adapter:outbound:fileserver:test --tests '*CrashRecoveryMatrixTest' :application-fileserver:test --tests '*FileReconciliationServiceTest' --rerun-tasks - --stacktrace fileserver-large-file-performance: @@ -69,7 +67,6 @@ jobs: :adapter:outbound:fileserver:test --tests '*LargeFileBoundedMemoryTest' :adapter:outbound:fileserver:test --tests '*LocalAppendMemoryTest' --rerun-tasks - --stacktrace fileserver-multi-instance-lease: @@ -84,5 +81,4 @@ jobs: ./gradlew :application-fileserver:test --tests '*MultiInstanceWriterLeaseTest' --rerun-tasks - --stacktrace diff --git a/.github/workflows/fileserver-pr.yml b/.github/workflows/fileserver-pr.yml index 66c09b43..780ab5f2 100644 --- a/.github/workflows/fileserver-pr.yml +++ b/.github/workflows/fileserver-pr.yml @@ -56,7 +56,6 @@ jobs: ./gradlew :application-fileserver:test :composition:fileserver-platform:test - --stacktrace fileserver-local-ext4-contract: @@ -70,7 +69,6 @@ jobs: run: >- ./gradlew :adapter:outbound:fileserver:test - --stacktrace fileserver-http-contract: @@ -84,7 +82,6 @@ jobs: run: >- ./gradlew :adapter:inbound:web-fileserver:test - --stacktrace fileserver-security-suite: @@ -99,7 +96,6 @@ jobs: ./gradlew :adapter:inbound:web-fileserver:test --tests '*FileserverHardeningContractTest' :adapter:outbound:fileserver:test --tests '*PhysicalPathResolverTest' - --stacktrace fileserver-bounded-memory: @@ -113,5 +109,4 @@ jobs: run: >- ./gradlew :adapter:outbound:fileserver:test --tests '*LargeFileBoundedMemoryTest' - --stacktrace diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml index f8e52026..79090826 100644 --- a/.github/workflows/integration-main.yml +++ b/.github/workflows/integration-main.yml @@ -152,6 +152,16 @@ jobs: # The container lanes take the build-wide `exclusiveRealServerLane` slot one at a time, so the # job's length is the sum of the lanes. Split the aggregate across jobs when it outgrows its # timeout rather than going back to naming lanes. + # + # Measured length (one local run of `:integrationCheck`, 2026-11-01, 37 lanes, images already + # pulled, machine load 24): 794 s for the command, of which the lanes' test JVMs took about 624 s + # in sum — mongoSecurityIntegrationTest 89, jpaPlatformContractTest 104, messagingCertificationTest + # 70, mongoCompatibilityTest 69, jpaPlatformMigrationTest 66, mongoFailoverTest 59, the eleven JPA + # readiness lanes 57 together, httpClientFailureInjectionTest 27, sample integrationTest 23, + # messaging starter integrationTest 21, the rest under 10 each — and the remainder was compilation + # and container start-up between lanes. A hosted runner adds cold image pulls (about 5 GB + # uncompressed across the PostgreSQL, MongoDB, Kafka, nginx, httpbin and Toxiproxy images) and a + # cold Gradle cache; expect 25 to 40 minutes (an estimate, not a measured hosted run). The 240-minute timeout is a ceiling for a hung container, not a budget. integration-check: runs-on: ubuntu-latest timeout-minutes: 240 diff --git a/.github/workflows/jpa-nightly.yml b/.github/workflows/jpa-nightly.yml index 0d7ad487..adbf1ff4 100644 --- a/.github/workflows/jpa-nightly.yml +++ b/.github/workflows/jpa-nightly.yml @@ -37,7 +37,6 @@ jobs: ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformContractTest -Pjpa.matrix.versions=${{ matrix.postgresql }} - --stacktrace jpa-failure-injection: @@ -51,7 +50,6 @@ jobs: run: >- ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformFailureTest - --stacktrace jpa-query-plan-and-security: @@ -66,7 +64,6 @@ jobs: ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformQueryPlanTest :adapter:outbound:persistence-jpa:jpaPlatformSecurityTest - --stacktrace jpa-pool-pressure: @@ -86,5 +83,4 @@ jobs: run: >- ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformPoolContractTest - --stacktrace diff --git a/.github/workflows/pr-adapters.yml b/.github/workflows/pr-adapters.yml index 0fa25631..11f0633a 100644 --- a/.github/workflows/pr-adapters.yml +++ b/.github/workflows/pr-adapters.yml @@ -142,7 +142,6 @@ jobs: ./gradlew :adapter:inbound:web:systemTest :adapter:inbound:web:webJettyCompatTest - --stacktrace - name: Publish the test reports if: always() @@ -165,7 +164,6 @@ jobs: run: >- ./gradlew :adapter:inbound:websocket:websocketJettyTest - --stacktrace # Docker-gated, and the lane fails rather than skipping. Upgrade handling is the single most @@ -183,7 +181,6 @@ jobs: run: >- ./gradlew :adapter:inbound:websocket:websocketNginxTest - --stacktrace # One transport per job, so a transport that stops satisfying the shared contract fails on its own @@ -206,7 +203,6 @@ jobs: ./gradlew :adapter:outbound:httpclient:httpClientStableContractTest -Phttpclient.contract.transports=${{ matrix.transport }} - --stacktrace # Only the Spring 7.0 lane. httpClientSecurityTest and spring62ApiSurfaceScan used to run here @@ -226,7 +222,6 @@ jobs: run: >- ./gradlew :adapter:outbound:httpclient:spring70CompatibilityTest - --stacktrace # 16 and 18 — the ends of the Stable matrix. 17 runs in the integration stage. What this does not @@ -250,7 +245,6 @@ jobs: ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformContractTest -Pjpa.matrix.versions=${{ matrix.postgresql }} - --stacktrace jpa-migration-smoke: @@ -266,5 +260,4 @@ jobs: run: >- ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformMigrationTest - --stacktrace diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 751fba40..43d2ff14 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -73,7 +73,6 @@ jobs: :adapter:inbound:web:systemTest :adapter:inbound:web:webJettyCompatTest :adapter:inbound:web-advanced:webAdvancedTest - --stacktrace - name: Publish the release evidence if: always() @@ -100,7 +99,6 @@ jobs: :adapter:inbound:websocket:websocketJettyTest :adapter:inbound:websocket:websocketNginxTest :adapter:inbound:websocket:websocketTransportQualificationTest - --stacktrace - name: Publish the release evidence if: always() diff --git a/AGENTS.md b/AGENTS.md index 11711907..f86cf3cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,11 +65,22 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 `ca.architecture`가 아키텍처 검증 태스크를 소유한다. 기능별 검사(notification·mongo·messaging· graphql·JPA readiness 등)는 build-logic이 아니라 소유 leaf의 테스트다. 테스트가 저장소 파일을 읽으면 그 파일을 그 leaf의 test task `inputs`로 선언한다. 저장소 문서와 대조하는 테스트는 `mainStage()` - 레인(`document-contract` 태그)으로 leaf `mainCheck`에서 돈다. + 레인(`document-contract` 태그)으로 leaf `mainCheck`에서 돈다. 문서가 아닌 저장소 파일(빌드 스크립트, + workflow, Compose, 다른 leaf 소스)을 읽어야 merge 전에 막을 수 있는 계약은 그 파일만 입력으로 둔 + 별도 레인(app-bootstrap `repository-contract`)에 둔다. 저장소 루트(`ca.repository.root`)는 이 두 + 레인에만 주므로 태그 없이 저장소를 읽는 테스트는 `test`에서 실패한다. +- strict lane 캐시: `TEST`·`ARCHITECTURE` lane은 입력이 같으면 up-to-date·build cache를 쓴다. + `INTEGRATION`·`SYSTEM`·`PERFORMANCE` lane과 `mainStage()` lane은 이미지·네트워크·시간·문서처럼 + 입력으로 잡히지 않는 것에 기대므로 매번 다시 돈다. hermetic lane이 저장소 파일을 읽으면 그 파일을 + 입력으로 선언해야 캐시가 거짓 통과를 내지 않는다. - `verifyEnvKeys`는 app-bootstrap 태스크로 유지한다(소유자 결정 4). 구현은 build-logic의 `ca.config-contract`다. `src/build-tools/` included build는 비워서 삭제했다. -- `src/build.gradle`: 루트 라이프사이클(`ci`, `mainCheck`, `releaseCheck`, `qualityCheck`, - `configContractCheck`, `integrationCheck`)과 버전/리비전 +- `src/build.gradle`: 루트 라이프사이클(`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, + `releaseCheck`, `qualityCheck`, `configContractCheck`)과 버전/리비전. `verifyStrictLaneStages + --dry-run`(PR 게이트)은 `explicitOnly`가 아닌 모든 strict lane이 workflow가 실제로 실행하는 단계 + (`ci`·`sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) + 중 하나에 들어 있는지, 그리고 workflow의 접힌(`>`) run 블록이 빈 줄 때문에 옵션을 별개 명령으로 + 떼어 내지 않는지 검사한다. 작업 파일의 소유 leaf는 registry의 `source_path`로 판단하고 가장 가까운 `src/**/CLAUDE.md`를 함께 읽는다. focused test는 registry의 `gradle_path`에서 @@ -140,6 +151,10 @@ Gradle 의존성 검증도 같은 registry를 읽는다. root 문서나 기억 9. endpoint는 마지막에 해당 `adapter:inbound:*` leaf에서 얇게 연결한다. 10. focused test를 먼저 돌리고, 가능한 경우 전체 Gradle test를 돌린다. +단계별 판단 지점(배치·저장 포트·트랜잭션·멱등성·오류·권한)은 `docs/manual/`, 뼈대는 +`scripts/new-feature.sh `이 계층 leaf에 만든다. `sample-portfolio`는 모든 계층을 한 leaf에 +두는 지울 수 있는 샘플이라 배치 예시가 아니다. 실제 기능은 계층 leaf별로 나눈다. + ## 테스트 전략 계층별 테스트 기준: @@ -154,8 +169,8 @@ Gradle 의존성 검증도 같은 registry를 읽는다. root 문서나 기억 테스트 작성 규칙 (새로 쓰거나 고치는 테스트에 적용): 1. 이름은 lowerCamelCase 행동 문장(`<상황/주체><결과>`)이다. 이름에 적은 성질은 반드시 단언한다. -2. `@DisplayName`은 메서드 이름으로 못 쓰는 내용(숫자, 기호, 이유)이 있을 때만 쓰고, 언어는 영어로 - 통일한다. +2. `@DisplayName`은 메서드 이름으로 못 쓰는 내용(숫자, 기호, 이유)이 있을 때만 쓰고, 한국어로 + 쓴다(소유자 결정 5). 기존 영어 `@DisplayName`은 그 테스트를 고칠 때 한국어로 바꾼다. 3. 본문 문장이 3개 이상이면 `// given` `// when` `// then` 주석과 구역 사이 빈 줄을 둔다. 준비할 것이 없으면 `// given`은 생략한다. `// when`은 정확히 하나다. 두 번 필요하면 테스트를 나눈다. 예외 테스트는 `catchThrowable`로 when을 분리한다(기존 `assertThatThrownBy`는 손댈 때 @@ -188,6 +203,9 @@ cd src ./gradlew qualityCheck # SpotBugs + FindSecBugs (leaf check에는 없다) ./gradlew ci # PR 게이트 = leaf check + architecture + quality ./gradlew mainCheck # main 단계 = env 계약·전체 기동·public path·전송/메시징 레인·leaf 문서 대조 레인 +./gradlew integrationCheck # 실제 컨테이너 integration 레인 전체(main·nightly, Docker 필요) +./gradlew performanceCheck # 부하·종료·자원 한계 레인(main·nightly) +./gradlew verifyStrictLaneStages --dry-run # 모든 strict lane이 workflow가 실행하는 단계에 속하는지 ./gradlew verifyPublicPathSnapshot ./gradlew :app-bootstrap:verifyEnvKeys ``` diff --git a/CLAUDE.md b/CLAUDE.md index de0b8f00..d749111f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,11 +30,16 @@ If this summary drifts from `AGENTS.md`, `AGENTS.md` wins and this summary must and one test-lane mechanism (`strictTestLanes`). Feature-specific checks are the owning leaf's tests; a test that reads repository files declares them as that leaf's test `inputs`, and a test that compares a leaf with repository documents is a `mainStage()` lane (tag `document-contract`) - in that leaf's `mainCheck`. + in that leaf's `mainCheck`; a merge-blocking contract over non-document repository files is a + pull-request lane whose inputs are exactly those files (app-bootstrap `repository-contract`). + `TEST`/`ARCHITECTURE` lanes are cacheable; `INTEGRATION`/`SYSTEM`/`PERFORMANCE` and main-stage + lanes rerun every time. - `verifyEnvKeys` stays an app-bootstrap task (owner decision 4); its implementation is build-logic's `ca.config-contract`. The `src/build-tools/` included build was emptied and removed. -- `src/build.gradle`: the root lifecycle (`ci`, `mainCheck`, `releaseCheck` and the named - repository-wide gates). +- `src/build.gradle`: the root lifecycle (`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, + `releaseCheck` and the named repository-wide gates). `verifyStrictLaneStages --dry-run` (pull + request) fails when a non-`explicitOnly` strict lane is in no stage a workflow executes, or a + folded workflow `run:` block splits an option off its command. Commit policy is `human-only`: agents do not stage, commit, amend, or push implementation changes. @@ -124,15 +129,17 @@ Repository-wide questions have their own names: `architectureCheck` (dependency of domain-core/shared-contract/application-*, Git-carryable sources, ArchUnit), `qualityCheck` (SpotBugs, FindSecBugs), `configContractCheck` (the environment contract), `integrationCheck` (the declared strict integration lanes; a lane that needs an input the build was not given is left out -and named). `ci` (pull request) is leaf checks (API surfaces included, owner decision 20) + -architectureCheck + qualityCheck; `mainCheck` (main branch) is configContractCheck + +and named), `performanceCheck` (the declared performance lanes; main and nightly). `ci` (pull +request) is leaf checks (API surfaces included, owner decision 20) + architectureCheck + +qualityCheck, and the workflow also runs `verifyStrictLaneStages --dry-run`; `mainCheck` (main branch) is configContractCheck + qualificationCheck + the sample web contract + the public-path snapshot + the transport and messaging qualification lanes + every leaf's `mainCheck` (document-contract lanes, MinIO lanes); `releaseCheck` is the tag-only checks: release provenance and the public-path snapshot. -Test-writing rules (behavior-sentence names that assert what they promise, given/when/then comments, -one `// when`, one fake per port in the port owner's testFixtures, fake and adapter sharing one -abstract contract test) are canonical in `AGENTS.md`. +Test-writing rules (behavior-sentence names that assert what they promise, `@DisplayName` in Korean +only when the name cannot say it (owner decision 5), given/when/then comments, one `// when`, one +fake per port in the port owner's testFixtures, fake and adapter sharing one abstract contract test) +are canonical in `AGENTS.md`. Use public-path and env-key checks only when their surfaces changed. Full `test`, `check` or `ci` requires the controller's workflow authorization. diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index fc063c6f..b81721bb 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -64,7 +64,7 @@ services: -Djava.rmi.server.hostname=127.0.0.1 ports: - "8080:8080" - - "9001:9001" + - "127.0.0.1:9001:9001" # management — localhost only (07-13) - "127.0.0.1:9999:9999" # JMX — localhost only # No health check constraint in dev; let the app start at its own pace. healthcheck: diff --git a/docker-compose.infra.yml b/docker-compose.infra.yml index 218bb48b..7f0b49c5 100644 --- a/docker-compose.infra.yml +++ b/docker-compose.infra.yml @@ -13,16 +13,16 @@ # The local MinIO runtime, used by the server and by the object-storage smoke client below. # -# It is deliberately not the image the MinIO qualification lanes run. Those read their image from -# src/adapter/outbound/objectstorage/src/test/resources/object-storage/minio-provider-evidence.json, -# whose digest is the release the recorded findings (status UNSUPPORTED, the excluded create-only -# profiles) were measured on. This one is a later release because the healthcheck runs `mc ready` -# and the smoke script runs the bundled mc, and moving it onto the evidence release is unverified. -# A local runtime is not evidence, so the two may differ; they must not be mistaken for each other. +# It is the image the MinIO qualification lanes measured, by the same digest: +# src/adapter/outbound/objectstorage/src/test/resources/object-storage/minio-provider-evidence.json +# records it with the conditional-write findings, and ComposeMinioImageMatchesEvidenceTest in that +# leaf fails when this default and the evidence disagree. Change both together. # -# Both come from Docker Hub's minio/minio, which stopped serving it (review 05-09). LOCAL_MINIO_IMAGE -# points this runtime at a mirror; the lanes take OBJECT_STORAGE_MINIO_IMAGE, digest-checked. -x-local-minio-image: &local-minio-image "${LOCAL_MINIO_IMAGE:-minio/minio:RELEASE.2024-09-13T20-26-02Z}" +# Source: pgsty/minio, a community fork on Docker Hub, after Docker Hub's minio/minio and quay.io +# stopped serving MinIO images (review 05-09). cgr.dev/chainguard/minio measured the same but was +# not chosen; the evidence file's rejectedCandidates says why. LOCAL_MINIO_IMAGE points this runtime +# at a mirror; the lanes take OBJECT_STORAGE_MINIO_IMAGE, digest-checked. +x-local-minio-image: &local-minio-image "${LOCAL_MINIO_IMAGE:-pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372}" services: # ---- PostgreSQL -------------------------------------------------------------- @@ -217,7 +217,9 @@ services: profiles: - shared-infra - prod-smoke - image: minio/mc:RELEASE.2024-09-16T17-43-14Z + # The client from the same supplier as the server. cgr.dev/chainguard/minio-client was not used: + # it has no shell, and the bootstrap below is a shell script. + image: "${LOCAL_MINIO_MC_IMAGE:-pgsty/mc@sha256:ce62c9053c69ce12a527a322345b5ad9f44b5f8a7b8189f82e516f2e3f30f1d8}" depends_on: minio: condition: service_healthy @@ -428,7 +430,7 @@ services: - caskeleton-infra restart: "no" - # The server image, not the mc client image: minio/mc ships no sed, grep or cmp, and the round-trip + # The server image, not the mc client image: the mc image ships no sed, grep or cmp, and the round-trip # client needs a digest tool. See infra/minio/smoke/object-storage-smoke.sh for how that went # unnoticed. The lane already pulls this image for the server itself. object-storage-smoke: diff --git a/docker-compose.local.yml b/docker-compose.local.yml index 7b3bd030..3e6f777f 100644 --- a/docker-compose.local.yml +++ b/docker-compose.local.yml @@ -34,7 +34,7 @@ services: TZ: "UTC" LANG: "C.UTF-8" LC_ALL: "C.UTF-8" - # fallback matches env-keys.yaml SSOT default (30s); base compose grace is 40s. + # fallback matches env-keys.yaml SSOT default (30s); base compose grace is 60s. APP_SERVER_SHUTDOWN_TIMEOUT: "${APP_SERVER_SHUTDOWN_TIMEOUT:-30s}" APP_SERVER_SHUTDOWN: "graceful" # Database connection — points to the local `db` service below. diff --git a/docker-compose.prod-smoke.yml b/docker-compose.prod-smoke.yml index edbe8edc..74b6f925 100644 --- a/docker-compose.prod-smoke.yml +++ b/docker-compose.prod-smoke.yml @@ -26,7 +26,6 @@ services: # generated file and injected an empty string — which the prod env validator then refused, for # the right reason, about a value the lane had actually supplied. APP_DATASOURCE_DDL_AUTO: "validate" - APP_LOG_JSON_ENABLED: "true" APP_SECURITY_JWT_ISSUER: "http://keycloak:8080/realms/ca-skeleton" APP_SECURITY_JWT_AUDIENCE: "ca-skeleton-api" networks: diff --git a/docker-compose.yml b/docker-compose.yml index dcb44cdb..b63042d3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,11 +9,17 @@ # Graceful-shutdown sync table (feature-container-runtime-contract D5): # App shutdown timeout : 30s (APP_SERVER_SHUTDOWN_TIMEOUT — SSOT: docs/registries/ # env-keys.yaml, owner feature-env-driven-runtime-configuration) +# Async executor wait : 19s (AsyncExecutorConfig.AWAIT_TERMINATION_SECONDS) # Container preStop : 5s (handled by the orchestrator / stop_grace_period offset) -# stop_grace_period : 40s (30s app drain + 5s preStop + 5s safety margin) +# stop_grace_period : 60s (30s app drain + 19s async + 5s preStop + 6s safety margin) +# +# The drain and the async wait are consecutive, not concurrent: Spring finishes the lifecycle +# phase (the web server's graceful drain) before it destroys the executor, which then waits for +# its queue. A 40s grace let the container be killed 9s into that wait (07-07). +# DeveloperExperienceContractTest fails when this value is below the sum. # # Ownership: env-driven-config owns the app shutdown *value* (30s); this contract owns the -# *relationship* (stop_grace_period >= app timeout + preStop + margin). The grace is therefore +# *relationship* (stop_grace_period >= app timeout + async wait + preStop + margin). The grace is therefore # sized UP to the env-keys SSOT value (30s) — you do not shrink the app drain window to fit an # arbitrary grace. This resolves the earlier 20s/35s drift, which had assumed an app-timeout # value this branch does not own (env-keys.yaml is the SSOT and sets 30s). @@ -49,7 +55,10 @@ services: required: false ports: - "${APP_SERVER_PORT:-8080}:8080" - - "9001:9001" + # Management (health, info, prometheus — answered without authentication) on loopback only: + # published on every interface it reaches the whole LAN (07-13). The smoke lanes read it from + # inside the container, so they need no host port at all. + - "127.0.0.1:9001:9001" environment: TZ: "UTC" LANG: "C.UTF-8" @@ -85,8 +94,9 @@ services: mem_limit: 512m memswap_limit: 512m # ---- Graceful shutdown (D5) --------------------------------------------- - # stop_grace_period = app drain (30s, env-keys SSOT) + preStop (5s) + margin (5s) = 40s. - stop_grace_period: 40s + # stop_grace_period = app drain (30s, env-keys SSOT) + async wait (19s) + preStop (5s) + # + margin (6s) = 60s. + stop_grace_period: 60s # ---- Health check ------------------------------------------------------- # Targets the actuator readiness probe on the management port (9001). # The warning that used to stand here — that this probe would report UNHEALTHY until two diff --git a/docs/README.md b/docs/README.md index 1bd530f6..4d745431 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,6 +24,7 @@ | --- | --- | | `adr/` | 아키텍처 결정 기록 | | `architecture/` | 공개 API 표면 스냅숏 | +| `manual/` | 개발 매뉴얼: 새 기능을 만드는 순서와 판단 지점, 생성 명령(`scripts/new-feature.sh`) | | `evidence/` | 작업 단계별 증거·체크포인트 | | `registries/` | env 키·에러 코드·메트릭·헤더 등 레지스트리 SSOT | | `reviews/` | 모듈 코드 리뷰 결과 | diff --git a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md index deb788bd..495d3480 100644 --- a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md +++ b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md @@ -53,8 +53,10 @@ request takes it over with `GrpcOperationLedger.reclaimStale` — one conditiona `UPDATE … WHERE state = 'IN_PROGRESS' AND claimed_at < :cutoff`, so of two concurrent takeovers exactly one wins, the same shape as `reclaimFailed`. The TTL is the `claimTtl` argument of `GrpcIdempotencyInterceptor`, refused at construction when it is not longer than every keyed method's -deadline. It is not a configuration key: the starter does not assemble the interceptor yet (03-11), so -there is nothing for a key to configure. +deadline. Since the 03-11 follow-up the starter assembles the interceptor when +`app.grpc.platform.operation-ledger-enabled=true` and takes the TTL from +`app.grpc.platform.operation-ledger-claim-ttl` (default 5m); a TTL the constructor refuses fails startup +naming that key, and an enabled flag without a `GrpcOperationLedger` bean fails startup too. The takeover is safe only because the commit is recorded in the mutation's own transaction: then a claim still `IN_PROGRESS` means the mutation never committed. An adopter that commits them separately @@ -65,7 +67,18 @@ method and not just its deadline. Rejected: an owner token with a heartbeat lease (the outbox lease model) — needed only when a keyed method can run longer than any fixed TTL; revisit when one exists. A sweeper job that deletes stale rows — it needs a scheduler this family does not have, and deleting a claim makes the next retry a -fresh claim with no record that an attempt was abandoned. Retention of terminal rows is still open. +fresh claim with no record that an attempt was abandoned. + +**Finished rows are purged after a retention; in-progress rows never are** (03-10 follow-up). +`GrpcOperationLedger.purgeCompletedBefore(cutoff, limit)` deletes at most `limit` `COMMITTED` or +`FAILED_TERMINAL` rows that completed before the cutoff, oldest first — on PostgreSQL one bounded +`DELETE … WHERE storage_key IN (SELECT … LIMIT … FOR UPDATE SKIP LOCKED)` served by the partial index +of migration V002. `GrpcOperationLedgerRetention.purgeExpired(now)` applies +`app.grpc.platform.operation-ledger-retention` (default 24h, the HTTP idempotency replay TTL) in +batches. A retry after its record was purged is a fresh claim and runs again, so the retention must +exceed the callers' retry window. The adopter schedules the purge; the starter assembles the policy +only, because a scheduled bean would force a scheduler onto every deployment and the starter cannot +know which replica should run it. **A key reused for a different request is a caller error, not a duplicate.** The stored request fingerprint turns that into `FAILED_PRECONDITION` rather than silently returning the first request's diff --git a/docs/architecture/graphql-api-surface.txt b/docs/architecture/graphql-api-surface.txt index b1e149b1..cd61da7e 100644 --- a/docs/architecture/graphql-api-surface.txt +++ b/docs/architecture/graphql-api-surface.txt @@ -52,7 +52,6 @@ dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchValue dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName -dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderRequestRegistry dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyPolicy dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory @@ -75,7 +74,6 @@ dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheKey dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheMetrics dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCachePolicy dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException -dev.caskeleton.adapter.inbound.graphql.execution.GraphQlTimeoutPolicy dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlFetchProfile dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlFetchProfileClassifier dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlFetchProfileName @@ -132,12 +130,14 @@ dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlCostBudgetHandler dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataFetcherExceptionResolver +dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDeadlineInstrumentation dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDocumentAuthorizationHandler dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionChain dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionContext dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionHandler dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionRequest dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlOperationSelectionHandler +dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPerParentFetchInstrumentation dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformInstrumentation dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformWebInterceptor dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPreparsedDocumentAdapter diff --git a/docs/architecture/jpa-api-surface.txt b/docs/architecture/jpa-api-surface.txt index 505ce8df..e2d3f24a 100644 --- a/docs/architecture/jpa-api-surface.txt +++ b/docs/architecture/jpa-api-surface.txt @@ -5,7 +5,7 @@ # root yet. # Update only after review with: # ./gradlew :adapter:outbound:persistence-jpa:updateJpaApiSurface -PapproveJpaApiSurfaceChange -# types: 166 +# types: 165 dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName dev.caskeleton.adapter.outbound.persistence.api.capability.CapabilitySupport dev.caskeleton.adapter.outbound.persistence.api.capability.JpaCapability @@ -74,7 +74,6 @@ dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaTenantRegi dev.caskeleton.adapter.outbound.persistence.experimental.schema.TenantMigrationStatus dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantAwareRepositoryGuard dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantContext -dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping diff --git a/docs/httpclient/configuration-reference.md b/docs/httpclient/configuration-reference.md index 01f8ebb1..6feb9cc8 100644 --- a/docs/httpclient/configuration-reference.md +++ b/docs/httpclient/configuration-reference.md @@ -82,8 +82,6 @@ materialise a nameless client in every deployment, which the aggregate validatio | `max-idle-time` | `30s` | Idle eviction | | `max-life-time` | `5m` | Picks up DNS, load-balancer, and certificate changes | | `validate-after-inactivity` | `5s` | Stale and half-open detection | -| `eviction-interval` | `15s` | Background cleanup | -| `shutdown-timeout` | `5s` | Drain deadline before forced close | | `requires-route-pool` | `false` | Set when route-scoped limits are mandatory; the JDK transport then refuses the profile | | `requires-bounded-pending-queue` | `false` | Same, for a bounded pending queue | @@ -94,14 +92,49 @@ materialise a nameless client in every deployment, which the aggregate validatio | `dns` | `300ms` | Hostname resolution | | `connect` | `500ms` | Socket connect | | `tls-handshake` | `1s` | TLS and ALPN | -| `proxy-connect` | `500ms` | Proxy socket or CONNECT | -| `request-write-idle` | `1s` | No progress writing the request | | `response-header` | `2s` | Until final response headers | | `read-idle` | `3s` | Between response chunks | | `total-call` | `4s` | The whole logical call, including retry backoff | `total-call` must not be shorter than `connect` or `response-header`; the validator emits -`INVALID_TIMEOUT_BUDGET` otherwise. +`INVALID_TIMEOUT_BUDGET` otherwise. Every timeout above, and `pool.pending-acquire-timeout`, must be +greater than zero (`TIMEOUT_NOT_POSITIVE`): both engines read zero as "wait forever". + +`total-call` also bounds the setup of a streaming download — connect, send, and the wait for +response headers. Once the stream is handed over, each gap of the body is bounded by `read-idle` +instead, so a long download is not cut at an arbitrary total (design §15.3). + +### Removed settings + +Six keys were removed because they were bound and reached no transport (review 2026-11-01 05-15). +Setting one now fails startup with `HTTPCLIENT_UNKNOWN_SETTING` naming the key, instead of being +accepted and ignored. + +| Removed key | Why | +|---|---| +| `timeout.request-write-idle` | Neither engine can bound a blocking socket write | +| `timeout.proxy-connect`, `proxy.connect-timeout` | The TCP connect to a proxy is governed by `timeout.connect` | +| `pool.eviction-interval` | Apache's idle evictor runs at `max-idle-time` | +| `pool.shutdown-timeout` | A retired runtime drains for `app.httpclient.rotation-drain-timeout` | +| `observability.operation-name-required` | An operation name is mandatory in the API; the switch could only be true | + +### `circuit-breaker` + +What counts as a failure is fixed: a 5xx, 408 or 429 response — whether the call throws or returns +it as a result — and every transport failure. Every other 4xx is a healthy answer. These settings +only say how many failures, out of how many calls, open the circuit. Defaults are Resilience4j's own, +which every profile ran with before the keys existed. + +| Property | Default | Meaning | +|---|---|---| +| `failure-rate-threshold` | `50` | Percent of failed calls in the window that opens the circuit, 1–100 | +| `minimum-number-of-calls` | `100` | Calls recorded before the rate is evaluated; at most `sliding-window-size` | +| `sliding-window-size` | `100` | The last N calls the rate is computed over (count-based) | +| `wait-duration-in-open-state` | `60s` | How long an open circuit rejects before trial calls; positive | +| `permitted-calls-in-half-open-state` | `10` | Trial calls while half-open; at least 1 | + +An out-of-range value fails startup with `CIRCUIT_BREAKER_SETTING_INVALID`. The breaker belongs to +the profile, not to a runtime generation, so a certificate rotation keeps its state. ### `redirect`, `request`, `response` @@ -132,12 +165,12 @@ materialise a nameless client in every deployment, which the aggregate validatio | Property | Default | Meaning | |---|---|---| | `policy` | `none` | Named policy for reporting | -| `max-attempts` | `1` | Attempts, not retries | +| `max-attempts` | `1` | Attempts, not retries; at most 5 (`RETRY_MAX_ATTEMPTS_EXCEEDED`) | | `base-backoff` | `50ms` | | | `max-backoff` | `200ms` | | | `jitter` | `FULL` | `NONE` \| `FULL` \| `DECORRELATED` | | `retry-after` | `HONOR` | `HONOR` \| `IGNORE` \| `CAP` | -| `budget` | — | Shared token bucket name | +| `budget` | — | Shared token bucket name. A retrying profile that names none gets its own bucket, with the same pool-derived capacity (`max-total-connections / 10`, at least 1, refilled each minute) | ### `tls` @@ -158,9 +191,7 @@ materialise a nameless client in every deployment, which the aggregate validatio | `proxy.enabled` | `false` | | | `proxy.host` / `proxy.port` / `proxy.type` | — / `0` / `HTTP` | | | `proxy.credential-provider` | — | Proxy authentication is separate from target authentication | -| `proxy.connect-timeout` | `500ms` | Recorded as its own metric | | `proxy.import-ambient-no-proxy` | `false` | Ambient `NO_PROXY` never widens a validated profile | -| `observability.operation-name-required` | `true` | | | `observability.full-url-recording` | `false` | | | `observability.body-logging` | `false` | | @@ -193,9 +224,16 @@ materialise a nameless client in every deployment, which the aggregate validatio `HTTP2_REQUIRED_TRANSPORT_UNSUPPORTED`, `POOL_ROUTE_EXCEEDS_TOTAL`, `TLS_PROTOCOL_SET_REQUIRED`, `RETRY_POLICY_CONTRADICTS_ATTEMPTS`, `FULL_URL_RECORDING_FORBIDDEN`, `BODY_LOGGING_FORBIDDEN`, -`DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED`, `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED`. +`DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED`, `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED`, +`TIMEOUT_NOT_POSITIVE`, `RETRY_MAX_ATTEMPTS_EXCEEDED`, `CIRCUIT_BREAKER_SETTING_INVALID`, +`HTTPCLIENT_UNKNOWN_SETTING`. -The last three name settings the platform binds but cannot yet honour. Neither the Apache classic +`HTTPCLIENT_UNKNOWN_SETTING` covers a gap in the shared strict binder: Spring's unbound-key check +stops at the first level under a list element, so `clients[0].timeout.` used to bind nothing +and fail nothing. The platform now checks every key under `clients[N]` and `dynamic-targets[N]` +against the settings records. + +`DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED` and `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED` name settings the platform binds but cannot yet honour. Neither the Apache classic client nor the JDK client exposes a DNS-resolution timeout, and no proxy-credential path exists, so a non-default value is refused rather than accepted and ignored. Leaving the defaults alone is unaffected — only a deliberate, unmet request fails. diff --git a/docs/httpclient/env-fields.yaml b/docs/httpclient/env-fields.yaml index e0578fa5..b8ecbf59 100644 --- a/docs/httpclient/env-fields.yaml +++ b/docs/httpclient/env-fields.yaml @@ -57,10 +57,6 @@ fields: env: APP_HTTPCLIENT_CLIENTS_N_POOL_MAX_LIFE_TIME - field: clients[N].pool.validate-after-inactivity env: APP_HTTPCLIENT_CLIENTS_N_POOL_VALIDATE_AFTER_INACTIVITY - - field: clients[N].pool.eviction-interval - env: APP_HTTPCLIENT_CLIENTS_N_POOL_EVICTION_INTERVAL - - field: clients[N].pool.shutdown-timeout - env: APP_HTTPCLIENT_CLIENTS_N_POOL_SHUTDOWN_TIMEOUT - field: clients[N].pool.requires-route-pool env: APP_HTTPCLIENT_CLIENTS_N_POOL_REQUIRES_ROUTE_POOL - field: clients[N].pool.requires-bounded-pending-queue @@ -71,10 +67,6 @@ fields: env: APP_HTTPCLIENT_CLIENTS_N_TIMEOUT_CONNECT - field: clients[N].timeout.tls-handshake env: APP_HTTPCLIENT_CLIENTS_N_TIMEOUT_TLS_HANDSHAKE - - field: clients[N].timeout.proxy-connect - env: APP_HTTPCLIENT_CLIENTS_N_TIMEOUT_PROXY_CONNECT - - field: clients[N].timeout.request-write-idle - env: APP_HTTPCLIENT_CLIENTS_N_TIMEOUT_REQUEST_WRITE_IDLE - field: clients[N].timeout.response-header env: APP_HTTPCLIENT_CLIENTS_N_TIMEOUT_RESPONSE_HEADER - field: clients[N].timeout.read-idle @@ -123,8 +115,6 @@ fields: env: APP_HTTPCLIENT_CLIENTS_N_RETRY_RETRY_AFTER - field: clients[N].retry.budget env: APP_HTTPCLIENT_CLIENTS_N_RETRY_BUDGET - - field: clients[N].observability.operation-name-required - env: APP_HTTPCLIENT_CLIENTS_N_OBSERVABILITY_OPERATION_NAME_REQUIRED - field: clients[N].observability.full-url-recording env: APP_HTTPCLIENT_CLIENTS_N_OBSERVABILITY_FULL_URL_RECORDING - field: clients[N].observability.body-logging @@ -153,12 +143,20 @@ fields: env: APP_HTTPCLIENT_CLIENTS_N_PROXY_TYPE - field: clients[N].proxy.credential-provider env: APP_HTTPCLIENT_CLIENTS_N_PROXY_CREDENTIAL_PROVIDER - - field: clients[N].proxy.connect-timeout - env: APP_HTTPCLIENT_CLIENTS_N_PROXY_CONNECT_TIMEOUT - field: clients[N].proxy.import-ambient-no-proxy env: APP_HTTPCLIENT_CLIENTS_N_PROXY_IMPORT_AMBIENT_NO_PROXY - field: clients[N].experimental-acknowledgement env: APP_HTTPCLIENT_CLIENTS_N_EXPERIMENTAL_ACKNOWLEDGEMENT + - field: clients[N].circuit-breaker.failure-rate-threshold + env: APP_HTTPCLIENT_CLIENTS_N_CIRCUIT_BREAKER_FAILURE_RATE_THRESHOLD + - field: clients[N].circuit-breaker.minimum-number-of-calls + env: APP_HTTPCLIENT_CLIENTS_N_CIRCUIT_BREAKER_MINIMUM_NUMBER_OF_CALLS + - field: clients[N].circuit-breaker.sliding-window-size + env: APP_HTTPCLIENT_CLIENTS_N_CIRCUIT_BREAKER_SLIDING_WINDOW_SIZE + - field: clients[N].circuit-breaker.wait-duration-in-open-state + env: APP_HTTPCLIENT_CLIENTS_N_CIRCUIT_BREAKER_WAIT_DURATION_IN_OPEN_STATE + - field: clients[N].circuit-breaker.permitted-calls-in-half-open-state + env: APP_HTTPCLIENT_CLIENTS_N_CIRCUIT_BREAKER_PERMITTED_CALLS_IN_HALF_OPEN_STATE - field: dynamic-targets[N].name env: APP_HTTPCLIENT_DYNAMIC_TARGETS_N_NAME - field: dynamic-targets[N].allowed-schemes[M] diff --git a/docs/httpclient/retry-and-ambiguity.md b/docs/httpclient/retry-and-ambiguity.md index bfc426c0..0f7e5b4c 100644 --- a/docs/httpclient/retry-and-ambiguity.md +++ b/docs/httpclient/retry-and-ambiguity.md @@ -33,15 +33,20 @@ upgraded to `NOT_SENT`, because that is exactly how a timeout becomes a duplicat `DefaultRetryEligibilityEngine` evaluates in this order, and a later rule can never re-enable something an earlier one forbade: -1. attempts exhausted → `RetryDenied.maxAttempts()` -2. retry budget empty → `RetryDenied.budgetExhausted()` -3. body not replayable → `RetryDenied.bodyNotReplayable()` -4. first byte already delivered → `RetryDenied.responseAlreadyDelivered()` -5. runtime draining → `RetryDenied.runtimeDraining()` -6. remaining deadline below the minimum attempt budget → `RetryDenied.deadline()` -7. permanent failure category → `RetryDenied.permanentFailure(...)` -8. `SENT_NO_RESPONSE` on an operation that is not safely idempotent → `AmbiguousFailure` -9. status- and failure-specific rules +1. `SENT_NO_RESPONSE` on an operation that is not safely idempotent → `AmbiguousFailure` +2. attempts exhausted → `RetryDenied.maxAttempts()` +3. retry budget empty → `RetryDenied.budgetExhausted()` +4. body not replayable → `RetryDenied.bodyNotReplayable()` +5. first byte already delivered → `RetryDenied.responseAlreadyDelivered()` +6. runtime draining → `RetryDenied.runtimeDraining()` +7. remaining deadline below the minimum attempt budget → `RetryDenied.deadline()` +8. permanent failure category → `RetryDenied.permanentFailure(...)` +9. `PARTIAL_RESPONSE` on an operation that is not safely idempotent → `AmbiguousFailure` +10. status- and failure-specific rules + +Ambiguity comes first because it describes the outcome, not whether another attempt is allowed. It +used to sit below the attempt check, so with the default `max-attempts: 1` a POST that timed out +after it was sent reached the caller as an ordinary timeout (review 2026-11-01 05-14). ## Status rules @@ -50,7 +55,7 @@ something an earlier one forbade: | 408 | retry inside deadline and budget | | 425 | at most one retry, first attempt only | | 429 | retry inside `Retry-After`, deadline, and budget | -| 401 | one refresh-and-replay, safe replayable operations only | +| 401 | one refresh-and-replay, safe replayable operations only. The credential is refreshed only once the retry is granted; a 401 that will not be replayed (one attempt, no budget, no deadline) leaves the token cache alone | | 500 | denied unless the upstream registered it as transient **and** the operation is safely idempotent | | 502, 503, 504 | retry for safely idempotent operations; ambiguous otherwise | | other 4xx | denied | @@ -63,6 +68,17 @@ effect, and reporting a plain failure would tell the caller the request did not be false. The caller reconciles, usually by querying the upstream or replaying with an idempotency key. +### Where the evidence comes from + +Whether a failed request was sent is read from the stage the attempt reached and the engine's +exception type. Apache reports the moment it starts writing the request onto an established +connection (`RequestWriteSignal`), so a failure while leasing, resolving, connecting or completing +the TLS handshake is `NOT_SENT` even when the engine throws a generic exception. Transports that +cannot report that moment (JDK, Jetty) are treated as writing from the moment the engine is called, +because guessing "not sent" is what turns a timeout into a duplicate payment. An HTTP/2 +`REFUSED_STREAM` frame is proof the peer processed nothing and is kept as `NOT_SENT` through +exception mapping. + ## Budget and backoff Retry tokens come from a per-upstream token bucket sized as a fraction of real traffic, so a failing diff --git a/docs/jpa/transaction-guide.md b/docs/jpa/transaction-guide.md index 747931c8..491d7530 100644 --- a/docs/jpa/transaction-guide.md +++ b/docs/jpa/transaction-guide.md @@ -7,7 +7,18 @@ Design §15-§20. What owns a transaction, what may be retried, and what must ne Repository adapters do not open transactions. The use case does, through `TransactionPort`, because the unit of work is a business decision and only the use case knows where it starts and ends. `SpringTransaction` is the only implementation: one pre-built `TransactionTemplate` per -mode over Spring's `PlatformTransactionManager`, every mode pinned to `READ_COMMITTED`. +mode over Spring's `PlatformTransactionManager`, every mode running at `READ_COMMITTED` and +bounded in time. + +- **Isolation** is pinned on the pool, not per transaction: the module defaults set + `spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED` and + `HikariPoolConstraintValidator` refuses any other level. A template that names the level makes + pgjdbc ask the server for it (`SHOW TRANSACTION ISOLATION LEVEL`) at every begin. +- **Time bound**: `app.persistence-jpa.transaction.write-timeout` (`inWrite`, `inRootWrite`) and + `read-timeout` (`inRead`), 30 s each by default; `inNew` is fixed at 30 s. Spring hands the + remaining time to each statement, so the server cancels a slow statement or lock wait + (`DB_QUERY_CANCELED`) and the connection returns to the pool. A unit of work that needs longer + is usually a batch job that should be split, not a reason to raise the bound. | Call | Propagation | When | |---|---|---| @@ -29,7 +40,8 @@ maximumPoolSize >= (concurrent_threads x (1 + max_requires_new_depth)) + 1 ## Nothing is retried by the port `SpringTransaction` runs the action once. A failure rolls back and propagates, translated to -the shared persistence error codes where the SQLSTATE is known. A caller that decides to retry must +the shared persistence error codes where the SQLSTATE is known; a lost `@Version` race has no +SQLSTATE and is reported as `DB_OPTIMISTIC_CONFLICT` (409). A caller that decides to retry must re-run the whole use case in a new transaction — never re-issue one statement — because an optimistic conflict or a serialization failure means the state the attempt computed against is no longer the committed state. diff --git a/docs/manual/01-generator.md b/docs/manual/01-generator.md new file mode 100644 index 00000000..79bebae6 --- /dev/null +++ b/docs/manual/01-generator.md @@ -0,0 +1,95 @@ +# 01. 생성 명령 — 새 기능 뼈대 + +## 핵심 + +`scripts/new-feature.sh ` 한 번으로 새 업무 기능의 뼈대가 계층 leaf 다섯 곳에 생긴다. +만든 직후 그대로 PR 게이트(`ci`의 해당 leaf check)와 `architectureCheck`를 통과한다. 이 성질은 +`scripts/verify-feature-scaffold.sh`가 main 단계(`mainCheck`)에서 매번 확인한다. + +```text +scripts/new-feature.sh Invoice + -> domain-core Invoice, InvoiceId, InvoiceIdFactory, InvoiceRepository, InvoiceInvariantException + + testFixtures: InMemoryInvoiceRepository, SequentialInvoiceIdFactory, InvoiceRepositoryContract + -> application-core CreateInvoiceUseCase, GetInvoiceUseCase, command·query·view, InvoiceErrorCode, 예외 2개 + -> outbound:identifier UuidInvoiceIdFactory + -> inbound:web InvoiceController (POST /invoices, GET /invoices/{id}), 요청·응답 DTO + -> app-bootstrap InvoiceConfig + AutoConfiguration.imports 한 줄 + -> 각 leaf 테스트 불변식, id 문법, 유스케이스, 공유 계약, HTTP 계약, 조립 조건 + -> spotlessApply (이름 길이에 따라 Javadoc 줄바꿈이 달라져서) +``` + +## 사용법 + +```bash +scripts/new-feature.sh Invoice # /invoices, 권한 invoice:create +scripts/new-feature.sh PurchaseOrder # /purchaseOrders, 권한 purchase-order:create +scripts/new-feature.sh Person --path people # 복수형이 규칙대로 안 될 때 +scripts/new-feature.sh Invoice --no-format # Gradle 없이 파일만 (뒤에 spotlessApply 직접) +``` + +| 입력 | 규칙 | 어디서 막나 | +| --- | --- | --- | +| 이름 | PascalCase, 영숫자 | 스크립트 | +| 패키지 이름 | 이름을 소문자로(`purchaseorder`). Java 예약어·플랫폼 패키지(`operation`, `lock`, `cache`…)와 겹치면 거절 | 스크립트 | +| HTTP 경로 | lowerCamel 복수형. AIP-122 모양 | 스크립트, `ForbiddenApiArchitectureTest.CONTROLLER_REQUEST_MAPPINGS_FOLLOW_AIP122` | +| 이미 있는 파일·패키지 | 덮어쓰지 않고 멈춘다 | 스크립트 | + +생성 뒤 확인: + +```bash +cd src +./gradlew :domain-core:check :application-core:check :adapter:outbound:identifier:check \ + :adapter:inbound:web:check :app-bootstrap:check architectureCheck --console=plain +``` + +## 만드는 것과 만들지 않는 것 + +| 만든다 | 만들지 않는다 | 이유 | +| --- | --- | --- | +| 도메인 모델·포트·불변식, 유스케이스 두 개(쓰기·읽기), id adapter, 컨트롤러, 조립, 테스트 | **저장 adapter**(JPA 엔티티·Spring Data·마이그레이션) | 저장소 종류(JPA/Mongo), 마이그레이션 위치·번호대, 실 DB 계약 lane은 서비스가 정한다(04장). 템플릿이 정하면 upstream과 병합 충돌이 나는 자리다 | +| 권한 선언 `@RequiresPermission(":create")` | 역할 → 권한 매핑 | 어떤 역할이 쓸 수 있는지는 서비스의 결정이다(07장). 매핑 전에는 쓰기가 모두 403 — 안전한 쪽 | +| `ErrorCode` enum | `docs/registries/error-codes.yaml` 행 | 그 registry는 템플릿 운영 코드 전용이다. 서비스 코드는 서비스 registry에(06장) | +| 읽기 유스케이스 | 목록·수정·삭제 | 목록은 페이지·정렬·N+1 판단이, 수정은 동시성(버전) 판단이 필요하다(04장) | + +저장 adapter가 없으면 `Config`의 `@ConditionalOnBean(Repository)`가 꺼져 있어 엔드포인트가 +**없다**. 반쯤 켜진 상태(엔드포인트는 있는데 저장이 안 됨)가 생기지 않는다. + +생성 결과는 placeholder 필드 `name` 하나를 가진다. 기능의 실제 상태로 바꾸는 것이 첫 작업이다. + +## 왕복 검사 + +```text +verify-feature-scaffold.sh + -> 작업 트리를 임시 디렉터리로 복사(추적 + 무시되지 않은 새 파일), git init + -> new-feature.sh Invoice, new-feature.sh PurchaseOrder (한 단어 / 여러 단어) + -> 생성 파일이 있는지 확인 + -> ./gradlew 5 leaf check + architectureCheck + -> 각 leaf 테스트 결과에 생성된 테스트 클래스가 실행·통과로 남았는지 확인 + -> 임시 디렉터리 삭제 +``` + +- 루트 태스크 `verifyFeatureScaffold`(`src/build.gradle`)가 이 스크립트를 부르고 `mainCheck`에 들어 + 있다. 중첩 Gradle 빌드라 PR 단계가 아니라 main 단계다. +- 템플릿이나 템플릿이 기대는 규칙(ArchUnit, Error Prone, 포맷)이 바뀌어 생성물이 깨지면 여기서 빨강이 된다. +- 생성된 테스트가 실행되지 않고 지나가는 일(빈 녹색)을 막으려고 결과 XML을 확인한다. + +## 고른 형태와 버린 대안 + +| 형태 | 결정 | 이유 | +| --- | --- | --- | +| `scripts/`의 bash + 텍스트 템플릿(`scripts/feature-scaffold/templates/**/*.tmpl`) | **채택** | 개발자 도구는 `scripts/`에 둔다는 repo 관례(`ca.developer-bootstrap` 플러그인을 지우고 `scripts/bootstrap-local.sh`로 옮긴 것, `src/build-logic/README.md`). 템플릿이 실제 Java 파일 모양이라 리뷰가 쉽다. Gradle 설정 단계를 거치지 않아 빠르다 | +| build-logic의 Gradle 태스크(`./gradlew newFeature -Pname=…`) | 버림 | build-logic은 빌드 규약·아키텍처 검사만 둔다(`CLAUDE.md` Gradle policy). 소스를 쓰는 태스크는 configuration cache·up-to-date와 맞지 않는다 | +| 생성 대신 예시 기능을 커밋해 두고 복사 | 버림 | 복사본이 하나 더 생겨 규칙과 갈라진다. 이름 바꾸기를 사람이 손으로 한다 | +| 왕복 검사를 JUnit 안에서 javac로 컴파일 | 버림 | Spotless·Error Prone·ArchUnit 전체를 다시 구현해야 하고, 실제 게이트와 다른 것을 검사하게 된다. 실제 Gradle 게이트를 그대로 돌리는 쪽을 골랐다 | +| 생성 뒤 자동 `spotlessApply` | 채택(끄려면 `--no-format`) | google-java-format이 Javadoc을 이름 길이에 따라 다시 접는다. 템플릿만으로는 모든 이름에서 포맷 검사를 통과시킬 수 없다 | + +## 생성 결과가 기대는 빌드 설정 + +생성물이 컴파일되려고 다음 의존이 미리 들어 있다(모두 registry가 허용한 edge). + +| 파일 | 설정 | 왜 | +| --- | --- | --- | +| `src/domain-core/build.gradle` | `java-test-fixtures` | domain 소유 포트의 fake·계약이 포트 소유자 testFixtures에 있어야 한다(AGENTS.md 테스트 규칙 6) | +| `src/application-core/build.gradle`, `src/adapter/inbound/web/build.gradle`, `src/app-bootstrap/build.gradle` | `testImplementation testFixtures(project(':domain-core'))` | 유스케이스·HTTP·조립 테스트가 그 fake를 쓴다 | +| `src/adapter/inbound/web/build.gradle` | `implementation project(':domain-core')` | 컨트롤러가 경로 문자열을 도메인 id로 바꾼다 | +| `src/adapter/outbound/identifier/build.gradle` | `implementation project(':domain-core')` | id adapter가 도메인 `IdFactory` 포트를 구현한다 | diff --git a/docs/manual/02-new-feature.md b/docs/manual/02-new-feature.md new file mode 100644 index 00000000..8bdf7814 --- /dev/null +++ b/docs/manual/02-new-feature.md @@ -0,0 +1,143 @@ +# 02. 새 도메인·유스케이스 추가 + +## 핵심 + +안쪽 계층부터 바깥으로 만든다. 각 단계는 그 단계의 테스트까지 끝내고 다음으로 간다. +생성 명령(01장)이 1~5단계의 뼈대를 만들고, 이 장은 각 단계에서 사람이 정할 것을 적는다. + +```text +1 domain-core ─▶ 2 application-core ─▶ 3 outbound adapter ─▶ 4 inbound adapter ─▶ 5 app-bootstrap + 모델·불변식 유스케이스·포트 저장·외부 연동 전송·DTO·오류 bean·조건·권한 + (Java만) (Java + 계약 타입) (Spring·JPA 등) (HTTP 등) (조립) +``` + +바깥 계층은 안쪽을 알지만 안쪽은 바깥을 모른다. 그래서 안쪽부터 만들면 각 단계가 앞 단계만 보고 +컴파일된다. 한 단계가 다른 leaf나 계층을 고쳐야 하면 거기서 멈추고 설계를 다시 본다(`CLAUDE.md` +Layer workflow). + +## 0단계 — 배치를 정한다 + +먼저 03장으로 이 기능을 어디 둘지 정한다. 기본은 계층 leaf 안 `` 패키지다. 생성 명령은 이 +기본값만 만든다. + +## 1단계 — domain-core: 모델과 불변식 + +만드는 것: aggregate(`@AggregateRoot`), id(`@ValueObject` record, `ResourceId`), id 생성 포트 +(`IdFactory` 상속), 저장 포트(`*Repository`), 불변식 예외(`Reason` enum). +예: 생성 결과 `src/domain-core/src/main/java/dev/caskeleton/domain//`. + +검사: `DomainPurityArchitectureTest`(Spring·JPA·전송 타입 금지, setter 비공개, 감사 필드 금지), +`ForbiddenApiArchitectureTest.NO_LONG_ID_PK`. + +### 판단: id를 누가 만드나 + +- **고르는 기준**: 클라이언트가 같은 요청을 다시 보낼 때 같은 리소스를 가리켜야 하는가. +- **기본값**: 서버가 만든다. domain `XIdFactory extends IdFactory` + `adapter:outbound:identifier` + 구현. 문법은 id 값 객체 생성자에서 검사한다. +- **예외**: 클라이언트가 자연 키(주문번호 등)를 주는 기능은 그 키를 id로 쓴다. 이때 중복은 DB 유일성 + 제약이 막는다(04장). UUIDv7이 필요하면 `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/UuidWorkLogIdFactory.java`처럼 바꾼다. + +### 판단: 불변식을 어디 두나 + +- **고르는 기준**: 규칙이 aggregate 하나의 상태만 보고 판정되는가. +- **기본값**: aggregate 메서드·팩토리 안. 위반은 `XInvariantException(Reason)`. +- **예외**: 둘 이상의 aggregate나 저장된 다른 행을 봐야 하는 규칙(중복 금지 등)은 유스케이스 + DB 제약. + 조회 후 insert만으로는 동시 요청에서 깨진다(04장). + +### 판단: 저장 포트를 누가 소유하나 + +- **고르는 기준**: 포트가 aggregate 단위로 말하는가, 기술적 저장·조회인가. +- **기본값**: aggregate를 통째로 저장·로드하면 domain 소유 `XRepository`. +- **예외**: 읽기 모양이 aggregate와 다르면 application 소유 `XQueryPort` + projection(record). + `QUERY_PORTS_DO_NOT_LEAK_DOMAIN_JPA_OR_WEB_TYPES`가 반환 타입을 검사한다. lease·claim 같은 기술 + 저장은 application 소유 `*StorePort`. 이름 규칙의 정본은 `src/application-core/CLAUDE.md`. + +## 2단계 — application-core: 유스케이스와 포트 + +만드는 것: command/query record, 유스케이스(쓰기 `CommandUseCase`, 읽기 `QueryUseCase`), 반환용 view +record, 오류 코드 enum과 carrier 예외. 예: `src/application-core/src/main/java/dev/caskeleton/application//`. + +필수 선언(ArchUnit이 강제, `ApplicationBoundaryArchitectureTest`): + +- 모든 유스케이스에 `@UseCaseCapability(transactionMode, idempotency, repositoryAccess)`. 선언과 + 실제 `TransactionPort` 호출이 맞아야 한다(`USE_CASE_CAPABILITY_MATCHES_TRANSACTION_PORT_BOUNDARY`). +- 쓰기 유스케이스에 `@RequiresPermission(":")`(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`). +- 유스케이스 클래스는 `final`이 아니다. 권한 프록시가 하위 클래스를 만든다 + (`src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/authz/RequiresPermissionProxyabilityTest.java`). + +### 판단: 트랜잭션 모양 + +- **고르는 기준**: 결과를 커밋 뒤에 내보내야 하는가, 호출자와 독립적으로 커밋해야 하는가. +- **기본값**: 쓰기 `tx.inWrite`, 읽기 `tx.inRead`. +- **예외**: 커밋 확인 뒤 결과를 노출해야 하면 `inRootWrite`(바깥 트랜잭션이 있으면 거부). 감사·보상만 + `inNew`(루프 안 금지). 외부 HTTP·메시지 발행은 트랜잭션 밖. 표: `src/application-core/CLAUDE.md` + 「Allowed transactional shapes」. + +### 판단: 무엇을 반환하나 + +- **기본값**: application view record(`XView`). 전송 계층이 aggregate를 받지 않는다 + (`TypeBoundaryArchitectureTest.CONTROLLERS_DO_NOT_RETURN_DOMAIN_OR_ENTITY_TYPES`). +- **예외**: 같은 leaf 안 다른 유스케이스가 aggregate를 이어 받아야 하면 aggregate를 반환해도 된다. + 컨트롤러는 그때도 응답 DTO로 바꾼다. + +### 판단: 멱등성 선언 + +05장. 기본값 `NOT_IDEMPOTENT`(쓰기), `IDEMPOTENT`(읽기). 클라이언트가 재전송할 수 있는 결제·주문류 +쓰기는 `KEYED`. + +## 3단계 — outbound adapter + +만드는 것: 포트 구현. 생성 명령은 id adapter(`adapter:outbound:identifier//UuidIdFactory`)만 +만든다. 저장 adapter는 04장 순서로 직접 만든다. + +필수: adapter는 포트 소유자 testFixtures의 `XRepositoryContract`를 실제 저장소로 상속하는 테스트를 +가진다(08장). 실 DB가 필요하면 strict lane(`integrationTest` 등)에 둔다. + +## 4단계 — inbound adapter (HTTP) + +만드는 것: 컨트롤러, 요청·응답 DTO. 예: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web//`. + +- 컨트롤러는 변환만 한다: 요청 → command/query → 유스케이스 → `Envelope.ok(응답 DTO, ResponseMetaFactory.fromMdc())`. + repository·엔티티 직접 사용 금지(`CONTROLLERS_DO_NOT_ACCESS_REPOSITORIES_OR_JPA_ENTITIES`). +- 생성 201은 `Location` 헤더를 준다. 비동기 수락은 202(`DurableOperationController`). +- 경로는 lowerCamel 복수형(AIP-122). +- 실패는 던지기만 한다. `ApiErrorCarrier`를 전역 핸들러가 매핑한다(06장). 기능 전용 핸들러를 만들지 않는다. + +### 판단: 입력 검증을 어디서 하나 + +- **고르는 기준**: 규칙이 도메인 규칙인가, wire 모양(형식·필수 키)인가. +- **기본값**: 도메인 규칙은 aggregate가 한 번만 검사한다. DTO에 같은 규칙을 bean validation으로 또 쓰지 + 않는다(두 벌이 갈라진다). +- **예외**: 도메인이 볼 수 없는 wire 모양 — 크기 상한, 형식 패턴, 필수 키 — 은 DTO에 + `@NotNull`·`@Size`·`@Pattern`으로 둔다(`SubmitOperationHttpRequest`). 이것은 400 `VALIDATION_FAILED`로 나간다. + +## 5단계 — app-bootstrap 조립 + +만드는 것: `@AutoConfiguration` 클래스 하나 + `AutoConfiguration.imports` 한 줄. +예: `src/composition/durable-operation/src/main/java/dev/caskeleton/composition/operation/DurableOperationAutoConfiguration.java`. + +- `@ConditionalOnBean(필요한 포트들)`: 포트 구현이 없으면 기능 전체가 없다. +- 유스케이스는 `@Bean`으로 만든다. 직접 `new` 하면 권한 프록시가 없어 `@RequiresPermission`이 조용히 + 빠진다. +- 컨트롤러는 component scan이 아니라 `@Import`로 등록한다. scan은 `dev.caskeleton.bootstrap`만 본다 + (`CaSkeletonApplication`). +- 포트 구현이 다른 자동 설정에서 오면 `afterName`으로 순서를 적는다. 안 적으면 조건이 그 bean을 못 본다. +- 이벤트를 내면 계약 contribution도 `@Bean`으로 등록한다(09장). +- 역할 → 권한 매핑을 `app.authz.role-permissions`에 더한다(07장). + +## 6단계 — 공개 계약이 바뀌었으면 함께 고친다 + +| 바뀐 것 | 같이 할 것 | +| --- | --- | +| 새 공개 경로(인증 없이 열림) | `docs/security/public-paths-snapshot.txt`, `./gradlew verifyPublicPathSnapshot` | +| 새 env 키 | `docs/registries/env-keys.yaml`, `./gradlew :app-bootstrap:verifyEnvKeys` | +| 새 의존성 | lockfile 갱신(`./gradlew ::resolveAndLockAll --write-locks`), `verifyDependencyLocks` | +| 새 마이그레이션 | 04장 번호 규칙 | +| 새 이벤트 계약 | 09장 | + +## 지금 이해하면 되는 것 + +- 안쪽부터: domain → application → outbound → inbound → bootstrap. +- 쓰기 유스케이스는 non-final + `@RequiresPermission` + bean. 셋 중 하나라도 빠지면 권한 검사가 없다. +- 조립은 포트가 있을 때만 켜진다. 저장 adapter가 생기기 전 기능은 없는 상태다. +- 같은 규칙을 두 곳에 쓰지 않는다. 도메인 규칙은 aggregate, wire 모양은 DTO. diff --git a/docs/manual/03-placement.md b/docs/manual/03-placement.md new file mode 100644 index 00000000..448d13fc --- /dev/null +++ b/docs/manual/03-placement.md @@ -0,0 +1,73 @@ +# 03. 새 기능을 둘 곳 고르기 + +## 핵심 + +새 기능을 두는 모양은 셋이다. **업무 기능의 기본은 ① 계층 leaf 안 `` 패키지**다. +선택해서 켜고 끄는 플랫폼 기능만 ② 별도 `application-*` leaf로 만든다. ③ 한 leaf 수직 슬라이스는 +지울 수 있는 샘플 전용이다. 생성 명령은 ①만 만든다. + +```text +① 계층 leaf 안 패키지 (기본) + domain-core/.../domain/ -> application-core/.../application/ -> adapter:*/.../ -> app-bootstrap/.../autoconfigure/ + +② 기능 전용 leaf (capability) + application- -> persistence-, adapter:outbound:, adapter:inbound:web- -> composition:-platform + app-bootstrap/build.gradle 에 runtimeOnly 한 줄 + +③ 한 leaf 수직 슬라이스 (샘플 전용) + sample-portfolio = domain + application + adapter + bootstrap 패키지 +``` + +## 기준표 + +| 질문 | ① 계층 leaf 패키지 | ② 기능 leaf | ③ 수직 슬라이스 | +| --- | --- | --- | --- | +| 서비스마다 켜고 끌 수 있어야 하나 | 아니오 | **예** | — | +| 다른 서비스가 같은 기능을 라이브러리로 받나 | 아니오 | **예** | 아니오 | +| 한 줄 지워 기능을 통째로 빼야 하나 | 아니오(패키지 삭제) | **예**(`runtimeOnly` 한 줄) | 예(leaf 삭제) | +| leaf 단위 의존 방향 검사가 기능 안에도 걸리나 | 예(계층이 leaf) | 예 | **아니오**(ArchUnit 패키지 규칙에만 기댐) | +| 고칠 공용 파일 | 없음(+ imports 한 줄) | `modules.json`, `settings.gradle` 매핑, `app-bootstrap/build.gradle`, lockfile | `modules.json` | +| 예시 | 생성 명령 출력, `application-core/.../operation` | `application-notification`, `application-fileserver`, `application-objectstorage` | `sample-portfolio` | + +### 판단: ①과 ② 중 무엇인가 + +- **고르는 기준**: 이 기능을 쓰지 않는 서비스(또는 같은 서비스의 다른 배포)가 있는가. +- **기본값**: ①. 업무 기능은 그 서비스의 존재 이유라 끌 일이 없다. 파일 추가만으로 끝나고, leaf 경계 + 검사가 계층마다 걸린다. +- **예외**: ② — 여러 서비스가 쓰는 플랫폼 기능, 배포마다 켜고 끄는 기능, 자기 설정 prefix와 자기 + 저장소를 가진 기능. 이때는 capability 완료 기준 7개를 모두 지킨다(`AGENTS.md`, 10장). +- **다시 볼 조건**: 파생 서비스가 둘 이상 생겨 같은 업무 기능을 공유하거나, application-core 컴파일·테스트 + 시간이 문제가 되면 ①을 ②로 옮긴다(리뷰 01 영역 5.2절). + +### 판단: ③을 써도 되나 + +- **기본값**: 쓰지 않는다. ③은 leaf 하나가 모든 계층에 의존해서 leaf 단위 방향 검사가 기능 안에서는 + 아무것도 막지 못한다. +- **예외**: 통째로 지울 수 있어야 하는 샘플·데모. `sample-portfolio`가 그 예다. 샘플을 계층 leaf로 쪼개지 + 않는 이유는 "leaf 하나 지우면 끝"이라는 성질을 지키려는 것이다. + +## ① 안의 패키지 규칙 + +| 계층 | 패키지 | 하위 패키지 | +| --- | --- | --- | +| domain | `dev.caskeleton.domain.` | fake·계약은 testFixtures `dev.caskeleton.domain..testkit` | +| application | `dev.caskeleton.application.` | 종류별 하위 패키지(`command`, `usecase`, `port`)를 만들지 않는다. 기능별 한 패키지(sample P30 결정과 같다) | +| outbound | `dev.caskeleton.adapter.outbound..` | | +| inbound | `dev.caskeleton.adapter.inbound.web.` | | +| bootstrap | `dev.caskeleton.bootstrap.autoconfigure.` | `@AutoConfiguration`만(`BOOTSTRAP_AUTOCONFIGURE_STEREOTYPES_ARE_AUTO_CONFIGURATIONS`) | + +- ``는 템플릿 플랫폼 패키지(`operation`, `outbox`, `lock`, `cache`, `idempotency`, `security`, + `tenant`, `transaction`…)와 겹치지 않는다. 생성 명령이 막는다. 겹치면 upstream 템플릿을 받을 때 같은 + 패키지 트리에서 병합 충돌이 난다. +- 이름 규칙은 `src/application-core/CLAUDE.md` 「Naming convention」이 정본이다. + +## 저장 adapter는 어디에 + +① 기능의 저장 adapter 위치는 04장 「판단: 저장 adapter를 둘 leaf」. 요약: persistence-jpa에 업무 코드를 +넣지 않는다(그 leaf는 capability라 "모듈을 아는 곳은 모듈 자신뿐" 규칙이 걸린다). + +## 지금 이해하면 되는 것 + +- 업무 기능 = ① 계층 leaf 패키지. 생성 명령이 이 모양을 만든다. +- 켜고 끄는 플랫폼 기능 = ② 별도 leaf, capability 기준 7개. +- sample-portfolio는 기법 참고용이지 배치 예시가 아니다. diff --git a/docs/manual/04-persistence.md b/docs/manual/04-persistence.md new file mode 100644 index 00000000..4b40ee6e --- /dev/null +++ b/docs/manual/04-persistence.md @@ -0,0 +1,126 @@ +# 04. 영속성 + +## 핵심 + +저장 adapter는 생성 명령이 만들지 않는다. 이 장의 순서로 만든다. 세 가지를 지킨다. + +1. 엔티티 연관관계는 한쪽에서만 맵핑한다. 빌드가 막는다. +2. 중복·경쟁은 코드 순서가 아니라 **DB 제약**이 막고, 위반은 기능의 오류로 바꾼다. +3. 마이그레이션은 템플릿 운영 스트림과 **번호가 겹치지 않는 자기 스트림**에 둔다. + +```text +use case ── tx.inWrite ──▶ XRepository (domain 포트) + │ + ▼ + JpaXRepository (adapter) ── CallerTransaction.require + │ 엔티티 ↔ aggregate 변환(mapper) + ▼ + Spring Data / EntityManager ──▶ PostgreSQL (제약·인덱스) + │ + 위반·장애 ──▶ PersistenceExceptionTranslator ──▶ OperationalError 또는 기능 예외 +``` + +## 순서 + +1. 계약 테스트부터: 생성된 `XRepositoryContract`(domain-core testFixtures)에 필요한 동작을 더한다. + in-memory fake가 먼저 통과해야 한다. +2. 마이그레이션을 쓴다(아래 번호 규칙). +3. 엔티티·Spring Data repository·mapper·adapter를 쓴다. adapter는 aggregate만 주고받는다 + (`OUTBOUND_ADAPTER_METHOD_RETURNS_ONLY_DOMAIN_OR_PRIMITIVES`). +4. `JpaXRepositoryContractTest extends XRepositoryContract`를 실 PostgreSQL lane에 둔다(08장 lane). + 예: `src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterContractTest.java`. +5. adapter를 bean으로 등록하는 자동 설정을 쓰고, 기능의 `XConfig`에 `afterName`으로 그 순서를 적는다. + +## 판단: 저장 adapter를 둘 leaf + +- **고르는 기준**: upstream 템플릿 leaf에 서비스 코드가 섞이는가. +- **기본값**: 서비스 전용 persistence leaf 하나(`adapter:outbound:persistence-`)를 registry에 + 등록하고 업무 기능의 adapter를 모두 거기 둔다. 모양은 `src/adapter/outbound/persistence-notification` + (`persistence-jpa`에 의존, 자기 엔티티 scan·자기 Flyway 스트림·자기 자동 설정). +- **예외**: 하나도 없다고 보는 편이 낫다. `persistence-jpa`에 업무 패키지를 넣으면 ① capability 규칙 7 + ("모듈을 아는 곳은 모듈 자신뿐")을 어기고, ② 그 leaf의 공개 API 기준선 + (`docs/architecture/jpa-api-surface.txt`)과 엔티티 scan 목록(`PersistenceJpaConfig`, + `PersistenceEntityScanCoverageTest`)을 고쳐야 하며, ③ upstream 병합 충돌 면이 넓어진다. + sample은 자기 leaf 안에 adapter를 둔다(③ 수직 슬라이스라서). +- 새 leaf는 `modules.json` 등록, lockfile 생성, `app-bootstrap/build.gradle` 한 줄이 필요하다(10장). + +## 엔티티 매핑 + +정본: `docs/jpa/entity-mapping-guide.md`. + +| 규칙 | 막는 곳 | +| --- | --- | +| 연관관계는 한쪽만. aggregate 사이는 id 참조, 같은 aggregate 안은 단방향 `@ManyToOne(LAZY)`, 컬렉션은 쿼리 | `JpaArchitectureRules.associationsAreMappedFromOneSideOnly()`(`src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRules.java`) — `JpaProductionArchitectureTest`가 운영 그래프 전체에 건다 | +| 엔티티는 adapter 밖으로 나가지 않는다 | `PERSISTENCE_ENTITIES_STAY_INSIDE_A_PERSISTENCE_ADAPTER`, `noEntityFromWeb` | +| `Long` id 금지, id 컬럼 `varchar(255)` 금지 | `NO_LONG_ID_PK`, `NO_VARCHAR_255_FOR_ID_COLUMN` | +| 벤더 전용 `columnDefinition` 금지 | `PERSISTENCE_RDBMS_ENTITIES_DO_NOT_PIN_VENDOR_COLUMN_DEFINITIONS` | +| 감사 필드는 엔티티에만, 도메인에는 없다 | `DOMAIN_ENTITIES_DO_NOT_CARRY_AUDIT_FIELDS` | + +### 판단: 단방향 `@OneToMany(@JoinColumn)`을 써도 되나 + +- **기본값**: 쓰지 않는다. 자식 목록은 repository 쿼리(`findByParentId`, 페이지는 SQL에서). +- **예외**: 루트만 바꾸는 자식(루트를 통해서만 생기고 지워짐). 규칙은 `mappedBy`만 막으므로 허용되지만 + nullable join column이면 자식마다 UPDATE가 한 번 더 나간다(가이드 「Associations」). + +## 트랜잭션 안에서만 쓴다 + +store는 자기 트랜잭션을 열지 않는다. 유스케이스가 연 트랜잭션에 합류해야 하는 쓰기는 시작 전에 +`CallerTransaction.require("<무엇>")` +(`src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CallerTransaction.java`)를 +부른다. 없으면 트랜잭션 밖 호출이 문장마다 따로 커밋되어, 같이 커밋돼야 할 행(업무 행 + outbox 행)이 +갈라진다. + +## 중복·경쟁은 DB가 막는다 + +- **고르는 기준**: "같은 X가 둘 있으면 안 된다", "한 작업을 두 인스턴스가 집으면 안 된다" 같은 규칙인가. +- **기본값**: DB 제약. + - 중복 금지 → 유일성 제약/인덱스. 유스케이스의 사전 조회(`existsBy…`)는 빠른 거절일 뿐이다. + READ COMMITTED에서 두 요청이 모두 "없음"을 보고 둘 다 insert한다. + - adapter가 그 **이름 붙은 제약**의 위반만 잡아 기능 예외로 바꾼다. 다른 제약 위반은 그대로 둔다. + 예: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapter.java` + (`DataIntegrityViolationException` → 제약 이름 확인 → `PosterTitleAlreadyExistsException` 409), + 제약은 `src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql`. + - 여러 인스턴스가 집는 작업 → `FOR UPDATE SKIP LOCKED`는 **트랜잭션 안에서**, 그리고 lease(만료 시각)와 + fence 값을 함께 저장한다. 예: `ReconciliationJobStorePort.claimDue`(application-notification), + gRPC operation ledger의 claim. + - 수정 충돌 → 버전 열(낙관적 잠금). 예: `UpdateWorkLogUseCase`의 version 비교와 `@Version`. +- **예외**: DB가 볼 수 없는 규칙(외부 시스템 상태)은 분산 락(`DistributedLockPort`)이나 멱등성 키(05장). +- 동시성 테스트는 실 DB lane에서 동시 요청 N개 → 행 1개를 단언한다(sample `integrationTest` 참고). + +## 기술 실패는 공통 코드로 나간다 + +어떤 기능 예외로도 바꾸지 않은 DB 실패는 `PersistenceExceptionTranslator` +(`src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java`)가 +SQLState로 `OperationalError`를 고른다. `DB_UNIQUE_VIOLATION` 409, `DB_SERIALIZATION_FAILURE`·`DB_DEADLOCK` +409(retryable), 커밋 중 연결 끊김은 `DB_COMPLETION_UNKNOWN` 500(05장). 분류표는 이 한 곳이다. adapter가 +SQLState 표를 복사하지 않는다. + +## 마이그레이션 번호 + +```text +템플릿 운영 스트림 classpath:db/migration/postgresql V1 … V19 … (upstream이 계속 늘린다) +capability 스트림 db/migration/jpa/ 각자 history table +샘플 스트림 db/sample-migration flyway_sample_schema_history +서비스 스트림(권장) db/migration/ flyway__schema_history +``` + +- **고르는 기준**: upstream 템플릿을 계속 받을 것인가. +- **기본값**: 서비스 마이그레이션은 **자기 위치 + 자기 history table** 스트림에 둔다. 모양은 + `SamplePostgreSqlPersistenceConfig.sampleMigrationStrategy` + (`src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfig.java`)와 + `NotificationSchemaStream`(persistence-notification). 그러면 번호가 템플릿 스트림과 독립이라 V1부터 쓴다. +- **예외**: 템플릿 운영 스트림(`db/migration/postgresql`)에 직접 넣으면 upstream이 다음에 쓸 번호와 + 겹친다. 어쩔 수 없으면 upstream이 쓰지 않을 큰 번호대를 정해 문서에 적는다. +- 이미 적용된 파일은 고치지 않는다. 고치면 체크섬 불일치로 기동이 멈추고, `repair`는 쓰지 않는다 + (`docs/jpa/migration-guide.md`). +- 같은 스트림 안에서 기존 두 버전 사이에 끼워야 하면 소수 버전(`V8_1`)을 쓴다. 샘플 테스트 일부가 운영 + 스트림과 샘플 스트림을 한 목록으로 합치는데, 정수 V9 이상은 운영이 이미 쓰고 있어서 `V8_1`을 골랐다 + (리뷰 README 13.2, 09-02). +- 기존 데이터가 새 제약을 어기면 마이그레이션이 이유를 남기고 멈추게 쓴다(`V8_1`의 `DO $$` 블록). 조용히 + 지우지 않는다. + +## 지금 이해하면 되는 것 + +- 저장 adapter는 서비스 전용 persistence leaf에. persistence-jpa에 업무 코드를 넣지 않는다. +- 중복은 유일성 제약, 경쟁은 트랜잭션 안 claim + lease, 수정 충돌은 버전 열. +- 마이그레이션은 자기 스트림(자기 history table). 적용된 파일은 고치지 않는다. diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md new file mode 100644 index 00000000..8ffd3d4f --- /dev/null +++ b/docs/manual/05-idempotency.md @@ -0,0 +1,79 @@ +# 05. 멱등성·결과 불명 처리 + +## 핵심 + +쓰기 요청의 결과는 세 가지다: 됐다, 안 됐다, **모른다**. "모른다"를 "안 됐다(다시 해도 됨)"로 적으면 +같은 작업이 두 번 적용된다. 그래서 결과를 증명할 수 없을 때는 항상 "모른다"로 답하고, 클라이언트가 +안전하게 다시 물을 방법(같은 멱등성 키)을 준다. + +```text +클라이언트 ── POST + Idempotency-Key ──▶ 컨트롤러 ──▶ KEYED 유스케이스 + │ IdempotencyExecutor + ├─ 처음 본 키 → 실행 → 결과 저장 → 응답 + ├─ 끝난 키 → 저장된 결과 재생 + ├─ 실행 중 키 → 409 IDEMPOTENT_IN_FLIGHT (retryable, Retry-After 2) + └─ 다른 본문 → 422 IDEMPOTENT_REQUEST_MISMATCH +DB 커밋 중 연결 끊김 ─────────────────────────────────────▶ 500 DB_COMPLETION_UNKNOWN (retryable=false) +``` + +정본: `docs/web/http-contract.md` 2절(wire 응답), `src/application-core/CLAUDE.md` 「Idempotency (KEYED)」 +(executor 구조), `docs/adr/ADR-JPA-003-completion-unknown.md`(커밋 결과 불명). + +## 판단: 이 쓰기를 KEYED로 만드나 + +- **고르는 기준**: 클라이언트가 응답을 못 받았을 때 다시 보내는가, 그리고 두 번 적용되면 피해가 있는가. +- **기본값**: 생성·결제·주문·발송처럼 "두 번 = 피해"인 쓰기는 `KEYED`. 같은 입력이면 같은 결과인 + 쓰기(상태를 X로 설정)는 `IDEMPOTENT`. 그 밖은 `NOT_IDEMPOTENT`(생성 명령의 기본값 — 바꿀지 여기서 + 정한다). +- **예외**: 자연 키가 있어 DB 유일성 제약이 중복을 막으면(04장) 키 없이도 두 번째 요청이 409로 끝난다. + 다만 그 409는 "이미 있음"이지 "첫 요청의 결과"가 아니다. 클라이언트가 첫 결과를 받아야 하면 KEYED. + +### KEYED로 만드는 순서 + +1. `@UseCaseCapability(idempotency = Idempotency.KEYED)`. +2. 유스케이스 본문을 `IdempotencyExecutor`로 감싼다. executor를 유스케이스가 만들지 않는다 — + `composition:idempotency`가 한 번 만든다. +3. scope digest(주체 + 키 + operation 코드의 HMAC)와 요청 fingerprint(SHA-256)를 유스케이스 밖(전송)에서 + 만든다. 원본 키는 저장소에 닿지 않는다. +4. 작업 결과를 `IdempotentAction.Outcome`(`Success` / `RetryableNoEffect` / `EffectUnknown`)으로 돌려준다. + 예외를 던지면 effect-unknown으로 센다. +5. 저장소 provider를 고른다: `app.capabilities.idempotency.provider` = `postgresql` 또는 `redis` + (기본 `disabled`). 운영에서 in-memory 금지. + +예: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/` 의 +`PosterImagePublicationController`(키 헤더 검증), 유스케이스 쪽은 sample `application/posterimage`. + +## 클라이언트에게 무엇을 약속하나 + +| 응답 | 의미 | 클라이언트 행동 | +| --- | --- | --- | +| 409 `IDEMPOTENT_IN_FLIGHT`, `retryable=true`, `Retry-After: 2` | 같은 키가 아직 실행 중. 결과 불명 | **같은 키로** 기다렸다 재전송. 새 키 금지 | +| 422 `IDEMPOTENT_REQUEST_MISMATCH` | 같은 키에 다른 본문 | 클라이언트 버그. 재전송 안 함 | +| 503 `IDEMPOTENCY_UNAVAILABLE` | 실행 전 거부 | 같은 키로 나중에 | +| 500 `IDEMPOTENCY_RECOVERY_REQUIRED` | 이전 시도 효과를 증명 못함 | 재전송·재실행 모두 위험. 업무 데이터로 확인 | +| 500 `DB_COMPLETION_UNKNOWN`, `retryable=false` | DB 커밋 중 연결 끊김. 커밋됐을 수도 있음 | 키 없이 재시도 금지. KEYED면 같은 키로 재전송하면 서버가 판정 | + +409를 `retryable=true`로 바꾼 이유(리뷰 02-01 결정): 같은 키 재전송은 서버가 안전하게 판정하므로 다시 +보내는 것이 맞고, 새 키로 보내면 서버가 막지 못한다. 짝 프론트 분류기도 이 표를 따른다. + +## 결과 불명을 만드는 곳마다 같은 규칙 + +리뷰가 찾은 반복 원인 1번이 "결과 불명을 확실함으로 기록"이었다(05-01, 04-01, 06-01). 새 경계를 +만들 때 아래 질문에 답한다. + +- **고르는 기준**: 실패한 호출이 **상대편에서 이미 효과를 냈을 수 있는가**. +- **기본값**: 그럴 수 있으면 "결과 불명"으로 분류한다. 재시도 가능(`retryable=true`)으로 분류하지 + 않는다. 근거 코드: + - DB 커밋 중 끊김 → `DB_COMPLETION_UNKNOWN` + (`src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java`) + - 메시지 발행 응답 없음 → `OutboxPublishAmbiguousException`(application-core `outbox`) + - 알림 발송 시작 뒤 crash → 재발송하지 않고 reconcile(application-notification evidence 모델) +- **예외**: 요청이 상대에게 **도달하기 전**에 실패한 것이 증명되면(연결 수립 실패, 실행 전 거부) + 재시도 가능이다. 반대 방향 실수(확실히 안 간 것을 불명으로)도 결함이다(리뷰 05-17). +- 불명 상태를 푸는 방법(reconcile, 키 재전송, 운영자 확인)을 runbook에 적는다(`docs/runbooks/`). + +## 지금 이해하면 되는 것 + +- "두 번 = 피해"인 쓰기는 KEYED. executor는 composition이 만든다. +- 409 in-flight는 같은 키로 다시, 422는 버그, 500 completion-unknown은 키 없이 재시도 금지. +- 상대편에 효과가 났을 수 있으면 "모른다"로 분류한다. diff --git a/docs/manual/06-errors.md b/docs/manual/06-errors.md new file mode 100644 index 00000000..4afebb58 --- /dev/null +++ b/docs/manual/06-errors.md @@ -0,0 +1,67 @@ +# 06. 오류 모델 + +## 핵심 + +실패마다 먼저 **클라이언트 탓인가 서버 탓인가**를 정한다. 클라이언트 탓이면 안정된 오류 코드를 가진 +예외를 던지고, 서버 탓이면 코드 없이 던진다. 어느 쪽이든 기능 코드는 던지기만 하고, 전송별 핸들러 +하나가 wire 모양으로 바꾼다. + +```text +domain XInvariantException(Reason) ← 코드 없음. domain-core는 shared-contract를 못 본다 + │ 유스케이스가 잡아서 감싼다 +application XRejectedException implements ApiErrorCarrier → XErrorCode.X_INVALID (VALIDATION, 400) + XNotFoundException implements ApiErrorCarrier → XErrorCode.X_NOT_FOUND (NOT_FOUND, 404) + │ 던진다 +web GlobalExceptionHandler: ApiErrorCarrier → errorCode() → status + Envelope{error{code, category, retryable}} +gRPC/GraphQL/WebSocket: 같은 ApiErrorCarrier를 자기 status 모양으로 +``` + +정본: `src/shared-contract/src/main/java/dev/caskeleton/shared/error/ApiErrorCarrier.java`, +`ApiErrorCode.java`, `OperationalError.java`, `docs/registries/error-codes.yaml`, wire 모양은 +`docs/web/http-contract.md` 1절(null 필드는 내보내지 않는다). + +## 판단: 오류 코드를 어디에 두나 + +- **고르는 기준**: 같은 유스케이스를 여는 전송이 둘 이상이 될 수 있는가. +- **기본값**: application 기능 패키지의 `XErrorCode implements ApiErrorCode` enum + 예외가 + `ApiErrorCarrier` 구현. 전송마다 핸들러를 만들 필요가 없다. 생성 명령 출력이 이 모양이다 + (`ErrorCode`, `NotFoundException`, `RejectedException`). +- **예외**: 한 전송에서만 의미가 있는 실패(HTTP 헤더 형식 등)는 그 전송 adapter에 둔다. sample은 기능 + 코드를 web 패키지(`PortfolioErrorCode`, `DomainExceptionHandler`)에 두는데, 한 leaf 수직 샘플이라 + 가능한 모양이다. 따라 하지 않는다. + +## 판단: 어떤 예외 타입으로 던지나 + +| 상황 | 던질 것 | 결과 | +| --- | --- | --- | +| 도메인 불변식 위반 | domain `XInvariantException(Reason)` → 유스케이스가 `XRejectedException`으로 감쌈 | 400 기능 코드 | +| 찾는 것이 없음 / 남의 것 | `XNotFoundException`(carrier) | 404. 남의 것도 404로 존재를 숨긴다(07장) | +| 상태 충돌(이미 있음, 버전 불일치) | 기능 carrier(Category.CONFLICT, 409) | 409 | +| 요청 파라미터 형식 오류(경로 id 문법 등) | `IllegalArgumentException` | 400 `BAD_PARAMETER` | +| 서버 조립·설정 오류, 있을 수 없는 상태 | `IllegalStateException` | 500, 로그 남음 | +| DB·외부 의존 실패 | adapter가 shared-contract carrier(`PersistenceFailureException`, `DependencyFailureException`)로 | 분류표대로(04·05장) | + +- `IllegalArgumentException`을 "서버 조립이 틀렸다"에 쓰지 않는다. web은 그것을 로그 없이 400으로 + 바꿔서 서버 결함이 클라이언트 오류로 숨는다(리뷰 01-04). +- 메시지는 로그용이다. 클라이언트에는 코드와 category별 고정 문구(`ClientErrorMessages`)만 간다. + 메시지에 SQLState·내부 경로·토큰을 넣어도 클라이언트에 새지 않지만, 로그 정책은 지킨다. + +## 판단: `retryable`을 무엇으로 + +- **기본값**: `false`. 기능 오류 대부분은 같은 요청을 다시 보내도 결과가 같다. +- **예외**: 시간이 지나면 성공할 수 있고 **다시 보내도 안전한** 경우만 `true`(일시적 의존 실패, + `IDEMPOTENT_IN_FLIGHT`). `true`인 코드는 runbook 링크가 필요하다(registry 규칙). + +## 코드 등록 + +- 템플릿 운영 코드: `OperationalError` + `docs/registries/error-codes.yaml`을 같은 변경에서 고친다. + `ErrorCodeRegistryMappingTest`(app-bootstrap)가 status 일치를 검사한다. +- 서비스 기능 코드: 그 registry에 넣지 않는다(registry 머리말 "Product/fork ApiErrorCode enums own local + registries"). 서비스 자기 registry를 만들고 같은 모양의 대조 테스트를 둔다. 예: + `src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCodeRegistryMappingTest.java`. + +## 지금 이해하면 되는 것 + +- 클라이언트 탓 = carrier 예외 + 기능 코드. 서버 탓 = `IllegalStateException`. +- 기능 코드는 application에 두고, 전송 핸들러는 기능을 모른다. +- `retryable=true`는 다시 보내도 안전할 때만. diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md new file mode 100644 index 00000000..bbdfa5a9 --- /dev/null +++ b/docs/manual/07-authorization.md @@ -0,0 +1,74 @@ +# 07. 권한 + +## 핵심 + +권한 검사는 두 층이다. **"이 종류의 작업을 해도 되나"**(권한 이름)는 유스케이스의 `@RequiresPermission` +선언과 web이 켜는 method security가 맡는다. **"이 객체를 봐도 되나"**(소유자·tenant)는 유스케이스가 +객체를 읽은 뒤 직접 판정한다. + +```text +요청 ─▶ 인증 필터(JWT 또는 세션) ─▶ AuthenticatedPrincipal(roles, tenant) + ─▶ 컨트롤러 ─▶ [프록시] RequiresPermissionAuthorizationManager + │ role → permission (app.authz.role-permissions) + │ 없으면 403, 인증 없으면 401 + ─▶ 유스케이스 본문 ─▶ 객체 로드 ─▶ 소유자·tenant 판정 ─▶ 남의 것이면 404(존재 숨김) +``` + +## 작업 단위 권한: `@RequiresPermission` + +| 무엇 | 어디 | +| --- | --- | +| 선언 | `src/application-core/src/main/java/dev/caskeleton/application/security/RequiresPermission.java` — 쓰기 유스케이스에 필수(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`) | +| 검사 장치 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/authz/MethodSecurityConfig.java`의 advisor | +| 켜는 곳 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMethodSecurityAutoConfiguration.java` | +| 역할 → 권한 | `app.authz.role-permissions` (`src/app-bootstrap/src/main/resources/config/security.yml`), 바인딩 `RolePermissionPolicy` | +| 프록시 가능 | `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/authz/RequiresPermissionProxyabilityTest.java` | + +검사 자동 설정은 인증 체인(`WebSecurityAutoConfiguration`)과 **분리**되어 있다. 서비스가 자기 인증 +방식으로 인증 체인을 바꿔도 권한 검사는 꺼지지 않는다(1라운드 07-03 수정). + +### 지켜야 할 것 셋 + +1. 유스케이스는 **bean**이다. 직접 `new` 하면 프록시가 없어 선언이 주석이 된다. +2. 유스케이스 클래스와 그 public 메서드는 **final이 아니다**. final이면 프록시를 못 만들어 기동이 실패한다. +3. 유스케이스 안에서 자기 다른 메서드를 부르면(self-invocation) 프록시를 거치지 않는다. 권한이 다른 두 + 작업은 유스케이스 둘로 나눈다. + +### 판단: 권한 이름과 역할 매핑 + +- **고르는 기준**: 운영자가 따로 주고 뺄 필요가 있는 작업인가. +- **기본값**: `:`, resource는 kebab-case(`purchase-order:create`). 생성 명령은 + `:create` 하나를 만든다. 역할 매핑은 권한을 명시적으로 나열한다(와일드카드 없음). +- **예외**: 같은 역할이 항상 함께 가지는 작업은 한 역할에 여러 권한을 준다 + (`operation-submit: operation:submit,operation:cancel`). +- 매핑하지 않은 권한은 아무도 갖지 않는다. 새 기능의 쓰기는 매핑 전까지 모두 403이다 — 실수로 열리지 + 않는 쪽. +- 읽기 유스케이스는 선언이 필수가 아니다. 인증된 누구나 읽으면 안 되는 데이터면 선언하거나 객체 판정을 둔다. + +### 역할은 어디서 오나 + +JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `resource_access..roles`만 +읽는다. audience는 필수다(1라운드 02-03 수정). 같은 issuer의 다른 client가 같은 이름의 역할을 정의해도 +이 서비스 권한이 되지 않는다(`JwtToAuthenticatedPrincipalConverter`, `docs/runbooks/auth-audience-mismatch.md`). + +## 객체 단위 권한 + +- **고르는 기준**: 같은 권한을 가진 두 사람이 같은 객체에 대해 다른 답을 받아야 하는가(소유자, tenant). +- **기본값**: 유스케이스가 객체를 읽은 뒤 판정하고, 남의 것이면 **없는 것과 같은 404**로 답한다. + 존재 여부도 정보다. 예: `GetDurableOperationUseCase`와 `DurableOperationAccessPolicy` + (`src/application-core/src/main/java/dev/caskeleton/application/operation/`). +- **예외**: 여러 전송이 같은 판정을 써야 하거나 목록에서 한 번에 판정해야 하면 + `ObjectAccessPolicy`(`src/application-core/src/main/java/dev/caskeleton/application/security/ObjectAccessPolicy.java`, + batch 메서드로 N+1 회피)를 구현한다. 존재를 숨길 필요가 없는 관리 화면은 403도 된다. +- tenant: 인증 정보에서만 만든 `TenantId`를 command에 싣는다. 요청 본문의 tenant 값을 믿지 않는다. + +## 지금 확인되지 않는 것 + +- web이 빠진 조립(gRPC 전용·배치 전용)에서는 advisor가 없어 선언이 검사되지 않는다. 이때 기동을 막는 + 장치는 아직 없다(리뷰 01-06). web 없이 조립하는 서비스는 그 전에 이 문제를 먼저 푼다. + +## 지금 이해하면 되는 것 + +- 쓰기 = `@RequiresPermission` + non-final + bean + 역할 매핑. +- 객체 판정은 유스케이스 안, 남의 것은 404. +- 역할은 자기 client 것만 읽는다. diff --git a/docs/manual/08-testing.md b/docs/manual/08-testing.md new file mode 100644 index 00000000..631d0af7 --- /dev/null +++ b/docs/manual/08-testing.md @@ -0,0 +1,80 @@ +# 08. 테스트 작성 규칙 + +## 핵심 + +테스트 규칙의 정본은 `AGENTS.md` 「테스트 전략」이다. 이 장은 새 기능을 만들 때 그 규칙이 **어떤 +파일 배치가 되는지**와 **어느 단계(PR/main/integration)에서 도는지**를 적는다. + +```text +포트 XRepository (domain-core) + ├─ testFixtures: InMemoryXRepository (fake, 포트당 하나) + ├─ testFixtures: XRepositoryContract (abstract, 약속 목록) + ├─ test: InMemoryXRepositoryContractTest extends XRepositoryContract → ci (leaf test) + └─ 저장 adapter leaf integrationTest: + JpaXRepositoryContractTest extends XRepositoryContract → integrationCheck (실 PostgreSQL) + +유스케이스 테스트 = 실제 유스케이스 + InMemoryXRepository + DirectTransactionPort +``` + +fake와 실제 adapter가 **같은 계약**을 통과해야 fake 위의 유스케이스 테스트가 거짓 녹색이 되지 않는다. +생성 명령은 이 배치를 그대로 만든다(01장). + +## 계층별 테스트 + +| 계층 | 테스트 | 쓰는 대역 | 예 (생성 결과) | +| --- | --- | --- | --- | +| domain | 순수 JUnit. 불변식·id 문법 | 없음 | `Test`, `IdTest` | +| domain 포트 | 공유 계약 | fake | `InMemoryRepositoryContractTest` | +| application | 유스케이스 흐름·트랜잭션 경계·오류 코드 | 포트 소유자 testFixtures의 fake, `DirectTransactionPort` | `CreateUseCaseTest` | +| outbound adapter | 같은 공유 계약을 실제 저장소로 | Testcontainers(strict lane) | 04장 4번 | +| inbound | HTTP status·Envelope·오류 코드 | 실제 유스케이스 + fake, standalone MockMvc | `ControllerTest` | +| bootstrap | 조립 조건(있을 때 켜짐, 없을 때 없음), imports 등록 | fake bean | `ConfigTest` | + +## 작성 규칙 요약 (정본은 AGENTS.md) + +1. 이름은 lowerCamelCase 행동 문장. 이름이 말한 성질을 단언한다. 예: 이름에 "트랜잭션 전에"를 넣었으면 + 트랜잭션이 없었다는 것도 단언하거나, 이름에서 뺀다. +2. `@DisplayName`은 메서드 이름으로 못 쓰는 내용(숫자, 기호, 이유)이 있을 때만, **한국어**로 + (소유자 결정 5). 예: `@DisplayName("이름이 NAME_MAX_LENGTH + 1자이면 거절한다")`. +3. 본문 3문장 이상이면 `// given` `// when` `// then`. `// when`은 하나. 예외는 `catchThrowable`로 분리. +4. then은 when의 결과 하나만. 예외는 타입과 reason/code를 함께. +5. 포트 대역은 hand-rolled fake 하나, **포트 소유 leaf의 testFixtures**에. Mockito는 프레임워크 경계와 + 장애 주입만. + +### 판단: fake가 어디 사나 + +- **고르는 기준**: 포트 인터페이스가 어느 leaf에 있나. +- **기본값**: 그 leaf의 `src/testFixtures/java/...//testkit/`. domain 포트면 domain-core, + application 포트면 application-core. 소비 leaf는 `testImplementation testFixtures(project(':'))`. +- **예외**: 없다. 테스트 안 private fake는 계약 밖에 있어 실제와 갈라진다(리뷰 01-05의 lock fake). + +## lane과 단계 + +`ci`(PR)의 leaf `test`는 Docker 없이 빠르게 끝나야 한다. 실 DB·실 서버가 필요한 테스트는 strict +lane으로 선언하고 단계를 지정한다. 선언은 `ca.strict-test-lane`(`src/build-logic/README.md`). + +| lane 종류 | 선언 | 도는 단계 | +| --- | --- | --- | +| 단위·slice | 기본 `test` | `ci` | +| 문서 대조·느린 계약 | 태그 lane + `mainStage()` | `mainCheck` | +| 실 DB·컨테이너 | `integration()` + 자기 sourceSet(예: `integrationTest`) | `integrationCheck` | +| 성능·부하 | performance 범주 | `performanceCheck` | +| 외부 입력 필요(자격증명 등) | `explicitOnly(reason)` | 어떤 집계에도 안 들어가고 이유가 출력된다 | + +예: `src/sample-portfolio/build.gradle`의 `strictTestLanes { lane('integrationTest') { integration() … } }`, +`src/app-bootstrap/build.gradle`의 `publicPathSnapshotTest`(`mainStage()`). + +### 판단: 새 테스트를 어느 lane에 + +- **고르는 기준**: Docker·네트워크·실 서버가 필요한가, 몇 초 넘게 걸리는가. +- **기본값**: 필요 없으면 `test`(ci). 필요하면 integration lane. +- **예외**: 반드시 실행돼야 하는 소수 테스트(계약 자격 검사)는 `requires(클래스)` + `rejectSkipped = true`로 + 이름을 박는다. 이름이 바뀌거나 지워지면 lane이 실패한다. +- 새 lane이 어떤 단계에도 속하지 않으면 PR 게이트의 `verifyStrictLaneStages --dry-run`이 실패한다 + (1라운드 08-01). 단계는 집계 태스크(`integrationCheck` 등)를 통해 붙고, workflow 파일을 고치지 않는다. + +## 지금 이해하면 되는 것 + +- fake와 계약은 포트 주인 testFixtures에, adapter는 같은 계약을 실제 저장소로. +- `@DisplayName`은 꼭 필요할 때만, 한국어로. +- Docker가 필요한 테스트는 strict lane + 단계 지정. 단계 없는 lane은 PR에서 막힌다. diff --git a/docs/manual/09-outbox-events.md b/docs/manual/09-outbox-events.md new file mode 100644 index 00000000..780d20cc --- /dev/null +++ b/docs/manual/09-outbox-events.md @@ -0,0 +1,73 @@ +# 09. outbox·이벤트 + +## 핵심 + +업무 저장과 이벤트 발행을 **같은 DB 트랜잭션**에 묶는다. 유스케이스는 broker에 직접 보내지 않고, +이벤트를 outbox 테이블에 업무 행과 함께 쓴다. 별도 relay가 커밋된 outbox 행을 broker로 옮긴다. + +```text +use case ── tx.inWrite ─┬─▶ repository.save(aggregate) ┐ 한 커밋 + └─▶ OutboxAppendPort.append(validated) ┘ + ▲ + IntegrationEventDraft ──▶ IntegrationEventEncoderPort (계약으로 검증·인코딩) + +(커밋 뒤, 따로) composition:outbox-relay ─▶ OutboxStorePort.claim(lease) ─▶ broker ─▶ 완료/재시도/DEAD +``` + +DB 저장과 broker 발행을 따로 하면(dual write) 둘 중 하나만 성공하는 순간이 생긴다. outbox는 그 순간을 +없앤다. 대가는 **적어도 한 번** 전달이다 — 소비자는 event id로 중복을 걸러야 한다. + +정본: `src/application-core/CLAUDE.md`(이벤트 타입 표), `docs/messaging/outbox-inbox.md`, +`docs/messaging/delivery-guarantees.md`. + +## 순서 + +1. 계약을 정한다: 계약 id(`..`), 버전, payload record, JSON schema 파일과 해시. + 예: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedContractContribution.java`, + `src/sample-portfolio/src/main/resources/contracts/messaging/portfolio.worklog.reserved/v1.schema.json`(+ `.sha256`). +2. payload record(`IntegrationPayload`)를 만든다. +3. 유스케이스의 `tx.inWrite` 안에서 저장 뒤 draft → encode → append. 예: + `CreateWorkLogUseCase`(sample)와 그 헬퍼 `PortfolioEventOutbox`. +4. 계약 contribution을 조립에서 `@Bean`으로 등록한다. encoder는 컨텍스트의 계약 bean으로 만들어진다. + 등록을 빠뜨리면 append 때 실패한다. 예: `DurableOperationAutoConfiguration.durableOperationSubmittedContract()`. +5. 테스트: 계약 contribution 테스트(해시 고정), 유스케이스가 append했는지(`InMemoryOutboxStore`), + 소비자 중복 제거 계약(sample `WorkLogReservedConsumerDedupeContractTest`). + +## 판단 지점 + +### 도메인 이벤트가 필요한가, 통합 이벤트만인가 + +- **고르는 기준**: 같은 서비스 안에서 이 사실에 반응하는 코드가 있는가. +- **기본값**: 통합 이벤트만. 유스케이스가 저장 뒤 바로 payload를 만든다. +- **예외**: aggregate 안에서 일어난 사실을 여러 유스케이스가 같은 방식으로 내보내면 domain + `@DomainEvent` record를 두고 유스케이스가 그것을 payload로 옮긴다(sample `WorkLogReserved`). + +### payload에 무엇을 넣나 + +- **기본값**: id만(+ 소비자가 라우팅에 필요한 최소 값). 상태 전체를 넣으면 계약이 aggregate 변경마다 깨진다. +- **예외**: 소비자가 원 서비스를 다시 조회할 수 없는 경우(외부 파트너)는 필요한 상태를 넣고 버전을 올린다. + +### event id·correlation·순서 + +- event id: UUIDv7, 소비자 중복 제거 키. 같은 작업의 재시도가 같은 event id를 내야 하면(durable + operation) 작업 id에서 파생한다. +- correlation: 요청의 correlation id가 문법에 맞으면 그것, 아니면 event id. 문법 밖 헤더가 업무 쓰기를 + 실패시키면 안 된다. +- aggregate 순서: aggregate에 version 열이 있으면 그것, 없으면 발생 시각(µs). +- 이 규칙은 아직 기능마다 다시 쓴다(sample `PortfolioEventOutbox`). application-core 헬퍼로 올리는 일은 + 리뷰 01-09 후속이다. 그 전까지는 위 세 규칙을 지킨다. + +## relay와 실패 + +- relay는 `composition:outbox-relay`가 조립한다. 유스케이스로 만든 relay를 bean으로 등록하지 않는다 + (스케줄러 스레드에는 인증이 없어 권한 프록시가 매번 거부한다). +- broker의 **재시도 가능한** 거부는 DEAD가 아니라 backoff 재시도다. broker가 멈춰도 대량 DEAD가 되지 + 않는다(1라운드 06-01·06-03). 진짜 인증 오류도 재시도로 남으니 경보로 잡는다. +- 발행 응답을 못 받으면 결과 불명(`OutboxPublishAmbiguousException`) — 05장 규칙과 같다. +- 운영: `docs/runbooks/outbox-dead-letter.md`, `docs/runbooks/outbox-publish-failed.md`. + +## 지금 이해하면 되는 것 + +- 저장과 append는 같은 `tx.inWrite` 안. +- 계약(id·버전·schema·해시)을 먼저 정하고 계약 bean을 등록한다. +- 전달은 적어도 한 번. 소비자는 event id로 중복을 거른다. diff --git a/docs/manual/10-capabilities.md b/docs/manual/10-capabilities.md new file mode 100644 index 00000000..880a5a1e --- /dev/null +++ b/docs/manual/10-capabilities.md @@ -0,0 +1,65 @@ +# 10. capability 추가·제거 + +## 핵심 + +JPA·Redis·Kafka·알림·파일 서버 같은 부가 기능은 **의존성 한 줄로 켜지고, 그 줄을 지우면 사라지는 +모듈**이다. 서비스는 `src/app-bootstrap/build.gradle`에서 필요한 모듈만 `runtimeOnly`로 고른다. +기본 조립은 web, 운영 관측, cores, support/identifier뿐이다. JPA도 한 줄로 켠다. + +```text +app-bootstrap/build.gradle + runtimeOnly project(':adapter:outbound:persistence-jpa') ← 이 한 줄 + │ + ▼ + 모듈의 META-INF/spring/...AutoConfiguration.imports → 자동 설정 → 포트 구현 bean + │ + ▼ + 기능 XConfig의 @ConditionalOnBean(포트) → 유스케이스·엔드포인트가 켜진다 +``` + +정본: `AGENTS.md` 「부가 기능(capability) 모듈 규칙」(완료 기준 7개), +`docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md`, 현황은 `docs/capability-status.md`. + +## 켜기 + +1. `src/app-bootstrap/build.gradle`의 해당 `runtimeOnly` 줄 주석을 푼다. +2. lockfile 갱신: `./gradlew :app-bootstrap:resolveAndLockAll --write-locks`, 확인 + `./gradlew verifyDependencyLocks`. +3. 모듈 README의 env 키를 채운다. 키 목록 정본은 `docs/registries/env-keys.yaml`. +4. 기본값은 `config/module-defaults/<모듈>.yml`에 이미 있다. 서비스 값만 덮어쓴다. +5. `./gradlew :app-bootstrap:check architectureCheck`. 공개 경로가 생기면 `verifyPublicPathSnapshot`. + +## 끄기 + +줄을 지우고 lockfile을 갱신한다. 그 모듈의 포트에 기대던 기능(`@ConditionalOnBean`)은 함께 꺼진다. +기능이 꺼지면 안 되는데 꺼졌다면, 그 기능이 다른 구현을 가져야 한다는 신호다. + +## 판단: 서비스 코드가 모듈 타입을 직접 불러도 되나 + +- **기본값**: 안 된다. 서비스 코드는 application-core 포트만 부른다. 그래야 `runtimeOnly`로 받을 수 있다. +- **예외**: 라이브러리형 기능(모듈 타입을 상속·호출해야 하는 것)은 서비스의 adapter leaf에서만 + `implementation`으로 받는다. 예: 서비스 persistence leaf가 `persistence-jpa`의 감사 base 타입을 상속. + +## 새 capability 모듈을 만들 때 + +03장에서 ②(기능 leaf)를 골랐을 때만 해당한다. 완료 기준 7개를 모두 지킨다. + +| # | 기준 | 확인 | +| --- | --- | --- | +| 1 | 서비스는 포트만 호출 | `runtimeOnly`로 컴파일되는가 | +| 2 | 자기 `AutoConfiguration.imports`, 필요하면 `enabled` 스위치, 순서는 `afterName` | 모듈 자동 설정 테스트 | +| 3 | 켜면 완전히 동작. 동작하지 않는 설정 키는 두지 않는다 | 설정 바인딩 테스트 | +| 4 | 설정 prefix 하나(`app.<모듈>`), `StrictSettingsBinder`, 검증은 record compact constructor | | +| 5 | 포트 계약 테스트를 fake와 실제 adapter가 모두 통과, 실 벤더(Testcontainers) 1개 이상 | strict lane(08장) | +| 6 | README: 제공하는 것, 추가할 한 줄, env 키 | | +| 7 | 이 모듈을 아는 곳은 모듈 자신뿐. bootstrap scan·스위치 목록에 등록하지 않는다 | 줄을 지우면 기능이 완전히 사라지는가 | + +등록할 공용 파일: `src/config/architecture/modules.json`(leaf와 허용 edge), `src/settings.gradle`이 읽는 +디렉터리 매핑, app-bootstrap의 허용 edge, 새 leaf lockfile. registry가 허용하지 않은 edge는 +`architectureCheck`(의존 방향)가 막는다. + +## 지금 이해하면 되는 것 + +- 켜기 = `runtimeOnly` 한 줄 + lockfile + env 키. +- 서비스 코드는 포트만 부른다. +- 새 capability는 완료 기준 7개. 업무 기능은 capability로 만들지 않는다(03장). diff --git a/docs/manual/11-checklist.md b/docs/manual/11-checklist.md new file mode 100644 index 00000000..53cfc670 --- /dev/null +++ b/docs/manual/11-checklist.md @@ -0,0 +1,67 @@ +# 11. 체크리스트 — PR 올리기 전 + +빠진 것이 있으면 해당 장으로 돌아간다. 검사 명령은 `src/`에서 실행한다. + +## 배치·이름 + +- [ ] 배치를 03장 기준표로 정했다(기본: 계층 leaf 안 `` 패키지). +- [ ] 패키지 이름이 템플릿 플랫폼 패키지와 겹치지 않는다. +- [ ] 이름이 `src/application-core/CLAUDE.md` 「Naming convention」을 따른다. + +## domain + +- [ ] 불변식은 aggregate 안에 있고, 위반은 `XInvariantException(Reason)`이다. +- [ ] id 문법은 id 값 객체 생성자가 검사한다. +- [ ] Spring·JPA·전송 타입을 import하지 않는다. + +## application + +- [ ] 모든 유스케이스에 `@UseCaseCapability`, 선언과 `TransactionPort` 호출이 맞다. +- [ ] 쓰기 유스케이스: `@RequiresPermission`, non-final, bean으로 조립. +- [ ] 외부 호출은 트랜잭션 밖이다. +- [ ] 멱등성 선언을 05장 기준으로 골랐다(재전송될 쓰기는 `KEYED`). +- [ ] 클라이언트 탓 실패는 carrier 예외 + 기능 코드, 서버 탓은 `IllegalStateException`. + +## persistence + +- [ ] 저장 adapter가 서비스 전용 persistence leaf에 있다(persistence-jpa 아님). +- [ ] 연관관계는 한쪽만(`mappedBy` 없음). +- [ ] 중복 규칙은 DB 유일성 제약이 막고, adapter가 그 제약 위반만 기능 예외로 바꾼다. +- [ ] 여러 인스턴스가 집는 작업은 트랜잭션 안 claim + lease. +- [ ] 마이그레이션은 자기 스트림(자기 history table)에 있고, 적용된 파일을 고치지 않았다. +- [ ] adapter가 `XRepositoryContract`를 실 DB lane에서 상속한다. + +## inbound + +- [ ] 컨트롤러는 변환만 한다. repository·엔티티를 모른다. +- [ ] 경로는 lowerCamel 복수형(AIP-122). 생성은 201 + `Location`. +- [ ] 도메인 규칙을 DTO bean validation에 다시 쓰지 않았다. + +## 조립·권한 + +- [ ] `XConfig`가 `@ConditionalOnBean(포트)`이고 imports에 한 줄 있다. 포트가 다른 자동 설정에서 오면 `afterName`. +- [ ] 역할 → 권한 매핑을 `app.authz.role-permissions`에 더했다. +- [ ] 객체 단위 판정이 필요하면 유스케이스 안에서 하고, 남의 것은 404. + +## 이벤트 + +- [ ] 저장과 outbox append가 같은 `tx.inWrite` 안이다. +- [ ] 계약 id·버전·schema·해시를 정했고 계약 bean을 등록했다. + +## 테스트 + +- [ ] 포트마다 fake 하나와 공유 계약이 포트 소유 leaf testFixtures에 있다. +- [ ] 이름은 행동 문장, `@DisplayName`은 필요할 때만 한국어, GWT 주석, `// when` 하나. +- [ ] Docker가 필요한 테스트는 strict lane이고 단계가 있다. + +## 검사 + +```bash +./gradlew :check --console=plain # 건드린 leaf마다 +./gradlew architectureCheck --console=plain # leaf 경계를 넘었으면 +./gradlew verifyPublicPathSnapshot # 공개 경로가 바뀌었으면 +./gradlew :app-bootstrap:verifyEnvKeys # env 키가 바뀌었으면 +./gradlew verifyDependencyLocks # 의존성이 바뀌었으면 +``` + +- [ ] 실행한 명령과 결과를 PR 본문 「검증」에 적었다. 못 돌린 것은 이유와 함께 적었다. diff --git a/docs/manual/README.md b/docs/manual/README.md new file mode 100644 index 00000000..d5216db7 --- /dev/null +++ b/docs/manual/README.md @@ -0,0 +1,82 @@ +# 개발 매뉴얼 — 이 템플릿으로 기능을 만드는 순서와 판단 지점 + +이 매뉴얼은 **새 업무 기능을 추가하는 사람**이 읽는다. 무엇을 어떤 순서로 만들고, 갈림길마다 +무엇을 기준으로 고르는지를 적는다. 규칙의 정본은 따로 있다. 이 매뉴얼은 그 정본을 **가리키고** +작업 순서로 엮을 뿐, 규칙을 다시 쓰지 않는다(아래 「정본 위치」). + +판단 지점은 모두 같은 틀로 적는다. + +- **고르는 기준** — 무엇을 보고 고르는가 +- **기본값** — 기준이 애매하면 이것 +- **예외** — 기본값을 벗어나도 되는 경우와 그때 같이 해야 하는 것 + +근거는 코드 경로로 단다. 경로는 저장소 루트 기준이다. + +## 읽는 순서 + +처음이면 1 → 2 → 3을 읽고 생성 명령을 한 번 돌려 본다. 그다음은 기능에 필요한 장만 읽는다. + +| 장 | 언제 읽나 | +| --- | --- | +| [01. 생성 명령](01-generator.md) | 새 기능 뼈대를 만들 때. 무엇을 만들고 무엇을 안 만드는지 | +| [02. 새 도메인·유스케이스 추가](02-new-feature.md) | 기능 하나를 domain → application → outbound → inbound → bootstrap 순서로 만들 때 | +| [03. 새 기능을 둘 곳 고르기](03-placement.md) | 계층 leaf 안 패키지 / `application-*` capability / 별도 수직 중 고를 때 | +| [04. 영속성](04-persistence.md) | 저장 adapter, 엔티티 매핑, DB 제약과 충돌 변환, 마이그레이션 번호 | +| [05. 멱등성·결과 불명](05-idempotency.md) | 재시도될 수 있는 쓰기, 409/422, `DB_COMPLETION_UNKNOWN` | +| [06. 오류 모델](06-errors.md) | 실패를 클라이언트 탓/서버 탓으로 나누고 코드로 내보낼 때 | +| [07. 권한](07-authorization.md) | `@RequiresPermission`, 역할 매핑, 객체 단위 인가 | +| [08. 테스트 작성 규칙](08-testing.md) | 포트당 fake, 공유 계약, 이름·주석, lane 단계 지정 | +| [09. outbox·이벤트](09-outbox-events.md) | 저장과 함께 이벤트를 내보낼 때 | +| [10. capability 추가·제거](10-capabilities.md) | JPA·Redis·Kafka 같은 부가 기능을 켜고 끌 때 | +| [11. 체크리스트](11-checklist.md) | PR 올리기 전 | +| [부록. 공통 원칙 후보](appendix-common-principles.md) | 프론트·백엔드 공통 실무 원칙으로 옮길 후보 | + +## 정본 위치 + +매뉴얼과 정본이 다르면 정본이 맞다. 매뉴얼을 고친다. + +| 무엇 | 정본 | +| --- | --- | +| 계층 경계·금지 규칙·테스트 작성 규칙 | `AGENTS.md`(요약은 `CLAUDE.md`) | +| leaf 목록·허용 의존 | `src/config/architecture/modules.json` | +| 이름 규칙(유스케이스·포트·command·query) | `src/application-core/CLAUDE.md` 「Naming convention」. 기계 검사는 `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java`와 `ApplicationBoundaryArchitectureTest.java` | +| 유스케이스 모양·트랜잭션 모양 | `src/application-core/CLAUDE.md` 「Canonical use case shape」「Allowed transactional shapes」 | +| HTTP wire 계약(Envelope·멱등성 응답) | `docs/web/http-contract.md` | +| 운영 오류 코드 | `docs/registries/error-codes.yaml`, `src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java` | +| 엔티티 매핑·마이그레이션 | `docs/jpa/entity-mapping-guide.md`, `docs/jpa/migration-guide.md`, `docs/jpa/transaction-guide.md` | +| capability 완료 기준 7개 | `AGENTS.md` 「부가 기능(capability) 모듈 규칙」 | + +이름 규칙은 위 한 곳에만 둔다. 이 매뉴얼과 생성 명령은 그 규칙을 **따른 결과**를 보여 줄 뿐이고, +규칙 문장을 복사하지 않는다. 생성 명령의 템플릿(`scripts/feature-scaffold/templates/`)이 규칙과 +어긋나면 `scripts/verify-feature-scaffold.sh`가 ArchUnit으로 잡는다. + +## 따라 할 예시는 하나 + +예시가 셋(sample-portfolio 수직, onboarding fixture, durable operation)이라 어느 것을 베끼느냐에 따라 +배치가 달라졌다(리뷰 2026-11-01 01-01·07-09). 이제 **새 업무 기능의 예시는 생성 명령의 출력 하나**다. + +| 코드 | 역할 | 따라 하나 | +| --- | --- | --- | +| `scripts/new-feature.sh` 출력 | 계층 leaf에 나눈 업무 기능 | **이것을 따른다** | +| `src/sample-portfolio` | 한 leaf에 모든 계층을 둔 지울 수 있는 샘플. 개별 기법(조건부 PATCH, 페이지, outbox, DB 유일성 제약)의 참고 | 기법만 본다. 배치는 따르지 않는다 | +| `src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/**` | ArchUnit 규칙이 새 기능 모양에 적용되는지 확인하는 테스트 fixture | 따르지 않는다 | +| `application-core/.../operation` + `DurableOperationAutoConfiguration`(composition:durable-operation) | 템플릿 플랫폼 기능 | 조립 모양(`@ConditionalOnBean` + 유스케이스 `@Bean`)만 본다 | + +## 1라운드 수정으로 생긴 패턴 (리뷰 README 13절) + +리뷰 뒤 1라운드에서 굳은 모양이다. 각 장에 반영했다. + +| 패턴 | 근거 코드 | 장 | +| --- | --- | --- | +| Envelope는 null 필드를 내보내지 않는다 | `docs/web/http-contract.md` 1절 | 06 | +| 처리 중 409 `IDEMPOTENT_IN_FLIGHT`는 `retryable=true` + `Retry-After: 2`, 같은 키로 재전송 | `docs/web/http-contract.md` 2절 | 05 | +| 커밋 중 연결이 끊기면 재시도 가능이 아니라 결과 불명(`DB_COMPLETION_UNKNOWN`, 500) | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java`, `docs/adr/ADR-JPA-003-completion-unknown.md` | 05 | +| 중복 규칙은 조회 후 insert가 아니라 DB 유일성 제약, 위반은 같은 409로 변환 | `src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql`, `PosterRepositoryAdapter` | 04 | +| 여러 인스턴스가 집는 작업은 lease 있는 claim | `ReconciliationJobStorePort.claimDue`(application-notification) | 04 | +| 양방향 연관관계 금지를 ArchUnit으로 | `JpaArchitectureRules.associationsAreMappedFromOneSideOnly()` | 04 | +| store는 호출자 트랜잭션을 요구한다 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CallerTransaction.java` | 04 | +| `@RequiresPermission` 검사는 인증 체인과 분리된 자동 설정 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMethodSecurityAutoConfiguration.java` | 07 | +| JWT audience 필수, 자기 client role만 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfig.java`, `docs/runbooks/auth-audience-mismatch.md` | 07 | +| strict lane은 반드시 어떤 단계에 속한다 | `verifyStrictLaneStages`(`src/build.gradle` `strictLaneStages`) | 08 | +| 샘플 마이그레이션은 별도 history table, 번호는 운영과 겹치지 않게 | `SamplePostgreSqlPersistenceConfig`, `V8_1__…` | 04 | +| 재시도 가능한 broker 거부는 DEAD가 아니라 재시도 | `docs/runbooks/outbox-dead-letter.md` | 09 | diff --git a/docs/manual/appendix-common-principles.md b/docs/manual/appendix-common-principles.md new file mode 100644 index 00000000..2d3cba03 --- /dev/null +++ b/docs/manual/appendix-common-principles.md @@ -0,0 +1,20 @@ +# 부록. 프론트·백엔드 공통 원칙 후보 + +사용자 결정(2026-11-01): 프론트·백엔드에 공통인 실무 원칙은 `desktop-server-git/design-docs/`에 둔다. +그 위치는 이 repo 밖이라 여기서 쓰지 않는다. 이 매뉴얼을 쓰며 나온 **후보만** 적는다. 옮길 때는 원칙 +문장만 옮기고, 이 repo의 장은 그 원칙을 가리키도록 바꾼다(두 벌을 두지 않는다). + +| # | 후보 원칙 | 이 repo에서 드러난 곳 | 프론트 쪽 짝 | +| --- | --- | --- | --- | +| 1 | 결과를 증명할 수 없으면 "모른다"로 분류한다. "실패(재시도 가능)"로 적지 않는다 | 05장, `DB_COMPLETION_UNKNOWN`, outbox ambiguous | 요청 분류기의 timeout·네트워크 오류 처리 | +| 2 | 같은 요청의 재전송은 같은 멱등성 키로. 새 키는 새 작업이다 | `docs/web/http-contract.md` 2절 | 재시도 정책, 409 in-flight 처리 | +| 3 | 중복·경쟁은 저장소의 제약이 막는다. 앞선 조회는 빠른 거절일 뿐이다 | 04장 | 낙관적 UI 갱신과 서버 409 | +| 4 | 같은 규칙을 두 곳에 쓰지 않는다. 쓸 수밖에 없으면 하나가 다른 하나를 검사한다 | DTO 검증 vs aggregate(02장), 오류 코드 registry 대조 테스트 | 폼 검증 스키마 vs 서버 검증 | +| 5 | 실패는 클라이언트 탓/서버 탓으로 먼저 나누고, 클라이언트에는 안정된 코드만 보낸다 | 06장 | 오류 코드 → 화면 문구 매핑 | +| 6 | 권한이 없으면 닫힌 쪽이 기본이다(매핑 전 403, 남의 것은 404) | 07장 | 권한 없는 메뉴·라우트 숨김과 서버 거절 | +| 7 | 계약은 버전·schema·해시로 고정하고, 바꾸면 소비자 계약 테스트가 깨진다 | 09장, Envelope wire 테스트 | 응답 스키마 strict 파싱 | +| 8 | 포트(경계)마다 대역 하나, 대역과 실제가 같은 계약 테스트를 통과한다 | 08장 | API mock과 실제 서버의 계약 테스트 | +| 9 | 선택 기능은 한 줄로 켜고 한 줄로 끈다. 그 기능을 아는 곳은 자기 자신뿐이다 | 10장 | feature flag·라우트 모듈 | +| 10 | 위험은 코드에 드러나야 한다: 의도한 제약·생략은 주석과 테스트 이름에 적는다 | 생성 명령 템플릿의 Javadoc(`NOT_IDEMPOTENT` 이유 등) | 같음 | +| 11 | 게이트는 지우지 않고 단계를 지정한다(PR / main / nightly) | 08장 lane 단계, `verifyStrictLaneStages` | 프론트 CI 단계 | +| 12 | 선택지가 여럿이면 고른 것·버린 것·이유를 남긴다 | 각 장의 「고른 형태와 버린 대안」 | 같음 | diff --git a/docs/messaging/outbox-inbox.md b/docs/messaging/outbox-inbox.md index bf68398f..7167b1e6 100644 --- a/docs/messaging/outbox-inbox.md +++ b/docs/messaging/outbox-inbox.md @@ -1,5 +1,10 @@ # Outbox · Inbox +> **이 템플릿 application의 소비 경로**: application의 `MessageHandler`와 inbox 부품(애플리케이션 +> DataSource 위 `JdbcInboxRepository`, `PlatformTransactionManager` 위 `TransactionRunner`)은 +> `adapter:inbound:messaging`(`src/adapter/inbound/messaging/README.md`)이 둔다. platform starter는 두 +> bean이 있을 때 `IdempotentConsumer`를 만들어 `INBOX_TRANSACTIONAL` destination의 handler를 감싼다. + ## 두 패턴이 각각 무엇을 해결하는가 | 패턴 | 해결하는 문제 | 해결하지 않는 문제 | diff --git a/docs/mongodb/consumer-leaf-guide.md b/docs/mongodb/consumer-leaf-guide.md new file mode 100644 index 00000000..06d8699f --- /dev/null +++ b/docs/mongodb/consumer-leaf-guide.md @@ -0,0 +1,144 @@ +# Mongo 소비 leaf 등록 절차 + +파생 서비스가 `adapter:outbound:persistence-mongo`를 실제로 쓰려면 **자기 Mongo 어댑터 leaf**를 하나 +만든다. 이 leaf(이하 "플랫폼 leaf")는 client·template·정책·실패 분류를 주고, document·repository· +mapper·port 구현은 서비스 leaf가 가진다. 플랫폼 leaf에는 예시 도메인을 production으로 넣지 않는다 +(`src/adapter/outbound/persistence-mongo/CLAUDE.md` "Forbidden"). + +전체 흐름: + +```text +domain-core (Note) application-core (NoteStore port) + \ / + adapter:outbound:persistence-note ← 서비스가 새로 만드는 leaf + NoteDocument / NoteDocumentMapper / NoteDocumentRepository / MongoNoteStore + | + | implementation + v + adapter:outbound:persistence-mongo ← 플랫폼 leaf (executor, 실패 분류, 정책) + ^ + | runtimeOnly (둘 다) + app-bootstrap +``` + +## 1. 동작하는 예시 + +예시 한 벌이 플랫폼 leaf의 테스트 소스에 있다. `mongoStableContractTest`(그래서 `check`)에서 +컴파일되고 실행되므로 API가 바뀌면 예시도 같이 깨진다. + +| 역할 | 예시 타입 | 실제 서비스에서 둘 곳 | +| --- | --- | --- | +| 도메인 타입 | `Note` | `domain-core` | +| outbound port, 도메인 예외 | `NoteStore`, `NoteStore.NoteAlreadyExistsException` | `application-core` | +| 저장 형태 | `NoteDocument` (`@Document`, `@Id`, `@Field`) | 서비스 Mongo leaf | +| 변환 | `NoteDocumentMapper` | 서비스 Mongo leaf | +| collection 접근 | `NoteDocumentRepository` (`DefaultMongoImperativeExecutor` 사용) | 서비스 Mongo leaf | +| port 구현, 예외 변환 | `MongoNoteStore` | 서비스 Mongo leaf | +| 실행 확인 | `MongoNoteStoreExampleTest` | 서비스 Mongo leaf 테스트 | + +위치: `src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/`. + +testFixtures가 아니라 테스트 소스에 둔 이유: testFixtures는 소비 leaf의 테스트 classpath에 그대로 +올라가는 variant다. 예시 타입이 거기 있으면 API처럼 import된다. 테스트 소스는 아무 데도 export되지 않는다. + +## 2. 레지스트리와 Gradle에 leaf 등록 + +leaf 목록과 허용 의존 방향의 원본은 `src/config/architecture/modules.json`이다. 레지스트리에 없는 edge는 +`verifyCleanArchitectureDependencies`가 거부한다. + +1. `modules.json`의 `modules`에 서비스 leaf를 추가한다. 플랫폼 leaf로 가는 edge를 여기서 연다. + + ```json + { + "id": "adapter-outbound-persistence-note", + "gradle_path": ":adapter:outbound:persistence-note", + "source_path": "src/adapter/outbound/persistence-note", + "allowed_dependencies": [ + "domain-core", + "application-core", + "adapter-outbound-persistence-mongo" + ] + } + ``` + + 같은 모양의 선례: `adapter-outbound-persistence-notification`이 `adapter-outbound-persistence-jpa`를 + 같은 방식으로 받는다. + +2. `app-bootstrap`의 `allowed_dependencies`에 `"adapter-outbound-persistence-note"`를 더한다. + `adapter-outbound-persistence-mongo`는 이미 들어 있다. + +3. 서비스 leaf의 `build.gradle`: + + ```groovy + dependencies { + implementation project(':domain-core') + implementation project(':application-core') + implementation project(':adapter:outbound:persistence-mongo') + } + ``` + +4. `app-bootstrap/build.gradle`에서 두 leaf를 켠다. 플랫폼 leaf 줄은 주석으로 이미 있다. + + ```groovy + runtimeOnly project(':adapter:outbound:persistence-mongo') + runtimeOnly project(':adapter:outbound:persistence-note') + ``` + +5. 확인: `./gradlew :adapter:outbound:persistence-note:check architectureCheck --console=plain`. + +## 3. 서비스 leaf가 등록해야 하는 bean + +자동 구성되는 `MongoCollectionProfileRegistry`는 **비어 있다**. 등록하지 않은 collection profile로 +executor를 부르면 거부된다. 서비스 leaf가 자기 collection을 등록한 registry bean을 준다. + +```java +@Bean +MongoCollectionProfileRegistry mongoCollectionProfileRegistry() { + return MongoCollectionProfileRegistry.builder() + .register(NoteDocument.COLLECTION, NoteDocument.COLLECTION) + .build(); +} +``` + +여러 서비스 leaf가 각자 collection을 가지면 registry bean은 하나여야 하므로 composition(보통 +`app-bootstrap`)에서 합친다. + +`DefaultMongoImperativeExecutor`는 자동 구성 bean이다. 서비스 leaf는 그것을 주입받아 +`NoteDocumentRepository`처럼 감싼다. + +## 4. 예외 변환 + +- executor는 driver·Spring 실패를 한 번만 플랫폼 예외로 바꾼다: + `MongoDuplicateKeyException`, `MongoTimeoutException`, `MongoWriteConcernException`, + `MongoServerSelectionException` 등(`dev.caskeleton.adapter.outbound.mongo.api.error`). +- port 구현은 **port가 약속한 실패만** 도메인 예외로 바꾼다. 예시에서는 + `MongoDuplicateKeyException` → `NoteAlreadyExistsException` 하나다. +- 나머지는 그대로 내보낸다. 플랫폼 예외는 `outcome()`·`ambiguous()`로 "쓰기가 됐는지 모름"을 알려 + 준다. 이것을 일반 도메인 예외로 감싸면 호출자가 재시도해도 되는지 판단할 근거가 사라진다. +- 트랜잭션은 `MongoTransactionRetryCoordinator`로 실행한다. 본문의 `TransientTransactionError`는 새 + 세션에서 본문을 다시 실행하고, commit 결과를 모르면 commit만 재시도한 뒤 + `MongoTransactionCommitUnknownException`으로 알린다. 본문은 재실행될 수 있으므로 본문 안에서 외부 + 호출(메시지 발행, HTTP)을 하지 않는다. + +## 5. 정책을 우회하는 경로 — 쓰기 전에 알 것 + +| 경로 | 받는 것 | 잃는 것 | +| --- | --- | --- | +| `DefaultMongoImperativeExecutor` (+ `MongoAtomicOperationsTemplate`, `MongoBulkExecutor`) | operation 이름, collection profile 확인, consistency, deadline, 관측, 실패 변환 | 없음. 기본 경로 | +| Spring Data `MongoRepository` (adapter-local) | 짧은 CRUD 코드 | 위 전부. 실패가 Spring `DuplicateKeyException` 등으로 온다. derived query는 `MongoQueryPolicy`를 거치지 않는다. deadline·consistency profile이 붙지 않는다 | +| `MongoTemplate` / `MongoClient` 직접 주입 | 모든 명령 | 위 전부 + collection 범위 확인 | + +- `MongoRepository`는 adapter leaf 안에서만 허용된다 + (`MongoRepositoryArchitectureRules.allowedRepositorySuperTypes`). 고르면 예외 변환과 timeout을 서비스 + leaf가 직접 책임진다. 플랫폼 공통 CRUD base(`CommonMongoRepository` 등)는 만들지 않는다. +- 사용자 입력으로 조건이 바뀌는 **동적 조회**는 `PolicyAwareMongoQueryBuilder`(`MongoQueryPolicy` + allowlist)로 만든다. 예시의 `_id` 조회처럼 adapter 코드가 고정한 조건은 `Query`를 직접 써도 된다. +- inbound adapter(controller 등)는 `MongoTemplate`·`MongoClient`를 갖지 않는다. 서비스 leaf 테스트에서 + 플랫폼 testFixtures의 `MongoAccessRules.noMongoAccessFrom(...)`으로 확인할 수 있다 + (`testImplementation testFixtures(project(':adapter:outbound:persistence-mongo'))`). + +## 6. 연결 설정 + +URI만 주는 배포(`SPRING_MONGODB_URI`)는 유한 timeout·pool 기본값을 받는다. 값과 바꾸는 법은 +`src/adapter/outbound/persistence-mongo/README.md`의 `SPRING_MONGODB_URI` 예시 바로 아래 문단과 `MongoUriOnlyClientDefaults`에 있다. +production은 typed profile(`app.persistence-mongo.platform.profiles.*`)을 쓴다. diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 70a33d25..8f06cee0 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -259,9 +259,9 @@ env_keys: - name: APP_MULTI_INSTANCE_ENABLED # source: feature-env-driven-runtime-configuration D8 (2026-06-06) - # When true, StartupSafetyValidator (SmartInitializingSingleton) requires the 5 - # instance-coordination beans (distributed lock / cache-stampede / outbox leader - # / rate-limiter / migration runner) to be present, else startup fails. Consumed + # When true, StartupSafetyValidator (a StartupRule, run before any other singleton) + # requires a cross-instance DistributedLockPort bean named distributedLockProvider, + # else startup fails (exit 72). Consumed # by feature-runtime-health-lifecycle-contract, feature-background-job-async-contract, # feature-cache-consistency-contract, feature-domain-event-outbox-contract, # feature-rate-limit-idempotency-contract, feature-migration-startup-contract. @@ -2587,6 +2587,11 @@ env_keys: required_test: cache-contract:redis-soft-hard-ttl-order - name: APP_CACHE_REDIS_TTL_JITTER + # DEPRECATED 2026-11-02: no settings class binds it. Its only reader was a block in + # sample-portfolio's application.yml that nothing bound either (07-10), removed with it. + # Kept so a deployment still setting it is told it does nothing. + deprecated_orphaned: true + removal_deadline: 2027-02-28 type: float default: 0.10 allowed_values: null @@ -3710,7 +3715,7 @@ env_keys: property: spring.jpa.properties.hibernate.jdbc.batch_size owner_module: adapter-outbound-persistence-jpa type: integer - default: 0 + default: 50 allowed_values: null classification: public-config required: false @@ -3718,14 +3723,14 @@ env_keys: reload_policy: restart-only owner_branch: 2026-09-22-persistence-jpa-review-remediation validation: non_negative_integer - compatibility_impact: additive + compatibility_impact: behavior-change required_test: jpa-contract:hibernate-runtime-settings - name: APP_JPA_HIBERNATE_ORDER_INSERTS property: spring.jpa.properties.hibernate.order_inserts owner_module: adapter-outbound-persistence-jpa type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -3733,14 +3738,14 @@ env_keys: reload_policy: restart-only owner_branch: 2026-09-22-persistence-jpa-review-remediation validation: boolean_strict - compatibility_impact: additive + compatibility_impact: behavior-change required_test: jpa-contract:hibernate-runtime-settings - name: APP_JPA_HIBERNATE_ORDER_UPDATES property: spring.jpa.properties.hibernate.order_updates owner_module: adapter-outbound-persistence-jpa type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -3748,7 +3753,7 @@ env_keys: reload_policy: restart-only owner_branch: 2026-09-22-persistence-jpa-review-remediation validation: boolean_strict - compatibility_impact: additive + compatibility_impact: behavior-change required_test: jpa-contract:hibernate-runtime-settings - name: APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE @@ -3920,6 +3925,81 @@ env_keys: compatibility_impact: behavior-change required_test: websocket-contract:canonical-property-namespace + - name: APP_WEBSOCKET_MESSAGE_SIZE_LIMIT + # Spring's own default, now explicit (review 03-06); at most 2147483647 bytes. + property: app.websocket.message-size-limit + owner_module: adapter-inbound-websocket + type: data_size + default: 64KB + allowed_values: null + classification: public-config + required: false + reload_policy: restart-only + owner_branch: 2026-11-01-maturity-review-round2 + validation: positive_data_size + compatibility_impact: additive + required_test: websocket-contract:canonical-property-namespace + + - name: APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT + # Spring's own default, now explicit (review 03-06); at most 2147483647 bytes. + property: app.websocket.send-buffer-size-limit + owner_module: adapter-inbound-websocket + type: data_size + default: 512KB + allowed_values: null + classification: public-config + required: false + reload_policy: restart-only + owner_branch: 2026-11-01-maturity-review-round2 + validation: positive_data_size + compatibility_impact: additive + required_test: websocket-contract:canonical-property-namespace + + - name: APP_WEBSOCKET_SEND_TIME_LIMIT + # Spring's own default, now explicit (review 03-06); at most 2147483647 ms. + property: app.websocket.send-time-limit + owner_module: adapter-inbound-websocket + type: duration + default: 10s + allowed_values: null + classification: public-config + required: false + reload_policy: restart-only + owner_branch: 2026-11-01-maturity-review-round2 + validation: positive_duration + compatibility_impact: additive + required_test: websocket-contract:canonical-property-namespace + + - name: APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE + # Spring's own default, now explicit (review 03-06); at most 2147483647 ms. + property: app.websocket.time-to-first-message + owner_module: adapter-inbound-websocket + type: duration + default: 60s + allowed_values: null + classification: public-config + required: false + reload_policy: restart-only + owner_branch: 2026-11-01-maturity-review-round2 + validation: positive_duration + compatibility_impact: additive + required_test: websocket-contract:canonical-property-namespace + + - name: APP_WEBSOCKET_MAX_CONNECTIONS + # New per-node STOMP session ceiling (review 03-06); the next session is closed with 1013. 1000 x 512KB send buffer bounds worst-case outbound buffering near 512 MiB. + property: app.websocket.max-connections + owner_module: adapter-inbound-websocket + type: integer + default: 1000 + allowed_values: null + classification: public-config + required: false + reload_policy: restart-only + owner_branch: 2026-11-01-maturity-review-round2 + validation: positive_integer + compatibility_impact: behavior-change + required_test: websocket-contract:canonical-property-namespace + - name: APP_GRAPHQL_ENABLED # 2026-09-25 capability packaging: the module is on when present (its own config yml maps # this key with default true); false is the explicit off. Absent from the build is the @@ -4087,6 +4167,21 @@ env_keys: compatibility_impact: additive required_test: graphql-contract:wired-operator-settings + - name: APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD + property: app.graphql.limits.per-parent-fetch-warning-threshold + owner_module: adapter-inbound-graphql + type: integer + default: 10 + allowed_values: null + classification: public-config + required: false + required_when: APP_GRAPHQL_ENABLED=true + reload_policy: restart-only + owner_branch: 2026-11-01-maturity-review-round2 + validation: positive_integer + compatibility_impact: additive + required_test: graphql-contract:wired-operator-settings + - name: APP_OUTBOX_ENABLED # source: five-adapter-runtime-remediation §6.1 JPA-INT-004 — the outbox capability switch. # relay-enabled below only starts the scheduler; conflating the two meant a relay-off deployment diff --git a/docs/reviews/2026-11-01-maturity-review/README.md b/docs/reviews/2026-11-01-maturity-review/README.md index 65862998..72b44439 100644 --- a/docs/reviews/2026-11-01-maturity-review/README.md +++ b/docs/reviews/2026-11-01-maturity-review/README.md @@ -358,7 +358,15 @@ | `-p optional-platforms ci` (gRPC 플랫폼) | rc=0 | 71초 | load 8.99 | | `:integrationCheck` (컨테이너 lane 37개 전부) | rc=1 — MinIO lane 2개만 실패(위와 같은 이유). 나머지 35 lane 통과: JPA 실 PostgreSQL 11 lane, notification·sample·Redis·Mongo·websocket nginx·messaging certification 등. 04-01·04-02·09-02 수정이 실 DB에서 함께 통과 | 794초 | load 23.84 | -남은 빨강은 05-09 하나(대체 이미지 미정)다. `releaseCheck`, `qualityCheck` 단독, `performanceCheck`, gRPC ledger PG lane(`-p optional-platforms integrationCheck`)은 합친 트리에서 다시 돌리지 않았다(ledger는 03-10 수정 에이전트가 30건 통과 확인). +추가 실행(같은 합친 트리, 2026-11-01 23:32~23:45): + +| 게이트 | 결과 | 시간 | 부하 | +|---|---|---|---| +| `-p optional-platforms integrationCheck` (gRPC ledger 실 PostgreSQL) | rc=0, 30건 통과 · skip 0 | 118초 | load 7.33 | +| `:performanceCheck` (08-01로 신설) | rc=0 | 284초 | load 6.45 | +| `:releaseCheck` | 인자 없이 rc=1 — `verifyReleaseProvenance: no source revision`(릴리스는 커밋 sha가 필요하다는 설계상 전제). `-PgitRevision=$(git rev-parse HEAD)`로 rc=0. 작업 트리가 미커밋이라 실제 릴리스 증거로는 쓸 수 없다 | 105초 | load 17.50 | + +남은 빨강은 05-09 하나(대체 이미지 미정)다. ### 13.2 결정이 필요한 것 (수정 중 새로 생김) @@ -378,3 +386,81 @@ | 04-03 DisplayName | 에이전트가 AGENTS.md(영어)를 따름. 소유자 결정 5(한국어)와 AGENTS.md 불일치(08 영역 기존 지적) | AGENTS.md를 소유자 결정에 맞춘다 | | 05-09 MinIO 대체 이미지 | 여전히 미정. lane 2개는 구분된 메시지로 실패 | 소유자 결정 | + +## 14. 2라운드 조치 현황 (남은 P2·P3, 1라운드 후속, 매뉴얼) + +사용자가 2026-11-01 23:20에 "남은 작업까지 모두 완수"를 지시했다. 1라운드 수정을 합친 상태를 임시 클론(baseline)으로 고정하고, 영역별 11개 묶음 에이전트가 각자 클론에서 RED→GREEN으로 고쳤다. 오케스트레이터가 패치를 메인 작업 트리에 합쳤다(커밋 없음). 사용량 한도로 모든 에이전트가 00:20쯤 한 번 멈췄다가 재개했다. + +| 묶음 | 상태 | 검증 (에이전트 클론) | 처리 내용 | 합칠 때 조치·결정 필요 | +|---|---|---|---|---| +| r2-10 | 완료 | scaffold 왕복(5 leaf check+architectureCheck) rc=0, verifyDependencyLocks rc=0, verifyStrictLaneStages rc=0 | 01-01·07-09 완료, 01-12 부분(정본은 r2-01), 생성 명령 scripts/new-feature.sh + verifyFeatureScaffold(mainCheck) | 결정: JPA adapter는 생성 안 함(서비스 전용 persistence leaf 기본), 생성 권한은 역할 매핑 전 403 | +| r2-02 | 완료(02-09 부분) | web·web-advanced·web-fileserver·sample check, architectureCheck, web 300, webSecurityBoundary 15, web systemTest 16, app-bootstrap test 321, sample webSystemTest 5 | 02-04~02-12 RED 확인 후 수정 | 결정: 비JSON 본문 상한 없음(엔드포인트가 직접), 새 오류 코드는 leaf enum(http-contract.md §4), correlation ID 규칙 밖이면 서버가 교체, sample 키 오류 BAD_PARAMETER→IDEMPOTENCY_KEY_INVALID(프론트 반영 필요) | +| r2-09 | 완료 | sample check 307, systemTest 14, integrationTest 58, webSystemTest 5, web check 274, architectureCheck pass (에이전트). 합칠 때 EnvelopeBodyAdvice 충돌(02-06 vs 09-04)을 오케스트레이터가 byte[]만 제외로 합침 → web check + SampleApiDocsSystemTest 재실행 | 09-01 SQL 46→6, rps 765→2528, 09-04, 09-06, 09-07, 01-13, 09-02 후속 | 결정: batchCreate 상한 1000·한 트랜잭션 유지(원격 DB면 100으로 낮출지), 관리자도 남의 기록 수정 불가 | +| r2-01 | 10 완료·3 부분·01-10 못함 | leaf check 11개, architectureCheck 2회, sample webSystemTest·systemTest, PG lock IT (에이전트) | 01-02,04,06,07,08,09,12,13,14 완료 / 01-03 부분(notification TenantId 유지), 01-05 부분(Transaction·Idempotency 계약 키트 못함), 01-11 부분(edge 없는 4 leaf) / 01-10 못함(패키지 규칙 선행) | 합칠 때: sample PortfolioErrorCode 충돌 → r2-09의 WORKLOG_NOT_OWNER와 r2-01의 WORKLOG_INVALID·OPERATION_NOT_FOUND 수동 합침. UpdateWorkLogUseCase "소유자 검사 없음" Javadoc은 r2-09가 소유자 검사를 넣어 사실이 아니게 되어 제외. 결정: sample 이벤트 tenant 범위 global, 새 오류 코드 2개 | +| r2-03 | 10건 완료 | graphql test 388·systemTest 34·API surface, websocket check 92·qualification 7·Tomcat IT, grpc adapter check 61·transport 29, grpc 4 leaf check·ledger PG IT 35, -p optional-platforms ci, verifyEnvKeys 352 keys | 03-02~03-09, 03-11, 03-10 후속 | 결정: gRPC 기본값(스레드 32·큐 256·동시 100·deadline 10s·drain 2s), ledger claimTtl 5m·보존 24h·purge 스케줄은 adopter, websocket max-connections 1000·초과 시 1013, GraphQL per-parent 경고 임계 10 | +| r2-07 | 대부분 완료(07-08·09-11 부분) | leaf check 11개, architectureCheck, verifyDependencyLocks, verifyEnvKeys 346, app-bootstrap systemTest 11·IT 10, sample systemTest 8·webSystemTest 5·IT 55, 실제 docker build+healthy | 07-02 후속, 02-03 후속(${} 자리표시자 거부), 07-04, 07-06, 07-07, 07-10~14, 09-08, 09-10 완료 / 07-08 부분(fileserver 볼륨 미룸), 09-11 부분(Jackson 2 유지: logstash·springdoc 요구), 07-03 advisor 규칙은 r2-01과 중복이라 제외 | 합칠 때 sample application.yml을 r2-09 JDBC batch 설정과 context 1줄로 합침. 결정: 새 leaf composition:durable-operation 등록, logback이 app.logging.* 읽음, APP_CACHE_REDIS_TTL_JITTER deprecated | +| r2-08 | 대부분 완료(08-07 측정만, TEST-F-1 못함) | build-logic 94, ci verifyDependencyLocks, verifyStrictLaneStages, documentContractTest 60, 컨테이너 lane 12, -p optional-platforms ci integrationCheck (에이전트) | 1R-a(workflow --stacktrace 22곳), 08-02, 08-03, 08-04(MinIO 제외), 08-05, 08-06, 1R-b·c(AGENTS/CLAUDE 단계·DisplayName 한국어), O-10·O-11 완료 / 08-07 MEDIUM 298건 측정·계획만 / TEST-F-1 못함(포트 83개) | 합칠 때 app-bootstrap build.gradle·DeveloperExperienceContractTest·StructuredLogFieldContractTest를 r2-07과 수동 병합, r2-07이 새로 만든 저장소 읽는 테스트 4개(Dockerfile·compose 3, SampleRuntimeDefaults)에 repository-contract 태그 부여 | +| r2-05b | 10 완료·3 부분 | objectstorage check 148 + MinIO 계약 14·fault 1 통과(새 이미지 pgsty/minio digest), support·identifier·httpclient·redis-runtime·redis-sdk·cache-redis·application-core check, app-bootstrap test 321, architectureCheck, verifyEnvKeys, 실 Redis topology, httpclient Toxiproxy | 05-09 완료(MinIO 대체: pgsty/minio@sha256:b6bfe723…, Chainguard 기각), 05-16 objectstorage 완료(S3 어댑터 결함 2개 발견·수정), 05-23b·d·e·f·g, 05-21, 05-05/06/14, 05-02/03/04/17/18 완료 / 05-15 부분(support binder 2단계 키), 05-16 Redis·HTTP 부분 / objectstorage 계약 testFixtures 이동 못함 | 합칠 때 objectstorage build.gradle, httpclient FailureInjectionContractTest를 r2-08 이미지 일원화와 수동 병합. 결정: AGENTS.md 규칙 4에 Redis 예외 한 줄 필요, objectstorage provider type 하나 추가 | +| r2-06 | v2(baseline2 위 재작업) 완료, 06-08 부분 | application-core 264, outbox-relay 30, durable-operation 3, persistence-jpa 526, messaging 41, starter 74, inbound messaging 4, identifier 12, web 305, sample 319, architectureCheck, verifyDependencyLocks, verifyStrictLaneStages, Kafka relay 2, PG lane 5(28) | 06-02·06-01 후속, 06-04~06-07, 06-09 완료, durable operation id v4→v7 결함 RED→GREEN / 06-08 최소 경로(실 Kafka+PG 중복 전달 lane 없음) | 합칠 때 identifier README·CLAUDE.md를 r2-05b 문서 재작성과 수동 병합. r2-01 AggregateOrder.ofOccurrence(벽시계)를 지우고 OutboxAggregateSequencePort로 일원화 — ofOccurrence 테스트 2개 삭제·first() 테스트 1개로 대체. 결정: V20/V21, 새 leaf adapter:inbound:messaging, V21 유일 인덱스는 기존 중복 있으면 마이그레이션 실패 | +| r2-04 | 13 완료·04-14/04-16/04-04후반 부분 | persistence-jpa 557, sample test 299, app-bootstrap 321, architectureTest 183, fileserver·notification·mongo leaf check, architectureCheck, verifyEnvKeys, verifyDependencyLocks, 실 PG lane(transaction 7, platformFailure 5, platformContract 244, fileserver 47, migration·notification 13, sample IT 55) | 04-05,06,07,08,10,11,12,13,15,17, 09-05, 09-07, 09-09 완료 / 04-14 부분(notification 포트 10개 계약 미이동), 04-16 부분(notification 패키지 분할 못함), 04-04 후반 부분(fileserver test 0→3) / 04-03 sample DisplayName 1개 못 고침 | 새 실 PG 테스트 3개는 수정 전 실패를 실 PG로 확인 안 함(단위 테스트로 RED). 결정: 트랜잭션 제한 30초, batch 기본 50, H2 운영 jar에서 제거, 격리 수준을 Hikari에서 고정, 포트 시그니처 변경(fileserver claimDue·markAbandoned·claimToken), 마이그레이션 notification V12 | +| r2-05a | **합치지 않음** | — | 알림·파일 서버 묶음(05-10~13, 05-19, 05-20, 05-22, 05-23 일부, 05-16 일부, 05-07 쿼터 상한 등). 마감까지 패치·검증 보고가 없었다. 클론 `round2/wt-r2-05a-notif-file`에 미검증 변경 86개 파일이 있다 | 다음 작업에서 이 클론을 baseline 최신 상태로 다시 올려 검증 후 합친다 | + +### 14.1 합칠 때 생긴 충돌과 처리 + +- `EnvelopeBodyAdvice`(r2-02 02-06 ↔ r2-09 09-04): springdoc 3.0이 OpenAPI 문서를 `byte[]`로 돌려주는 것을 jar에서 확인하고, `byte[]`만 감싸지 않고 `String`은 02-06대로 감싸게 합쳤다. web check·`SampleApiDocsSystemTest` 통과. +- sample `PortfolioErrorCode`(r2-01 ↔ r2-09): 두 쪽 코드 모두 넣었다. r2-01의 "UpdateWorkLogUseCase는 소유자 검사 없음" Javadoc은 r2-09가 소유자 검사를 넣어 거짓이 되므로 넣지 않았다. +- sample `application.yml`(r2-07 ↔ r2-09): context 1줄로 합쳐 JDBC batch 설정과 설정 정리 둘 다 반영. +- app-bootstrap `build.gradle`·계약 테스트 2개(r2-08 ↔ r2-07): lane 분리 블록으로 바꾸고 r2-07의 sample yml 입력을 살렸다. r2-07이 새로 만든 저장소 읽는 테스트 4개에 `repository-contract` 태그를 달았다(태그 없으면 08-03 규칙상 `test` lane에서 실패). 합친 뒤 `:app-bootstrap:check`·`documentContractTest` 통과. +- r2-06은 10개 파일 충돌로 baseline2(그 시점 메인 상태) 위에서 다시 작업시켰다(v2). r2-01의 `AggregateOrder.ofOccurrence`(벽시계)를 지우고 `OutboxAggregateSequencePort`로 일원화했다. +- objectstorage `build.gradle`·httpclient `FailureInjectionContractTest`(r2-05b ↔ r2-08 이미지 일원화), identifier README·CLAUDE.md(r2-05b ↔ r2-06): 수동 병합. +- 매뉴얼(`docs/manual/`)이 가리키던 `DurableOperationConfig`는 r2-07이 `composition:durable-operation`의 `DurableOperationAutoConfiguration`으로 옮겨서 경로를 고쳤다. 매뉴얼이 인용한 `src/`·`docs/` 경로를 전수 검사해 템플릿 자리표시자(``) 외에 없는 경로가 없음을 확인했다. + +### 14.2 합친 뒤 전체 게이트 + +r2-05a를 뺀 10개 묶음을 합친 메인 작업 트리에서 오케스트레이터가 실행했다(공유 잠금). + +첫 실행(05:40)은 실패 3건이었다. 모두 합치는 과정에서 생긴 문제라 고쳤다. + +| 실패 | 원인 | 조치 | +|---|---|---| +| `ci` `verifyCleanArchitectureDependencies` | 08-05의 새 검사가 git-ignore 대상인 IDE 출력 `bin/` 안의 복사된 build 스크립트(`grpc-codegen/bin/test/...`)를 잡았다 | `ModuleRegistry.unregisteredBuildScripts`가 `bin/`을 건너뛴다 | +| `mainCheck` `verifyFeatureScaffold` | 작업 트리 복사가 지웠지만 미커밋인 추적 파일 26개에서 `tar` 실패 | `scripts/verify-feature-scaffold.sh`가 `git ls-files -d` 경로를 뺀다 | +| sample `WorkLogStatementCostSystemTest` | 기대 202, 실제 8. 04-17(`Persistable`) 뒤 컬렉션 행도 owner를 넘어 묶여 표마다 50행씩(2+4+2) | 기대값 8로, 테스트 설명·sample README·`application.yml` 주석 수정. 202·400 회귀는 계속 잡는다 | +| (확인 중 발견) build-logic `PlatformModuleConventionTest` 6건 | 08-04 뒤 `java-conventions`가 이미지 목록 파일을 요구하는데 TestKit fixture에 없음 | fixture가 빈 목록 파일을 쓴다 | + +재실행 결과: + +| 게이트 | 결과 | 시간 | 실행 직전 부하 | +|---|---|---|---| +| `ci` | rc=0 | 365초 | load 4.24 | +| `mainCheck` (`verifyFeatureScaffold` 생성 왕복 포함) | rc=0 | 171초 | load 15.86 | +| `:integrationCheck` (MinIO 계약·fault 포함 전 컨테이너 lane) | rc=0 | 697초 | load 11.23 | +| `-p optional-platforms ci integrationCheck` | rc=0 | 51초 | — | + +1라운드 끝까지 빨갛던 MinIO lane이 05-09 대체 이미지(`pgsty/minio` digest)로 통과한다. 이 시점 기준으로 빨간 게이트는 없다. `releaseCheck`·`performanceCheck`는 2라운드 뒤 다시 돌리지 않았다. + + + +### 14.3 남은 것 (2026-11-02 06:15 기준) + +**합치지 않은 묶음** +- r2-05a(알림·파일 서버). 06:45에 패치(`round2/patches/r2-05a-notif-file.patch`, 103파일)가 왔지만 합치지 않았다. 이유: 메인 작업 트리에 6곳 충돌(r2-04가 같은 fileserver fake를 testFixtures로 옮김, `application-fileserver` build.gradle·lockfile, `applied-migrations.sha256`, `NotificationFixtures`), 알림 마이그레이션 `V12`가 r2-04의 `V12__notification_suppression_target_unique`와 번호 충돌, 05-11은 수정 뒤 GREEN 실행 없음. 07:30 마감 안에 합치고 전체 게이트를 다시 돌릴 시간이 없어 초록 상태를 유지했다. + - 묶음 보고상 완료: 파일 서버 05-07 후속(쿼터 상한·대상 namespace·MOVE/READ_METADATA 소유자 테스트)·05-12·05-13·05-22·05-23a, 알림 05-10(+ `collapse_key` 미저장 결함 발견)·05-23c·05-01 후속 테스트 이름. 부분: 05-11(GREEN 미실행), 05-16 fileserver. 못 함: 05-19, 05-20, 05-16 notification. + - 다음 작업: 최신 메인 위로 다시 올리고 마이그레이션을 `V13`으로 바꾼 뒤 05-11 GREEN과 전체 게이트를 확인하고 합친다. + +**부분 완료·못 한 것 (묶음 보고 기준, 이유는 14절 표)** +- 01-03(notification `TenantId` 유지), 01-05(트랜잭션·멱등성 포트 공유 계약), 01-10(패키지 이동), 01-11(edge 없는 4 leaf) +- 02-09(JSON 아닌 본문 상한 — 엔드포인트가 직접 두도록 문서화) +- 04-14(notification 포트 10개 계약), 04-16(notification 패키지 분할), 04-04 후반(persistence-fileserver 테스트 3개만), 04-03 sample `@DisplayName` 1개 +- 05-15(support binder 2단계 키), 05-16 Redis·HTTP 계약 상속, objectstorage 계약 testFixtures 이동 +- 06-08(실 Kafka+PG 중복 전달 lane 없음) +- 07-08(fileserver 볼륨), 09-11(Jackson 2는 logstash·springdoc 요구로 유지) +- 08-07(SpotBugs MEDIUM 298건 — 측정과 단계 계획만), TEST-F-1(공유 계약 없는 포트 정리) + +**결정 필요** — 13.2 표와 14절 표의 "결정" 칸. 파생 서비스 동작을 바꾸는 것: JWT audience 필수, JDBC batch 기본 켜기·H2 제거·트랜잭션 30초·격리 수준 Hikari 고정, gRPC·WebSocket·GraphQL 새 한도 기본값, 새 leaf 2개(`composition:durable-operation`, `adapter:inbound:messaging`) 등록, 새 마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1, grpc-ledger V002). + +**짝 프론트가 맞출 것** — 처리 중 409 `retryable=true`+`Retry-After`, 키 재사용 `422 IDEMPOTENT_REQUEST_MISMATCH`, 키 형식 오류 `400 IDEMPOTENCY_KEY_INVALID`, Envelope null 필드 생략, 계약 §4.1·§6이 `docs/web/http-contract.md`를 가리키게. + +**검증하지 않은 것** — 2라운드 뒤 `releaseCheck`·`performanceCheck`, GitHub Actions 실제 실행. + +**커밋** — 하지 않았다(`human-only`). 1·2라운드 변경이 main 작업 트리에 미커밋으로 있다. diff --git a/docs/runbooks/grpc-platform-operations.md b/docs/runbooks/grpc-platform-operations.md index d218f26e..0b632126 100644 --- a/docs/runbooks/grpc-platform-operations.md +++ b/docs/runbooks/grpc-platform-operations.md @@ -39,8 +39,8 @@ the time, and which half is not knowable from the status. escalate to the service owner. This is the case the keyed profile exists to avoid. 7. `IN_PROGRESS` means a claim exists and has not finished. If its owner died, the claim is not - stuck forever: once it is older than the claim TTL (the `claimTtl` given to - `GrpcIdempotencyInterceptor`), the next retry of the same request takes it over and runs again, + stuck forever: once it is older than the claim TTL (`app.grpc.platform.operation-ledger-claim-ttl`, + default 5m), the next retry of the same request takes it over and runs again, and a later reconciler pass sees that attempt's `COMMITTED` or `FAILED_TERMINAL`. Until a retry arrives, the case stays pending. The re-run is safe only when the ledger commit is recorded in the mutation's own transaction; if this service commits them separately, check the business resource @@ -52,6 +52,32 @@ retry arriving is a caller that gave up; it needs the business resource checked, --- +## The operation ledger table keeps growing + +**What you are seeing.** `grpc_operation_ledger` grows without bound, or a retry of an old key runs +the mutation again instead of replaying. + +**What it means.** Finished rows (`COMMITTED`, `FAILED_TERMINAL`) are deleted only when something +calls `GrpcOperationLedgerRetention.purgeExpired(now)`; the starter assembles that bean +(`app.grpc.platform.operation-ledger-enabled=true`) but does not schedule it. A growing table means +the service's scheduler is not calling it. A retry that re-ran after the retention +(`app.grpc.platform.operation-ledger-retention`, default 24h) is the trade the retention makes: its +record was purged, so it was a new operation. + +**What to do.** + +1. Check that the service schedules `purgeExpired`. Each call deletes in batches of 500 until a batch + comes back short, never touching `IN_PROGRESS` rows. +2. For a large backlog, call it repeatedly; each batch is a short transaction that skips rows another + transaction holds. +3. If retried keys re-run after the retention, raise the retention above the callers' retry window + rather than skipping the purge. + +**Escalate when** old `IN_PROGRESS` rows accumulate. Those are not purged by design; each is an +abandoned claim no retry has taken over (see `IN_PROGRESS` above). + +--- + ## A stream ended with FULL_RESYNC_REQUIRED **What you are seeing.** A client's resume was refused and it was told to resynchronise. diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index 911f7f51..7d98487b 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -8,7 +8,10 @@ - 응답 원문의 키 집합: `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java` - 멱등성 응답의 status·code·retryable·`Retry-After`: `IdempotencyExceptionMappingTest`, - `RetryAfterAdvisorTest`, `OperationalErrorTest` + `RetryAfterAdvisorTest`, `OperationalErrorTest`, 키 형식은 `IdempotencyKeyHeaderTest` +- 헤더 규칙(3절): `WebMvcRequestIdFilterTest`, `CorsSecurityFilterIntegrationTest` +- web 전용 코드(4절): `TransportErrorHandlingTest`, `IdempotencyKeyHeaderTest`, web-advanced + `WebAdvancedErrorMappingTest` ## 1. Envelope 키 존재 규칙 @@ -24,6 +27,8 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). ** - `success`가 판별자다. 클라이언트는 `success`로 갈라 읽고, 키가 있는지로 판단하지 않는다. - 성공인데 `data`가 `null`이면 `data` 키도 없다. 본문이 아예 없는 응답(204)은 Envelope가 아니다. +- 컨트롤러가 `String`을 반환해도 JSON을 요청하면(`Accept: application/json`) 같은 Envelope로 나간다 + (`"data": "<문자열>"`). 텍스트를 요청하면 문자열 그대로다. - 빈 컬렉션 결과는 `"data": []`, 빈 bulk 결과는 `"results": []`, 항목 없는 부분 실패는 `"details": []`로 나간다. @@ -67,7 +72,7 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). ** | 재생(replay): 같은 키·같은 본문, 첫 요청 완료 | 첫 요청과 같은 성공 status | — (성공 Envelope) | — | 없음 | 첫 요청의 결과로 받아들인다. `meta`의 id는 이번 요청의 것이다 | | 처리 중(in-flight): 같은 키, 첫 요청이 아직 실행 중 | 409 | `IDEMPOTENT_IN_FLIGHT` | `true` | `2` | 결과 불명. **같은 `Idempotency-Key`로** `Retry-After` 뒤 재전송한다. **새 키 금지** | | 본문 불일치(mismatch): 같은 키·다른 본문 | 422 | `IDEMPOTENT_REQUEST_MISMATCH` | `false` | 없음 | 클라이언트 버그. 다시 보내지 않는다. 새 작업이면 새 키를 만든다 | -| 키 누락·형식 오류 | 400 | `BAD_PARAMETER` | `false` | 없음 | 키를 붙여 다시 보낸다 | +| 키 누락·형식 오류 | 400 | `IDEMPOTENCY_KEY_INVALID` (`details.reason` = `MISSING`/`MALFORMED`) | `false` | 없음 | 문법에 맞는 키를 붙여 다시 보낸다 | - **처리 중을 `retryable=true`로 두는 이유.** 같은 키 재전송은 서버가 재생·처리 중·불일치로 안전하게 판정하므로, 다시 보내는 것이 맞는 행동이다. 새 키로 보내면 서버는 다른 요청으로 보고 막지 못해, @@ -77,9 +82,9 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). ** 결과가 바뀌지는 않는다. lease를 2초보다 짧게 설정한 서비스는 이 값이 lease를 넘으므로 값을 다시 정한다(`RetryAfterAdvisor`, `docs/registries/error-codes.yaml`). - executor는 기다리지 않는다. 처리 중이면 바로 409를 돌려준다. 키로 결과를 조회하는 엔드포인트는 없다. -- 키 누락 처리는 엔드포인트가 정한다(공용 검증 부품 없음, 리뷰 02-12). 템플릿 예시 - (`PosterImagePublicationController`)는 헤더가 없으면 `MissingRequestHeaderException`, 비었거나 - 256자를 넘으면 `IllegalArgumentException`으로 둘 다 400 `BAD_PARAMETER`다. 키를 요구하지 않는 +- **키 문법**: 보이는 ASCII(`0x21`–`0x7E`) 1~256자. 서버는 trim하거나 고치지 않는다. 짝 프론트의 + `isValidIdempotencyKey`와 같은 규칙이다. KEYED 엔드포인트는 모두 `IdempotencyKeyHeader.parse`로 헤더를 + 읽어 같은 코드로 거부한다(리뷰 02-12). 키 원문은 응답에 돌려 쓰지 않는다. 키를 요구하지 않는 엔드포인트는 키 없이 보호 없이 실행된다. 같은 executor가 내는 나머지 두 실패: @@ -89,9 +94,54 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). ** | 멱등성 저장소 응답 없음 | 503 | `IDEMPOTENCY_UNAVAILABLE` | `true` | 없음 | 작업 실행 전에 거부됐다. 같은 키로 나중에 다시 보낸다 | | 이전 시도의 효과를 증명할 수 없음 | 500 | `IDEMPOTENCY_RECOVERY_REQUIRED` | `false` | 없음 | 재전송도 재실행도 안전하지 않다. 업무 데이터로 결과를 확인한다 | -## 3. 바꿀 때 +## 3. 헤더 + +### 요청 id·correlation id + +| 헤더 | 방향 | 규칙 | +| --- | --- | --- | +| `X-Request-Id` | 응답(항상) | 서버가 만든다. 신뢰 설정(`app.web.mvc.trust-inbound-request-id`)일 때만 요청 값을 받는다 | +| `X-Correlation-Id` | 요청·응답(항상) | 요청 값이 `[A-Za-z0-9._-]{1,128}`(앞뒤 공백 제거 후)이면 그대로 잇고, 아니면 서버가 새로 만든다. 고치지 않고 바꾼다 | +| `traceparent` | 요청·응답(항상) | 유효한 W3C 값이면 잇고, 아니면 새로 만든다 | + +세 값은 응답 `meta`의 `requestId`·`correlationId`·`traceId`와 같다. 셋 다 짝 프론트의 +`[A-Za-z0-9._:-]{1,128}` 안에 든다. + +### 브라우저가 읽을 수 있는 응답 헤더(CORS) + +CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 `Access-Control-Expose-Headers`에 +아래가 들어간다. 이 목록 밖의 헤더(안전 목록 `Cache-Control`·`Content-Type` 등 제외)는 브라우저 코드에서 +`null`로 보인다. + +- 플랫폼(`CorsExposedHeaders.PLATFORM`): `Retry-After`, `X-Request-Id`, `X-Correlation-Id`, + `traceparent`, `Location`, `ETag`, `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` +- fileserver를 실은 배포: `Tus-Resumable`, `Tus-Version`, `Tus-Extension`, `Tus-Max-Size`, + `Upload-Offset`, `Upload-Length`, `Upload-Defer-Length`, `Upload-Expires`, `Upload-Complete`, + `Upload-Limit`, `Content-Disposition`, `Accept-Ranges` + +새 응답 헤더를 쓰는 모듈은 `CorsExposedHeaders` bean으로 자기 헤더를 기여한다. + +## 4. web 전용 오류 코드 + +`OperationalError`(`docs/registries/error-codes.yaml`) 밖에서 HTTP 어댑터가 내는 코드다. + +| 코드 | status | category | `retryable` | `Retry-After` | 언제 | +| --- | --- | --- | --- | --- | --- | +| `REQUEST_TIMEOUT` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 없음 | 비동기 요청(`Callable`·`DeferredResult`·스트리밍)이 시간 안에 끝나지 않았다 | +| `IDEMPOTENCY_KEY_INVALID` | 400 | `VALIDATION` | `false` | 없음 | 2절 | +| `RATE_LIMIT_UNAVAILABLE` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 있음 | rate-limit 저장소 응답 없음(`docs/web/runbook.md`) | +| `RATE_LIMIT_INCOMPATIBLE` | 503 | `INTERNAL` | `false` | 없음 | rate-limit 제공자가 계약과 맞지 않음 | + +- 컨트롤러 파라미터 제약 위반(`@RequestParam @Max(10)`)은 요청 본문 위반과 같은 + `400 VALIDATION_FAILED`이고 `details`는 `[{field, code, message}]`다. 거절된 값은 싣지 않는다. +- web-advanced를 실은 서비스의 예외 코드(`ADMISSION_REFUSED` 503 등 10종)는 + `src/adapter/inbound/web-advanced/README.md` 「오류 응답」이 정본이다. +- 직접 쓰는 거부 응답(401·403·429·503)도 컨트롤러 응답과 같이 `application/json;charset=UTF-8`이다. + +## 5. 바꿀 때 - 응답 키를 더하거나 빼면 `EnvelopeWireShapeTest`와 이 문서 1절을 같이 고친다. +- 응답 헤더를 새로 쓰면 `CorsExposedHeaders`에 넣고 3절을 고친다. - 멱등성 코드의 status·retryable·`Retry-After`를 바꾸면 `OperationalError`, `RetryAfterAdvisor`, `docs/registries/error-codes.yaml`, 이 문서 2절을 같은 변경에서 고친다. - 짝 프론트의 백엔드 계약 문서(`clean-architecture-frontend-template` diff --git a/docs/web/repository-adaptation.md b/docs/web/repository-adaptation.md index d4be93dc..c3b43f84 100644 --- a/docs/web/repository-adaptation.md +++ b/docs/web/repository-adaptation.md @@ -139,10 +139,11 @@ application use cases: `adapter:inbound:web` `operation/DurableOperationControll `POST /operations` (202 + `Location`), `GET /operations/{id}`, `DELETE /operations/{id}` (202), answers in the `Envelope` contract, and a caller's operation that is not theirs is the same 404 (`OPERATION_NOT_FOUND`) as one that does not exist. The controller and the three use cases are -assembled by `app-bootstrap` `autoconfigure/operation/DurableOperationConfig`, which turns on only +assembled by `composition:durable-operation` (`DurableOperationAutoConfiguration`), which turns on only when the operation store and the outbox append port exist (the JPA module with `app.outbox.enabled=true`). Submit and cancel need `operation:submit` / `operation:cancel` -(`security.yml` grants both to the `operation-submit` role). +(that module's `config/module-defaults/durable-operation.yml` grants both to the `operation-submit` +role). The state machine is enforced three times on purpose: in `DurableOperation`'s constructor, in the `CHECK` constraints of `V11__durable_operation.sql`, and in the `WHERE` clause of every statement diff --git a/docs/web/runbook.md b/docs/web/runbook.md index a2f1389e..dde6316c 100644 --- a/docs/web/runbook.md +++ b/docs/web/runbook.md @@ -78,6 +78,12 @@ Two more start fine and still fail in the browser: - `https://*.example.com` in the origin list — it is compared as a literal and matches nothing. - An origin with a path (`https://app.example.com/ui`) — an origin is scheme, host and port only. +The response arrives but a header reads as `null` in browser code (`Retry-After`, `X-Request-Id`, +`Location`, a tus `Upload-Offset`): the header is not in `Access-Control-Expose-Headers`. The exposed +list is `CorsExposedHeaders.PLATFORM` plus each module's `CorsExposedHeaders` bean +(`docs/web/http-contract.md` §3); a header a service adds needs its own bean. A proxy that strips or +rewrites `Access-Control-Expose-Headers` has the same symptom. + A preflight answered `401` means CORS ran after authentication. Preflights carry no credentials by design; the order is asserted by `WebPipelineOrderContract`. diff --git a/infra/minio/smoke/object-storage-smoke.sh b/infra/minio/smoke/object-storage-smoke.sh index 4187aa74..4d949ed3 100755 --- a/infra/minio/smoke/object-storage-smoke.sh +++ b/infra/minio/smoke/object-storage-smoke.sh @@ -6,12 +6,13 @@ # on. The wrong-credential step is here because a bucket that accepts anyone is also "working". # # It runs on the MinIO server image rather than the mc client image, and the reason is worth keeping: -# minio/mc ships mc and almost nothing else — no sed, no grep, no cmp — so steps 2 and 3 below called +# The mc client image ships mc and almost nothing else — no sed, no grep, no cmp — so steps 2 and 3 below called # two binaries that are not there. The script had never run to find out. The wrapper's one-shot loop # lost its stdin to `docker compose run` and executed only the first client per lane, so this one was # skipped in every lane that declared it while all three lanes reported green. # -# minio/minio carries mc, and also sha256sum, cut and tr. The lane already pulls it for the server, +# The server image (now pgsty/minio, review 05-09; checked 2026-11-02) carries mc, and also +# sha256sum, cut and tr. The lane already pulls it for the server, # so this costs no image, and the digest comparison is a stronger identity check than cmp: it fails # on any differing byte and says so without dumping the bytes. set -eu diff --git a/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/Create__Feature__HttpRequest.java.tmpl b/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/Create__Feature__HttpRequest.java.tmpl new file mode 100644 index 00000000..a44a7fe7 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/Create__Feature__HttpRequest.java.tmpl @@ -0,0 +1,12 @@ +package dev.caskeleton.adapter.inbound.web.__feature__; + +/** + * The body of {@code POST /__featurePath__}. + * + *

      No bean-validation constraint on {@code name}: the aggregate owns the rule (blank, length) and + * answers {@code __FEATURE___INVALID}. A constraint here would be a second copy of that rule that can + * drift from the first. Put a constraint here only for what the domain cannot see — the wire shape. + * + * @param name the requested name + */ +public record Create__Feature__HttpRequest(String name) {} diff --git a/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__Controller.java.tmpl b/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__Controller.java.tmpl new file mode 100644 index 00000000..376b00a7 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__Controller.java.tmpl @@ -0,0 +1,69 @@ +package dev.caskeleton.adapter.inbound.web.__feature__; + +import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; +import dev.caskeleton.application.__feature__.Create__Feature__Command; +import dev.caskeleton.application.__feature__.Create__Feature__UseCase; +import dev.caskeleton.application.__feature__.Get__Feature__Query; +import dev.caskeleton.application.__feature__.Get__Feature__UseCase; +import dev.caskeleton.application.__feature__.__Feature__View; +import dev.caskeleton.domain.__feature__.__Feature__Id; +import dev.caskeleton.shared.response.Envelope; +import java.net.URI; +import java.util.Objects; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +/** + * __Feature__ over HTTP. A transport only: it turns the request into a command or query, calls the + * use case and wraps the view in an {@link Envelope}. Who may create is the use case's {@code + * @RequiresPermission}; failures are {@code ApiErrorCarrier}s the global handler maps. + * + *

      Registered by {@code __Feature__Config} in app-bootstrap, which exists only when a {@code + * __Feature__Repository} adapter is on the classpath; not found by a component scan. + */ +@RestController +@RequestMapping("/__featurePath__") +public class __Feature__Controller { + + private final Create__Feature__UseCase create; + private final Get__Feature__UseCase get; + + /** + * A controller over the two use cases. + * + * @param create creates a __Feature__ + * @param get reads one + */ + public __Feature__Controller(Create__Feature__UseCase create, Get__Feature__UseCase get) { + this.create = Objects.requireNonNull(create, "create"); + this.get = Objects.requireNonNull(get, "get"); + } + + /** Creates one; {@code 201} with its {@code Location}. */ + @PostMapping + public ResponseEntity> create( + @RequestBody Create__Feature__HttpRequest request) { + __Feature__View created = create.handle(new Create__Feature__Command(request.name())); + URI location = + ServletUriComponentsBuilder.fromCurrentRequestUri() + .path("/{id}") + .buildAndExpand(created.id()) + .toUri(); + return ResponseEntity.created(location) + .body(Envelope.ok(__Feature__HttpResponse.from(created), ResponseMetaFactory.fromMdc())); + } + + /** Reads one; {@code 404 __FEATURE___NOT_FOUND} when none has the id. */ + @GetMapping("/{id}") + public ResponseEntity> get(@PathVariable String id) { + __Feature__View found = get.handle(new Get__Feature__Query(__Feature__Id.of(id))); + return ResponseEntity.ok( + Envelope.ok(__Feature__HttpResponse.from(found), ResponseMetaFactory.fromMdc())); + } +} diff --git a/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__HttpResponse.java.tmpl b/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__HttpResponse.java.tmpl new file mode 100644 index 00000000..d46c39db --- /dev/null +++ b/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__HttpResponse.java.tmpl @@ -0,0 +1,17 @@ +package dev.caskeleton.adapter.inbound.web.__feature__; + +import dev.caskeleton.application.__feature__.__Feature__View; + +/** + * One __Feature__ on the wire. Its own type, so a change to the application view is a decision here + * rather than a silent change of the HTTP contract. + * + * @param id the identifier + * @param name the name + */ +public record __Feature__HttpResponse(String id, String name) { + + static __Feature__HttpResponse from(__Feature__View view) { + return new __Feature__HttpResponse(view.id(), view.name()); + } +} diff --git a/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__ControllerTest.java.tmpl b/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__ControllerTest.java.tmpl new file mode 100644 index 00000000..722579ad --- /dev/null +++ b/scripts/feature-scaffold/templates/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__ControllerTest.java.tmpl @@ -0,0 +1,98 @@ +package dev.caskeleton.adapter.inbound.web.__feature__; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; +import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.application.__feature__.Create__Feature__UseCase; +import dev.caskeleton.application.__feature__.Get__Feature__UseCase; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.domain.__feature__.__Feature__; +import dev.caskeleton.domain.__feature__.__Feature__Id; +import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository; +import dev.caskeleton.domain.__feature__.testkit.Sequential__Feature__IdFactory; +import dev.caskeleton.shared.tracing.SpanErrorRecorder; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +/** + * The HTTP contract of {@code /__featurePath__} over the real use cases and the port owners' fakes. + * + *

      Standalone MockMvc: no security filter chain and no method-security proxy, so the permission + * on create is not exercised here. The composition test in app-bootstrap builds the beans the proxy + * wraps. + */ +class __Feature__ControllerTest { + + private static final __Feature__Id STORED = Sequential__Feature__IdFactory.idAt(1); + + private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository(); + private final DirectTransactionPort tx = new DirectTransactionPort(); + private final MockMvc mvc = + MockMvcBuilders.standaloneSetup( + new __Feature__Controller( + new Create__Feature__UseCase( + repository, new Sequential__Feature__IdFactory(), tx), + new Get__Feature__UseCase(repository, tx))) + .setControllerAdvice( + new GlobalExceptionHandler(SpanErrorRecorder.NOOP), new EnvelopeBodyAdvice()) + .build(); + + @Test + void aCreateAnswers201WithTheNewResourcesLocation() throws Exception { + // when + ResultActions response = create("{\"name\":\"first\"}"); + + // then + response + .andExpect(status().isCreated()) + .andExpect(header().string("Location", "http://localhost/__featurePath__/" + STORED.value())) + .andExpect(jsonPath("$.data.name").value("first")); + } + + @Test + void aBlankNameAnswers400WithTheFeaturesOwnCode() throws Exception { + // when + ResultActions response = create("{\"name\":\" \"}"); + + // then + response + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("__FEATURE___INVALID")); + } + + @Test + void aStored__Feature__IsReadWith200() throws Exception { + // given + repository.save(__Feature__.create(STORED, "first")); + + // when + ResultActions response = mvc.perform(get("/__featurePath__/" + STORED.value())); + + // then + response.andExpect(status().isOk()).andExpect(jsonPath("$.data.name").value("first")); + } + + @Test + void anUnknownIdAnswers404WithTheFeaturesOwnCode() throws Exception { + // when + ResultActions response = mvc.perform(get("/__featurePath__/" + STORED.value())); + + // then + response + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error.code").value("__FEATURE___NOT_FOUND")); + } + + private ResultActions create(String body) throws Exception { + return mvc.perform( + post("/__featurePath__").contentType(MediaType.APPLICATION_JSON).content(body)); + } +} diff --git a/scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactory.java.tmpl b/scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactory.java.tmpl new file mode 100644 index 00000000..e19f4f53 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactory.java.tmpl @@ -0,0 +1,20 @@ +package dev.caskeleton.adapter.outbound.identifier.__feature__; + +import dev.caskeleton.domain.__feature__.__Feature__Id; +import dev.caskeleton.domain.__feature__.__Feature__IdFactory; +import java.util.UUID; + +/** + * Mints {@link __Feature__Id}s as random (version 4) UUIDs from the JDK's secure generator. + * + *

      Random UUIDs scatter inserts across a B-tree primary key. When __Feature__ rows are written + * often, switch to a time-ordered UUIDv7 as the sample's {@code UuidWorkLogIdFactory} does; the + * domain contract (canonical UUID text) does not change. + */ +public final class Uuid__Feature__IdFactory implements __Feature__IdFactory { + + @Override + public __Feature__Id newId() { + return __Feature__Id.of(UUID.randomUUID().toString()); + } +} diff --git a/scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactoryTest.java.tmpl b/scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactoryTest.java.tmpl new file mode 100644 index 00000000..9be70cee --- /dev/null +++ b/scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactoryTest.java.tmpl @@ -0,0 +1,24 @@ +package dev.caskeleton.adapter.outbound.identifier.__feature__; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.domain.__feature__.__Feature__Id; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; + +class Uuid__Feature__IdFactoryTest { + + private final Uuid__Feature__IdFactory factory = new Uuid__Feature__IdFactory(); + + @Test + void aThousandMintedIdsAreAllDifferent() { + // when + Set<__Feature__Id> ids = + IntStream.range(0, 1000).mapToObj(i -> factory.newId()).collect(Collectors.toSet()); + + // then + assertThat(ids).hasSize(1000); + } +} diff --git a/scripts/feature-scaffold/templates/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__Config.java.tmpl b/scripts/feature-scaffold/templates/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__Config.java.tmpl new file mode 100644 index 00000000..4cc9b7c7 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__Config.java.tmpl @@ -0,0 +1,56 @@ +package dev.caskeleton.bootstrap.autoconfigure.__feature__; + +import dev.caskeleton.adapter.inbound.web.__feature__.__Feature__Controller; +import dev.caskeleton.adapter.outbound.identifier.__feature__.Uuid__Feature__IdFactory; +import dev.caskeleton.application.__feature__.Create__Feature__UseCase; +import dev.caskeleton.application.__feature__.Get__Feature__UseCase; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.domain.__feature__.__Feature__IdFactory; +import dev.caskeleton.domain.__feature__.__Feature__Repository; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; + +/** + * __Feature__: its use cases and its HTTP endpoints. + * + *

      Turns itself on from what is on the classpath: a {@link __Feature__Repository} adapter and a + * {@link TransactionPort}. Until a repository adapter exists the feature is absent rather than half + * present (docs/manual/02-new-feature.md step 5). When the adapter comes from another + * auto-configuration, name it in {@code afterName} so this condition sees its bean. + * + *

      The use cases are beans, not objects the controller builds, because the method security + * advisor proxies beans: {@code @RequiresPermission} on create is enforced by that proxy. Grant + * {@code __feature_kebab__:create} to a role under {@code app.authz.role-permissions}; until then + * every create is refused (docs/manual/07-authorization.md). + */ +@AutoConfiguration +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) +@ConditionalOnBean({__Feature__Repository.class, TransactionPort.class}) +@Import(__Feature__Controller.class) +public class __Feature__Config { + + /** Server-assigned ids, unless the application supplies its own factory. */ + @Bean + @ConditionalOnMissingBean(__Feature__IdFactory.class) + public __Feature__IdFactory __featureCamel__IdFactory() { + return new Uuid__Feature__IdFactory(); + } + + /** Creates a __Feature__. */ + @Bean + public Create__Feature__UseCase create__Feature__UseCase( + __Feature__Repository repository, __Feature__IdFactory ids, TransactionPort transactions) { + return new Create__Feature__UseCase(repository, ids, transactions); + } + + /** Reads one __Feature__. */ + @Bean + public Get__Feature__UseCase get__Feature__UseCase( + __Feature__Repository repository, TransactionPort transactions) { + return new Get__Feature__UseCase(repository, transactions); + } +} diff --git a/scripts/feature-scaffold/templates/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__ConfigTest.java.tmpl b/scripts/feature-scaffold/templates/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__ConfigTest.java.tmpl new file mode 100644 index 00000000..a398cf5f --- /dev/null +++ b/scripts/feature-scaffold/templates/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__ConfigTest.java.tmpl @@ -0,0 +1,52 @@ +package dev.caskeleton.bootstrap.autoconfigure.__feature__; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.web.__feature__.__Feature__Controller; +import dev.caskeleton.application.__feature__.Create__Feature__UseCase; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.domain.__feature__.__Feature__Repository; +import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.context.annotation.ImportCandidates; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; + +class __Feature__ConfigTest { + + private final WebApplicationContextRunner runner = + new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(__Feature__Config.class)); + + @Test + void bootDiscoversTheConfigurationThroughItsAutoConfigurationImports() { + // when + List candidates = + ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader()).getCandidates(); + + // then + assertThat(candidates).contains(__Feature__Config.class.getName()); + } + + @Test + void withoutARepositoryAdapterTheFeatureIsAbsent() { + runner + .withBean(TransactionPort.class, DirectTransactionPort::new) + .run(context -> assertThat(context).doesNotHaveBean(__Feature__Controller.class)); + } + + @Test + void withARepositoryAdapterTheUseCasesAndTheControllerAreBeans() { + runner + .withBean(TransactionPort.class, DirectTransactionPort::new) + .withBean(__Feature__Repository.class, InMemory__Feature__Repository::new) + .run( + context -> + assertThat(context) + .hasSingleBean(Create__Feature__UseCase.class) + .hasSingleBean(__Feature__Controller.class)); + } +} diff --git a/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__Command.java.tmpl b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__Command.java.tmpl new file mode 100644 index 00000000..33f19cf9 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__Command.java.tmpl @@ -0,0 +1,10 @@ +package dev.caskeleton.application.__feature__; + +import dev.caskeleton.application.command.Command; + +/** + * The intent to create a __Feature__. Carries plain values; the aggregate checks them. + * + * @param name the requested name + */ +public record Create__Feature__Command(String name) implements Command {} diff --git a/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__UseCase.java.tmpl b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__UseCase.java.tmpl new file mode 100644 index 00000000..47c1092c --- /dev/null +++ b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__UseCase.java.tmpl @@ -0,0 +1,63 @@ +package dev.caskeleton.application.__feature__; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.usecase.CommandUseCase; +import dev.caskeleton.domain.__feature__.__Feature__; +import dev.caskeleton.domain.__feature__.__Feature__IdFactory; +import dev.caskeleton.domain.__feature__.__Feature__InvariantException; +import dev.caskeleton.domain.__feature__.__Feature__Repository; + +/** + * Creates a __Feature__ under a server-minted id. + * + *

      Not {@code final} and built as a bean: {@code @RequiresPermission} is enforced by the method + * security proxy around the bean, and a class that cannot be proxied fails the boot + * ({@code RequiresPermissionProxyabilityTest}). {@code NOT_IDEMPOTENT}: a retried request creates a + * second __Feature__. Make it {@code KEYED} with {@code IdempotencyExecutor} when a client may + * resend (docs/manual/05-idempotency.md). + */ +@RequiresPermission("__feature_kebab__:create") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.NOT_IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) +public class Create__Feature__UseCase + implements CommandUseCase { + + private final __Feature__Repository repository; + private final __Feature__IdFactory ids; + private final TransactionPort tx; + + /** + * A use case over its ports. + * + * @param repository where the aggregate is stored + * @param ids mints the new id + * @param tx the transaction boundary + */ + public Create__Feature__UseCase( + __Feature__Repository repository, __Feature__IdFactory ids, TransactionPort tx) { + this.repository = repository; + this.ids = ids; + this.tx = tx; + } + + @Override + public __Feature__View handle(Create__Feature__Command command) { + __Feature__ created = build(command); + return tx.inWrite(() -> __Feature__View.from(repository.save(created))); + } + + private __Feature__ build(Create__Feature__Command command) { + try { + return __Feature__.create(ids.newId(), command.name()); + } catch (__Feature__InvariantException invalid) { + throw new __Feature__RejectedException(invalid); + } + } +} diff --git a/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Get__Feature__Query.java.tmpl b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Get__Feature__Query.java.tmpl new file mode 100644 index 00000000..21512b11 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Get__Feature__Query.java.tmpl @@ -0,0 +1,17 @@ +package dev.caskeleton.application.__feature__; + +import dev.caskeleton.application.query.Query; +import dev.caskeleton.domain.__feature__.__Feature__Id; +import java.util.Objects; + +/** + * The intent to read one __Feature__. + * + * @param id the identifier to read + */ +public record Get__Feature__Query(__Feature__Id id) implements Query { + + public Get__Feature__Query { + Objects.requireNonNull(id, "id"); + } +} diff --git a/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Get__Feature__UseCase.java.tmpl b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Get__Feature__UseCase.java.tmpl new file mode 100644 index 00000000..c12ce872 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Get__Feature__UseCase.java.tmpl @@ -0,0 +1,45 @@ +package dev.caskeleton.application.__feature__; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.usecase.QueryUseCase; +import dev.caskeleton.domain.__feature__.__Feature__Repository; + +/** + * Reads one __Feature__. A read needs no {@code @RequiresPermission}; add one, or an object access + * check, when not every authenticated caller may see every __Feature__ + * (docs/manual/07-authorization.md). + */ +@UseCaseCapability( + transactionMode = TransactionMode.READ_ONLY, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.READ_REPOSITORY) +public class Get__Feature__UseCase implements QueryUseCase { + + private final __Feature__Repository repository; + private final TransactionPort tx; + + /** + * A use case over its ports. + * + * @param repository where the aggregate is read from + * @param tx the transaction boundary + */ + public Get__Feature__UseCase(__Feature__Repository repository, TransactionPort tx) { + this.repository = repository; + this.tx = tx; + } + + @Override + public __Feature__View handle(Get__Feature__Query query) { + return tx.inRead( + () -> + repository + .findById(query.id()) + .map(__Feature__View::from) + .orElseThrow(() -> new __Feature__NotFoundException(query.id()))); + } +} diff --git a/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__ErrorCode.java.tmpl b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__ErrorCode.java.tmpl new file mode 100644 index 00000000..c3a9d56d --- /dev/null +++ b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__ErrorCode.java.tmpl @@ -0,0 +1,42 @@ +package dev.caskeleton.application.__feature__; + +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.Category; + +/** + * The client-facing failures of the __Feature__ use cases. Every transport maps them through {@code + * ApiErrorCarrier}; no handler names this feature. A service records its own codes in its own + * registry, not in docs/registries/error-codes.yaml (docs/manual/06-errors.md). + */ +public enum __Feature__ErrorCode implements ApiErrorCode { + __FEATURE___NOT_FOUND(Category.NOT_FOUND, 404), + __FEATURE___INVALID(Category.VALIDATION, 400); + + private final Category category; + private final int httpStatus; + + __Feature__ErrorCode(Category category, int httpStatus) { + this.category = category; + this.httpStatus = httpStatus; + } + + @Override + public String code() { + return name(); + } + + @Override + public Category category() { + return category; + } + + @Override + public int httpStatus() { + return httpStatus; + } + + @Override + public boolean retryable() { + return false; + } +} diff --git a/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__NotFoundException.java.tmpl b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__NotFoundException.java.tmpl new file mode 100644 index 00000000..4622554e --- /dev/null +++ b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__NotFoundException.java.tmpl @@ -0,0 +1,25 @@ +package dev.caskeleton.application.__feature__; + +import dev.caskeleton.domain.__feature__.__Feature__Id; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + +/** No __Feature__ has the requested id. A client error: {@code __FEATURE___NOT_FOUND}, 404. */ +public class __Feature__NotFoundException extends RuntimeException implements ApiErrorCarrier { + + private static final long serialVersionUID = 1L; + + /** + * The failure for one id. + * + * @param id the id that was not found + */ + public __Feature__NotFoundException(__Feature__Id id) { + super("__Feature__ not found: " + id.value()); + } + + @Override + public ApiErrorCode errorCode() { + return __Feature__ErrorCode.__FEATURE___NOT_FOUND; + } +} diff --git a/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__RejectedException.java.tmpl b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__RejectedException.java.tmpl new file mode 100644 index 00000000..1f828b1e --- /dev/null +++ b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__RejectedException.java.tmpl @@ -0,0 +1,29 @@ +package dev.caskeleton.application.__feature__; + +import dev.caskeleton.domain.__feature__.__Feature__InvariantException; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + +/** + * The request asked for a __Feature__ that breaks an invariant. A client error: {@code + * __FEATURE___INVALID}, 400. The domain exception stays the cause, so its {@code reason()} reaches + * the logs; only the code reaches the client. + */ +public class __Feature__RejectedException extends RuntimeException implements ApiErrorCarrier { + + private static final long serialVersionUID = 1L; + + /** + * Wraps the broken invariant. + * + * @param cause the domain failure + */ + public __Feature__RejectedException(__Feature__InvariantException cause) { + super("__Feature__ rejected: " + cause.reason(), cause); + } + + @Override + public ApiErrorCode errorCode() { + return __Feature__ErrorCode.__FEATURE___INVALID; + } +} diff --git a/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__View.java.tmpl b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__View.java.tmpl new file mode 100644 index 00000000..99966954 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__View.java.tmpl @@ -0,0 +1,17 @@ +package dev.caskeleton.application.__feature__; + +import dev.caskeleton.domain.__feature__.__Feature__; + +/** + * What a use case hands back about one __Feature__. An application type, so a transport never + * receives the aggregate itself. + * + * @param id the identifier text + * @param name the name + */ +public record __Feature__View(String id, String name) { + + static __Feature__View from(__Feature__ aggregate) { + return new __Feature__View(aggregate.id().value(), aggregate.name()); + } +} diff --git a/scripts/feature-scaffold/templates/src/application-core/src/test/java/dev/caskeleton/application/__feature__/Create__Feature__UseCaseTest.java.tmpl b/scripts/feature-scaffold/templates/src/application-core/src/test/java/dev/caskeleton/application/__feature__/Create__Feature__UseCaseTest.java.tmpl new file mode 100644 index 00000000..e46ecf4e --- /dev/null +++ b/scripts/feature-scaffold/templates/src/application-core/src/test/java/dev/caskeleton/application/__feature__/Create__Feature__UseCaseTest.java.tmpl @@ -0,0 +1,47 @@ +package dev.caskeleton.application.__feature__; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository; +import dev.caskeleton.domain.__feature__.testkit.Sequential__Feature__IdFactory; +import org.junit.jupiter.api.Test; + +class Create__Feature__UseCaseTest { + + private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository(); + private final DirectTransactionPort tx = new DirectTransactionPort(); + private final Create__Feature__UseCase useCase = + new Create__Feature__UseCase(repository, new Sequential__Feature__IdFactory(), tx); + + @Test + void aCreated__Feature__IsStoredUnderTheMintedId() { + // when + useCase.handle(new Create__Feature__Command("first")); + + // then + assertThat(repository.findById(Sequential__Feature__IdFactory.idAt(1)).map(found -> found.name())) + .contains("first"); + } + + @Test + void theCreateCommitsOneWriteTransaction() { + // when + useCase.handle(new Create__Feature__Command("first")); + + // then + assertThat(tx.committed()).containsExactly(DirectTransactionPort.Boundary.WRITE); + } + + @Test + void aBlankNameIsRejectedWithTheFeaturesInvalidCode() { + // when + Throwable thrown = catchThrowable(() -> useCase.handle(new Create__Feature__Command(" "))); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + __Feature__RejectedException.class, failure -> assertThat(failure.errorCode()).isEqualTo(__Feature__ErrorCode.__FEATURE___INVALID)); + } +} diff --git a/scripts/feature-scaffold/templates/src/application-core/src/test/java/dev/caskeleton/application/__feature__/Get__Feature__UseCaseTest.java.tmpl b/scripts/feature-scaffold/templates/src/application-core/src/test/java/dev/caskeleton/application/__feature__/Get__Feature__UseCaseTest.java.tmpl new file mode 100644 index 00000000..360cac9f --- /dev/null +++ b/scripts/feature-scaffold/templates/src/application-core/src/test/java/dev/caskeleton/application/__feature__/Get__Feature__UseCaseTest.java.tmpl @@ -0,0 +1,43 @@ +package dev.caskeleton.application.__feature__; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.domain.__feature__.__Feature__; +import dev.caskeleton.domain.__feature__.__Feature__Id; +import dev.caskeleton.domain.__feature__.testkit.InMemory__Feature__Repository; +import dev.caskeleton.domain.__feature__.testkit.Sequential__Feature__IdFactory; +import org.junit.jupiter.api.Test; + +class Get__Feature__UseCaseTest { + + private static final __Feature__Id STORED = Sequential__Feature__IdFactory.idAt(1); + + private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository(); + private final Get__Feature__UseCase useCase = + new Get__Feature__UseCase(repository, new DirectTransactionPort()); + + @Test + void aStored__Feature__IsReadAsItsView() { + // given + repository.save(__Feature__.create(STORED, "first")); + + // when + __Feature__View view = useCase.handle(new Get__Feature__Query(STORED)); + + // then + assertThat(view).isEqualTo(new __Feature__View(STORED.value(), "first")); + } + + @Test + void anIdNothingIsStoredUnderIsNotFound() { + // when + Throwable thrown = catchThrowable(() -> useCase.handle(new Get__Feature__Query(STORED))); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + __Feature__NotFoundException.class, failure -> assertThat(failure.errorCode()).isEqualTo(__Feature__ErrorCode.__FEATURE___NOT_FOUND)); + } +} diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl new file mode 100644 index 00000000..b0472666 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl @@ -0,0 +1,68 @@ +package dev.caskeleton.domain.__feature__; + +import dev.caskeleton.domain.stereotype.AggregateRoot; +import java.util.Objects; + +/** + * The __Feature__ aggregate root: the only way its state changes. + * + *

      Generated by {@code scripts/new-feature.sh} with one placeholder field, {@code name}. Replace it + * with the feature's real state and keep each invariant in this class: a rule that must always hold + * for one __Feature__ belongs here, not in a use case or a mapper (docs/manual/02-new-feature.md). + */ +@AggregateRoot +public final class __Feature__ { + + /** The longest name a __Feature__ accepts; the database column is sized to it. */ + public static final int NAME_MAX_LENGTH = 100; + + private final __Feature__Id id; + private final String name; + + private __Feature__(__Feature__Id id, String name) { + this.id = Objects.requireNonNull(id, "id"); + this.name = requireValidName(name); + } + + /** + * A new __Feature__. + * + * @param id the server-assigned identifier + * @param name the name; not blank, at most {@link #NAME_MAX_LENGTH} characters + * @return the new aggregate + * @throws __Feature__InvariantException when the name breaks an invariant + */ + public static __Feature__ create(__Feature__Id id, String name) { + return new __Feature__(id, name); + } + + /** + * A __Feature__ read back from storage. The same invariants hold: stored state that breaks them + * is a defect, and it fails here rather than later. + * + * @param id the stored identifier + * @param name the stored name + * @return the aggregate + */ + public static __Feature__ restore(__Feature__Id id, String name) { + return new __Feature__(id, name); + } + + public __Feature__Id id() { + return id; + } + + public String name() { + return name; + } + + private static String requireValidName(String name) { + if (name == null || name.isBlank()) { + throw new __Feature__InvariantException(__Feature__InvariantException.Reason.NAME_BLANK); + } + if (name.length() > NAME_MAX_LENGTH) { + throw new __Feature__InvariantException(__Feature__InvariantException.Reason.NAME_TOO_LONG); + } + return name; + } +} diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__Id.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__Id.java.tmpl new file mode 100644 index 00000000..e9fef678 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__Id.java.tmpl @@ -0,0 +1,38 @@ +package dev.caskeleton.domain.__feature__; + +import dev.caskeleton.domain.identifier.ResourceId; +import dev.caskeleton.domain.stereotype.ValueObject; +import java.util.regex.Pattern; + +/** + * Identifier of a {@link __Feature__}: the canonical 36-character UUID text. The grammar is checked + * here, at construction, so every layer that holds a __Feature__Id holds a valid one. + */ +@ValueObject +public record __Feature__Id(String value) implements ResourceId<__Feature__Id> { + + private static final Pattern CANONICAL_UUID = + Pattern.compile( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); + + /** + * Checks the grammar. + * + * @throws IllegalArgumentException when {@code value} is not canonical UUID text + */ + public __Feature__Id { + if (value == null || !CANONICAL_UUID.matcher(value).matches()) { + throw new IllegalArgumentException("invalid __Feature__Id: " + value); + } + } + + /** + * Parses identifier text. + * + * @param value canonical UUID text + * @return the identifier + */ + public static __Feature__Id of(String value) { + return new __Feature__Id(value); + } +} diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__IdFactory.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__IdFactory.java.tmpl new file mode 100644 index 00000000..786b8038 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__IdFactory.java.tmpl @@ -0,0 +1,9 @@ +package dev.caskeleton.domain.__feature__; + +import dev.caskeleton.domain.identifier.IdFactory; + +/** + * Mints new {@link __Feature__Id}s. The domain owns the contract; an outbound adapter ({@code + * adapter:outbound:identifier}) generates the value, and the create use case calls it. + */ +public interface __Feature__IdFactory extends IdFactory<__Feature__Id> {} diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__InvariantException.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__InvariantException.java.tmpl new file mode 100644 index 00000000..f1ef9e33 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__InvariantException.java.tmpl @@ -0,0 +1,33 @@ +package dev.caskeleton.domain.__feature__; + +/** + * A {@link __Feature__} invariant was broken. Carries a {@link Reason} and nothing about error + * codes or HTTP: the application turns it into a client error ({@code + * Create__Feature__UseCase}), because domain-core cannot see shared-contract. + */ +public final class __Feature__InvariantException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** Which invariant was broken. Safe to show a client. */ + public enum Reason { + NAME_BLANK, + NAME_TOO_LONG + } + + private final Reason reason; + + /** + * An invariant failure. + * + * @param reason which invariant was broken + */ + public __Feature__InvariantException(Reason reason) { + super("__Feature__ invariant violated: " + reason); + this.reason = reason; + } + + public Reason reason() { + return reason; + } +} diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__Repository.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__Repository.java.tmpl new file mode 100644 index 00000000..006b9e59 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__Repository.java.tmpl @@ -0,0 +1,30 @@ +package dev.caskeleton.domain.__feature__; + +import java.util.Optional; + +/** + * Stores and loads {@link __Feature__} aggregates, one whole aggregate at a time. + * + *

      Domain-owned because it speaks only in aggregates. A read whose shape differs from the + * aggregate is a separate application {@code *QueryPort} returning a projection + * (docs/manual/02-new-feature.md, decision "저장 포트 소유자"). Every implementation passes {@code + * __Feature__RepositoryContract} in this module's test fixtures. + */ +public interface __Feature__Repository { + + /** + * Saves the aggregate, inserting it or replacing the stored state with the same id. + * + * @param aggregate the aggregate to store + * @return the stored aggregate as the store now holds it + */ + __Feature__ save(__Feature__ aggregate); + + /** + * Loads one aggregate. + * + * @param id the identifier + * @return the aggregate, or empty when none has that id + */ + Optional<__Feature__> findById(__Feature__Id id); +} diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/__Feature__IdTest.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/__Feature__IdTest.java.tmpl new file mode 100644 index 00000000..2a357770 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/__Feature__IdTest.java.tmpl @@ -0,0 +1,31 @@ +package dev.caskeleton.domain.__feature__; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +class __Feature__IdTest { + + @Test + void canonicalUuidTextIsAccepted() { + assertThat(__Feature__Id.of("0190a3c4-7b2e-7d4f-9a1b-2c3d4e5f6a7b").value()) + .isEqualTo("0190a3c4-7b2e-7d4f-9a1b-2c3d4e5f6a7b"); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {"not-a-uuid", "0190a3c47b2e7d4f9a1b2c3d4e5f6a7b", "1"}) + void textThatIsNotCanonicalUuidIsRejected(String value) { + // when + Throwable thrown = catchThrowable(() -> __Feature__Id.of(value)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("invalid __Feature__Id"); + } +} diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/__Feature__Test.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/__Feature__Test.java.tmpl new file mode 100644 index 00000000..3b7acafe --- /dev/null +++ b/scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/__Feature__Test.java.tmpl @@ -0,0 +1,53 @@ +package dev.caskeleton.domain.__feature__; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +class __Feature__Test { + + private static final __Feature__Id ID = + __Feature__Id.of("00000000-0000-7000-8000-000000000001"); + + @Test + void aCreated__Feature__KeepsItsIdAndName() { + // when + __Feature__ created = __Feature__.create(ID, "first"); + + // then + assertThat(created).extracting(__Feature__::id, __Feature__::name).containsExactly(ID, "first"); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {" ", "\t"}) + void aBlankNameIsRejected(String name) { + // when + Throwable thrown = catchThrowable(() -> __Feature__.create(ID, name)); + + // then + assertThat(thrown) + .isInstanceOf(__Feature__InvariantException.class) + .hasFieldOrPropertyWithValue("reason", __Feature__InvariantException.Reason.NAME_BLANK); + } + + @Test + @DisplayName("이름이 NAME_MAX_LENGTH + 1자이면 거절한다") + void aNameLongerThanTheLimitIsRejected() { + // given + String name = "x".repeat(__Feature__.NAME_MAX_LENGTH + 1); + + // when + Throwable thrown = catchThrowable(() -> __Feature__.create(ID, name)); + + // then + assertThat(thrown) + .isInstanceOf(__Feature__InvariantException.class) + .hasFieldOrPropertyWithValue("reason", __Feature__InvariantException.Reason.NAME_TOO_LONG); + } +} diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/testkit/InMemory__Feature__RepositoryContractTest.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/testkit/InMemory__Feature__RepositoryContractTest.java.tmpl new file mode 100644 index 00000000..97724f1b --- /dev/null +++ b/scripts/feature-scaffold/templates/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/testkit/InMemory__Feature__RepositoryContractTest.java.tmpl @@ -0,0 +1,13 @@ +package dev.caskeleton.domain.__feature__.testkit; + +import dev.caskeleton.domain.__feature__.__Feature__Repository; + +class InMemory__Feature__RepositoryContractTest extends __Feature__RepositoryContract { + + private final InMemory__Feature__Repository repository = new InMemory__Feature__Repository(); + + @Override + protected __Feature__Repository repository() { + return repository; + } +} diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/InMemory__Feature__Repository.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/InMemory__Feature__Repository.java.tmpl new file mode 100644 index 00000000..61342a0e --- /dev/null +++ b/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/InMemory__Feature__Repository.java.tmpl @@ -0,0 +1,29 @@ +package dev.caskeleton.domain.__feature__.testkit; + +import dev.caskeleton.domain.__feature__.__Feature__; +import dev.caskeleton.domain.__feature__.__Feature__Id; +import dev.caskeleton.domain.__feature__.__Feature__Repository; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; + +/** + * The one fake of {@link __Feature__Repository}, held to the same promises as every real adapter by + * {@link __Feature__RepositoryContract}. Not thread-safe: a use case test is single-threaded. + */ +public final class InMemory__Feature__Repository implements __Feature__Repository { + + private final Map<__Feature__Id, __Feature__> rows = new LinkedHashMap<>(); + + @Override + public __Feature__ save(__Feature__ aggregate) { + __Feature__ stored = __Feature__.restore(aggregate.id(), aggregate.name()); + rows.put(stored.id(), stored); + return __Feature__.restore(stored.id(), stored.name()); + } + + @Override + public Optional<__Feature__> findById(__Feature__Id id) { + return Optional.ofNullable(rows.get(id)).map(row -> __Feature__.restore(row.id(), row.name())); + } +} diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/Sequential__Feature__IdFactory.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/Sequential__Feature__IdFactory.java.tmpl new file mode 100644 index 00000000..26f1a8aa --- /dev/null +++ b/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/Sequential__Feature__IdFactory.java.tmpl @@ -0,0 +1,29 @@ +package dev.caskeleton.domain.__feature__.testkit; + +import dev.caskeleton.domain.__feature__.__Feature__Id; +import dev.caskeleton.domain.__feature__.__Feature__IdFactory; +import java.util.concurrent.atomic.AtomicLong; + +/** + * The one fake of {@link __Feature__IdFactory}: predictable ids, so a test can name the id a create + * will mint ({@link #idAt(long)}). + */ +public final class Sequential__Feature__IdFactory implements __Feature__IdFactory { + + private final AtomicLong next = new AtomicLong(1); + + /** + * The id this factory mints on its {@code n}th call, counting from 1. + * + * @param n the call number + * @return that id + */ + public static __Feature__Id idAt(long n) { + return __Feature__Id.of(String.format("00000000-0000-7000-8000-%012d", n)); + } + + @Override + public __Feature__Id newId() { + return idAt(next.getAndIncrement()); + } +} diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/__Feature__RepositoryContract.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/__Feature__RepositoryContract.java.tmpl new file mode 100644 index 00000000..cbab07f8 --- /dev/null +++ b/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/__Feature__RepositoryContract.java.tmpl @@ -0,0 +1,56 @@ +package dev.caskeleton.domain.__feature__.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.domain.__feature__.__Feature__; +import dev.caskeleton.domain.__feature__.__Feature__Id; +import dev.caskeleton.domain.__feature__.__Feature__Repository; +import java.util.Optional; +import org.junit.jupiter.api.Test; + +/** + * What every {@link __Feature__Repository} promises. {@link InMemory__Feature__Repository} extends + * it in domain-core's tests; a real adapter extends it in a lane that runs against its real store + * (docs/manual/04-persistence.md). Add a test here before adding a repository method. + */ +public abstract class __Feature__RepositoryContract { + + private static final __Feature__Id FIRST = Sequential__Feature__IdFactory.idAt(1); + private static final __Feature__Id UNKNOWN = Sequential__Feature__IdFactory.idAt(99); + + /** + * The repository under test, empty at the start of each test. + * + * @return the repository + */ + protected abstract __Feature__Repository repository(); + + @Test + void aSaved__Feature__IsFoundByItsId() { + // given + repository().save(__Feature__.create(FIRST, "first")); + + // when + Optional<__Feature__> found = repository().findById(FIRST); + + // then + assertThat(found.map(__Feature__::name)).contains("first"); + } + + @Test + void anIdNothingWasSavedUnderIsNotFound() { + assertThat(repository().findById(UNKNOWN)).isEmpty(); + } + + @Test + void savingTheSameIdAgainReplacesTheStoredState() { + // given + repository().save(__Feature__.create(FIRST, "first")); + + // when + repository().save(__Feature__.restore(FIRST, "renamed")); + + // then + assertThat(repository().findById(FIRST).map(__Feature__::name)).contains("renamed"); + } +} diff --git a/scripts/new-feature.sh b/scripts/new-feature.sh new file mode 100755 index 00000000..c5655cff --- /dev/null +++ b/scripts/new-feature.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# 새 업무 기능의 뼈대를 계층 leaf에 만든다. +# +# scripts/new-feature.sh [--path ] [--no-format] +# +# 예: scripts/new-feature.sh Invoice -> /invoices +# scripts/new-feature.sh PurchaseOrder -> /purchaseOrders +# scripts/new-feature.sh Person --path people -> /people +# +# 만드는 것(배치·이름 근거는 docs/manual/03-placement.md, 단계는 02-new-feature.md): +# domain-core dev.caskeleton.domain. aggregate·id·IdFactory·Repository·불변식 예외 +# testFixtures ...//testkit 포트당 fake 하나 + 공유 계약(XxxRepositoryContract) +# application-core dev.caskeleton.application. Create/Get 유스케이스·command·query·view·오류 코드 +# outbound:identifier dev.caskeleton.adapter.outbound.identifier. UuidIdFactory +# inbound:web dev.caskeleton.adapter.inbound.web. 컨트롤러·요청/응답 DTO +# app-bootstrap dev.caskeleton.bootstrap.autoconfigure. Config + AutoConfiguration.imports 한 줄 +# 그리고 각 leaf의 테스트. +# +# 만들지 않는 것: 저장 adapter(JPA 엔티티·마이그레이션). 고를 저장소와 번호대가 서비스마다 달라 +# 사람이 정한다(docs/manual/04-persistence.md). 그 adapter가 생기기 전까지 Config는 꺼져 있다. +# +# 생성 뒤 그대로 통과해야 하는 검사(scripts/verify-feature-scaffold.sh가 왕복으로 고정한다): +# ./gradlew :domain-core:check :application-core:check :adapter:outbound:identifier:check \ +# :adapter:inbound:web:check :app-bootstrap:check architectureCheck +set -euo pipefail + +usage() { + sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//' + exit 2 +} + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +templates="$repo_root/scripts/feature-scaffold/templates" + +name="" +path_segment="" +format=1 +while [ $# -gt 0 ]; do + case "$1" in + --path) path_segment="${2:-}"; shift 2 ;; + --no-format) format=0; shift ;; + -h|--help) usage ;; + -*) echo "알 수 없는 옵션: $1" >&2; usage ;; + *) [ -z "$name" ] || usage; name="$1"; shift ;; + esac +done +[ -n "$name" ] || usage + +# --- 이름 검사 ----------------------------------------------------------------------------- +if ! [[ "$name" =~ ^[A-Z][a-z0-9]+([A-Z][a-z0-9]+)*$ ]]; then + echo "기능 이름은 PascalCase여야 한다(예: Invoice, PurchaseOrder): $name" >&2 + exit 2 +fi +package_name="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')" +camel="$(printf '%s' "${name:0:1}" | tr '[:upper:]' '[:lower:]')${name:1}" +upper_snake="$(printf '%s' "$name" | sed -E 's/([a-z0-9])([A-Z])/\1_\2/g' | tr '[:lower:]' '[:upper:]')" +kebab="$(printf '%s' "$name" | sed -E 's/([a-z0-9])([A-Z])/\1-\2/g' | tr '[:upper:]' '[:lower:]')" +if [ -z "$path_segment" ]; then + case "$camel" in + *s|*x|*ch|*sh) path_segment="${camel}es" ;; + *[!aeiou]y) path_segment="${camel%y}ies" ;; + *) path_segment="${camel}s" ;; + esac +fi +# AIP-122: 경로 조각은 소문자로 시작하는 영숫자(ForbiddenApiArchitectureTest.CONTROLLER_REQUEST_MAPPINGS_FOLLOW_AIP122). +if ! [[ "$path_segment" =~ ^[a-z][a-zA-Z0-9]*$ ]]; then + echo "--path는 AIP-122 모양([a-z][a-zA-Z0-9]*)이어야 한다: $path_segment" >&2 + exit 2 +fi + +# Java 예약어와 플랫폼 패키지 이름은 패키지로 쓸 수 없거나 템플릿 코드와 섞인다. +reserved=" abstract assert boolean break byte case catch char class const continue default do + double else enum extends final finally float for goto if implements import instanceof int + interface long native new package private protected public return short static strictfp super + switch synchronized this throw throws transient try void volatile while record sealed permits + var yield + capability command query usecase transaction security tenant operation outbox idempotency lease + lock cache messaging observability outbound realtime identifier stereotype notification + fileserver objectstorage auth authz error envelope mvc " +reserved=" $(printf '%s' "$reserved" | tr -s ' \n' ' ') " +if [[ "$reserved" == *" $package_name "* ]]; then + echo "'$package_name'는 Java 예약어이거나 템플릿 플랫폼 패키지 이름이다. 다른 이름을 고른다." >&2 + exit 2 +fi + +# --- 대상 경로 ----------------------------------------------------------------------------- +substitute() { + sed -e "s/__Feature__/$name/g" \ + -e "s/__featureCamel__/$camel/g" \ + -e "s/__feature_kebab__/$kebab/g" \ + -e "s/__featurePath__/$path_segment/g" \ + -e "s/__FEATURE__/$upper_snake/g" \ + -e "s/__feature__/$package_name/g" +} + +mapfile -t sources < <(cd "$templates" && find . -type f -name '*.tmpl' | sort) +[ "${#sources[@]}" -gt 0 ] || { echo "템플릿이 없다: $templates" >&2; exit 1; } + +targets=() +for source in "${sources[@]}"; do + relative="${source#./}" + target="$(printf '%s' "${relative%.tmpl}" | substitute)" + if [ -e "$repo_root/$target" ]; then + echo "이미 있다(덮어쓰지 않는다): $target" >&2 + exit 1 + fi + targets+=("$target") +done +for package_dir in \ + "src/domain-core/src/main/java/dev/caskeleton/domain/$package_name" \ + "src/application-core/src/main/java/dev/caskeleton/application/$package_name" \ + "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/$package_name"; do + if [ -d "$repo_root/$package_dir" ]; then + echo "패키지가 이미 있다: $package_dir" >&2 + exit 1 + fi +done + +imports="$repo_root/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports" +config_class="dev.caskeleton.bootstrap.autoconfigure.$package_name.${name}Config" +[ -f "$imports" ] || { echo "없다: $imports" >&2; exit 1; } + +# --- 생성 ---------------------------------------------------------------------------------- +for i in "${!sources[@]}"; do + mkdir -p "$(dirname "$repo_root/${targets[$i]}")" + substitute < "$templates/${sources[$i]#./}" > "$repo_root/${targets[$i]}" + echo "생성 ${targets[$i]}" +done +# 파일 끝 줄바꿈이 없으면 붙이고 한 줄을 더한다. +[ -z "$(tail -c1 "$imports")" ] || printf '\n' >> "$imports" +printf '%s\n' "$config_class" >> "$imports" +echo "추가 ${imports#"$repo_root/"}: $config_class" + +leaves=(:domain-core :application-core :adapter:outbound:identifier :adapter:inbound:web :app-bootstrap) + +# google-java-format은 Javadoc 줄바꿈을 이름 길이에 따라 다시 맞춘다. 템플릿만으로는 모든 이름에서 +# spotlessCheck를 통과시킬 수 없어 생성 직후 한 번 적용한다. +if [ "$format" -eq 1 ]; then + spotless=() + for leaf in "${leaves[@]}"; do spotless+=("$leaf:spotlessApply"); done + (cd "$repo_root/src" && ./gradlew -q --console=plain "${spotless[@]}") + echo "포맷 spotlessApply (${leaves[*]})" +fi + +checks=() +for leaf in "${leaves[@]}"; do checks+=("$leaf:check"); done +cat < $kebab:create 를 준다(07-authorization.md). + 주기 전까지 POST /$path_segment 는 모두 403이다. + 3. 저장 adapter: ${name}Repository를 구현하고 ${name}RepositoryContract를 실제 저장소로 상속한다 + (04-persistence.md). 그 전까지 ${name}Config는 꺼져 있어 /$path_segment 가 없다. + 4. placeholder 필드 name을 실제 상태로 바꾸고 불변식을 ${name} 안에 둔다. +EOF diff --git a/scripts/verify-feature-scaffold.sh b/scripts/verify-feature-scaffold.sh new file mode 100755 index 00000000..9d33fe97 --- /dev/null +++ b/scripts/verify-feature-scaffold.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# 생성 명령 왕복 검사: 새 기능을 만들면 그 결과가 손대지 않고 PR 게이트를 통과하는가. +# +# scripts/verify-feature-scaffold.sh [FeatureName ...] +# +# 작업 트리(추적 파일 + 무시되지 않은 새 파일)를 임시 디렉터리로 복사하고, 거기서 +# scripts/new-feature.sh를 이름마다 실행한 뒤, 생성물이 닿는 leaf의 check와 architectureCheck를 +# 돌린다. 작업 트리는 건드리지 않고, 임시 디렉터리는 끝나면 지운다(KEEP_SCAFFOLD_COPY=1이면 남긴다). +# +# 기본 이름 두 개: 한 단어(Invoice)와 여러 단어(PurchaseOrder). 여러 단어 이름은 패키지·경로· +# 오류 코드·권한 이름이 서로 다른 모양으로 갈리고 Javadoc 줄바꿈이 달라지는 경우다. +# +# 루트 Gradle 태스크 `verifyFeatureScaffold`가 이 스크립트를 부르고 mainCheck에 들어 있다. +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +names=("$@") +[ "${#names[@]}" -gt 0 ] || names=(Invoice PurchaseOrder) + +parent="${TMPDIR:-/tmp}" +copy="$(mktemp -d "$parent/feature-scaffold.XXXXXX")" +cleanup() { + if [ "${KEEP_SCAFFOLD_COPY:-0}" = "1" ]; then + echo "복사본을 남겼다: $copy" + else + rm -rf "$copy" + fi +} +trap cleanup EXIT + +# 작업 트리 그대로(커밋하지 않은 변경 포함). build 산출물은 .gitignore라 빠진다. +# 지웠지만 아직 커밋하지 않은 추적 파일은 목록에서 뺀다(`-d`로 받은 경로를 거른다). 그대로 두면 +# tar가 없는 파일을 만나 실패한다. +(cd "$repo_root" && git ls-files -co --exclude-standard -z \ + | grep -zvxF -f <(git ls-files -d -z | tr '\0' '\n' | sed '/^$/d'; echo '/dev/null/none')) \ + | (cd "$repo_root" && tar --null -T - -cf -) \ + | tar -xf - -C "$copy" +# architectureCheck의 Git-carryable 검사와 sourceRevision은 Git 저장소를 읽는다. +( + cd "$copy" + git init -q + git add -A + GIT_AUTHOR_NAME=scaffold GIT_AUTHOR_EMAIL=scaffold@invalid \ + GIT_COMMITTER_NAME=scaffold GIT_COMMITTER_EMAIL=scaffold@invalid \ + git commit -q -m "feature scaffold round trip baseline" +) + +for name in "${names[@]}"; do + "$copy/scripts/new-feature.sh" "$name" > "$copy/new-feature-$name.log" + echo "생성: $name" +done + +# 생성 명령이 정말로 무언가를 만들었는지(빈 왕복이 녹색이 되지 않게). +for name in "${names[@]}"; do + package_name="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')" + for required in \ + "src/domain-core/src/main/java/dev/caskeleton/domain/$package_name/${name}.java" \ + "src/application-core/src/main/java/dev/caskeleton/application/$package_name/Create${name}UseCase.java" \ + "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/$package_name/${name}Controller.java" \ + "src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/$package_name/${name}Config.java"; do + [ -f "$copy/$required" ] || { echo "생성되지 않았다: $required" >&2; exit 1; } + done +done + +cd "$copy/src" +./gradlew --console=plain --continue \ + :domain-core:check \ + :application-core:check \ + :adapter:outbound:identifier:check \ + :adapter:inbound:web:check \ + :app-bootstrap:check \ + architectureCheck + +# 생성된 테스트가 실제로 실행되었는지: 각 leaf의 테스트 결과에 기능 테스트 클래스가 있어야 한다. +for name in "${names[@]}"; do + for result in \ + "domain-core/build/test-results/test/TEST-dev.caskeleton.domain.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}Test.xml" \ + "application-core/build/test-results/test/TEST-dev.caskeleton.application.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').Create${name}UseCaseTest.xml" \ + "adapter/inbound/web/build/test-results/test/TEST-dev.caskeleton.adapter.inbound.web.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}ControllerTest.xml" \ + "app-bootstrap/build/test-results/test/TEST-dev.caskeleton.bootstrap.autoconfigure.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}ConfigTest.xml"; do + [ -f "$result" ] || { echo "생성된 테스트가 실행되지 않았다: $result" >&2; exit 1; } + if grep -q '&2 + exit 1 + fi + done +done +echo "feature scaffold 왕복 통과: ${names[*]}" diff --git a/scripts/verify-httpclient-docs.py b/scripts/verify-httpclient-docs.py index 2170e467..6c1bb3b9 100755 --- a/scripts/verify-httpclient-docs.py +++ b/scripts/verify-httpclient-docs.py @@ -19,7 +19,6 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent PLATFORM = REPO_ROOT / "src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient" -BOOTSTRAP = REPO_ROOT / "src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/httpclient" DOCS_DIR = REPO_ROOT / "docs/httpclient" ENV_FIELD_MANIFEST = REPO_ROOT / "docs/httpclient/env-fields.yaml" @@ -61,7 +60,9 @@ def violation_codes() -> list[str]: for source_file in [ PLATFORM / "profile/ClientProfileValidator.java", PLATFORM / "security/TlsPolicyValidator.java", - BOOTSTRAP / "HttpClientStartupValidator.java", + # The startup validator moved from app-bootstrap into the leaf; the old path made this + # script fail on a missing file before it checked anything. + PLATFORM / "autoconfigure/HttpClientStartupValidator.java", ]: source = source_file.read_text(encoding="utf-8") codes.update(re.findall(r'"([A-Z][A-Z0-9_]{4,})"', source)) diff --git a/src/.env.example b/src/.env.example index 491d11f7..f7210dde 100644 --- a/src/.env.example +++ b/src/.env.example @@ -257,9 +257,9 @@ APP_ASYNC_EXECUTOR_CORE_SIZE=10 APP_ASYNC_EXECUTOR_MAX_SIZE=50 APP_ASYNC_EXECUTOR_QUEUE_CAPACITY=200 APP_PERSISTENCE_JPA_ENABLED=true -APP_JPA_HIBERNATE_BATCH_SIZE=0 -APP_JPA_HIBERNATE_ORDER_INSERTS=false -APP_JPA_HIBERNATE_ORDER_UPDATES=false +APP_JPA_HIBERNATE_BATCH_SIZE=50 +APP_JPA_HIBERNATE_ORDER_INSERTS=true +APP_JPA_HIBERNATE_ORDER_UPDATES=true APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE=0 APP_JPA_HIBERNATE_GENERATE_STATISTICS=false APP_PERSISTENCE_MONGO_ENABLED=true @@ -279,6 +279,8 @@ APP_GRAPHQL_MAXIMUM_COMPLEXITY=10000 APP_GRAPHQL_PREPARSED_CACHE_ENTRIES=1000 APP_GRAPHQL_PREPARSED_CACHE_WEIGHT=10000000 APP_GRAPHQL_PREPARSED_CACHE_EXPIRE_AFTER_ACCESS=30m +# 한 요청에서 같은 필드가 DataLoader 없이 이 횟수보다 많이 resolve 되면 WARN + metric (N+1 신호) +APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD=10 # Optional build-composition: these bind only when :adapter:inbound:websocket is present. # The default bootJar does not contain that leaf. @@ -287,6 +289,11 @@ APP_WEBSOCKET_ENDPOINT=/ws APP_WEBSOCKET_ALLOWED_ORIGINS=http://localhost:3000 APP_WEBSOCKET_BROADCAST_DESTINATION=/topic/events APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY=10000 +APP_WEBSOCKET_MESSAGE_SIZE_LIMIT=64KB +APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT=512KB +APP_WEBSOCKET_SEND_TIME_LIMIT=10s +APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE=60s +APP_WEBSOCKET_MAX_CONNECTIONS=1000 APP_OUTBOX_ENABLED=false APP_OUTBOX_RELAY_ENABLED=false APP_NOTIFICATION_PLATFORM_ENABLED=true diff --git a/src/Dockerfile b/src/Dockerfile index f8e4dbf8..a2e9df3a 100644 --- a/src/Dockerfile +++ b/src/Dockerfile @@ -198,8 +198,10 @@ EXPOSE 8080 9001 # the actuator work lived on an unmerged branch. It has been merged for some time, and a stale # warning about a healthcheck is the kind of comment that gets a real red container ignored.) # -# A readiness failure here is a correct UNHEALTHY, not a broken probe: the readiness group includes -# the datasource, so a container started with no reachable PostgreSQL is genuinely not ready. +# A readiness failure here is a correct UNHEALTHY, not a broken probe. In the default composition +# the readiness group is readinessState alone (config/observability.yml); a capability that owns a +# connection adds its own indicator when it is selected — the JPA module adds the datasource — so a +# container started without that dependency reachable is genuinely not ready. # Kubernetes ignores HEALTHCHECK and uses its own probes against the same path; this exists for # docker and Compose. # diff --git a/src/Dockerfile.sample b/src/Dockerfile.sample index c3835c6d..7c04fa00 100644 --- a/src/Dockerfile.sample +++ b/src/Dockerfile.sample @@ -18,8 +18,12 @@ # # The multi-stage build, --parents descriptor glob, STRICT lock verification, # non-root user, read-only-root-fs writable mounts, and JVM container ergonomics -# are all identical to src/Dockerfile — only the bootJar target differs. Keep the -# two files' builder stages in sync. +# are all identical to src/Dockerfile — only the bootJar target differs. +# +# Two files rather than one with a COMPOSITION=sample argument: the release image refuses to build +# without version and source metadata, and folding a zero-argument demo into it would make that +# refusal conditional. The part that must not drift — the dependency stage's COPY lines — is held +# equal by DeveloperExperienceContractTest. # ============================================================================= # Demo defaults so the image builds with zero build-args. Two format constraints from the root @@ -49,8 +53,14 @@ WORKDIR /build/src # (Requires the labs Dockerfile frontend — see the `# syntax` directive at the top of this file.) COPY gradlew ./ COPY gradle/ gradle/ +COPY gradle.properties ./ COPY config/ ./config/ COPY --parents settings.gradle build.gradle **/build.gradle **/gradle.lockfile ./ +# The convention plugins, whole — see src/Dockerfile. Without them settings.gradle's +# includeBuild('build-logic') has no version catalog and no plugins, and this stage failed before +# resolving anything (07-04). DeveloperExperienceContractTest holds these COPY lines equal to the +# release image's. +COPY build-logic/ ./build-logic/ # Resolve every module configuration in STRICT mode (no --write-locks in a demo build either). RUN test -n "${RELEASE_VERSION}" \ diff --git a/src/adapter/inbound/graphql/CLAUDE.md b/src/adapter/inbound/graphql/CLAUDE.md index fd33c85b..c2fa22eb 100644 --- a/src/adapter/inbound/graphql/CLAUDE.md +++ b/src/adapter/inbound/graphql/CLAUDE.md @@ -162,6 +162,8 @@ health 스키마만 소유한다. | 관측 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` | +| 요청 deadline (`maxExecutionTime`) | `wired` | `systemTest/runtime/GraphQlRequestDeadlineTest`(virtual thread: deadline 근처 `REQUEST_TIMEOUT`, 하위 필드 미실행), `GraphQlRequestDeadlineOnRequestThreadTest`(요청 스레드: 느린 resolver 가 끝난 뒤 응답 — 한계). 이미 도는 resolver 는 끊지 않는다(README 「요청 deadline」) | +| per-parent fetch(N+1) 신호 | `wired` | `systemTest/runtime/GraphQlPerParentFetchTest`(일반 `@SchemaMapping` 자식 → WARN 1줄 + `graphql.per.parent.fetch`, registrar 자식 → 조용함). 거부하지 않는다 | | cursor 서명·connection (`pagination/`), fetch profile (`fetch/`) | 라이브러리 | 요청 경로에 없다. 서비스가 직접 호출한다 — README "라이브러리 API". `autoconfigure/GraphQlPolicyRequestPathTest` 가 auto-configuration 이 codec·key ring 을 만들지 않음을 고정 | | 실부하·장애 | 미달성 | 증거 없음 | diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index cd779ce7..69252f30 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -126,6 +126,7 @@ app: preparsed-cache-entries: 1000 preparsed-cache-weight: 10000000 preparsed-cache-expire-after-access: 30m + per-parent-fetch-warning-threshold: 10 # 아래 「N+1」 절 observed-operation-names: [] # 비우면 모든 operation 이름이 `other` 로 접힌다 ``` @@ -238,9 +239,82 @@ tenant/정렬 축으로 넘어가는 것을 막기 위함이며, 키 회전은 ` ## DataLoader 는 요청 스코프, 캐시 키는 actor·tenant 지문으로 격리 -`dataloader/GraphQlDataLoaderRequestRegistry` 는 요청마다 새 인스턴스를 만든다. 전역 캐시는 -tenant 간 데이터 누출 경로가 된다. `security/GraphQlBatchContext.cacheScope()` 는 raw tenant id 가 -아니라 **sha256 지문**을 캐시 스코프에 쓴다(로그·메트릭에 tenant 원문이 새지 않도록). +요청 스코프는 Spring 이 준다. `runtime/GraphQlBatchLoaderRegistrar.register` 는 loader 를 Spring 의 +`BatchLoaderRegistry` 에 등록하고, Spring 은 실행마다 새 `DataLoaderRegistry` 를 만든다. 그래서 +loader 캐시는 그 요청이 끝나면 함께 사라지고, 한 호출자가 받은 행이 다음 호출자에게 가지 않는다 +(`GraphQlBatchLoaderRegistrationTest.oneRequestsCacheIsNotHandedToTheNext`). 전역 캐시는 tenant 간 +데이터 누출 경로가 된다. 각 chunk 는 `dataloader/GraphQlBatchContext` 를 받고, 그 +`cacheScope()` 는 raw tenant id 가 아니라 actor·tenant 의 **sha256 지문**이다(로그·메트릭에 tenant +원문이 새지 않도록). + +요청마다 새로 만든다고 설명하던 `GraphQlDataLoaderRequestRegistry` 와 +`GraphQlDataLoaderFactory.newRequestRegistry()` 는 어느 요청 경로에도 연결되지 않아 2026-11-02 에 +삭제했다(리뷰 03-04). + +플랫폼 context 없이 batch 가 불리면(transport interceptor 미배선) `GraphQlPlatformContextMissingException` +으로 거부한다. wire 는 `INTERNAL_ERROR` + `constraint: PLATFORM_CONTEXT`, 로그는 WARN 한 줄이다. +instrumentation 이 context 없는 요청을 거부할 때와 같은 constraint 다. 예전에는 `REQUEST_TIMEOUT` 으로 +나가서 조립 오류가 "느리다"로 보였고 클라이언트가 재시도했다(리뷰 03-05). + +## N+1 — list 부모 아래 자식 필드는 `GraphQlBatchLoaderRegistrar.register` 로 + +플랫폼의 batch 보호(chunk 크기, 요청 deadline 으로 줄인 batch 예산, actor·tenant scope)는 +`GraphQlBatchLoaderRegistrar.register` 로 등록한 loader 에만 붙는다. 조립 예시는 복사본을 두지 않고 +컴파일·실행되는 테스트 소스를 가리킨다: +[`src/systemTest/java/.../example/OrderCustomerBatchLoading.java`](src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/example/OrderCustomerBatchLoading.java). +세 부분이다 — loader 이름의 `GraphQlBatchPolicy` 를 담은 `GraphQlBatchPolicyRegistry` bean, 생성자에서 +`registrar.register(batchLoaders, CUSTOMER_BY_ID, (ids, batch) -> customers.findByIds(ids))` 한 번, +자식 필드 `@SchemaMapping` 은 `environment.getDataLoader(...).load(key)` 만 한다. +`GraphQlPerParentFetchTest` 가 이 예시로 부모 8개 → downstream 1번을 확인한다. + +같은 일을 하는 다른 길과의 차이: + +| 방법 | 부모 N개일 때 downstream 호출 | chunk·deadline·tenant scope | +| --- | --- | --- | +| `GraphQlBatchLoaderRegistrar.register` | batch 당 1번(policy 의 `maxBatchSize` 로 chunk) | 적용 | +| Spring `@BatchMapping` | 1번 | 미적용 — 크기 상한·deadline·tenant 지문이 없다 | +| 부모마다 부르는 일반 `@SchemaMapping` | N번 | 미적용 | + +adopter 가 잊었을 때를 위해 `runtime/GraphQlPerParentFetchInstrumentation` 이 실행을 센다. 한 +요청에서 같은 필드 좌표가 **DataLoader 를 거치지 않고**(환경에서 DataLoader·registry 를 꺼내지 않고) +resolver 를 `app.graphql.limits.per-parent-fetch-warning-threshold`(기본 10)번보다 많이 부르면 그 +좌표로 WARN 한 줄과 `graphql.per.parent.fetch` observation(태그 `graphql.schema.coordinate`) 하나를 +남긴다. 거부하지는 않는다 — 부모마다 부르는 resolver 가 싼지는 adopter 만 안다. property 읽기 같은 +trivial fetcher 는 세지 않는다. 기본 10 은 기본 page 크기 20 보다 작아서 기본 page 아래의 N+1 은 +잡히고, 보통 문서가 alias 로 root 를 몇 번 부르는 정도로는 울리지 않는 값이다. metric 은 애플리케이션의 +`ObservationRegistry` 로 나가며(Actuator 가 있으면 timer 로 집계), 없으면 WARN 만 남는다. + +버린 대안: 카탈로그에 등록되지 않은 list 자식 필드를 기동 때 경고 — 모든 list 필드를 adopter 가 +카탈로그에 등록해야 의미가 생겨 비용에 비해 효과가 작다. 재검토 조건: sample 에 GraphQL feature 가 +들어오면 그 코드가 위 예시를 대신한다. + +## 요청 deadline — 무엇이 끊기고 무엇이 안 끊기나 + +`GraphQlClientPolicy.maxExecutionTime`(기본 10초)으로 만든 `GraphQlDeadline` 하나를 다음이 읽는다. + +- `runtime/GraphQlPlatformWebInterceptor`: deadline 까지 남은 시간으로 응답에 timer 를 건다. 시간이 + 지나면 클라이언트는 `REQUEST_TIMEOUT`(category `TIMEOUT`)을 받고, Spring 이 실행을 cancel 해서 + graphql-java 가 다음 필드를 더 dispatch 하지 않는다. +- `runtime/GraphQlDeadlineInstrumentation`: deadline 이 지난 뒤에는 non-trivial resolver 를 부르지 않고 + 그 필드를 `REQUEST_TIMEOUT` 으로 실패시킨다. +- `GraphQlCostBudgetHandler`: deadline 이 이미 지났으면 실행을 시작하지 않는다. +- `GraphQlBatchExecutor`: registrar 로 등록한 batch 예산을 남은 시간으로 줄이고, chunk 사이에서 멈춘다. + +**한계(테스트로 고정).** 이미 돌고 있는 resolver 는 끊지 않는다. 그 스레드는 resolver 가 끝날 때까지 +돌고, 그 안의 DB·HTTP 호출은 각 client 의 timeout 이 끊는다 — JPA/Mongo/HTTP client 에 deadline 을 +넘겨주는 장치는 없다. 응답이 deadline 에 바로 나가는지는 resolver 가 어느 스레드에서 도는지에 달렸다. + +| 실행 스레드 | 클라이언트가 응답을 받는 때 | 테스트 | +| --- | --- | --- | +| virtual thread 켬(템플릿 기본 `SPRING_THREADS_VIRTUAL_ENABLED=true`): Spring 이 blocking controller 를 executor 에서 부른다 | deadline 근처 | `GraphQlRequestDeadlineTest` | +| virtual thread 끔: blocking controller 가 요청 스레드에서 돈다 | 느린 resolver 가 끝난 뒤. 그 아래 필드는 실행되지 않는다 | `GraphQlRequestDeadlineOnRequestThreadTest` | + +고른 방법과 버린 대안: deadline 은 플랫폼 interceptor 안에서 요청 context 의 `GraphQlDeadline` 값 +그대로 건다. Spring 의 `TimeoutWebGraphQlInterceptor` 는 GraphQL 본문 없는 HTTP 408 로 끝나 플랫폼 +`REQUEST_TIMEOUT` 코드를 잃고, 자기 duration 을 따로 받아 deadline 과 갈라질 수 있어 쓰지 않았다. +resolver 마다 deadline 을 검사하게 하는 방법은 adopter 가 기억해야 하는 숨은 규칙이 되어 버렸다. +예산을 좁히기만 하던 `execution/GraphQlTimeoutPolicy` 는 main 호출자가 없었고 같은 계산이 +`GraphQlBatchExecutor.effectiveBudget` 에 있어 삭제했다(리뷰 03-02). ## 관측은 저-카디널리티 강제 diff --git a/src/adapter/inbound/graphql/build.gradle b/src/adapter/inbound/graphql/build.gradle index 080ead2c..8f0a9a00 100644 --- a/src/adapter/inbound/graphql/build.gradle +++ b/src/adapter/inbound/graphql/build.gradle @@ -119,7 +119,6 @@ strictTestLanes { description = 'Runs exact no-skip GraphQL conditional transport wire evidence.' requires 'dev.caskeleton.adapter.inbound.graphql.GraphqlHttpBoundaryQualificationTest' rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' } // The transport-boundary ArchUnit suite runs in `test` too; this lane is the guard that it is // still discovered and not skipped — a missing class leaves `test` green. @@ -127,7 +126,6 @@ strictTestLanes { description = 'Runs the GraphQL transport-boundary architecture suite and fails if it is gone or skipped.' requires 'dev.caskeleton.adapter.inbound.graphql.GraphQlTransportBoundaryArchitectureTest' rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' } } 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 index e1df4958..43d04108 100644 --- 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 @@ -9,15 +9,19 @@ 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.GraphQlDeadlineInstrumentation; 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.GraphQlPerParentFetchInstrumentation; 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 io.micrometer.observation.ObservationRegistry; import java.time.Clock; import java.util.List; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -130,4 +134,31 @@ class GraphQlExecutionChainConfiguration { GraphQlExecutionChain chain, GraphQlWireErrorMapper errors) { return new GraphQlPlatformInstrumentation(chain, errors); } + + /** + * Refuses to start a resolver after the request deadline (review 03-02). + * + *

      The transport interceptor's timer answers the client at the deadline; this is the part that + * still holds when the execution runs on the request thread and the timer cannot fire in time. + */ + @Bean + @ConditionalOnMissingBean(GraphQlDeadlineInstrumentation.class) + Instrumentation graphQlDeadlineInstrumentation(Clock graphQlPlatformClock) { + return new GraphQlDeadlineInstrumentation(graphQlPlatformClock); + } + + /** + * Logs and records a field that resolves per parent without a DataLoader (review 03-03). + * + *

      Records through the application's {@link ObservationRegistry} when there is one, the same + * registry Spring for GraphQL's own observations use; without one only the WARN line remains. + */ + @Bean + @ConditionalOnMissingBean(GraphQlPerParentFetchInstrumentation.class) + Instrumentation graphQlPerParentFetchInstrumentation( + GraphQlPlatformSettings properties, ObjectProvider observations) { + return new GraphQlPerParentFetchInstrumentation( + properties.limits().perParentFetchWarningThreshold(), + observations.getIfAvailable(() -> ObservationRegistry.NOOP)); + } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java index d9f70b5e..f7a9ddb5 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java @@ -82,17 +82,23 @@ public record GraphQlPlatformSettings( * @param preparsedCacheEntries largest number of cached parsed documents * @param preparsedCacheWeight largest total cached document weight, in characters * @param preparsedCacheExpireAfterAccess how long an unused cached document is kept + * @param perParentFetchWarningThreshold how many times one field coordinate may run a resolver + * without a DataLoader in one request before it is logged and recorded as a likely N+1 + * ({@code GraphQlPerParentFetchInstrumentation}). 10 sits below the default page size of 20, + * so a default page whose child resolves per parent is reported, and above the handful of + * aliased root calls an ordinary document makes */ public record Limits( @DefaultValue("100") int maximumPageSize, @DefaultValue("10000") long maximumComplexity, @DefaultValue("1000") long preparsedCacheEntries, @DefaultValue("10000000") long preparsedCacheWeight, - @DefaultValue("30m") Duration preparsedCacheExpireAfterAccess) { + @DefaultValue("30m") Duration preparsedCacheExpireAfterAccess, + @DefaultValue("10") int perParentFetchWarningThreshold) { /** The declared defaults, for programmatic construction. */ public static Limits defaults() { - return new Limits(100, 10_000, 1_000, 10_000_000, Duration.ofMinutes(30)); + return new Limits(100, 10_000, 1_000, 10_000_000, Duration.ofMinutes(30), 10); } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidator.java index 984adb71..31a28578 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidator.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidator.java @@ -52,6 +52,9 @@ public final class GraphQlPlatformStartupValidator { if (properties.limits().maximumComplexity() < 1) { problems.add("maximum complexity must be positive"); } + if (properties.limits().perParentFetchWarningThreshold() < 1) { + problems.add("per-parent fetch warning threshold must be positive"); + } return List.copyOf(problems); } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlDeadline.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlDeadline.java index 2c5085f9..3baa3a76 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlDeadline.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlDeadline.java @@ -7,10 +7,24 @@ import java.time.Instant; /** * The absolute instant a GraphQL request must be finished by. * - *

      A deadline rather than a duration, because the same budget has to be handed down to resolvers, - * DataLoader batches and the JPA/Mongo/HTTP client deadlines without each layer restarting the - * clock. Remaining time is always computed from an injected {@link Clock} so the value stays - * testable and the record itself holds no mutable state. + *

      A deadline rather than a duration, so every reader measures against the same instant instead + * of restarting the clock. Who reads it today, and nothing more: + * + *

        + *
      • {@code GraphQlPlatformWebInterceptor} ends the request with {@code REQUEST_TIMEOUT} when it + * passes, and Spring cancels the execution so no further field is dispatched. A resolver + * already running is not interrupted. + *
      • {@code GraphQlCostBudgetHandler} refuses to start an execution whose deadline has passed. + *
      • {@code GraphQlBatchExecutor} clamps each platform-registered DataLoader batch to what is + * left, and stops between chunks once it is spent. + *
      + * + *

      It is not handed to JPA, Mongo or HTTP client calls. A resolver that calls one is + * bounded by that client's own timeout; a resolver that wants the request's remainder reads it from + * {@link GraphQlRequestContext#deadline()} and passes it on itself. + * + *

      Remaining time is always computed from an injected {@link Clock} so the value stays testable + * and the record itself holds no mutable state. * * @param value the instant at which the request budget is exhausted */ diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderFactory.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderFactory.java index eaac7a22..0c42d22e 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderFactory.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderFactory.java @@ -5,10 +5,11 @@ import java.time.Clock; import java.util.Objects; /** - * Creates the loaders for one execution. + * Supplies the per-loader batch executor and the per-execution batch context. * - *

      A factory rather than a bean per loader: instances must be created per execution, and a - * factory is what makes that structurally true instead of a convention someone has to remember. + *

      It does not hold loader instances. The request scope is Spring's: {@code + * GraphQlBatchLoaderRegistrar} registers with Spring's {@code BatchLoaderRegistry}, and Spring + * builds a fresh {@code DataLoaderRegistry} — and so a fresh loader cache — for every execution. */ public final class GraphQlDataLoaderFactory { @@ -33,11 +34,6 @@ public final class GraphQlDataLoaderFactory { this.clock = Objects.requireNonNull(clock); } - /** A registry holding this execution's loader instances. */ - public GraphQlDataLoaderRequestRegistry newRequestRegistry() { - return new GraphQlDataLoaderRequestRegistry(); - } - /** The batch context for this execution. */ public GraphQlBatchContext batchContext(GraphQlRequestContext context) { return GraphQlBatchContext.from(context); diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderRequestRegistry.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderRequestRegistry.java deleted file mode 100644 index 17be491b..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderRequestRegistry.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.dataloader; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -/** - * The DataLoader instances belonging to one GraphQL execution (design §13). - * - *

      A new registry per execution, never a shared singleton. The request-scoped cache is the - * reason: it is keyed by entity id and holds whatever the loader returned for this caller, - * so sharing it across requests means one user's cached order is served to the next user who asks - * for the same id. - * - *

      Cross-request caching is a separate concern with a different key model, and belongs to the - * cache capability rather than here. - */ -public final class GraphQlDataLoaderRequestRegistry { - - private final Map loaders = new LinkedHashMap<>(); - - /** Whether any loader has been created for this execution. */ - public boolean isEmpty() { - return loaders.isEmpty(); - } - - /** - * Registers a loader instance for this execution. - * - * @throws IllegalArgumentException when the loader is already registered for this execution - */ - public GraphQlDataLoaderRequestRegistry register(GraphQlDataLoaderName name, Object loader) { - if (name == null || loader == null) { - throw new IllegalArgumentException("loader name and instance are required"); - } - if (loaders.putIfAbsent(name, loader) != null) { - throw new IllegalArgumentException("loader " + name.value() + " is already registered"); - } - return this; - } - - /** - * The loader instance registered for this execution. - * - * @throws IllegalArgumentException when it was not registered - */ - public Object require(GraphQlDataLoaderName name) { - Object loader = loaders.get(name); - if (loader == null) { - throw new IllegalArgumentException("loader " + name.value() + " is not registered"); - } - return loader; - } - - /** Loader names registered for this execution. */ - public Set loaderNames() { - return Set.copyOf(loaders.keySet()); - } - - /** Releases every loader when the execution finishes, so nothing outlives the request. */ - public void clear() { - loaders.clear(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlRequestCancelledException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlRequestCancelledException.java index 0f81538e..74544c26 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlRequestCancelledException.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlRequestCancelledException.java @@ -6,7 +6,10 @@ import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection; import dev.caskeleton.shared.error.Category; /** - * Raised when work continues after the request was cancelled or its budget expired. + * Raised when the request budget ({@code GraphQlClientPolicy.maxExecutionTime}) has run out. + * + *

      Two places raise it: the cost stage, when the deadline passed before execution started, and + * the transport interceptor, when it passes while the execution is running. * *

      Carries the stable timeout error code and no request content. */ @@ -17,12 +20,12 @@ public class GraphQlRequestCancelledException extends RuntimeException /** Creates the failure. */ public GraphQlRequestCancelledException() { - super("GraphQL request was cancelled: " + GraphQlTimeoutPolicy.TIMEOUT_ERROR_CODE); + super("GraphQL request was cancelled: " + GraphQlErrorCode.REQUEST_TIMEOUT); } /** The stable error code clients see. */ public String code() { - return GraphQlTimeoutPolicy.TIMEOUT_ERROR_CODE; + return GraphQlErrorCode.REQUEST_TIMEOUT; } @Override diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicy.java deleted file mode 100644 index 6823e6b6..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicy.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import java.time.Duration; - -/** - * A remaining time budget that only ever narrows (design §10). - * - *

      Every layer below GraphQL — resolver, DataLoader batch, database statement, HTTP call — asks - * this for its own budget, and gets the smaller of what it asked for and what is actually left. - * Without that clamp a five-second database timeout under a two-second request budget keeps the - * connection busy for three seconds after the client has already been answered. - * - * @param remaining time left in the parent budget - */ -public record GraphQlTimeoutPolicy(Duration remaining) { - - /** Stable error code emitted when the request budget is exhausted. */ - public static final String TIMEOUT_ERROR_CODE = "REQUEST_TIMEOUT"; - - public GraphQlTimeoutPolicy { - if (remaining == null || remaining.isZero() || remaining.isNegative()) { - throw new IllegalArgumentException("remaining time must be positive"); - } - } - - /** The budget a child operation may use: never more than what remains. */ - public Duration child(Duration requested) { - if (requested == null || requested.isZero() || requested.isNegative()) { - throw new IllegalArgumentException("requested budget must be positive"); - } - return requested.compareTo(remaining) < 0 ? requested : remaining; - } - - /** A policy for the child budget, for chaining further down. */ - public GraphQlTimeoutPolicy childPolicy(Duration requested) { - return new GraphQlTimeoutPolicy(child(requested)); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlObservationNames.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlObservationNames.java index 7ea96914..e273eb9f 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlObservationNames.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlObservationNames.java @@ -18,5 +18,12 @@ public final class GraphQlObservationNames { /** One DataLoader batch. */ public static final String DATA_LOADER = "graphql.dataloader"; + /** + * The platform's own: one request in which a field coordinate crossed the per-parent fetch + * threshold ({@code GraphQlPerParentFetchInstrumentation}). Not emitted by Spring; tagged only + * with the schema coordinate. + */ + public static final String PER_PARENT_FETCH = "graphql.per.parent.fetch"; + private GraphQlObservationNames() {} } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlBatchLoaderRegistrar.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlBatchLoaderRegistrar.java index 77bcaf5f..40985066 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlBatchLoaderRegistrar.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlBatchLoaderRegistrar.java @@ -3,13 +3,14 @@ package dev.caskeleton.adapter.inbound.graphql.runtime; import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchContext; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchExecutor; -import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.BiFunction; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.graphql.execution.BatchLoaderRegistry; import reactor.core.publisher.Mono; @@ -31,6 +32,8 @@ import reactor.core.publisher.Mono; */ public final class GraphQlBatchLoaderRegistrar { + private static final Logger LOG = LoggerFactory.getLogger(GraphQlBatchLoaderRegistrar.class); + private final GraphQlDataLoaderFactory factory; /** @@ -73,7 +76,14 @@ public final class GraphQlBatchLoaderRegistrar { if (context == null) { // Fail closed. A loader running without the platform context has no deadline, no // tenant and no actor, and would happily batch across whatever the caller was. - return Mono.error(new GraphQlBatchTimeoutException(loaderName.value())); + // Reported as the assembly fault it is, the same way the instrumentation reports a + // request without the context: INTERNAL_ERROR on the wire, the cause in the log. + LOG.warn( + "graphql batch rejected: no platform context (loader={});" + + " the platform transport interceptor is not wired", + loaderName.value()); + return Mono.error( + new GraphQlPlatformContextMissingException("loader " + loaderName.value())); } GraphQlBatchContext batchContext = factory.batchContext(context); return Mono.fromCallable( diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDeadlineInstrumentation.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDeadlineInstrumentation.java new file mode 100644 index 00000000..e3b25e70 --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDeadlineInstrumentation.java @@ -0,0 +1,61 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; +import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException; +import graphql.execution.instrumentation.InstrumentationState; +import graphql.execution.instrumentation.SimplePerformantInstrumentation; +import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters; +import graphql.schema.DataFetcher; +import java.time.Clock; +import java.util.Objects; + +/** + * Refuses to start a resolver once the request deadline has passed (review 03-02). + * + *

      The transport interceptor ends the request at its deadline with a timer, and that is enough + * whenever the execution runs off the request thread. It is not enough when it runs on it: on a + * servlet stack without virtual threads Spring for GraphQL invokes a blocking controller method on + * the request thread, the whole execution happens inside the subscription, and the timer only + * starts after it has finished. This check is what still holds there: every non-trivial fetch after + * the deadline fails with {@code REQUEST_TIMEOUT} instead of calling the resolver, so a slow parent + * does not drag its children's downstream calls behind it. + * + *

      Trivial fetchers (property reads) are left alone: they do no downstream work, and checking the + * clock on every one of them would cost more than it saves. A resolver already running is not + * interrupted — nothing here can stop a blocking call it did not start. + * + *

      Chosen over cancelling the {@code ExecutionInput}: graphql-java answers a cancelled execution + * with its own {@code AbortExecutionException} message, which would replace the platform's {@code + * REQUEST_TIMEOUT} code with an unmapped one. + */ +public final class GraphQlDeadlineInstrumentation extends SimplePerformantInstrumentation { + + private final Clock clock; + + /** + * Creates the instrumentation. + * + * @param clock the clock the request deadline is measured against + */ + public GraphQlDeadlineInstrumentation(Clock clock) { + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + @Override + public DataFetcher instrumentDataFetcher( + DataFetcher dataFetcher, + InstrumentationFieldFetchParameters parameters, + InstrumentationState state) { + if (parameters.isTrivialDataFetcher()) { + return dataFetcher; + } + return environment -> { + GraphQlRequestContext context = + environment.getGraphQlContext().get(GraphQlRequestContext.CONTEXT_KEY); + if (context != null && context.deadline().expired(clock)) { + throw new GraphQlRequestCancelledException(); + } + return dataFetcher.get(environment); + }; + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPerParentFetchInstrumentation.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPerParentFetchInstrumentation.java new file mode 100644 index 00000000..3679041a --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPerParentFetchInstrumentation.java @@ -0,0 +1,150 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationNames; +import graphql.execution.ExecutionStepInfo; +import graphql.execution.instrumentation.InstrumentationState; +import graphql.execution.instrumentation.SimplePerformantInstrumentation; +import graphql.execution.instrumentation.parameters.InstrumentationCreateStateParameters; +import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters; +import graphql.schema.DataFetcher; +import graphql.schema.DataFetchingEnvironment; +import graphql.schema.DelegatingDataFetchingEnvironment; +import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationRegistry; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import org.dataloader.DataLoader; +import org.dataloader.DataLoaderRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Makes an N+1 resolver visible: counts, per request, how often one field coordinate runs a + * resolver that did not go through a DataLoader (review 03-03). + * + *

      The platform's batch protection — chunking, the request deadline, the tenant-scoped cache — + * reaches only loaders registered through {@link GraphQlBatchLoaderRegistrar}. A child field under + * a list parent written as a plain {@code @SchemaMapping} calls its downstream once per parent, and + * nothing in the platform can see that from the schema. What it can see is the execution: the same + * coordinate fetched again and again in one request, each time without touching a DataLoader. + * + *

      "Through a DataLoader" means the resolver asked its {@code DataFetchingEnvironment} for one or + * for the registry. Spring resolves a {@code DataLoader} method argument that way, + * {@code @BatchMapping} does too, and so does a hand-written fetcher; none of those are counted. + * Trivial property reads are not counted either. Counting is by invocation, not by thread, so a + * resolver Spring runs on the executor (virtual threads) is counted the same as one on the request + * thread. + * + *

      When a coordinate crosses the threshold in one request this logs one WARN for it and records + * one {@value GraphQlObservationNames#PER_PARENT_FETCH} observation tagged with the schema + * coordinate, which is bounded by the schema. It never rejects: a per-parent resolver may be + * perfectly cheap, and only the adopter knows. The signal exists so an expensive one is found in + * the log or a dashboard rather than in a database incident. + * + *

      Chosen over a startup check of unregistered list children (review 03-03 option c): that needs + * every list field registered in the cost catalog before it can say anything, while this needs + * nothing from the adopter. + */ +public final class GraphQlPerParentFetchInstrumentation extends SimplePerformantInstrumentation { + + private static final Logger LOG = + LoggerFactory.getLogger(GraphQlPerParentFetchInstrumentation.class); + + /** The metric tag carrying the field coordinate; allowlisted by the cardinality policy. */ + public static final String COORDINATE_TAG = "graphql.schema.coordinate"; + + private final int warningThreshold; + private final ObservationRegistry observations; + + /** + * Creates the instrumentation. + * + * @param warningThreshold per-parent fetches of one coordinate in one request that are still + * quiet; one more logs and records + * @param observations where the crossing is recorded; {@link ObservationRegistry#NOOP} records + * nothing + */ + public GraphQlPerParentFetchInstrumentation( + int warningThreshold, ObservationRegistry observations) { + if (warningThreshold < 1) { + throw new IllegalArgumentException("per-parent fetch warning threshold must be positive"); + } + this.warningThreshold = warningThreshold; + this.observations = Objects.requireNonNull(observations, "observation registry is required"); + } + + @Override + public InstrumentationState createState(InstrumentationCreateStateParameters parameters) { + return new Counts(); + } + + @Override + public DataFetcher instrumentDataFetcher( + DataFetcher dataFetcher, + InstrumentationFieldFetchParameters parameters, + InstrumentationState state) { + if (parameters.isTrivialDataFetcher() || !(state instanceof Counts counts)) { + return dataFetcher; + } + return environment -> { + LoaderTracking tracking = new LoaderTracking(environment); + Object value = dataFetcher.get(tracking); + if (!tracking.usedDataLoader) { + record(counts, coordinate(environment.getExecutionStepInfo())); + } + return value; + }; + } + + private void record(Counts counts, String coordinate) { + int fetches = + counts + .byCoordinate + .computeIfAbsent(coordinate, key -> new AtomicInteger()) + .incrementAndGet(); + if (fetches != warningThreshold + 1) { + return; + } + LOG.warn( + "graphql field {} resolved per parent more than {} times in one request without a" + + " DataLoader; register it with GraphQlBatchLoaderRegistrar", + coordinate, + warningThreshold); + Observation.createNotStarted(GraphQlObservationNames.PER_PARENT_FETCH, observations) + .lowCardinalityKeyValue(COORDINATE_TAG, coordinate) + .observe(() -> {}); + } + + private static String coordinate(ExecutionStepInfo step) { + return step.getObjectType().getName() + "." + step.getFieldDefinition().getName(); + } + + /** Per-execution counts, one per coordinate. */ + private static final class Counts implements InstrumentationState { + private final Map byCoordinate = new ConcurrentHashMap<>(); + } + + /** Notes whether the resolver reached for a DataLoader; changes nothing it sees. */ + private static final class LoaderTracking extends DelegatingDataFetchingEnvironment { + + private volatile boolean usedDataLoader; + + LoaderTracking(DataFetchingEnvironment delegate) { + super(delegate); + } + + @Override + public DataLoader getDataLoader(String dataLoaderName) { + usedDataLoader = true; + return super.getDataLoader(dataLoaderName); + } + + @Override + public DataLoaderRegistry getDataLoaderRegistry() { + usedDataLoader = true; + return super.getDataLoaderRegistry(); + } + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformContextMissingException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformContextMissingException.java new file mode 100644 index 00000000..ccfde751 --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformContextMissingException.java @@ -0,0 +1,52 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode; +import dev.caskeleton.adapter.inbound.graphql.error.GraphQlPlatformRejection; +import dev.caskeleton.shared.error.Category; +import java.util.Optional; + +/** + * Raised when platform machinery runs without the request context the transport interceptor puts in + * place. + * + *

      That is an assembly fault — the interceptor is not wired — not anything the client did, so the + * client sees an opaque {@code INTERNAL_ERROR} carrying the {@value #CONSTRAINT} constraint and the + * operator gets the WARN line naming the cause. It replaced the batch registrar's {@code + * GraphQlBatchTimeoutException}, which reported the same fault as a retryable {@code + * REQUEST_TIMEOUT}: a mis-assembled deployment looked slow, and clients retried it (review 03-05). + * + *

      Package-private: only the runtime machinery raises it, and the wire mapper reads it through + * {@link GraphQlPlatformRejection}, so no adopter code needs the type. + */ +final class GraphQlPlatformContextMissingException extends RuntimeException + implements GraphQlPlatformRejection { + + private static final long serialVersionUID = 1L; + + /** The constraint identity every missing-context rejection carries on the wire. */ + static final String CONSTRAINT = "PLATFORM_CONTEXT"; + + /** + * Creates the failure. + * + * @param where bounded name of the machinery that found the context missing + */ + GraphQlPlatformContextMissingException(String where) { + super("no GraphQL platform context in " + where); + } + + @Override + public GraphQlErrorCode wireCode() { + return GraphQlErrorCode.platform(GraphQlErrorCode.INTERNAL_ERROR); + } + + @Override + public Category failureCategory() { + return Category.INTERNAL; + } + + @Override + public Optional constraint() { + return Optional.of(CONSTRAINT); + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformInstrumentation.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformInstrumentation.java index 3eab5756..e3c50b9c 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformInstrumentation.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformInstrumentation.java @@ -36,7 +36,8 @@ public final class GraphQlPlatformInstrumentation extends SimplePerformantInstru private static final Logger LOG = LoggerFactory.getLogger(GraphQlPlatformInstrumentation.class); /** Constraint reported when the request arrived without a platform context. */ - public static final String MISSING_CONTEXT_CONSTRAINT = "PLATFORM_CONTEXT"; + public static final String MISSING_CONTEXT_CONSTRAINT = + GraphQlPlatformContextMissingException.CONSTRAINT; private final GraphQlExecutionChain chain; private final GraphQlWireErrorMapper errors; diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptor.java index 88e229ff..d9f5cd5f 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptor.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptor.java @@ -6,6 +6,7 @@ import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; import dev.caskeleton.adapter.inbound.graphql.context.TenantContext; import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext; import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper; +import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException; import dev.caskeleton.adapter.inbound.graphql.http.GraphQlExtensionsPolicy; import dev.caskeleton.adapter.inbound.graphql.http.GraphQlJsonStructurePolicy; import dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestSize; @@ -18,6 +19,7 @@ import graphql.ExecutionInput; import graphql.ExecutionResult; import java.nio.charset.StandardCharsets; import java.time.Clock; +import java.time.Duration; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -38,6 +40,10 @@ import reactor.core.publisher.Mono; * the context this interceptor puts into the GraphQL context, so a deployment that omits it gets a * rejected request rather than an unpoliced one. * + *

      It also ends the request at its deadline: the execution is answered with {@code + * REQUEST_TIMEOUT} when {@code GraphQlClientPolicy.maxExecutionTime} runs out, whatever is still + * running (see {@link #intercept} for what that does and does not stop). + * *

      The document size check is here rather than in a policy object for the same reason: the * transport is where the size is known, and refusing a large document before parsing is the only * place the refusal is cheap. @@ -111,7 +117,25 @@ public final class GraphQlPlatformWebInterceptor implements WebGraphQlIntercepto // Also on the Reactor context, so a reactive resolver reads the same value rather than a // second one assembled from whatever it can reach. - return chain.next(request).contextWrite(view -> view.put(GraphQlRequestContext.class, context)); + // + // The timeout is the request deadline itself, read from the context just built, so the budget + // the pipeline and the DataLoader batches check and the one that ends the request are one value + // (review 03-02). On expiry the client gets REQUEST_TIMEOUT and Spring cancels the execution, + // which stops graphql-java from dispatching further fields. A resolver already running is not + // interrupted: it finishes on its own thread, and its downstream timeouts are what bound it. On + // a servlet stack without virtual threads that resolver is running on the request thread, so + // the answer can only leave when it returns (GraphQlRequestDeadlineOnRequestThreadTest). + // + // Chosen over Spring's TimeoutWebGraphQlInterceptor: that one answers with an HTTP 408 and no + // GraphQL body, so the client would lose the platform's REQUEST_TIMEOUT code, and it needs its + // own duration — a second copy of the budget that could drift from this deadline. + Duration budget = context.deadline().remaining(clock); + return chain + .next(request) + .contextWrite(view -> view.put(GraphQlRequestContext.class, context)) + .timeout( + budget, + Mono.fromSupplier(() -> reject(request, new GraphQlRequestCancelledException()))); } /** diff --git a/src/adapter/inbound/graphql/src/main/resources/config/graphql.yml b/src/adapter/inbound/graphql/src/main/resources/config/graphql.yml index 527797e4..d4d1677e 100644 --- a/src/adapter/inbound/graphql/src/main/resources/config/graphql.yml +++ b/src/adapter/inbound/graphql/src/main/resources/config/graphql.yml @@ -22,6 +22,9 @@ app: preparsed-cache-entries: ${APP_GRAPHQL_PREPARSED_CACHE_ENTRIES:1000} preparsed-cache-weight: ${APP_GRAPHQL_PREPARSED_CACHE_WEIGHT:10000000} preparsed-cache-expire-after-access: ${APP_GRAPHQL_PREPARSED_CACHE_EXPIRE_AFTER_ACCESS:30m} + # 한 요청에서 같은 필드 좌표가 DataLoader 없이 resolver 를 이 횟수보다 많이 부르면 WARN 한 줄과 + # graphql.per.parent.fetch metric 을 남긴다(N+1 신호, 거부하지 않는다). 기본 10 = 기본 page 크기 20 보다 작다. + per-parent-fetch-warning-threshold: ${APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD:10} # /actuator/info 에 싣는 이 모듈의 상태(management.info.env). compose smoke 가 lane 이 실제로 켠 # capability 를 이 값으로 확인한다. 위 스위치를 해석한 값이고, 기본값은 GraphQlRootAutoConfiguration 의 diff --git a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/example/OrderCustomerBatchLoading.java b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/example/OrderCustomerBatchLoading.java new file mode 100644 index 00000000..07bef48a --- /dev/null +++ b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/example/OrderCustomerBatchLoading.java @@ -0,0 +1,79 @@ +package dev.caskeleton.adapter.inbound.graphql.example; + +import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicy; +import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicyRegistry; +import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName; +import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar; +import graphql.schema.DataFetchingEnvironment; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.graphql.data.method.annotation.SchemaMapping; +import org.springframework.graphql.execution.BatchLoaderRegistry; +import org.springframework.stereotype.Controller; + +/** + * The README example "a child field under a list parent" — compiled and executed here. + * + *

      {@code src/adapter/inbound/graphql/README.md} points at this file instead of carrying a copy, + * so the example cannot drift from code that compiles. {@code GraphQlPerParentFetchTest} runs it + * over the real endpoint and counts the downstream calls. + * + *

      Three parts, all on the adopter's side: + * + *

        + *
      1. a policy for the loader name (batch size and batch timeout), as a {@link + * GraphQlBatchPolicyRegistry} bean; + *
      2. the downstream call, registered once through {@link GraphQlBatchLoaderRegistrar} — the + * platform wraps it in chunking, the request deadline and the request's actor/tenant scope; + *
      3. the child field, which only asks the DataLoader for its key. + *
      + */ +@Controller +public class OrderCustomerBatchLoading { + + /** The loader's platform name; the policy and the registration meet on it. */ + public static final GraphQlDataLoaderName CUSTOMER_BY_ID = + new GraphQlDataLoaderName("customer-by-id"); + + /** The adopter's downstream port: one call for many ids. */ + public interface CustomerDirectory { + Map findByIds(List ids); + } + + public record Order(String id, String customerId) {} + + public record Customer(String id, String name) {} + + public OrderCustomerBatchLoading( + BatchLoaderRegistry batchLoaders, + GraphQlBatchLoaderRegistrar registrar, + CustomerDirectory customers) { + // The batch context carries the request's actor, tenant, deadline and cache scope; a downstream + // that filters by tenant reads it from there rather than from a thread-local. + registrar.register( + batchLoaders, CUSTOMER_BY_ID, (ids, batch) -> customers.findByIds(ids)); + } + + /** The child field: one {@code load} per parent, one downstream call per batch. */ + @SchemaMapping(typeName = "Order", field = "customer") + public CompletableFuture customer(Order order, DataFetchingEnvironment environment) { + return environment + .getDataLoader(CUSTOMER_BY_ID.value()) + .load(order.customerId()); + } + + /** The loader's policy: at most 100 keys per downstream call, two seconds per batch. */ + @Configuration(proxyBeanMethods = false) + public static class Policies { + + @Bean + GraphQlBatchPolicyRegistry graphQlBatchPolicyRegistry() { + return new GraphQlBatchPolicyRegistry() + .register(new GraphQlBatchPolicy(CUSTOMER_BY_ID, 100, Duration.ofSeconds(2), true)); + } + } +} diff --git a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPerParentFetchTest.java b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPerParentFetchTest.java new file mode 100644 index 00000000..4f1eeb28 --- /dev/null +++ b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPerParentFetchTest.java @@ -0,0 +1,191 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading; +import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading.Customer; +import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading.CustomerDirectory; +import dev.caskeleton.adapter.inbound.graphql.example.OrderCustomerBatchLoading.Order; +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationNames; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.observation.DefaultMeterObservationHandler; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import io.micrometer.observation.ObservationRegistry; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.resttestclient.TestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.graphql.data.method.annotation.Argument; +import org.springframework.graphql.data.method.annotation.QueryMapping; +import org.springframework.graphql.data.method.annotation.SchemaMapping; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; + +/** + * A child field resolved once per parent is reported; the same field through the registrar is not + * (review 03-03). + * + *

      Both children of {@code Order} return the same customer. {@code customerPerParent} is the + * plain {@code @SchemaMapping} an adopter writes first; {@code customer} is the README example + * ({@link OrderCustomerBatchLoading}). The downstream counter is what tells them apart; the WARN + * line and the metric are what an operator would see. + */ +@SpringBootTest( + classes = GraphQlPerParentFetchTest.TestApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { + "app.graphql.enabled=true", + "app.graphql.deployment-mode=LOCAL", + "spring.graphql.graphiql.enabled=false", + "app.graphql.limits.per-parent-fetch-warning-threshold=5", + RuntimeLimitsTestSupport.SCHEMA_LOCATIONS, + RuntimeLimitsTestSupport.SCHEMA_FILES + }) +@AutoConfigureTestRestTemplate +class GraphQlPerParentFetchTest { + + private static final AtomicInteger DOWNSTREAM_CALLS = new AtomicInteger(); + + @LocalServerPort int port; + + @Autowired TestRestTemplate http; + + @Autowired MeterRegistry meters; + + private final ListAppender warnings = new ListAppender<>(); + + private final Logger logger = + (Logger) LoggerFactory.getLogger(GraphQlPerParentFetchInstrumentation.class); + + @BeforeEach + void captureWarningsAndReset() { + meters.clear(); + DOWNSTREAM_CALLS.set(0); + warnings.start(); + logger.addAppender(warnings); + } + + @AfterEach + void releaseCapture() { + logger.detachAppender(warnings); + warnings.stop(); + } + + @Test + @DisplayName("list 부모 아래 일반 @SchemaMapping 자식이 임계값을 넘으면 WARN 한 줄과 좌표 metric 이 남는다") + void aChildResolvedPerParentPastTheThresholdIsLoggedOnceAndCounted() { + // when + ResponseEntity response = + RuntimeLimitsTestSupport.post( + http, port, "{ orders(count: 8) { id customerPerParent { name } } }"); + + // then + assertThat(response.getBody()).contains("\"name\":\"customer c-7\""); + assertThat(DOWNSTREAM_CALLS).as("eight parents, eight downstream calls").hasValue(8); + assertThat(warnings.list) + .singleElement() + .extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage) + .containsExactly( + Level.WARN, + "graphql field Order.customerPerParent resolved per parent more than 5 times in one" + + " request without a DataLoader; register it with GraphQlBatchLoaderRegistrar"); + assertThat( + meters + .get(GraphQlObservationNames.PER_PARENT_FETCH) + .tag(GraphQlPerParentFetchInstrumentation.COORDINATE_TAG, "Order.customerPerParent") + .timer() + .count()) + .isEqualTo(1); + } + + @Test + @DisplayName("registrar 로 조립한 자식은 한 번의 downstream 호출로 끝나고 경고하지 않는다") + void theSameChildThroughTheRegistrarIsOneCallAndStaysQuiet() { + // when + ResponseEntity response = + RuntimeLimitsTestSupport.post(http, port, "{ orders(count: 8) { id customer { name } } }"); + + // then + assertThat(response.getBody()).contains("\"name\":\"customer c-7\""); + assertThat(DOWNSTREAM_CALLS).as("eight parents, one batch").hasValue(1); + assertThat(warnings.list).isEmpty(); + assertThat(meters.find(GraphQlObservationNames.PER_PARENT_FETCH).timer()).isNull(); + } + + /** The list parent and the per-parent child an adopter writes before knowing better. */ + @Controller + static class OrderController { + + private final CustomerDirectory customers; + + OrderController(CustomerDirectory customers) { + this.customers = customers; + } + + @QueryMapping + List orders(@Argument int count) { + return IntStream.range(0, count) + .mapToObj(index -> new Order("o-" + index, "c-" + index)) + .toList(); + } + + @SchemaMapping(typeName = "Order", field = "customerPerParent") + Customer customerPerParent(Order order) { + return customers.findByIds(List.of(order.customerId())).get(order.customerId()); + } + } + + @SpringBootConfiguration + @EnableAutoConfiguration + @Import({ + RuntimeLimitsTestSupport.Transport.class, + OrderController.class, + OrderCustomerBatchLoading.class, + OrderCustomerBatchLoading.Policies.class + }) + static class TestApplication { + + /** A downstream that counts its calls. */ + @Bean + CustomerDirectory customerDirectory() { + return ids -> { + DOWNSTREAM_CALLS.incrementAndGet(); + Map rows = new LinkedHashMap<>(); + ids.forEach(id -> rows.put(id, new Customer(id, "customer " + id))); + return rows; + }; + } + + @Bean + SimpleMeterRegistry meterRegistry() { + return new SimpleMeterRegistry(); + } + + /** Observations become meters, as they do in a deployment with Actuator. */ + @Bean + ObservationRegistry observationRegistry(SimpleMeterRegistry meters) { + ObservationRegistry registry = ObservationRegistry.create(); + registry.observationConfig().observationHandler(new DefaultMeterObservationHandler(meters)); + return registry; + } + } +} diff --git a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineOnRequestThreadTest.java b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineOnRequestThreadTest.java new file mode 100644 index 00000000..9f57f5de --- /dev/null +++ b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineOnRequestThreadTest.java @@ -0,0 +1,93 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; +import dev.caskeleton.adapter.inbound.graphql.runtime.RuntimeLimitsTestSupport.SlowWork; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.resttestclient.TestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.http.ResponseEntity; + +/** + * The limit of the request deadline, pinned so nobody reads more into it (review 03-02). + * + *

      With virtual threads off, Spring for GraphQL runs a blocking controller method on the servlet + * thread that is executing the request. The deadline still fires on time and cancels the execution, + * but the thread that would write the answer is the one stuck in the resolver: the client receives + * {@code REQUEST_TIMEOUT} only when that resolver returns. Nothing in the JVM can stop a blocking + * call it did not start; the resolver's own downstream timeouts are what bound it. + */ +@SpringBootTest( + classes = GraphQlRequestDeadlineOnRequestThreadTest.TestApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { + "app.graphql.enabled=true", + "app.graphql.deployment-mode=LOCAL", + "spring.graphql.graphiql.enabled=false", + "spring.threads.virtual.enabled=false", + RuntimeLimitsTestSupport.SCHEMA_LOCATIONS, + RuntimeLimitsTestSupport.SCHEMA_FILES + }) +@AutoConfigureTestRestTemplate +class GraphQlRequestDeadlineOnRequestThreadTest { + + private static final Duration BUDGET = Duration.ofMillis(500); + private static final int SLOW_RESOLVER_MILLIS = 2_000; + + @LocalServerPort int port; + + @Autowired TestRestTemplate http; + + @BeforeEach + void warmUpAndReset() { + RuntimeLimitsTestSupport.post(http, port, "{ _health }"); + SlowWork.reset(); + } + + @Test + @DisplayName("요청 스레드에서 도는 blocking resolver 는 끝난 뒤에 REQUEST_TIMEOUT 이 나가고 하위 필드는 실행되지 않는다") + void aBlockingResolverOnTheRequestThreadDelaysTheTimeoutAnswerUntilItReturns() { + // given + long started = System.nanoTime(); + + // when + ResponseEntity response = + RuntimeLimitsTestSupport.post( + http, port, "{ slowNode(millis: " + SLOW_RESOLVER_MILLIS + ") { id detail } }"); + + // then + long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started); + assertThat(response.getBody()) + .contains("\"code\":\"REQUEST_TIMEOUT\"") + .doesNotContain("detail-of-"); + assertThat(SlowWork.DETAIL_INVOCATIONS) + .as("the cancelled execution stops before the child field") + .hasValue(0); + assertThat(elapsedMillis) + .as("the servlet thread was inside the resolver; the answer could not leave earlier") + .isGreaterThanOrEqualTo(SLOW_RESOLVER_MILLIS); + } + + @SpringBootConfiguration + @EnableAutoConfiguration + @Import({RuntimeLimitsTestSupport.Transport.class, RuntimeLimitsTestSupport.SlowController.class}) + static class TestApplication { + + @Bean + GraphQlClientPolicy shortBudgetClientPolicy() { + return RuntimeLimitsTestSupport.policyWithExecutionBudget(BUDGET); + } + } +} diff --git a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineTest.java b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineTest.java new file mode 100644 index 00000000..6bf15a36 --- /dev/null +++ b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestDeadlineTest.java @@ -0,0 +1,118 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; +import dev.caskeleton.adapter.inbound.graphql.runtime.RuntimeLimitsTestSupport.SlowWork; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.resttestclient.TestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.http.ResponseEntity; + +/** + * The request budget ({@code GraphQlClientPolicy.maxExecutionTime}) is enforced while the request + * runs, not only checked before it starts (review 03-02). + * + *

      Runs with virtual threads on, which is the template's default ({@code + * SPRING_THREADS_VIRTUAL_ENABLED:true}): Spring for GraphQL then invokes a blocking controller + * method on the application executor, the servlet thread is free, and the answer can leave at the + * deadline. {@link GraphQlRequestDeadlineOnRequestThreadTest} pins what happens when it cannot. + */ +@SpringBootTest( + classes = GraphQlRequestDeadlineTest.TestApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { + "app.graphql.enabled=true", + "app.graphql.deployment-mode=LOCAL", + "spring.graphql.graphiql.enabled=false", + "spring.threads.virtual.enabled=true", + RuntimeLimitsTestSupport.SCHEMA_LOCATIONS, + RuntimeLimitsTestSupport.SCHEMA_FILES + }) +@AutoConfigureTestRestTemplate +class GraphQlRequestDeadlineTest { + + private static final Duration BUDGET = Duration.ofSeconds(1); + private static final int SLOW_RESOLVER_MILLIS = 4_000; + + @LocalServerPort int port; + + @Autowired TestRestTemplate http; + + @BeforeEach + void warmUpAndReset() { + // The first request pays for class loading and parsing; it must not eat the budget under test. + RuntimeLimitsTestSupport.post(http, port, "{ _health }"); + SlowWork.reset(); + } + + @Test + @DisplayName("deadline 이 지나도 resolver 가 끝나지 않으면 deadline 근처에서 REQUEST_TIMEOUT 으로 응답한다") + void aResolverStillRunningAtTheDeadlineIsAnsweredWithRequestTimeoutNearTheDeadline() { + // given + long started = System.nanoTime(); + + // when + ResponseEntity response = + RuntimeLimitsTestSupport.post( + http, port, "{ slowNode(millis: " + SLOW_RESOLVER_MILLIS + ") { id detail } }"); + + // then + long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started); + assertThat(response.getBody()) + .contains("\"code\":\"REQUEST_TIMEOUT\"") + .contains("\"category\":\"TIMEOUT\"") + .doesNotContain("detail-of-"); + assertThat(SlowWork.SLOW_STARTED) + .as("the budget must have run out during execution, not before it") + .hasValue(1); + assertThat(elapsedMillis) + .as("answered at the deadline, not when the %d ms resolver returned", SLOW_RESOLVER_MILLIS) + .isGreaterThanOrEqualTo(BUDGET.toMillis()) + .isLessThan(SLOW_RESOLVER_MILLIS - 1_000L); + } + + @Test + @DisplayName("deadline 응답 뒤에는 느린 resolver 가 끝나도 그 아래 필드를 더 실행하지 않는다") + void noChildFieldStartsAfterTheDeadlineAnswerHasGone() throws InterruptedException { + // given + RuntimeLimitsTestSupport.post( + http, port, "{ slowNode(millis: " + SLOW_RESOLVER_MILLIS + ") { id detail } }"); + + // when + boolean finished = + SlowWork.slowFinished.await(SLOW_RESOLVER_MILLIS * 2L, TimeUnit.MILLISECONDS); + + // then + assertThat(finished) + .as("the running resolver is not interrupted; it finishes on its own thread") + .isTrue(); + // Room for graphql-java to have dispatched the child, had the cancellation not stopped it. + Thread.sleep(500); + assertThat(SlowWork.DETAIL_INVOCATIONS) + .as("a cancelled execution must not start new fields once the client has been answered") + .hasValue(0); + } + + @SpringBootConfiguration + @EnableAutoConfiguration + @Import({RuntimeLimitsTestSupport.Transport.class, RuntimeLimitsTestSupport.SlowController.class}) + static class TestApplication { + + @Bean + GraphQlClientPolicy shortBudgetClientPolicy() { + return RuntimeLimitsTestSupport.policyWithExecutionBudget(BUDGET); + } + } +} diff --git a/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/RuntimeLimitsTestSupport.java b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/RuntimeLimitsTestSupport.java new file mode 100644 index 00000000..cc8529d2 --- /dev/null +++ b/src/adapter/inbound/graphql/src/systemTest/java/dev/caskeleton/adapter/inbound/graphql/runtime/RuntimeLimitsTestSupport.java @@ -0,0 +1,146 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import dev.caskeleton.adapter.inbound.graphql.HealthGraphqlController; +import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; +import java.net.URI; +import java.time.Duration; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; +import org.springframework.boot.graphql.autoconfigure.GraphQlSourceBuilderCustomizer; +import org.springframework.boot.resttestclient.TestRestTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.graphql.data.method.annotation.Argument; +import org.springframework.graphql.data.method.annotation.QueryMapping; +import org.springframework.graphql.data.method.annotation.SchemaMapping; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; +import org.springframework.stereotype.Controller; + +/** + * What the runtime-limit evidence tests share: the transport fixture and the slow resolver. + * + *

      The request deadline (review 03-02) and the per-parent fetch signal (review 03-03) are both + * properties of a running request, so both are measured over the real {@code /graphql} endpoint + * rather than against a policy object. + */ +final class RuntimeLimitsTestSupport { + + /** Schema properties every runtime-limit test boots with. */ + static final String SCHEMA_LOCATIONS = + "spring.graphql.schema.locations=classpath:graphql-runtime-limits-no-discovery/"; + + static final String SCHEMA_FILES = + "spring.graphql.schema.additional-files=" + + "classpath:graphql/skeleton.graphqls," + + "classpath:graphql-runtime-limits/runtime-limits.graphqls"; + + private RuntimeLimitsTestSupport() {} + + /** + * A client policy whose only difference from the platform default is the execution budget. + * + *

      A short budget instead of an injected clock: what is under test is a timer firing while a + * resolver is still running, and only real time can be in the middle of that. + */ + static GraphQlClientPolicy policyWithExecutionBudget(Duration maxExecutionTime) { + GraphQlClientPolicy defaults = GraphQlClientPolicy.defaults(100, 10_000, false); + return new GraphQlClientPolicy( + defaults.maxDocumentBytes(), + defaults.maxVariablesBytes(), + defaults.maxDepth(), + defaults.maxFields(), + defaults.maxAliases(), + defaults.maxFragments(), + defaults.maxInputListElements(), + defaults.defaultPageSize(), + defaults.maxPageSize(), + defaults.maxComplexity(), + maxExecutionTime, + defaults.introspectionAllowed(), + defaults.namedOperationRequired()); + } + + static ResponseEntity post(TestRestTemplate http, int port, String document) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + String body = "{\"query\":\"" + document.replace("\"", "\\\"") + "\"}"; + return http.exchange( + new RequestEntity<>( + body, headers, HttpMethod.POST, URI.create("http://localhost:" + port + "/graphql")), + String.class); + } + + /** Counts the slow resolver and the child that must not start after the answer has gone. */ + static final class SlowWork { + + static final AtomicInteger SLOW_STARTED = new AtomicInteger(); + static final AtomicInteger DETAIL_INVOCATIONS = new AtomicInteger(); + static volatile CountDownLatch slowFinished = new CountDownLatch(1); + + private SlowWork() {} + + static void reset() { + SLOW_STARTED.set(0); + DETAIL_INVOCATIONS.set(0); + slowFinished = new CountDownLatch(1); + } + } + + record SlowNode(String id) {} + + /** A resolver that is still working when the request budget runs out. */ + @Controller + static class SlowController { + + @QueryMapping + SlowNode slowNode(@Argument int millis) throws InterruptedException { + SlowWork.SLOW_STARTED.incrementAndGet(); + try { + Thread.sleep(millis); + } finally { + SlowWork.slowFinished.countDown(); + } + return new SlowNode("slow-1"); + } + + @SchemaMapping(typeName = "SlowNode", field = "detail") + String detail(SlowNode node) { + SlowWork.DETAIL_INVOCATIONS.incrementAndGet(); + return "detail-of-" + node.id(); + } + } + + /** The transport fixture: the schema source switched on and every request let through. */ + @Configuration(proxyBeanMethods = false) + @Import(HealthGraphqlController.class) + static class Transport { + + /** Boot's schema condition does not inspect additional-files; this activates the source. */ + @Bean + GraphQlSourceBuilderCustomizer runtimeLimitsSchemaActivation() { + return builder -> {}; + } + + /** + * Lets every request through to the GraphQL endpoint, exempting only that endpoint from CSRF + * (see {@code GraphQlPlatformExecutionPathTest} for why this is not a deployment-wide disable). + */ + @Bean + SecurityFilterChain runtimeLimitsSecurityFilterChain(HttpSecurity http) throws Exception { + return http.csrf( + csrf -> + csrf.ignoringRequestMatchers( + PathPatternRequestMatcher.withDefaults().matcher("/graphql"))) + .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()) + .build(); + } + } +} diff --git a/src/adapter/inbound/graphql/src/systemTest/resources/graphql-runtime-limits/runtime-limits.graphqls b/src/adapter/inbound/graphql/src/systemTest/resources/graphql-runtime-limits/runtime-limits.graphqls new file mode 100644 index 00000000..30bd322f --- /dev/null +++ b/src/adapter/inbound/graphql/src/systemTest/resources/graphql-runtime-limits/runtime-limits.graphqls @@ -0,0 +1,28 @@ +# Schema for the runtime-limit evidence tests: the request deadline (review 03-02) and the +# per-parent fetch signal (review 03-03). +# +# `slowNode` sleeps on purpose so the deadline has something to cut, and its `detail` child is the +# work that must not start once the request has been answered. `orders` is a list parent with two +# children that resolve the same data two ways: `customerPerParent` with a plain @SchemaMapping — +# one downstream call per order — and `customer` through GraphQlBatchLoaderRegistrar. + +extend type Query { + slowNode(millis: Int!): SlowNode + orders(count: Int!): [Order!]! +} + +type SlowNode { + id: ID! + detail: String +} + +type Order { + id: ID! + customer: Customer + customerPerParent: Customer +} + +type Customer { + id: ID! + name: String! +} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidatorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidatorTest.java index 2475a666..c7cac1d1 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidatorTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidatorTest.java @@ -33,7 +33,8 @@ class GraphQlPlatformStartupValidatorTest { GraphQlPlatformSettings.productionDefaults() .withGraphiqlEnabled(true) .withLimits( - new GraphQlPlatformSettings.Limits(0, 0, 1, 1, java.time.Duration.ofMinutes(1))); + new GraphQlPlatformSettings.Limits( + 0, 0, 1, 1, java.time.Duration.ofMinutes(1), 10)); assertThat(new GraphQlPlatformStartupValidator().problems(properties)).hasSize(3); } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderRequestRegistryTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderFactoryTest.java similarity index 80% rename from src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderRequestRegistryTest.java rename to src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderFactoryTest.java index 52c9588c..a99a79a4 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderRequestRegistryTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/dataloader/GraphQlDataLoaderFactoryTest.java @@ -6,18 +6,15 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.inbound.graphql.testkit.GraphQlRequestContexts; import java.time.Clock; import java.time.Duration; -import java.util.function.Supplier; import org.junit.jupiter.api.Test; -/** Request-scoped DataLoader policy and registry (Stable plan Task 36). */ -class GraphQlDataLoaderRequestRegistryTest { - - @Test - void createsDifferentRegistryForEachExecution() { - Supplier factory = GraphQlDataLoaderRequestRegistry::new; - - assertThat(factory.get()).isNotSameAs(factory.get()); - } +/** + * DataLoader policy registry and factory (Stable plan Task 36). + * + *

      The per-execution request scope is Spring's {@code DataLoaderRegistry}, exercised end to end + * by {@code GraphQlBatchLoaderRegistrationTest.oneRequestsCacheIsNotHandedToTheNext}. + */ +class GraphQlDataLoaderFactoryTest { @Test void loaderNamesMustBeRegisteredInTheBoundedCatalog() { @@ -59,16 +56,6 @@ class GraphQlDataLoaderRequestRegistryTest { .hasMessageContaining("downstream limit"); } - @Test - void loadersAndTheirCachesDoNotOutliveTheExecution() { - var registry = new GraphQlDataLoaderRequestRegistry(); - registry.register(new GraphQlDataLoaderName("order.customer"), new Object()); - - assertThat(registry.isEmpty()).isFalse(); - registry.clear(); - assertThat(registry.isEmpty()).isTrue(); - } - @Test void keysAreNeverSharedBetweenExecutionsWithDifferentActorsOrTenants() { var factory = @@ -81,7 +68,6 @@ class GraphQlDataLoaderRequestRegistryTest { var tenantB = factory.batchContext(GraphQlRequestContexts.testContext("tenant-b")); assertThat(tenantA.cacheScope()).isNotEqualTo(tenantB.cacheScope()); - assertThat(factory.newRequestRegistry()).isNotSameAs(factory.newRequestRegistry()); } @Test diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java index 6106ac37..3a39c97d 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException; +import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; @@ -16,12 +17,13 @@ class GraphQlWireErrorMapperTest { return Stream.of( Arguments.of( new GraphQlBatchTimeoutException("customer-by-id"), "REQUEST_TIMEOUT", "TIMEOUT"), + Arguments.of(new GraphQlRequestCancelledException(), "REQUEST_TIMEOUT", "TIMEOUT"), Arguments.of(new GraphQlMissingKeyException(), "GRAPHQL_BATCH_KEY_MISSING", "BUSINESS")); } @ParameterizedTest @MethodSource("dataLoaderFailures") - @DisplayName("DataLoader 의 timeout·missing key 는 INTERNAL_ERROR 로 가려지지 않고 플랫폼 code 로 나간다") + @DisplayName("요청·DataLoader 의 timeout·missing key 는 INTERNAL_ERROR 로 가려지지 않고 플랫폼 code 로 나간다") void dataLoaderFailuresKeepAPlatformCode( RuntimeException failure, String expectedCode, String expectedCategory) { // given diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicyTest.java deleted file mode 100644 index 5a5cfefb..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicyTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import org.junit.jupiter.api.Test; - -/** Layered timeout, resolver budget and cancellation contract (Stable plan Task 22). */ -class GraphQlTimeoutPolicyTest { - - @Test - void childBudgetCannotExceedParent() { - GraphQlTimeoutPolicy policy = new GraphQlTimeoutPolicy(Duration.ofSeconds(2)); - - assertThat(policy.child(Duration.ofSeconds(5))).isEqualTo(Duration.ofSeconds(2)); - assertThat(policy.child(Duration.ofSeconds(1))).isEqualTo(Duration.ofSeconds(1)); - } - - @Test - void budgetsNarrowMonotonicallyDownTheChain() { - GraphQlTimeoutPolicy request = new GraphQlTimeoutPolicy(Duration.ofSeconds(5)); - GraphQlTimeoutPolicy resolver = request.childPolicy(Duration.ofSeconds(3)); - GraphQlTimeoutPolicy database = resolver.childPolicy(Duration.ofSeconds(10)); - - assertThat(resolver.remaining()).isEqualTo(Duration.ofSeconds(3)); - assertThat(database.remaining()).isEqualTo(Duration.ofSeconds(3)); - } - - @Test - void anExhaustedBudgetCannotBecomeAPolicy() { - assertThatThrownBy(() -> new GraphQlTimeoutPolicy(Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GraphQlTimeoutPolicy(Duration.ofSeconds(-1))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void executionTimeoutMapsToAStableErrorCode() { - assertThat(GraphQlTimeoutPolicy.TIMEOUT_ERROR_CODE).isEqualTo("REQUEST_TIMEOUT"); - assertThat(new GraphQlRequestCancelledException().code()).isEqualTo("REQUEST_TIMEOUT"); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlBatchLoaderRegistrationTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlBatchLoaderRegistrationTest.java index 0e92fc7a..f25ec247 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlBatchLoaderRegistrationTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlBatchLoaderRegistrationTest.java @@ -2,6 +2,10 @@ package dev.caskeleton.adapter.inbound.graphql.runtime; import static org.assertj.core.api.Assertions.assertThat; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.adapter.inbound.graphql.context.GraphQlDeadline; import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchContext; @@ -11,6 +15,7 @@ import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicyRegis import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyPolicy; +import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper; import dev.caskeleton.adapter.inbound.graphql.testkit.GraphQlRequestContexts; import graphql.ExecutionInput; import graphql.ExecutionResult; @@ -33,7 +38,10 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.dataloader.DataLoaderRegistry; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.graphql.execution.DataFetcherExceptionResolver; import org.springframework.graphql.execution.DefaultBatchLoaderRegistry; /** @@ -134,6 +142,44 @@ class GraphQlBatchLoaderRegistrationTest { assertThat(downstream.calls).hasValue(0); } + @Test + @DisplayName("플랫폼 context 없이 불린 batch 는 시간 초과가 아니라 INTERNAL_ERROR 조립 오류로 나가고 WARN 한 줄을 남긴다") + void aLoaderWithoutThePlatformContextIsReportedAsAWiringFaultNotATimeout() { + // given + RecordingLoader downstream = new RecordingLoader(); + Fixture fixture = fixture(chunkSize(20), Clock.systemUTC()); + Logger logger = (Logger) LoggerFactory.getLogger(GraphQlBatchLoaderRegistrar.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + + // when + ExecutionResult result; + try { + result = fixture.executeWithoutRequestContext(orders(5, 5), downstream); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + + // then + assertThat(result.getErrors()) + .isNotEmpty() + .allSatisfy( + error -> + assertThat(error.getExtensions()) + .containsEntry("code", "INTERNAL_ERROR") + .containsEntry("category", "INTERNAL") + .containsEntry("constraint", "PLATFORM_CONTEXT")); + assertThat(appender.list) + .singleElement() + .extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage) + .containsExactly( + Level.WARN, + "graphql batch rejected: no platform context (loader=customer-by-id);" + + " the platform transport interceptor is not wired"); + } + @Test void aBatchThatOverrunsTheRequestBudgetStopsAtTheChunkThatSpentIt() { MutableClock clock = new MutableClock(Instant.parse("2026-08-14T00:00:00Z")); @@ -328,7 +374,14 @@ class GraphQlBatchLoaderRegistrationTest { DataLoaderRegistry dataLoaders = new DataLoaderRegistry(); batchLoaders.registerDataLoaders(dataLoaders, input.getGraphQLContext()); + // Spring's exception handling over the platform mapper, so a failure reaches the result as + // the + // wire error a client would see rather than as graphql-java's raw exception. return GraphQL.newGraphQL(schema(orders)) + .defaultDataFetcherExceptionHandler( + DataFetcherExceptionResolver.createExceptionHandler( + List.of( + new GraphQlDataFetcherExceptionResolver(GraphQlWireErrorMapper.masking())))) .build() .execute(input.transform(builder -> builder.dataLoaderRegistry(dataLoaders))); } diff --git a/src/adapter/inbound/grpc/CLAUDE.md b/src/adapter/inbound/grpc/CLAUDE.md index 4e27f052..4f431f17 100644 --- a/src/adapter/inbound/grpc/CLAUDE.md +++ b/src/adapter/inbound/grpc/CLAUDE.md @@ -52,8 +52,19 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`. | `bindAddress` | `127.0.0.1` | P1 insecure listener 바인드. loopback 주소만 허용한다 | | `allowInsecureLocal` | `false` | local plaintext 위험을 명시적으로 승인하는 개발용 override | | `reflectionEnabled` | `false` | v1 server reflection 노출을 독립적으로 opt-in 한다 | -| `shutdownGraceSeconds` | `5` | graceful shutdown 시 in-flight RPC 대기 초(0 이상) | +| `shutdownGraceSeconds` | `5` | graceful shutdown 전체 예산(초, 0 이상). drain 대기를 포함한다 | +| `shutdownDrainSeconds` | `2` | health NOT_SERVING 뒤 listener 를 열어 둔 채 기다리는 초. `shutdownGraceSeconds` 이하 | +| `maxInboundMessageBytes` | `1048576` | 요청 메시지 상한. 넘으면 `RESOURCE_EXHAUSTED` (플랫폼 `GrpcTransportLimits`와 같은 값) | +| `maxInboundMetadataBytes` | `8192` | 호출당 metadata 상한 (플랫폼과 같은 값) | +| `maxConcurrentCallsPerConnection` | `100` | 연결당 동시 호출(HTTP/2 stream) 상한. 넘친 호출은 클라이언트에서 기다린다 | +| `executorMaxPoolSize` | `32` | feature 호출을 실행하는 고정 스레드 수 (플랫폼 executor 기본값) | +| `executorQueueCapacity` | `256` | 스레드를 기다릴 수 있는 호출 수(1..10000). 넘친 호출은 즉시 `RESOURCE_EXHAUSTED` | +| `defaultDeadline` | `10s` | deadline 없는(또는 더 긴) feature 호출의 서버 deadline. 넘으면 `DEADLINE_EXCEEDED` | +| `keepAliveTime` / `keepAliveTimeout` | `30s` / `10s` | 서버 keep-alive ping 간격 / 응답 대기 (플랫폼 `GrpcServerProfile.stable`) | +| `permitKeepAliveTime` | `30s` | 클라이언트 ping 최소 간격. `keepAliveTime` 이하 | +| `maxConnectionAge` / `maxConnectionAgeGrace` | `30m` / `30s` | 연결 수명과 GOAWAY 뒤 유예 | +한도 값의 근거·플랫폼과의 대응·포화 동작은 [README.md](README.md) 「서버 한도」 절이 소유한다. `port`는 0..65535 범위여야 한다. 현재 transport credential은 plaintext뿐이므로 `enabled=true`는 `allowInsecureLocal=true`와 실제 loopback `bindAddress`가 함께 없으면 configuration binding/startup 단계에서 실패한다. @@ -93,9 +104,10 @@ listener 시작이 실패한다. 정책은 `Optional authenticate(Met - `GrpcSafeActivationTest`: 기본 비활성, 관련 빈 부재, 설정 검증, feature 인증 정책 필수 조건. - `GrpcP1BoundaryWireTest`: 실제 loopback ephemeral Netty unary service의 auth 성공/실패, reflection-off, handler/listener/observer/raw-status 오류 sanitization과 sentinel redaction. + 서버 한도(메시지 크기, 기본 deadline, 연결당 동시 호출, executor 포화)도 같은 wire 에서 검증한다. 이 증거는 local insecure unary qualification일 뿐 production-ready 근거가 아니다. TLS/mTLS, -external bind, deadline, streaming/backpressure, generated protobuf 호환성은 P2로 남아 있다. +external bind, 메서드별 deadline, streaming/backpressure, generated protobuf 호환성은 P2로 남아 있다. ## Test diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index fe5e311e..9c45f9fd 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -26,7 +26,8 @@ - 필요한 설정: 전용 `APP_*` env 키는 registry에 없다. 켜진 상태에서 지금 구현이 받는 listener는 loopback plaintext뿐이라 `app.grpc.server.allow-insecure-local=true`(env `APP_GRPC_SERVER_ALLOW_INSECURE_LOCAL=true`)를 명시해야 기동한다. 선택: `app.grpc.server.port` - (기본 9090), `.bind-address`(기본 127.0.0.1), `.reflection-enabled`, `.shutdown-grace-seconds`. + (기본 9090), `.bind-address`(기본 127.0.0.1), `.reflection-enabled`, `.shutdown-grace-seconds`, + `.shutdown-drain-seconds`, 그리고 아래 「서버 한도」 절의 전송 한도 키. ## 왜 self-managed Netty 인가 @@ -37,9 +38,14 @@ - **`getPhase()` = `Integer.MAX_VALUE - 1`.** web 서버가 뜬 **뒤에** 시작하고 종료 시 web 서버 **전에** 멈춘다(SmartLifecycle: 높은 phase 가 늦게 시작·먼저 종료). gRPC 는 web 과 별개의 TCP 포트를 소유하는 부가 전송이므로 애플리케이션 수명주기 맨 바깥에 둔다. -- **graceful shutdown.** `shutdownGraceSeconds` 동안 in-flight RPC 를 기다린 뒤 - `shutdownNow()`. 종료 진입 시 health 를 `enterTerminalState()`(NOT_SERVING)로 뒤집어 - 로드밸런서가 드레이닝을 인지하게 한다. +- **graceful shutdown.** 종료 진입 시 health 를 `enterTerminalState()`(NOT_SERVING)로 뒤집고, + listener 를 연 채로 `shutdownDrainSeconds`(기본 2초) 기다린 뒤 `shutdown()` → 남은 grace + (`shutdownGraceSeconds - shutdownDrainSeconds`) 동안 `awaitTermination` → `shutdownNow()` 순서로 + 닫는다. NOT_SERVING 과 listener 닫기를 같은 순간에 하면 health 확인이 UNAVAILABLE 로 끝나 + 로드밸런서가 드레이닝과 장애를 구분하지 못한다. drain 은 grace 예산 안에서 쓰며(drain > grace 는 + 기동 실패), `Health/Watch` 구독자는 즉시 알림을 받으므로 2초면 충분하다. 주기가 더 긴 poll 방식 + probe 는 이 값으로 기다릴 수 없으니 `preStop` 지연으로 맞춘다. 끝나면 call/dispatch executor 와 + deadline scheduler 도 `shutdownNow()` 한다. - **fail-closed local insecure bind.** 모듈이 있으면 서버가 켜지지만 reflection은 비활성이다. 현재 구현의 plaintext credential은 `allowInsecureLocal=true`를 명시하고 실제 loopback 주소에 바인딩할 때만 허용한다. wildcard/외부 주소의 insecure 시작은 실패한다. @@ -48,6 +54,62 @@ 만들 수 없다. 그런 cluster-facing 노출은 TLS/mTLS credential 경로와 non-loopback qualification이 추가된 뒤의 범위다. +## 서버 한도 — io.grpc 기본값을 쓰지 않는다 (리뷰 03-09) + +io.grpc 기본값은 메시지 4 MiB, 연결당 동시 호출 무제한, 호출마다 스레드를 늘리는 cached +executor, 서버 deadline 없음, 연결 수명 무제한이다. 어댑터 서버는 이 값을 모두 명시한다. + +| 키 (`app.grpc.server.*`) | 기본값 | 같은 값의 출처 (vendored 플랫폼) | +|---|---|---| +| `max-inbound-message-bytes` | 1048576 (1 MiB) | `GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES` | +| `max-inbound-metadata-bytes` | 8192 (8 KiB) | `GrpcTransportLimits.DEFAULT_MAX_METADATA_BYTES` | +| `executor-max-pool-size` | 32 | `GrpcPlatformProperties.executorMaxPoolSize` | +| `executor-queue-capacity` | 256 (최대 10000) | `GrpcPlatformProperties.executorQueueCapacity`, 상한은 `GrpcExecutorProfile` | +| `keep-alive-time` / `keep-alive-timeout` | 30s / 10s | `GrpcServerProfile.stable(..)` | +| `permit-keep-alive-time` | 30s | `GrpcServerProfile.stable(..)` | +| `max-connection-age` / `max-connection-age-grace` | 30m / 30s | `GrpcServerProfile.stable(..)` | +| `max-concurrent-calls-per-connection` | 100 | 플랫폼에 없음. RFC 9113 §6.5.2 가 권하는 `MAX_CONCURRENT_STREAMS` 하한 | +| `default-deadline` | 10s | 플랫폼은 메서드별 `GrpcDeadlineProfile` 만 있다. GraphQL 어댑터의 요청 예산 10초와 맞춤 | + +- **값이 두 곳에 있는 이유.** 03-09 는 (a) 어댑터가 같은 이름·값을 자기 설정으로 노출, (b) + 어댑터가 플랫폼 `GrpcServerProfile` 을 받음(registry edge 추가), (c) 현상 유지 중 (a)를 골랐다. + 두 스택 분리(X1-#10)를 건드리지 않기 위해서다. 어댑터는 플랫폼 타입을 import 할 수 없어(registry + edge 없음, 플랫폼은 `optional-platforms` 별도 빌드) 상수를 직접 비교하는 테스트는 만들 수 없다. + 대신 `GrpcSafeActivationTest.transportBoundDefaultsMatchTheVendoredPlatformDefaults` 가 위 표의 + 플랫폼 값을 literal 로 고정한다. 플랫폼 값을 바꾸면 이 표와 그 테스트를 같이 바꾼다. +- **duration 순서 검증.** `keep-alive-timeout < keep-alive-time`, `permit-keep-alive-time <= + keep-alive-time`, `max-connection-age-grace <= max-connection-age`, 모든 duration 양수 — + `GrpcServerProfile` 생성자가 거절하는 조합을 바인딩 단계에서 똑같이 거절한다. +- **keep-alive·connection age 를 loopback 에서도 켜는 이유.** 지금 listener 는 loopback 전용이라 + 중간 장비가 idle 연결을 끊는 일은 없다. 그래도 플랫폼과 같은 값을 둬서 non-loopback bind(P2)를 + 열 때 따로 정할 값이 남지 않게 했다. loopback 에서의 효과는 멈춘 클라이언트 연결을 30분에 + 정리하는 것뿐이다. +- **기본 deadline(`GrpcServerDeadlineInterceptor`).** 클라이언트가 deadline 없이 부른 feature + 호출은 `default-deadline` 에서 `DEADLINE_EXCEEDED` 로 끝난다. 클라이언트 deadline 이 더 짧으면 + 그대로 두고(io.grpc 가 집행), 더 길면 서버 값으로 줄인다. derived `Context` 를 취소해도 io.grpc 는 + 스트림을 닫지 않으므로 인터셉터가 직접 닫고, 그 close 가 handler 의 쓰기와 겹치지 않게 call 을 + 직렬화한다. handler 는 `Context.current().isCancelled()` 로 만료를 본다. 확인하지 않는 handler 는 + 반환할 때까지 스레드를 잡는다 — deadline 이 풀어 주는 것은 호출자이지 스레드가 아니다. 상태에는 + code/category trailer 를 붙이지 않는다(io.grpc 의 클라이언트 deadline 만료와 같은 모양). + health/reflection 에는 적용하지 않는다(`Health/Watch` 는 원래 오래 사는 스트림이다). +- **포화 시 동작(`GrpcCallAdmission`).** feature 호출은 `executor-max-pool-size + + executor-queue-capacity` 개까지만 받고, 넘친 호출은 handler 를 시작하지 않고 즉시 + `RESOURCE_EXHAUSTED`(`RATE_LIMIT_EXCEEDED`, retryable)로 닫는다. 구현: io.grpc + `ServerCallExecutorSupplier`(`@ExperimentalApi`, 1.39부터)가 호출 시작 전에 permit 을 확인해 + 받은 호출만 고정 크기 work pool 로 옮기고, 못 받은 호출은 가장 바깥 인터셉터가 닫는다. 메서드 + 조회·context 정리·health·reflection 은 작은 dispatch pool 에서 돈다. 버린 대안: + - bounded `ThreadPoolExecutor` + `AbortPolicy` 만 두기 — 실행으로 확인한 결과 io.grpc 는 거절을 + Netty 스레드 로그로만 남기고 스트림을 열어 둔다. 클라이언트는 자기 deadline 까지(없으면 영원히) + 기다린다. + - caller-runs — handler 가 dispatch/Netty 스레드에서 돌아 같은 연결의 다른 호출을 모두 멈춘다. + - 큰(또는 무제한) 대기열 — 같은 실패를 모든 호출자의 deadline 뒤로 미룰 뿐이다. + - 플랫폼 `GrpcAdmissionController` 사용 — 03-09 (b)의 배선 결정이 필요하다. + + work pool 대기열은 permit 수만큼 깊다. io.grpc 는 한 호출의 콜백을 직렬화하므로 받아들인 호출은 + pool 에 많아야 작업 하나를 두고, 따라서 이 대기열은 차지 않는다(`AbortPolicy` 는 도달하지 않는 + 안전장치다). 대기열에서 기다린 시간은 서버 기본 deadline 에 들어가지 않는다 — 서버 deadline 은 + handler 가 시작될 때부터 잰다. 클라이언트 deadline 은 도착 시점부터 잰다. + ## 왜 `.proto` 도 protobuf 플러그인도 없는가 이 모듈은 protobuf 를 **하나도 컴파일하지 않는다** — `com.google.protobuf` 플러그인도, @@ -117,8 +179,12 @@ Spring Boot BOM은 `io.grpc:*`/protobuf 버전을 관리하지 않는다. 이 `GrpcSafeActivationTest`는 disabled bean/listener 부재와 설정/인증-policy fail-closed를 검증한다. `GrpcP1BoundaryWireTest`는 실제 loopback ephemeral Netty unary service로 auth 성공/실패, -reflection-off, 모든 오류 경로의 안정 code/category 및 sentinel redaction을 검증한다. +reflection-off, 모든 오류 경로의 안정 code/category 및 sentinel redaction을 검증한다. 서버 한도도 +같은 wire 에서 검증한다: 1 MiB 초과 요청 `RESOURCE_EXHAUSTED`(정확히 1 MiB 는 통과), deadline 없는 +느린 호출의 서버 기본 deadline `DEADLINE_EXCEEDED`, 더 짧은 클라이언트 deadline 유지, 연결당 동시 +호출 상한, executor·대기열 포화 시 즉시 `RESOURCE_EXHAUSTED`. `GrpcServerRunnerBootTest`는 종료 +drain 동안 listener 가 살아서 health NOT_SERVING 을 답하는지 검증한다. 이는 local plaintext unary 경계에 대한 P1 증거이며 production-ready 주장 근거가 아니다. -TLS/mTLS, external bind, deadline, streaming/backpressure, generated protobuf 호환성은 P2에서 별도 -설계·검증해야 한다. +TLS/mTLS, external bind, 메서드별 deadline(지금은 서버 전체 기본값 하나), streaming/backpressure, +generated protobuf 호환성은 P2에서 별도 설계·검증해야 한다. diff --git a/src/adapter/inbound/grpc/build.gradle b/src/adapter/inbound/grpc/build.gradle index 888f5b6e..55f3dcc5 100644 --- a/src/adapter/inbound/grpc/build.gradle +++ b/src/adapter/inbound/grpc/build.gradle @@ -51,6 +51,5 @@ strictTestLanes { requires 'dev.caskeleton.adapter.inbound.grpc.GrpcSafeActivationTest', 'dev.caskeleton.adapter.inbound.grpc.GrpcP1BoundaryWireTest' rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' } } diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java new file mode 100644 index 00000000..1a8c8b77 --- /dev/null +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcCallAdmission.java @@ -0,0 +1,120 @@ +package dev.caskeleton.adapter.inbound.grpc; + +import dev.caskeleton.shared.error.OperationalError; +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallExecutorSupplier; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; +import java.util.concurrent.Executor; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Bounds how many feature calls the server holds, and refuses the rest with {@code + * RESOURCE_EXHAUSTED} (review 03-09). + * + *

      Why not just a bounded executor: when a bounded {@code ThreadPoolExecutor} rejects, io.grpc + * does not answer the call. The rejection is logged on the Netty thread and the stream stays open + * until the client's own deadline — forever for a client that set none. Admission therefore has to + * be decided before the call reaches the bounded pool, and the refusal has to be an ordinary call + * close. + * + *

      How: io.grpc asks this {@link ServerCallExecutorSupplier} for each found method, on the + * dispatch executor, before the call starts. A feature call that gets a permit is moved to the + * bounded work pool; one that does not stays on the dispatch executor and is marked, and this same + * object, installed as the outermost feature interceptor, closes the marked call with {@code + * RATE_LIMIT_EXCEEDED} without starting the handler. The permit is returned once, when the admitted + * call completes or is cancelled. Health and reflection are not feature calls: they take no permit + * and run on the dispatch executor, so a saturated pool cannot make health lie. + * + *

      Each admitted call has at most one task in the work pool at a time (io.grpc serializes a + * call's callbacks), so a work queue as deep as the permit count can never reject. + * + *

      {@code ServerCallExecutorSupplier} is an io.grpc {@code @ExperimentalApi} (stable since 1.39). + * The alternative that avoids it is the platform's {@code GrpcAdmissionController}, which the + * adapter cannot reach without the separate wiring decision (review 03-09 option b). + */ +final class GrpcCallAdmission implements ServerCallExecutorSupplier, ServerInterceptor { + + private final Set featureServiceNames; + private final Semaphore permits; + private final Executor workExecutor; + private final GrpcStatusMapper statusMapper; + private final Set refused = + Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>())); + + GrpcCallAdmission( + Set featureServiceNames, + int maxAdmittedCalls, + Executor workExecutor, + GrpcStatusMapper statusMapper) { + if (maxAdmittedCalls < 1) { + throw new IllegalArgumentException("admission needs at least one permit"); + } + this.featureServiceNames = Set.copyOf(featureServiceNames); + this.permits = new Semaphore(maxAdmittedCalls); + this.workExecutor = workExecutor; + this.statusMapper = statusMapper; + } + + @Override + public Executor getExecutor(ServerCall call, Metadata headers) { + if (!featureServiceNames.contains(call.getMethodDescriptor().getServiceName())) { + return null; + } + if (permits.tryAcquire()) { + return workExecutor; + } + refused.add(headers); + return null; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (refused.remove(headers)) { + call.close( + statusMapper.statusFor(OperationalError.RATE_LIMIT_EXCEEDED), + statusMapper.trailersFor(OperationalError.RATE_LIMIT_EXCEEDED)); + return new ServerCall.Listener<>() {}; + } + AtomicBoolean released = new AtomicBoolean(); + Runnable release = + () -> { + if (released.compareAndSet(false, true)) { + permits.release(); + } + }; + ServerCall.Listener delegate; + try { + delegate = next.startCall(call, headers); + } catch (RuntimeException | Error e) { + release.run(); + throw e; + } + return new SimpleForwardingServerCallListener<>(delegate) { + @Override + public void onComplete() { + try { + super.onComplete(); + } finally { + release.run(); + } + } + + @Override + public void onCancel() { + try { + super.onCancel(); + } finally { + release.run(); + } + } + }; + } +} diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerDeadlineInterceptor.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerDeadlineInterceptor.java new file mode 100644 index 00000000..3d136fe0 --- /dev/null +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerDeadlineInterceptor.java @@ -0,0 +1,145 @@ +package dev.caskeleton.adapter.inbound.grpc; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Deadline; +import io.grpc.ForwardingServerCall.SimpleForwardingServerCall; +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import java.time.Duration; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * Gives every feature call a server-side deadline (review 03-09). + * + *

      io.grpc enforces only the deadline the client sent. A client that sends none gets a call that + * may hold an executor thread forever. This interceptor bounds such a call at {@code + * app.grpc.server.default-deadline}. A client deadline that is already shorter is left alone — + * io.grpc enforces it and the server value would never fire; a longer one is capped, because the + * server value is the most this server will spend on one call. + * + *

      Cancelling a derived {@link Context} does not end the call by itself: io.grpc closes the + * stream only for the root context it created. So when the server deadline fires, this interceptor + * closes the call with {@code DEADLINE_EXCEEDED} itself. A {@link ServerCall} is not thread-safe + * and the deadline fires on the scheduler thread while the handler may still be writing, so the + * call handed inward is serialized and drops anything written after the close. + * + *

      The handler sees the expiry as a cancelled {@code Context.current()}; a handler that never + * checks it keeps its thread until it returns. The deadline frees the caller, not the thread. + * + *

      The status is plain {@code DEADLINE_EXCEEDED} without the code/category trailers, the same + * shape io.grpc gives a client-deadline expiry, so a client handles both the same way. + */ +final class GrpcServerDeadlineInterceptor implements ServerInterceptor { + + private final long defaultDeadlineNanos; + private final ScheduledExecutorService scheduler; + + GrpcServerDeadlineInterceptor(Duration defaultDeadline, ScheduledExecutorService scheduler) { + if (defaultDeadline == null || defaultDeadline.isZero() || defaultDeadline.isNegative()) { + throw new IllegalArgumentException("a server default deadline must be positive"); + } + this.defaultDeadlineNanos = defaultDeadline.toNanos(); + this.scheduler = scheduler; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Context current = Context.current(); + Deadline serverDeadline = Deadline.after(defaultDeadlineNanos, TimeUnit.NANOSECONDS); + Deadline clientDeadline = current.getDeadline(); + if (clientDeadline != null && !serverDeadline.isBefore(clientDeadline)) { + return next.startCall(call, headers); + } + + SerializedCall guarded = new SerializedCall<>(call); + Context.CancellableContext bounded = current.withDeadline(serverDeadline, scheduler); + bounded.addListener( + context -> { + if (context.cancellationCause() instanceof TimeoutException) { + guarded.closeOnDeadline(); + } + }, + Runnable::run); + ServerCall.Listener delegate = Contexts.interceptCall(bounded, guarded, headers, next); + return new SimpleForwardingServerCallListener<>(delegate) { + @Override + public void onComplete() { + try { + super.onComplete(); + } finally { + bounded.cancel(null); + } + } + + @Override + public void onCancel() { + try { + super.onCancel(); + } finally { + bounded.cancel(null); + } + } + }; + } + + /** Serializes writes so the deadline close cannot race the handler's own writes. */ + private static final class SerializedCall extends SimpleForwardingServerCall { + + private boolean closed; + + SerializedCall(ServerCall delegate) { + super(delegate); + } + + synchronized void closeOnDeadline() { + if (!closed) { + closed = true; + super.close( + Status.DEADLINE_EXCEEDED.withDescription("server default deadline exceeded"), + new Metadata()); + } + } + + @Override + public synchronized void request(int numMessages) { + if (!closed) { + super.request(numMessages); + } + } + + @Override + public synchronized void sendHeaders(Metadata headers) { + if (!closed) { + super.sendHeaders(headers); + } + } + + @Override + public synchronized void sendMessage(R message) { + if (!closed) { + super.sendMessage(message); + } + } + + @Override + public synchronized void close(Status status, Metadata trailers) { + if (!closed) { + closed = true; + super.close(status, trailers); + } + } + + @Override + public synchronized boolean isReady() { + return !closed && super.isReady(); + } + } +} diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java index 58fb8409..aedcd989 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java @@ -12,7 +12,15 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.net.InetSocketAddress; import java.util.List; +import java.util.Set; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.ObjectProvider; @@ -41,6 +49,9 @@ public class GrpcServerRunner implements SmartLifecycle { private final GrpcStatusMapper statusMapper; private final HealthStatusManager healthStatusManager; private volatile Server server; + private volatile ExecutorService dispatchExecutor; + private volatile ExecutorService workExecutor; + private volatile ScheduledExecutorService deadlineScheduler; public GrpcServerRunner( List services, @@ -72,19 +83,55 @@ public class GrpcServerRunner implements SmartLifecycle { policies.size() == 1 ? policies.getFirst() : null; var address = new InetSocketAddress(properties.resolvedBindAddress(), properties.getPort()); - var builder = NettyServerBuilder.forAddress(address, InsecureServerCredentials.create()); + int maxAdmittedCalls = + properties.getExecutorMaxPoolSize() + properties.getExecutorQueueCapacity(); + ExecutorService dispatch = dispatchExecutor(); + ExecutorService work = workExecutor(properties.getExecutorMaxPoolSize(), maxAdmittedCalls); + ScheduledExecutorService scheduler = + Executors.newSingleThreadScheduledExecutor(daemonThreads("grpc-server-deadline-")); + this.dispatchExecutor = dispatch; + this.workExecutor = work; + this.deadlineScheduler = scheduler; + var admission = + new GrpcCallAdmission( + featureServiceNames(featureServices), maxAdmittedCalls, work, statusMapper); + var builder = + NettyServerBuilder.forAddress(address, InsecureServerCredentials.create()) + .executor(dispatch) + .callExecutor(admission) + .maxInboundMessageSize(properties.getMaxInboundMessageBytes()) + .maxInboundMetadataSize(properties.getMaxInboundMetadataBytes()) + .maxConcurrentCallsPerConnection(properties.getMaxConcurrentCallsPerConnection()) + .keepAliveTime(properties.getKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS) + .keepAliveTimeout(properties.getKeepAliveTimeout().toNanos(), TimeUnit.NANOSECONDS) + .permitKeepAliveTime( + properties.getPermitKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS) + .maxConnectionAge(properties.getMaxConnectionAge().toNanos(), TimeUnit.NANOSECONDS) + .maxConnectionAgeGrace( + properties.getMaxConnectionAgeGrace().toNanos(), TimeUnit.NANOSECONDS); var authenticationInterceptor = authenticationPolicy == null ? null : new GrpcAuthenticationInterceptor(authenticationPolicy, statusMapper); - // Last, so outermost: the correlation is on MDC before authentication or error mapping logs. + // Correlation is outside authentication and error mapping, so it is on MDC before they log. var correlationInterceptor = new GrpcCorrelationInterceptor(); + // Outside the rest: every inner interceptor and the handler write through its serialized call, + // so the deadline close cannot race them. Health and reflection get no server deadline because + // Health/Watch is a long-lived stream by design. Admission is outermost, so a refused call + // starts nothing. + var deadlineInterceptor = + new GrpcServerDeadlineInterceptor(properties.getDefaultDeadline(), scheduler); int registered = 0; for (BindableService service : featureServices) { builder.addService( ServerInterceptors.intercept( - service, exceptionInterceptor, authenticationInterceptor, correlationInterceptor)); + service, + exceptionInterceptor, + authenticationInterceptor, + correlationInterceptor, + deadlineInterceptor, + admission)); registered++; } @@ -103,21 +150,76 @@ public class GrpcServerRunner implements SmartLifecycle { registered, properties.isReflectionEnabled()); } catch (IOException e) { + shutdownExecutors(); throw new UncheckedIOException( "failed to start gRPC server on port " + properties.getPort(), e); + } catch (RuntimeException e) { + shutdownExecutors(); + throw e; } } + /** + * Runs io.grpc's own dispatch work (method lookup, context closing) plus health and reflection. + * None of it is application code and none of it blocks, so a small fixed pool keeps up; its queue + * is unbounded on purpose, because a rejected dispatch task leaves a stream open with nobody to + * answer it (see {@link GrpcCallAdmission}). Its depth is bounded by the open streams, which + * {@code maxConcurrentCallsPerConnection} bounds per connection. + */ + private static ExecutorService dispatchExecutor() { + int threads = Math.max(2, Runtime.getRuntime().availableProcessors()); + return Executors.newFixedThreadPool(threads, daemonThreads("grpc-server-dispatch-")); + } + + /** + * Runs feature calls: a fixed pool in place of io.grpc's cached executor, which grows one thread + * per blocked call. Sizes are the platform's executor defaults. {@link GrpcCallAdmission} admits + * at most {@code maxAdmittedCalls} calls and each has at most one task here at a time, so the + * queue, as deep as the permit count, never fills; the abort policy is the unreachable backstop, + * not the overload behavior. Caller-runs was rejected because it would run a handler on the + * dispatch or Netty thread. + */ + private static ExecutorService workExecutor(int threads, int maxAdmittedCalls) { + ThreadPoolExecutor executor = + new ThreadPoolExecutor( + threads, + threads, + 60, + TimeUnit.SECONDS, + new ArrayBlockingQueue<>(maxAdmittedCalls), + daemonThreads("grpc-server-call-"), + new ThreadPoolExecutor.AbortPolicy()); + executor.allowCoreThreadTimeOut(true); + return executor; + } + + private static Set featureServiceNames(List featureServices) { + return featureServices.stream() + .map(service -> service.bindService().getServiceDescriptor().getName()) + .collect(Collectors.toUnmodifiableSet()); + } + + private static ThreadFactory daemonThreads(String prefix) { + return Thread.ofPlatform().name(prefix, 0).daemon(true).factory(); + } + @Override public void stop() { Server current = this.server; if (current == null) { return; } + // NOT_SERVING first, then a drain delay with the listener still up: a server that shuts the + // listener at the same moment answers a health check with UNAVAILABLE, which a load balancer + // cannot tell apart from a crash. The drain is spent out of the same grace budget. healthStatusManager.enterTerminalState(); + long drainMillis = TimeUnit.SECONDS.toMillis(properties.getShutdownDrainSeconds()); + long graceMillis = TimeUnit.SECONDS.toMillis(properties.getShutdownGraceSeconds()); try { + Thread.sleep(drainMillis); current.shutdown(); - if (!current.awaitTermination(properties.getShutdownGraceSeconds(), TimeUnit.SECONDS)) { + if (!current.awaitTermination( + Math.max(0, graceMillis - drainMillis), TimeUnit.MILLISECONDS)) { current.shutdownNow(); } log.info("gRPC server stopped"); @@ -126,6 +228,29 @@ public class GrpcServerRunner implements SmartLifecycle { Thread.currentThread().interrupt(); } finally { this.server = null; + shutdownExecutors(); + } + } + + /** + * The server is already terminated or forced down here, so a call still on the pool is one the + * grace budget gave up on: interrupt it rather than let it outlive the context. + */ + private void shutdownExecutors() { + ExecutorService work = this.workExecutor; + if (work != null) { + work.shutdownNow(); + this.workExecutor = null; + } + ExecutorService dispatch = this.dispatchExecutor; + if (dispatch != null) { + dispatch.shutdownNow(); + this.dispatchExecutor = null; + } + ScheduledExecutorService scheduler = this.deadlineScheduler; + if (scheduler != null) { + scheduler.shutdownNow(); + this.deadlineScheduler = null; } } diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerSettings.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerSettings.java index ecd3875a..53999aed 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerSettings.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerSettings.java @@ -4,8 +4,10 @@ import jakarta.validation.constraints.AssertTrue; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import java.net.InetAddress; import java.net.UnknownHostException; +import java.time.Duration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; @@ -13,6 +15,14 @@ import org.springframework.validation.annotation.Validated; * gRPC server settings bound from {@code app.grpc.server.*}. Typed configuration only (no * per-module {@code yml}); values live in the composition-root {@code application.yml}, matching * the ca-skeleton config convention. See README for the self-managed-Netty rationale. + * + *

      The transport bounds (review 03-09) carry the names and default values of the vendored + * platform's {@code GrpcTransportLimits}, {@code GrpcServerProfile.stable(..)} and {@code + * GrpcPlatformProperties} executor keys, so the adapter server and the platform's Netty evidence + * describe the same server. The adapter cannot import those types (no registry edge, and the + * platform is a separate build), so the values are restated here and the README cites their source. + * io.grpc's own defaults — 4 MiB messages, unlimited calls per connection, an unbounded cached + * executor, no server deadline, no connection age — are what this class replaces. */ @ConfigurationProperties(prefix = "app.grpc.server", ignoreUnknownFields = false) @Validated @@ -42,6 +52,74 @@ public class GrpcServerSettings { @Min(0) private int shutdownGraceSeconds = 5; + /** + * Seconds, inside {@link #shutdownGraceSeconds}, during which health already says NOT_SERVING but + * the listener still accepts calls, so a health watcher can stop routing before the listener + * closes. Two seconds: a {@code Health/Watch} subscriber is told at once, and the remaining three + * seconds of the default grace stay for in-flight calls. A poll-based probe with a longer period + * needs a {@code preStop} delay instead; this value cannot outwait it. + */ + @Min(0) + private int shutdownDrainSeconds = 2; + + /** Largest inbound message: 1 MiB, the platform's {@code DEFAULT_MAX_MESSAGE_BYTES}. */ + @Min(1) + private int maxInboundMessageBytes = 1024 * 1024; + + /** + * Largest inbound metadata per call: 8 KiB, the platform's {@code DEFAULT_MAX_METADATA_BYTES}. + */ + @Min(1) + private int maxInboundMetadataBytes = 8192; + + /** + * HTTP/2 {@code SETTINGS_MAX_CONCURRENT_STREAMS} the server advertises: calls one connection may + * have open at once. 100 is the floor RFC 9113 §6.5.2 recommends, so a conforming client is not + * starved; a client over it waits for a free stream rather than failing. The platform has no + * equivalent value to mirror. + */ + @Min(1) + private int maxConcurrentCallsPerConnection = 100; + + /** Threads running application work: the platform's {@code executor-max-pool-size}. */ + @Min(1) + private int executorMaxPoolSize = 32; + + /** + * Calls waiting for an executor thread: the platform's {@code executor-queue-capacity}. The upper + * bound is the platform's own refusal: a deeper queue holds work no caller is still waiting for. + */ + @Min(1) + @Max(10_000) + private int executorQueueCapacity = 256; + + /** + * Deadline the server gives a feature call whose client sent none, and the most it gives one that + * sent a longer one. Ten seconds, the same per-request budget the GraphQL adapter uses. The + * platform states deadlines per method ({@code GrpcDeadlineProfile}) and has no server-wide value + * to mirror. + */ + @NotNull private Duration defaultDeadline = Duration.ofSeconds(10); + + /** Server keep-alive ping interval: {@code GrpcServerProfile.stable(..)}'s 30 seconds. */ + @NotNull private Duration keepAliveTime = Duration.ofSeconds(30); + + /** How long a keep-alive ping may go unanswered: the platform's 10 seconds. */ + @NotNull private Duration keepAliveTimeout = Duration.ofSeconds(10); + + /** Most frequent client ping the server tolerates: the platform's 30 seconds. */ + @NotNull private Duration permitKeepAliveTime = Duration.ofSeconds(30); + + /** + * Connection age after which the server sends GOAWAY: the platform's 30 minutes. On the current + * loopback-only listener this only bounds a stuck client connection; once a non-loopback bind + * exists it is what lets a long-lived client move to a new instance during a rollout. + */ + @NotNull private Duration maxConnectionAge = Duration.ofMinutes(30); + + /** Time in-flight calls get after a max-age GOAWAY: the platform's 30 seconds. */ + @NotNull private Duration maxConnectionAgeGrace = Duration.ofSeconds(30); + public boolean isEnabled() { return enabled; } @@ -90,6 +168,141 @@ public class GrpcServerSettings { this.shutdownGraceSeconds = shutdownGraceSeconds; } + public int getShutdownDrainSeconds() { + return shutdownDrainSeconds; + } + + public void setShutdownDrainSeconds(int shutdownDrainSeconds) { + this.shutdownDrainSeconds = shutdownDrainSeconds; + } + + public int getMaxInboundMessageBytes() { + return maxInboundMessageBytes; + } + + public void setMaxInboundMessageBytes(int maxInboundMessageBytes) { + this.maxInboundMessageBytes = maxInboundMessageBytes; + } + + public int getMaxInboundMetadataBytes() { + return maxInboundMetadataBytes; + } + + public void setMaxInboundMetadataBytes(int maxInboundMetadataBytes) { + this.maxInboundMetadataBytes = maxInboundMetadataBytes; + } + + public int getMaxConcurrentCallsPerConnection() { + return maxConcurrentCallsPerConnection; + } + + public void setMaxConcurrentCallsPerConnection(int maxConcurrentCallsPerConnection) { + this.maxConcurrentCallsPerConnection = maxConcurrentCallsPerConnection; + } + + public int getExecutorMaxPoolSize() { + return executorMaxPoolSize; + } + + public void setExecutorMaxPoolSize(int executorMaxPoolSize) { + this.executorMaxPoolSize = executorMaxPoolSize; + } + + public int getExecutorQueueCapacity() { + return executorQueueCapacity; + } + + public void setExecutorQueueCapacity(int executorQueueCapacity) { + this.executorQueueCapacity = executorQueueCapacity; + } + + public Duration getDefaultDeadline() { + return defaultDeadline; + } + + public void setDefaultDeadline(Duration defaultDeadline) { + this.defaultDeadline = defaultDeadline; + } + + public Duration getKeepAliveTime() { + return keepAliveTime; + } + + public void setKeepAliveTime(Duration keepAliveTime) { + this.keepAliveTime = keepAliveTime; + } + + public Duration getKeepAliveTimeout() { + return keepAliveTimeout; + } + + public void setKeepAliveTimeout(Duration keepAliveTimeout) { + this.keepAliveTimeout = keepAliveTimeout; + } + + public Duration getPermitKeepAliveTime() { + return permitKeepAliveTime; + } + + public void setPermitKeepAliveTime(Duration permitKeepAliveTime) { + this.permitKeepAliveTime = permitKeepAliveTime; + } + + public Duration getMaxConnectionAge() { + return maxConnectionAge; + } + + public void setMaxConnectionAge(Duration maxConnectionAge) { + this.maxConnectionAge = maxConnectionAge; + } + + public Duration getMaxConnectionAgeGrace() { + return maxConnectionAgeGrace; + } + + public void setMaxConnectionAgeGrace(Duration maxConnectionAgeGrace) { + this.maxConnectionAgeGrace = maxConnectionAgeGrace; + } + + @AssertTrue(message = "shutdown-drain-seconds must fit inside shutdown-grace-seconds") + public boolean isShutdownDrainWithinGrace() { + return shutdownDrainSeconds <= shutdownGraceSeconds; + } + + /** + * The same orderings the platform's {@code GrpcServerProfile} refuses to break: every duration + * positive, a ping timeout below the ping interval, clients not allowed to ping less often than + * the server does, and a max-age grace no longer than the age it follows. + */ + @AssertTrue( + message = + "gRPC transport durations must be positive, keep-alive-timeout < keep-alive-time, " + + "permit-keep-alive-time <= keep-alive-time and max-connection-age-grace <= " + + "max-connection-age") + public boolean isTransportDurationsConsistent() { + if (!allPositive( + defaultDeadline, + keepAliveTime, + keepAliveTimeout, + permitKeepAliveTime, + maxConnectionAge, + maxConnectionAgeGrace)) { + return false; + } + return keepAliveTimeout.compareTo(keepAliveTime) < 0 + && permitKeepAliveTime.compareTo(keepAliveTime) <= 0 + && maxConnectionAgeGrace.compareTo(maxConnectionAge) <= 0; + } + + private static boolean allPositive(Duration... values) { + for (Duration value : values) { + if (value == null || value.isZero() || value.isNegative()) { + return false; + } + } + return true; + } + @AssertTrue( message = "insecure gRPC requires allow-insecure-local=true and a loopback bind address") public boolean isInsecureLocalConfigurationValid() { diff --git a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java index 37d074f2..97fd4735 100644 --- a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java +++ b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcP1BoundaryWireTest.java @@ -1,8 +1,10 @@ package dev.caskeleton.adapter.inbound.grpc; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.catchThrowableOfType; +import com.google.common.util.concurrent.ListenableFuture; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.ClientErrorMessages; import dev.caskeleton.shared.error.OperationalError; @@ -10,6 +12,7 @@ import io.grpc.BindableService; import io.grpc.CallOptions; import io.grpc.Channel; import io.grpc.ClientInterceptors; +import io.grpc.Context; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.Metadata; @@ -32,9 +35,14 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.security.Principal; +import java.time.Duration; +import java.util.List; import java.util.Optional; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import org.junit.jupiter.api.DisplayName; @@ -64,8 +72,18 @@ class GrpcP1BoundaryWireTest { unaryMethod("ListenerThrow"); private static final MethodDescriptor CLOSE_HANDLER_METHOD = unaryMethod("CloseHandler"); + private static final MethodDescriptor SLOW_METHOD = unaryMethod("Slow"); private static final CountDownLatch CLOSE_HANDLER_RAN = new CountDownLatch(1); + /** The platform's GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES, which this adapter mirrors. */ + private static final int ONE_MIB = 1024 * 1024; + + /** How long the slow handler holds its thread unless its gRPC Context is cancelled first. */ + private static final long SLOW_HANDLER_HOLD_MILLIS = 400; + + private static final AtomicInteger SLOW_IN_FLIGHT = new AtomicInteger(); + private static final AtomicInteger SLOW_MAX_IN_FLIGHT = new AtomicInteger(); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(GrpcServerConfig.class, FeatureConfiguration.class) @@ -203,6 +221,161 @@ class GrpcP1BoundaryWireTest { }); } + @Test + @DisplayName("1 MiB를 넘는 요청 메시지는 handler에 닿기 전에 RESOURCE_EXHAUSTED로 거절된다") + void aRequestMessageOverOneMebibyteIsRejectedAsResourceExhausted() { + withChannel( + channel -> { + // given + String oversized = "x".repeat(ONE_MIB + 1); + + // when + StatusRuntimeException failure = + catchThrowableOfType( + StatusRuntimeException.class, + () -> unary(authenticated(channel), UNARY_METHOD, oversized)); + + // then + assertThat(failure).isNotNull(); + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.RESOURCE_EXHAUSTED); + }); + } + + @Test + @DisplayName("정확히 1 MiB인 요청 메시지는 한도 안이라 feature handler에 닿는다") + void aRequestMessageOfExactlyOneMebibyteStillReachesTheHandler() { + withChannel( + channel -> { + // given + String atTheLimit = "x".repeat(ONE_MIB); + + // when + String response = unary(authenticated(channel), UNARY_METHOD, atTheLimit); + + // then + assertThat(response).hasSize("authorized-".length() + ONE_MIB); + }); + } + + @Test + @DisplayName("deadline 없이 부른 느린 호출은 서버 기본 deadline에서 DEADLINE_EXCEEDED로 끝난다") + void aSlowCallWithoutAClientDeadlineEndsAtTheServerDefaultDeadline() { + withChannel( + contextRunner.withPropertyValues("app.grpc.server.default-deadline=150ms"), + channel -> { + // given + ListenableFuture withoutDeadline = + ClientCalls.futureUnaryCall( + authenticated(channel).newCall(SLOW_METHOD, CallOptions.DEFAULT), "slow"); + + // when + Throwable failure = catchThrowable(() -> withoutDeadline.get(5, TimeUnit.SECONDS)); + + // then + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED); + }); + } + + @Test + @DisplayName("클라이언트 deadline이 서버 기본값보다 짧으면 클라이언트 deadline이 그대로 적용된다") + void aClientDeadlineShorterThanTheServerDefaultIsKept() { + withChannel( + contextRunner.withPropertyValues("app.grpc.server.default-deadline=10s"), + channel -> { + // given + long started = System.nanoTime(); + + // when + Throwable failure = + catchThrowable( + () -> + ClientCalls.blockingUnaryCall( + authenticated(channel), + SLOW_METHOD, + CallOptions.DEFAULT.withDeadlineAfter(100, TimeUnit.MILLISECONDS), + "slow")); + + // then + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED); + assertThat(Duration.ofNanos(System.nanoTime() - started)) + .isLessThan(Duration.ofSeconds(5)); + }); + } + + @Test + @DisplayName("연결당 동시 호출 상한이 1이면 같은 연결의 두 호출은 handler에서 겹치지 않는다") + void callsOnOneConnectionDoNotOverlapBeyondTheConcurrentCallCeiling() { + withChannel( + contextRunner.withPropertyValues("app.grpc.server.max-concurrent-calls-per-connection=1"), + channel -> { + // given + SLOW_MAX_IN_FLIGHT.set(0); + Channel caller = authenticated(channel); + CallOptions bounded = CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS); + ListenableFuture first = + ClientCalls.futureUnaryCall(caller.newCall(SLOW_METHOD, bounded), "slow"); + ListenableFuture second = + ClientCalls.futureUnaryCall(caller.newCall(SLOW_METHOD, bounded), "slow"); + + // when + List responses = List.of(getUnchecked(first), getUnchecked(second)); + + // then + assertThat(responses).containsExactly("slow-done", "slow-done"); + assertThat(SLOW_MAX_IN_FLIGHT.get()).isEqualTo(1); + }); + } + + @Test + @DisplayName("스레드와 대기열이 모두 찬 서버는 넘친 호출을 기다리게 두지 않고 즉시 RESOURCE_EXHAUSTED로 거절한다") + void aCallBeyondTheExecutorAndQueueIsRefusedAtOnceAsResourceExhausted() { + withChannel( + contextRunner.withPropertyValues( + "app.grpc.server.executor-max-pool-size=1", + "app.grpc.server.executor-queue-capacity=1"), + channel -> { + // given + Channel caller = authenticated(channel); + CallOptions bounded = CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS); + List> calls = + List.of( + ClientCalls.futureUnaryCall(caller.newCall(SLOW_METHOD, bounded), "slow"), + ClientCalls.futureUnaryCall(caller.newCall(SLOW_METHOD, bounded), "slow"), + ClientCalls.futureUnaryCall(caller.newCall(SLOW_METHOD, bounded), "slow")); + + // when + List outcomes = calls.stream().map(GrpcP1BoundaryWireTest::outcome).toList(); + + // then + assertThat(outcomes) + .extracting(Status::getCode) + .containsExactlyInAnyOrder( + Status.Code.OK, Status.Code.OK, Status.Code.RESOURCE_EXHAUSTED); + assertThat(outcomes) + .filteredOn(status -> !status.isOk()) + .extracting(Status::getDescription) + .containsExactly(ClientErrorMessages.of(Category.RATE_LIMIT)); + }); + } + + private static Status outcome(ListenableFuture call) { + Throwable failure = catchThrowable(() -> call.get(5, TimeUnit.SECONDS)); + return failure == null ? Status.OK : Status.fromThrowable(failure); + } + + private static String getUnchecked(ListenableFuture future) { + try { + return future.get(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while waiting for a call", e); + } catch (ExecutionException | TimeoutException e) { + throw new IllegalStateException("call did not complete", e); + } + } + private static boolean await(CountDownLatch latch) { try { return latch.await(5, TimeUnit.SECONDS); @@ -213,7 +386,12 @@ class GrpcP1BoundaryWireTest { } private void withChannel(Consumer assertion) { - contextRunner.run( + withChannel(contextRunner, assertion); + } + + private static void withChannel( + ApplicationContextRunner runner, Consumer assertion) { + runner.run( context -> { assertThat(context.getStartupFailure()).isNull(); int port = context.getBean(GrpcServerRunner.class).getListeningPort(); @@ -364,6 +542,14 @@ class GrpcP1BoundaryWireTest { observer.onNext("authorized-" + request); observer.onCompleted(); })) + .addMethod( + SLOW_METHOD, + ServerCalls.asyncUnaryCall( + (String request, StreamObserver observer) -> { + holdUntilCancelled(); + observer.onNext(request + "-done"); + observer.onCompleted(); + })) .addMethod( CLOSE_HANDLER_METHOD, ServerCalls.asyncUnaryCall( @@ -397,6 +583,24 @@ class GrpcP1BoundaryWireTest { } } + /** + * Holds the handler thread like a slow dependency would, but stops early when the call's gRPC + * Context is cancelled — the cooperative behavior a deadline is meant to trigger. + */ + private static void holdUntilCancelled() { + SLOW_MAX_IN_FLIGHT.accumulateAndGet(SLOW_IN_FLIGHT.incrementAndGet(), Math::max); + try { + long until = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(SLOW_HANDLER_HOLD_MILLIS); + while (System.nanoTime() < until && !Context.current().isCancelled()) { + Thread.sleep(10); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + SLOW_IN_FLIGHT.decrementAndGet(); + } + } + private enum StringMarshaller implements MethodDescriptor.Marshaller { INSTANCE; diff --git a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcSafeActivationTest.java b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcSafeActivationTest.java index 8e1ac2f1..c260ad9c 100644 --- a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcSafeActivationTest.java +++ b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcSafeActivationTest.java @@ -5,6 +5,9 @@ import static org.assertj.core.api.Assertions.assertThat; import io.grpc.BindableService; import io.grpc.ServerServiceDefinition; import io.grpc.protobuf.services.HealthStatusManager; +import java.time.Duration; +import java.util.List; +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; @@ -102,6 +105,66 @@ class GrpcSafeActivationTest { assertRootCauseContains(context.getStartupFailure(), "shutdownGraceSeconds")); } + @Test + @DisplayName("전송 한도 기본값은 플랫폼 GrpcTransportLimits·GrpcServerProfile.stable·executor 기본값과 같다") + void transportBoundDefaultsMatchTheVendoredPlatformDefaults() { + // given — the adapter cannot import the platform types (no registry edge, separate build), so + // the expected values are the platform's literals, cited in the README beside each key. + GrpcServerSettings properties = new GrpcServerSettings(); + + // when + var defaults = + List.of( + properties.getMaxInboundMessageBytes(), + properties.getMaxInboundMetadataBytes(), + properties.getExecutorMaxPoolSize(), + properties.getExecutorQueueCapacity(), + properties.getKeepAliveTime(), + properties.getKeepAliveTimeout(), + properties.getPermitKeepAliveTime(), + properties.getMaxConnectionAge(), + properties.getMaxConnectionAgeGrace()); + + // then + assertThat(defaults) + .containsExactly( + 1024 * 1024, + 8192, + 32, + 256, + Duration.ofSeconds(30), + Duration.ofSeconds(10), + Duration.ofSeconds(30), + Duration.ofMinutes(30), + Duration.ofSeconds(30)); + } + + @Test + @DisplayName("drain 대기가 종료 grace보다 길면 기동이 실패한다") + void aDrainDelayLongerThanTheShutdownGraceFailsStartup() { + contextRunner + .withPropertyValues( + "app.grpc.server.port=0", + "app.grpc.server.allow-insecure-local=true", + "app.grpc.server.shutdown-grace-seconds=1", + "app.grpc.server.shutdown-drain-seconds=2") + .run( + context -> + assertRootCauseContains(context.getStartupFailure(), "shutdown-drain-seconds")); + } + + @Test + @DisplayName("keep-alive timeout이 ping 간격 이상이면 기동이 실패한다") + void aKeepAliveTimeoutAtOrAboveTheIntervalFailsStartup() { + contextRunner + .withPropertyValues( + "app.grpc.server.port=0", + "app.grpc.server.allow-insecure-local=true", + "app.grpc.server.keep-alive-time=10s", + "app.grpc.server.keep-alive-timeout=10s") + .run(context -> assertRootCauseContains(context.getStartupFailure(), "keep-alive-timeout")); + } + @Test void featureServiceRequiresACallerSuppliedAuthenticationPolicy() { contextRunner diff --git a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunnerBootTest.java b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunnerBootTest.java index bc58686a..e6249b01 100644 --- a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunnerBootTest.java +++ b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunnerBootTest.java @@ -15,11 +15,13 @@ import io.grpc.reflection.v1.ServerReflectionRequest; import io.grpc.reflection.v1.ServerReflectionResponse; import io.grpc.reflection.v1.ServiceResponse; import io.grpc.stub.StreamObserver; +import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -91,6 +93,55 @@ class GrpcServerRunnerBootTest { }); } + @Test + @DisplayName("종료가 시작되면 drain 대기 동안 listener가 살아 있고 health는 NOT_SERVING을 보고한다") + void stoppingKeepsTheListenerUpReportingNotServingDuringTheDrainDelay() { + contextRunner + .withPropertyValues( + "app.grpc.server.shutdown-drain-seconds=2", "app.grpc.server.shutdown-grace-seconds=4") + .run( + context -> { + // given + GrpcServerRunner runner = context.getBean(GrpcServerRunner.class); + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", runner.getListeningPort()) + .usePlaintext() + .build(); + Thread stopping = Thread.ofVirtual().start(runner::stop); + try { + // when + ServingStatus duringDrain = firstStatusOtherThanServing(channel); + + // then + assertThat(duringDrain).isEqualTo(ServingStatus.NOT_SERVING); + } finally { + stopping.join(Duration.ofSeconds(10)); + channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + }); + } + + /** + * Polls health until it stops saying SERVING. A server that shut its listener the moment shutdown + * began answers this with UNAVAILABLE instead, which is what a load balancer cannot act on. + */ + private static ServingStatus firstStatusOtherThanServing(ManagedChannel channel) + throws InterruptedException { + long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(1); + while (System.nanoTime() < until) { + ServingStatus status = + HealthGrpc.newBlockingStub(channel) + .withDeadlineAfter(1, TimeUnit.SECONDS) + .check(HealthCheckRequest.newBuilder().build()) + .getStatus(); + if (status != ServingStatus.SERVING) { + return status; + } + Thread.sleep(10); + } + return ServingStatus.SERVING; + } + @Configuration(proxyBeanMethods = false) static class UnqualifiedServiceConfiguration { diff --git a/src/adapter/inbound/messaging/CLAUDE.md b/src/adapter/inbound/messaging/CLAUDE.md new file mode 100644 index 00000000..ff67113d --- /dev/null +++ b/src/adapter/inbound/messaging/CLAUDE.md @@ -0,0 +1,12 @@ +# adapter:inbound:messaging + +- Module ID `adapter-inbound-messaging`, Gradle path `:adapter:inbound:messaging`. Registry SSOT: + `src/config/architecture/modules.json`. +- Responsibility: the application's consume side of the vendored messaging platform — the inbox + parts the platform needs from the application (`JdbcInboxRepository` over the application + DataSource, a `TransactionRunner` over its `PlatformTransactionManager`) and the application's + `MessageHandler` implementations, each turning a delivery into one use case call. +- Boundaries: no business rule in a handler (HARD-STOP 4); no persistence entity or repository; no + broker SDK type. Allowed edges come only from the registry entry. +- Tests: focused auto-configuration and inbox behavior tests; `./gradlew :adapter:inbound:messaging:check`. +- Design and rejected alternatives: `README.md`. diff --git a/src/adapter/inbound/messaging/README.md b/src/adapter/inbound/messaging/README.md new file mode 100644 index 00000000..e9b2dc66 --- /dev/null +++ b/src/adapter/inbound/messaging/README.md @@ -0,0 +1,87 @@ +# adapter:inbound:messaging — 이벤트 소비 경로 + +- Module ID: `adapter-inbound-messaging` +- Gradle path: `:adapter:inbound:messaging` +- Package: `dev.caskeleton.adapter.inbound.messaging` +- 테스트: `./gradlew :adapter:inbound:messaging:test --console=plain` + +## 제공하는 것 + +소유자 결정 10("Kafka 소비 지원")을 application 쪽까지 잇는 최소 경로다(리뷰 2026-11-01 06-08). + +```text +Kafka ─▶ platform consumer (starter-kafka) + └─ INBOX_TRANSACTIONAL destination이면 + InboxMessageHandler ─▶ IdempotentConsumer.runOnce (platform이 감싼다) + ├─ JdbcInboxRepository.reserve ← 이 leaf가 조립 + └─ 애플리케이션 MessageHandler ─▶ use case + (같은 PlatformTransactionManager 트랜잭션) ← 이 leaf가 조립 +``` + +- `MessagingInboxAutoConfiguration`: `MessageHandler` bean과 `DataSource`·`PlatformTransactionManager`가 + 있을 때만, platform inbox가 요구하는 두 부품을 만든다. + - `JdbcInboxRepository`(애플리케이션 DataSource). `DataSourceUtils`로 연결을 얻으므로 runner가 연 + 트랜잭션에 참여한다. + - `IdempotentConsumer.TransactionRunner`(애플리케이션 `PlatformTransactionManager` 위의 + `TransactionTemplate`). inbox 예약과 use case의 JPA 쓰기가 한 트랜잭션에서 함께 커밋되거나 함께 + 롤백된다. handler가 실패하면 예약도 롤백되어 재전달이 효과를 다시 적용한다. +- platform starter(`MessagingReliabilityAutoConfiguration`)가 이 두 bean으로 `IdempotentConsumer`를 + 만든다. platform은 애플리케이션의 datasource·트랜잭션을 스스로 고르지 않는다는 기존 설계를 그대로 둔다. +- 애플리케이션의 handler(`MessageHandler` 구현)는 이 leaf에 둔다. 컨트롤러가 HTTP 요청을 use case + 호출로 바꾸듯 delivery를 use case 호출 하나로 바꾸는 inbound adapter다. 업무 규칙은 use case에 둔다. + +## 추가할 한 줄 + +```groovy +// app-bootstrap/build.gradle — 기본 조립에는 없다 +runtimeOnly project(':adapter:inbound:messaging') // 이벤트 소비 + inbox +``` + +`adapter:outbound:messaging-kafka` 줄(broker·platform)과 persistence-jpa(DataSource·트랜잭션)가 함께 +있어야 한다. inbox 테이블(`messaging_inbox`)은 platform의 +`messaging-reliability-jdbc-postgresql` `db/migration/messaging/V1101__messaging_inbox.sql`이 만든다. +그 위치를 애플리케이션 Flyway location에 넣는 일은 이번 변경에 포함되지 않았다(아래 "남은 것"). + +## destination 예시 + +```yaml +app: + messaging: + destinations: + order-events: + broker: kafka + kind: EVENT_STREAM + physical: + topic: order.events.v1 + schema: + message-types: [order.created] + guarantees: + delivery: AT_LEAST_ONCE + external-side-effect: INBOX_TRANSACTIONAL # handler를 inbox로 감싼다 + consumer: + group: order-projection # inbox의 consumer identity + dlq: + destination: order-events-dlq +``` + +handler 예시는 `MessagingInboxAutoConfigurationTest#exampleHandler`다. + +## 고른 방법과 버린 대안 + +- 고름: platform은 `InboxRepository` + `TransactionRunner` bean이 있을 때만 `IdempotentConsumer`를 + 만들고, 두 부품은 이 application leaf가 준다. platform 경계(애플리케이션 datasource를 고르지 않음)와 + registry 간선(messaging은 messaging만 의존)이 그대로다. +- 버림: app-bootstrap에서 handler·inbox를 직접 등록 — composition root에 업무 handler가 들어간다 + (HARD-STOP 4). +- 버림: `adapter:outbound:messaging`(발행 bridge)에 소비까지 넣기 — 발행 bridge는 + `messaging-core-api`만 보는 anti-corruption 경계이고, 소비는 inbound 방향이다. +- 버림: application-core에 소비 포트를 새로 만들어 platform `MessageHandler`로 감싸는 범용 bridge — + payload 타입 매핑과 결과 매핑 규칙을 먼저 정해야 해서 이번 범위보다 크다. 지금은 handler가 직접 + use case를 부른다. + +## 남은 것 + +- 실제 Kafka + PostgreSQL로 같은 메시지 두 번 전달 시 부작용 1회를 확인하는 lane이 없다. 지금은 + platform `InboxMessageHandler`·`IdempotentConsumer`를 실제로 쓰고 inbox 저장소만 in-memory인 단위 + 테스트다. +- inbox migration location 연결과 inbox cleanup 스케줄은 이 leaf가 하지 않는다. diff --git a/src/adapter/inbound/messaging/build.gradle b/src/adapter/inbound/messaging/build.gradle new file mode 100644 index 00000000..339dc526 --- /dev/null +++ b/src/adapter/inbound/messaging/build.gradle @@ -0,0 +1,35 @@ +plugins { + id 'ca.spring-library' + id 'ca.spring-config' +} + +// The application's consume side of the vendored messaging platform (review 2026-11-01 06-08), +// selected by one line in a composition root: +// +// runtimeOnly project(':adapter:inbound:messaging') +// +// The platform opens a consumer for every MessageHandler bean and, for a destination declared +// INBOX_TRANSACTIONAL, runs the handler inside an inbox reservation (IdempotentConsumer). It cannot +// build the inbox itself: the reservation must commit in the application's own transaction, against +// the application's own datasource. This leaf supplies exactly that — the JDBC inbox repository over +// the application DataSource and a transaction runner over its PlatformTransactionManager — and is +// where an application's message handlers live: an inbound adapter, which turns a delivery into a +// use case call, the same role a controller plays for HTTP. +dependencies { + implementation project(':application-core') + implementation project(':messaging:messaging-core-api') + implementation project(':messaging:messaging-reliability') + implementation project(':messaging:messaging-reliability-api') + // JdbcInboxRepository only. The leaf also exports the platform admin journal (api + // messaging-admin), which this leaf has no use for and no registered edge to; the starter puts it + // on the runtime classpath anyway. + implementation(project(':messaging:messaging-reliability-jdbc-postgresql')) { + exclude group: 'dev.caskeleton', module: 'messaging-admin' + } + + implementation 'org.springframework.boot:spring-boot-autoconfigure' + implementation 'org.springframework:spring-jdbc' + implementation 'org.springframework:spring-tx' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} diff --git a/src/adapter/inbound/messaging/gradle.lockfile b/src/adapter/inbound/messaging/gradle.lockfile new file mode 100644 index 00000000..4f61d2bc --- /dev/null +++ b/src/adapter/inbound/messaging/gradle.lockfile @@ -0,0 +1,152 @@ +# This is a Gradle generated file for dependency locking. +# Manual edits can break the build and are not advised. +# This file is expected to be part of source control. +biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath +ch.qos.logback:logback-classic:1.5.38=testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=testCompileClasspath,testRuntimeClasspath +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs +com.github.spotbugs:spotbugs:4.10.2=spotbugs +com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor +com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs +com.google.code.gson:gson:2.13.2=spotbugs +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.38.0=testCompileClasspath +com.google.errorprone:error_prone_annotations:2.41.0=spotbugs +com.google.errorprone:error_prone_annotations:2.47.0=checkstyle +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.guava:guava:33.6.0-jre=checkstyle +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins +com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath +com.puppycrawl.tools:checkstyle:13.5.0=checkstyle +com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath +commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-collections:commons-collections:3.2.2=checkstyle +commons-io:commons-io:2.21.0=spotbugs +commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +info.picocli:picocli:4.7.7=checkstyle +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor +io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=testCompileClasspath,testRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=testCompileClasspath,testRuntimeClasspath +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +jaxen:jaxen:2.0.6=spotbugs +net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs +org.antlr:antlr4-runtime:4.13.2=checkstyle +org.apache.bcel:bcel:6.12.0=spotbugs +org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs +org.apache.commons:commons-text:1.15.0=spotbugs +org.apache.commons:commons-text:1.3=checkstyle +org.apache.httpcomponents:httpclient:4.5.13=checkstyle +org.apache.httpcomponents:httpcore:4.4.16=checkstyle +org.apache.logging.log4j:log4j-api:2.25.5=spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-core:2.25.5=spotbugs +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=testCompileClasspath,testRuntimeClasspath +org.apache.maven.doxia:doxia-core:1.12.0=checkstyle +org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle +org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle +org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle +org.apache.tomcat.embed:tomcat-embed-core:11.0.24=testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-el:11.0.24=testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=testCompileClasspath,testRuntimeClasspath +org.apache.xbean:xbean-reflect:3.7=checkstyle +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath +org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle +org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle +org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle +org.codehaus.plexus:plexus-utils:3.3.0=checkstyle +org.dom4j:dom4j:2.2.0=spotbugs +org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.javassist:javassist:3.28.0-GA=checkstyle +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath +org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath +org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath +org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit:junit-bom:6.1.0=spotbugs +org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath +org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath +org.objenesis:objenesis:3.3=testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.osgi:org.osgi.annotation.bundle:2.0.0=testCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=testCompileClasspath +org.osgi:org.osgi.resource:1.0.0=testCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=testCompileClasspath +org.ow2.asm:asm-analysis:9.10.1=spotbugs +org.ow2.asm:asm-commons:9.10.1=spotbugs +org.ow2.asm:asm-tree:9.10.1=spotbugs +org.ow2.asm:asm-util:9.10.1=spotbugs +org.ow2.asm:asm:9.10.1=spotbugs +org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.reflections:reflections:0.10.2=checkstyle +org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j +org.slf4j:slf4j-simple:2.0.18=checkstyle +org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor +org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-jdbc:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-tx:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath +org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs +org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath +org.yaml:snakeyaml:2.5=testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-core:3.1.5=testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.5=testCompileClasspath,testRuntimeClasspath +tools.jackson:jackson-bom:3.1.5=testCompileClasspath,testRuntimeClasspath +empty= diff --git a/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java b/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java new file mode 100644 index 00000000..ac81ef9c --- /dev/null +++ b/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java @@ -0,0 +1,65 @@ +package dev.caskeleton.adapter.inbound.messaging; + +import dev.caskeleton.messaging.api.delivery.MessageHandler; +import dev.caskeleton.messaging.inbox.IdempotentConsumer; +import dev.caskeleton.messaging.inbox.JdbcInboxRepository; +import dev.caskeleton.messaging.reliability.InboxRepository; +import javax.sql.DataSource; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Supplies the platform's inbox with the application's datasource and transaction, so a handler of + * an {@code INBOX_TRANSACTIONAL} destination runs at most once per message and consumer group. + * + *

      The platform ({@code MessagingReliabilityAutoConfiguration}) assembles its {@link + * IdempotentConsumer} only from an {@link InboxRepository} and a {@link + * IdempotentConsumer.TransactionRunner} the application provides, and refuses to start an {@code + * INBOX_TRANSACTIONAL} destination without it. This configuration provides both: + * + *

        + *
      • {@link JdbcInboxRepository} over the application {@link DataSource}. It takes its + * connection through {@code DataSourceUtils}, so it joins the transaction the runner opens. + *
      • A runner over the application {@link PlatformTransactionManager}: the reservation row and + * whatever the use case writes through JPA commit together, and a handler that fails rolls + * the reservation back with its effect, so the redelivery applies it. + *
      + * + *

      Only while a {@link MessageHandler} exists — nothing to consume, nothing to assemble. Ordered + * before the platform root so its bean conditions see these beans. + */ +@AutoConfiguration( + afterName = { + "org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration", + "org.springframework.boot.hibernate.autoconfigure.HibernateJpaAutoConfiguration", + "org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration" + }, + beforeName = "dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration") +@ConditionalOnBean({MessageHandler.class, DataSource.class, PlatformTransactionManager.class}) +public class MessagingInboxAutoConfiguration { + + /** The platform's JDBC inbox over the application datasource. */ + @Bean + @ConditionalOnMissingBean(InboxRepository.class) + public JdbcInboxRepository messagingInboxRepository(DataSource dataSource) { + return new JdbcInboxRepository(dataSource); + } + + /** Runs the inbox reservation and the handler in one application transaction. */ + @Bean + @ConditionalOnMissingBean(IdempotentConsumer.TransactionRunner.class) + public IdempotentConsumer.TransactionRunner messagingInboxTransactions( + PlatformTransactionManager transactionManager) { + TransactionTemplate template = new TransactionTemplate(transactionManager); + return new IdempotentConsumer.TransactionRunner() { + @Override + public T inTransaction(java.util.function.Supplier work) { + return template.execute(status -> work.get()); + } + }; + } +} diff --git a/src/adapter/inbound/messaging/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/inbound/messaging/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..f26e647d --- /dev/null +++ b/src/adapter/inbound/messaging/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.caskeleton.adapter.inbound.messaging.MessagingInboxAutoConfiguration diff --git a/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java b/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java new file mode 100644 index 00000000..741d11e8 --- /dev/null +++ b/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java @@ -0,0 +1,212 @@ +package dev.caskeleton.adapter.inbound.messaging; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.messaging.api.ContentType; +import dev.caskeleton.messaging.api.MessageEnvelope; +import dev.caskeleton.messaging.api.MessageId; +import dev.caskeleton.messaging.api.MessageType; +import dev.caskeleton.messaging.api.ProducerId; +import dev.caskeleton.messaging.api.SchemaVersion; +import dev.caskeleton.messaging.api.TraceContext; +import dev.caskeleton.messaging.api.delivery.DeliveryContext; +import dev.caskeleton.messaging.api.delivery.DeliveryMetadata; +import dev.caskeleton.messaging.api.delivery.HandleResult; +import dev.caskeleton.messaging.api.delivery.MessageDelivery; +import dev.caskeleton.messaging.api.delivery.MessageHandler; +import dev.caskeleton.messaging.api.destination.DestinationName; +import dev.caskeleton.messaging.api.destination.MessageDestination; +import dev.caskeleton.messaging.api.header.MessageHeaders; +import dev.caskeleton.messaging.inbox.IdempotentConsumer; +import dev.caskeleton.messaging.inbox.InboxMessageHandler; +import dev.caskeleton.messaging.inbox.JdbcInboxRepository; +import dev.caskeleton.messaging.reliability.InboxRepository; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import javax.sql.DataSource; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; + +/** + * The application side of the platform inbox (review 06-08): what this leaf assembles, when, and + * that a delivery handled through it runs its side effect once per message. + */ +class MessagingInboxAutoConfigurationTest { + + private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z"); + private static final DestinationName ORDERS = new DestinationName("order-events"); + + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(MessagingInboxAutoConfiguration.class)) + .withBean(DataSource.class, () -> Mockito.mock(DataSource.class)) + .withBean(PlatformTransactionManager.class, RecordingTransactions::new); + + @Test + @DisplayName("메시지 handler가 있으면 애플리케이션 datasource 위의 inbox와 트랜잭션 runner를 조립한다") + void aMessageHandlerAssemblesTheInboxOverTheApplicationDatasource() { + // when & then + runner + .withBean(MessageHandler.class, () -> exampleHandler(new ArrayList<>())) + .run( + context -> { + assertThat(context).hasSingleBean(JdbcInboxRepository.class); + assertThat(context).hasSingleBean(IdempotentConsumer.TransactionRunner.class); + }); + } + + @Test + @DisplayName("소비할 handler가 없으면 inbox를 조립하지 않는다") + void withoutAHandlerNothingIsAssembled() { + // when & then + runner.run( + context -> { + assertThat(context).doesNotHaveBean(InboxRepository.class); + assertThat(context).doesNotHaveBean(IdempotentConsumer.TransactionRunner.class); + }); + } + + @Test + @DisplayName("트랜잭션 runner는 성공하면 커밋하고 실패하면 롤백해 예약과 부작용을 함께 되돌린다") + void theRunnerCommitsOnSuccessAndRollsBackOnFailure() { + // given + RecordingTransactions transactions = new RecordingTransactions(); + IdempotentConsumer.TransactionRunner runner = + new MessagingInboxAutoConfiguration().messagingInboxTransactions(transactions); + runner.inTransaction(() -> "applied"); + + // when + Throwable thrown = + catchThrowable( + () -> + runner.inTransaction( + () -> { + throw new IllegalStateException("use case failed"); + })); + + // then + assertThat(thrown).hasMessage("use case failed"); + assertThat(transactions.outcomes).containsExactly("commit", "rollback"); + } + + @Test + @DisplayName("같은 메시지가 두 번 전달돼도 handler의 부작용은 한 번만 일어난다") + void theSameMessageDeliveredTwiceRunsTheSideEffectOnce() { + // given: the platform's inbox wrapper around an application handler, over this leaf's runner + List effects = new ArrayList<>(); + IdempotentConsumer inbox = + new IdempotentConsumer( + new InMemoryInbox(), + new MessagingInboxAutoConfiguration() + .messagingInboxTransactions(new RecordingTransactions())); + MessageHandler handler = + new InboxMessageHandler<>(exampleHandler(effects), inbox, "order-projection", () -> NOW); + MessageDelivery delivery = delivery(MessageId.newId()); + handler.handle(delivery).toCompletableFuture().join(); + + // when + HandleResult redelivered = handler.handle(delivery).toCompletableFuture().join(); + + // then + assertThat(redelivered).isEqualTo(HandleResult.success()); + assertThat(effects).containsExactly("o-1"); + } + + /** The shape of an application handler: a delivery becomes one use case call. */ + private static MessageHandler exampleHandler(List effects) { + return new MessageHandler<>() { + @Override + public MessageDestination destination() { + return new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class); + } + + @Override + public CompletionStage handle(MessageDelivery delivery) { + effects.add(delivery.message().payload()); + return CompletableFuture.completedFuture(HandleResult.success()); + } + }; + } + + private static MessageDelivery delivery(MessageId id) { + return new MessageDelivery<>( + new MessageEnvelope<>( + id, + new MessageType("order.created"), + new SchemaVersion(1), + NOW, + Optional.empty(), + new ProducerId("orders"), + Optional.empty(), + Optional.empty(), + ContentType.JSON, + Optional.empty(), + Optional.empty(), + Optional.empty(), + TraceContext.none(), + MessageHeaders.empty(), + "o-1"), + new DeliveryMetadata( + ORDERS, 1, false, Optional.empty(), Optional.empty(), Optional.empty(), NOW), + new DeliveryContext(NOW.plusSeconds(30), false, "order-projection")); + } + + /** Records what the runner asked of the transaction manager. */ + private static final class RecordingTransactions extends AbstractPlatformTransactionManager { + + private static final long serialVersionUID = 1L; + + private final transient List outcomes = new ArrayList<>(); + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) { + outcomes.add("commit"); + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + outcomes.add("rollback"); + } + } + + private static final class InMemoryInbox implements InboxRepository { + private final Set reserved = new LinkedHashSet<>(); + + @Override + public boolean reserve(MessageId messageId, String consumerId, Instant now) { + return reserved.add(messageId.value() + "|" + consumerId); + } + + @Override + public boolean isProcessed(MessageId messageId, String consumerId) { + return reserved.contains(messageId.value() + "|" + consumerId); + } + + @Override + public int purgeProcessedBefore(Instant processedBefore, int limit) { + return 0; + } + } +} diff --git a/src/adapter/inbound/web-advanced/README.md b/src/adapter/inbound/web-advanced/README.md index caffe7f5..56e396a5 100644 --- a/src/adapter/inbound/web-advanced/README.md +++ b/src/adapter/inbound/web-advanced/README.md @@ -47,6 +47,34 @@ virtual thread 실행기는 `TaskDecorator` bean 을 요구한다(요청 상관 | `idempotency` | `JsonIdempotentResponseCodec` | | `admin.route` | `WebRouteInventory` | +## 오류 응답 + +이 leaf 의 예외는 모두 `ApiErrorCarrier` 다. 코드는 `error.WebAdvancedError` 한 enum 이 정하고, web 의 +`GlobalExceptionHandler.handleCarrier` 한 분기가 Envelope 로 답한다(별도 `@RestControllerAdvice` 없음). +예전에는 10종 모두 `500 INTERNAL_ERROR` 였다(리뷰 2026-11-01 02-07). 아래 표와 enum 은 같은 값을 말하고, +`WebAdvancedErrorMappingTest` 가 실제 응답으로 확인한다. + +| 예외 | `error.code` | status | category | retryable | 응답에 더 실리는 것 | 클라이언트 행동 | +| --- | --- | --- | --- | --- | --- | --- | +| `AdmissionRefusedException` | `ADMISSION_REFUSED` | 503 | `TRANSIENT_DEPENDENCY` | true | `Retry-After: 1` | 잠시 뒤 같은 요청 | +| `JsonPatchTestFailedException` | `PATCH_TEST_FAILED` | 409 | `CONFLICT` | false | `details.pointer`(서버 값은 없음) | 다시 읽고 새 patch | +| `JsonPatchRejectedException` | `PATCH_REJECTED` | 400 | `VALIDATION` | false | — | patch 문서를 고친다 | +| `PatchAuthorizationException` | `PATCH_PATH_FORBIDDEN` | 403 | `AUTHZ` | false | `details.refusedPaths` | 해당 경로를 빼거나 권한 확보 | +| `UnsupportedApiVersionException` | `API_VERSION_UNSUPPORTED` | 404 | `NOT_FOUND` | false | — | 지원 버전 경로로 | +| `SunsetViolationException` | `API_DEPRECATION_INVALID` | 500 | `INTERNAL` | false | — | 서버 설정 결함(등록 시점 오류) | +| `UntrustedTenantInputException` | `TENANT_INPUT_UNTRUSTED` | 403 | `AUTHZ` | false | — | 요청 입력으로 tenant 를 보내지 않는다 | +| `ReplayCursorExpiredException` | `STREAM_RESNAPSHOT_REQUIRED` | 410 | `NOT_FOUND` | false | — | 리소스를 다시 읽고 새 스트림(`docs/web/streaming-contract.md`) | +| `StreamItemTooLargeException` | `STREAM_ITEM_TOO_LARGE` | 500 | `INTERNAL` | false | — | 서버 데이터 문제. commit 뒤면 스트림 terminal failure 로 끝난다 | +| `RouteInventoryMismatchException` | `ROUTE_INVENTORY_MISMATCH` | 500 | `INTERNAL` | false | — | release gate 실패(요청 경로에서는 나오지 않아야 한다) | + +- `Retry-After` 는 `WebAdvancedError` 가 web 의 `RetryAfterHint` 로 직접 말한다. web 의 `RetryAfterAdvisor` + 표에 이 leaf 코드 이름을 넣지 않는다. +- `details` 는 `ClientSafeErrorDetails` 로 고른 값만 나간다. 예외 메시지는 나가지 않는다. +- 이 코드들은 `docs/registries/error-codes.yaml`(`OperationalError` SSOT) 밖이다. 5xx 는 + `handleCarrier` 가 ERROR 로그를 남긴다(admission 거절 포함 — 경보 임계는 운영에서 정한다). +- 응답 status 가 이미 commit 된 스트림 안에서는 HTTP status 가 바뀌지 않는다. 위 표는 commit 전에 던져진 + 경우다. + ## env 키 없다. 위 세 설정은 서비스가 자기 `application.yml` 에 둔다. 이 leaf 는 env key registry 에 키를 diff --git a/src/adapter/inbound/web-advanced/build.gradle b/src/adapter/inbound/web-advanced/build.gradle index 829213f1..21bc8394 100644 --- a/src/adapter/inbound/web-advanced/build.gradle +++ b/src/adapter/inbound/web-advanced/build.gradle @@ -35,7 +35,6 @@ strictTestLanes { lane('webAdvancedTest') { tag = 'web-advanced' description = 'Runs every web Advanced capability contract.' - jvmArgs '-Duser.timezone=UTC' } } @@ -44,3 +43,10 @@ strictTestLanes { tasks.named('mainCheck') { dependsOn 'webAdvancedTest' } + +// RepresentationBackendScopeTest reads this script to check which scope declares the codec +// backends, and a scope change can leave the test runtime classpath as it was. The script is an +// input, or a cached `test`/`webAdvancedTest` passes for the old scope (review 2026-11-01 08-02). +tasks.withType(Test).configureEach { + inputs.file('build.gradle').withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('buildScript') +} diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/RouteInventoryMismatchException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/RouteInventoryMismatchException.java index 7f3d96e0..eb40ce16 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/RouteInventoryMismatchException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/RouteInventoryMismatchException.java @@ -1,5 +1,9 @@ package dev.caskeleton.adapter.inbound.web.advanced.admin.route; +import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + /** * The routes this deployment actually serves are not the routes it declared. * @@ -7,7 +11,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.admin.route; * disagreement with the approved manifest stops the release: an endpoint that appears without a * review is an endpoint whose authorization, budget and idempotency policy nobody chose. */ -public final class RouteInventoryMismatchException extends RuntimeException { +public final class RouteInventoryMismatchException extends RuntimeException + implements ApiErrorCarrier { private static final long serialVersionUID = 1L; @@ -15,4 +20,12 @@ public final class RouteInventoryMismatchException extends RuntimeException { public RouteInventoryMismatchException(String message) { super(message); } + + /** + * {@link WebAdvancedError#ROUTE_INVENTORY_MISMATCH}; see the leaf README for the client contract. + */ + @Override + public ApiErrorCode errorCode() { + return WebAdvancedError.ROUTE_INVENTORY_MISMATCH; + } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java new file mode 100644 index 00000000..7729b0f0 --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedError.java @@ -0,0 +1,80 @@ +package dev.caskeleton.adapter.inbound.web.advanced.error; + +import dev.caskeleton.adapter.inbound.web.observability.RetryAfterHint; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.Category; + +/** + * The codes this leaf's exceptions carry to the client. Each exception implements {@link + * dev.caskeleton.shared.error.ApiErrorCarrier}, so the web adapter's one carrier branch answers it + * with this status — no second {@code @RestControllerAdvice}. The table the client reads is the + * leaf README's "오류 응답" section; it states the same values. + * + *

      Before this existed every one of these reached the client as {@code 500 INTERNAL_ERROR} with + * an ERROR log line, including an admission refusal the profile documents as a 503 (review + * 2026-11-01 02-07). + * + *

      Like {@code RateLimitTransportError}, these are not in {@code + * docs/registries/error-codes.yaml}, which is the {@code OperationalError} SSOT. + */ +public enum WebAdvancedError implements ApiErrorCode, RetryAfterHint { + + /** The virtual-thread admission limit was full. A refusal in a millisecond; come back shortly. */ + ADMISSION_REFUSED(Category.TRANSIENT_DEPENDENCY, 503, true, 1), + /** A JSON Patch {@code test} did not hold; nothing was applied. Re-read, then retry. */ + PATCH_TEST_FAILED(Category.CONFLICT, 409, false, 0), + /** The patch document is malformed or over a limit; nothing was applied. */ + PATCH_REJECTED(Category.VALIDATION, 400, false, 0), + /** The patch touches a field the caller may not modify. */ + PATCH_PATH_FORBIDDEN(Category.AUTHZ, 403, false, 0), + /** The request addressed an API major version this deployment does not serve. */ + API_VERSION_UNSUPPORTED(Category.NOT_FOUND, 404, false, 0), + /** A deprecation was declared with a past sunset or no link: a server configuration fault. */ + API_DEPRECATION_INVALID(Category.INTERNAL, 500, false, 0), + /** Request input proposed a tenant; only authentication may establish one. */ + TENANT_INPUT_UNTRUSTED(Category.AUTHZ, 403, false, 0), + /** The resume cursor is older than retained history. Re-read the resource, start a new stream. */ + STREAM_RESNAPSHOT_REQUIRED(Category.NOT_FOUND, 410, false, 0), + /** One stream item exceeded the per-item ceiling: the server's data, not the request. */ + STREAM_ITEM_TOO_LARGE(Category.INTERNAL, 500, false, 0), + /** Served routes differ from the approved manifest: a release-gate failure. */ + ROUTE_INVENTORY_MISMATCH(Category.INTERNAL, 500, false, 0); + + private final Category category; + private final int httpStatus; + private final boolean retryable; + private final int retryAfterSeconds; + + WebAdvancedError(Category category, int httpStatus, boolean retryable, int retryAfterSeconds) { + this.category = category; + this.httpStatus = httpStatus; + this.retryable = retryable; + this.retryAfterSeconds = retryAfterSeconds; + } + + @Override + public String code() { + return name(); + } + + @Override + public Category category() { + return category; + } + + @Override + public int httpStatus() { + return httpStatus; + } + + @Override + public boolean retryable() { + return retryable; + } + + /** Only read for a retryable code ({@code RetryAfterAdvisor}); zero for the others. */ + @Override + public int retryAfterSeconds() { + return retryAfterSeconds; + } +} diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchRejectedException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchRejectedException.java index 550a1410..ba0a9eb5 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchRejectedException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchRejectedException.java @@ -1,11 +1,21 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; +import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + /** A JSON Patch document that will not be applied, and was not partially applied either. */ -public final class JsonPatchRejectedException extends RuntimeException { +public final class JsonPatchRejectedException extends RuntimeException implements ApiErrorCarrier { private static final long serialVersionUID = 1L; public JsonPatchRejectedException(String message) { super(message); } + + /** {@link WebAdvancedError#PATCH_REJECTED}; see the leaf README for the client contract. */ + @Override + public ApiErrorCode errorCode() { + return WebAdvancedError.PATCH_REJECTED; + } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchTestFailedException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchTestFailedException.java index 071674bf..b74721af 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchTestFailedException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchTestFailedException.java @@ -1,5 +1,10 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; +import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; +import dev.caskeleton.adapter.inbound.web.error.ClientSafeErrorDetails; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; +import java.util.Map; import java.util.Objects; /** @@ -13,7 +18,8 @@ import java.util.Objects; * server's, and returning it would turn {@code test} into a read primitive for fields the caller * may not read. */ -public final class JsonPatchTestFailedException extends RuntimeException { +public final class JsonPatchTestFailedException extends RuntimeException + implements ApiErrorCarrier, ClientSafeErrorDetails { private static final long serialVersionUID = 1L; @@ -28,4 +34,15 @@ public final class JsonPatchTestFailedException extends RuntimeException { public String pointer() { return pointer; } + + /** {@link WebAdvancedError#PATCH_TEST_FAILED}; see the leaf README for the client contract. */ + @Override + public ApiErrorCode errorCode() { + return WebAdvancedError.PATCH_TEST_FAILED; + } + + @Override + public Map clientDetails() { + return Map.of("pointer", pointer); + } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java index 2136715c..93c1439c 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java @@ -1,6 +1,11 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; +import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; +import dev.caskeleton.adapter.inbound.web.error.ClientSafeErrorDetails; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; import java.util.List; +import java.util.Map; import java.util.Objects; /** @@ -9,7 +14,8 @@ import java.util.Objects; *

      Names the fields, because the caller needs to know which of them was refused and the names are * from the server's allowlist rather than from the request — so they are safe to echo. */ -public final class PatchAuthorizationException extends RuntimeException { +public final class PatchAuthorizationException extends RuntimeException + implements ApiErrorCarrier, ClientSafeErrorDetails { private static final long serialVersionUID = 1L; @@ -24,4 +30,15 @@ public final class PatchAuthorizationException extends RuntimeException { public List refusedPaths() { return refusedPaths; } + + /** {@link WebAdvancedError#PATCH_PATH_FORBIDDEN}; see the leaf README for the client contract. */ + @Override + public ApiErrorCode errorCode() { + return WebAdvancedError.PATCH_PATH_FORBIDDEN; + } + + @Override + public Map clientDetails() { + return Map.of("refusedPaths", refusedPaths); + } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/UntrustedTenantInputException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/UntrustedTenantInputException.java index 73dc786c..82160d41 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/UntrustedTenantInputException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/UntrustedTenantInputException.java @@ -1,5 +1,9 @@ package dev.caskeleton.adapter.inbound.web.advanced.security; +import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + /** * A tenant was proposed by request input rather than established by authentication. * @@ -10,7 +14,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.security; *

      The message names no value. Echoing the proposed tenant would put attacker-chosen content into * the log line that reports the attempt. */ -public final class UntrustedTenantInputException extends RuntimeException { +public final class UntrustedTenantInputException extends RuntimeException + implements ApiErrorCarrier { private static final long serialVersionUID = 1L; @@ -20,4 +25,12 @@ public final class UntrustedTenantInputException extends RuntimeException { "a tenant was supplied by request input; only an authenticated tenant may scope a request," + " because a caller-chosen one selects whose data is read"); } + + /** + * {@link WebAdvancedError#TENANT_INPUT_UNTRUSTED}; see the leaf README for the client contract. + */ + @Override + public ApiErrorCode errorCode() { + return WebAdvancedError.TENANT_INPUT_UNTRUSTED; + } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamItemTooLargeException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamItemTooLargeException.java index 3b1fde93..996d12c2 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamItemTooLargeException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamItemTooLargeException.java @@ -1,5 +1,9 @@ package dev.caskeleton.adapter.inbound.web.advanced.stream.encoding; +import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + /** * One stream item exceeded the policy's per-item ceiling. * @@ -8,7 +12,7 @@ package dev.caskeleton.adapter.inbound.web.advanced.stream.encoding; * written — leaves the consumer resynchronising past a partial record, which is recoverable for * JSON-seq and not for NDJSON. */ -public final class StreamItemTooLargeException extends RuntimeException { +public final class StreamItemTooLargeException extends RuntimeException implements ApiErrorCarrier { private static final long serialVersionUID = 1L; @@ -30,4 +34,12 @@ public final class StreamItemTooLargeException extends RuntimeException { public int maxBytes() { return maxBytes; } + + /** + * {@link WebAdvancedError#STREAM_ITEM_TOO_LARGE}; see the leaf README for the client contract. + */ + @Override + public ApiErrorCode errorCode() { + return WebAdvancedError.STREAM_ITEM_TOO_LARGE; + } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/ReplayCursorExpiredException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/ReplayCursorExpiredException.java index be9694c1..e714cc83 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/ReplayCursorExpiredException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/ReplayCursorExpiredException.java @@ -1,5 +1,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.stream.replay; +import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; import java.util.Objects; /** @@ -10,7 +13,8 @@ import java.util.Objects; * where the replay started, so nothing about the data says events are missing. An explicit * resnapshot-required answer costs the client a full re-read and is the only honest option. */ -public final class ReplayCursorExpiredException extends RuntimeException { +public final class ReplayCursorExpiredException extends RuntimeException + implements ApiErrorCarrier { private static final long serialVersionUID = 1L; @@ -25,4 +29,13 @@ public final class ReplayCursorExpiredException extends RuntimeException { public WebStreamResumeCursor cursor() { return cursor; } + + /** + * {@link WebAdvancedError#STREAM_RESNAPSHOT_REQUIRED}; see the leaf README for the client + * contract. + */ + @Override + public ApiErrorCode errorCode() { + return WebAdvancedError.STREAM_RESNAPSHOT_REQUIRED; + } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/SunsetViolationException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/SunsetViolationException.java index 08165370..bb86c8e5 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/SunsetViolationException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/SunsetViolationException.java @@ -1,5 +1,9 @@ package dev.caskeleton.adapter.inbound.web.advanced.versioning; +import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + /** * A deprecation was declared in a way a client cannot act on. * @@ -7,7 +11,7 @@ package dev.caskeleton.adapter.inbound.web.advanced.versioning; * deprecation with no documentation link, is a promise the deployment cannot keep — and discovering * that when the first client asks is discovering it from the client. */ -public final class SunsetViolationException extends RuntimeException { +public final class SunsetViolationException extends RuntimeException implements ApiErrorCarrier { private static final long serialVersionUID = 1L; @@ -15,4 +19,12 @@ public final class SunsetViolationException extends RuntimeException { public SunsetViolationException(String message) { super(message); } + + /** + * {@link WebAdvancedError#API_DEPRECATION_INVALID}; see the leaf README for the client contract. + */ + @Override + public ApiErrorCode errorCode() { + return WebAdvancedError.API_DEPRECATION_INVALID; + } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/UnsupportedApiVersionException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/UnsupportedApiVersionException.java index 203aec51..b8fc4b89 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/UnsupportedApiVersionException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/UnsupportedApiVersionException.java @@ -1,5 +1,9 @@ package dev.caskeleton.adapter.inbound.web.advanced.versioning; +import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + /** * A request addressed a major version this deployment does not serve. * @@ -10,7 +14,8 @@ package dev.caskeleton.adapter.inbound.web.advanced.versioning; * *

      The message names the version and never the path. A path carries identifiers. */ -public final class UnsupportedApiVersionException extends RuntimeException { +public final class UnsupportedApiVersionException extends RuntimeException + implements ApiErrorCarrier { private static final long serialVersionUID = 1L; @@ -36,4 +41,12 @@ public final class UnsupportedApiVersionException extends RuntimeException { public static UnsupportedApiVersionException missingVersion() { return new UnsupportedApiVersionException("the path carries no /api/v{major} version segment"); } + + /** + * {@link WebAdvancedError#API_VERSION_UNSUPPORTED}; see the leaf README for the client contract. + */ + @Override + public ApiErrorCode errorCode() { + return WebAdvancedError.API_VERSION_UNSUPPORTED; + } } diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java index 91ecd9a9..36912a06 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java @@ -1,5 +1,9 @@ package dev.caskeleton.adapter.inbound.web.advanced.virtualthread; +import dev.caskeleton.adapter.inbound.web.advanced.error.WebAdvancedError; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + /** * An arrival was refused because the concurrency limit was full. * @@ -7,7 +11,7 @@ package dev.caskeleton.adapter.inbound.web.advanced.virtualthread; * limit exists to produce — a request refused in a millisecond is strictly better for the client * than the same request accepted and timed out thirty seconds later behind a full connection pool. */ -public final class AdmissionRefusedException extends RuntimeException { +public final class AdmissionRefusedException extends RuntimeException implements ApiErrorCarrier { private static final long serialVersionUID = 1L; @@ -22,4 +26,10 @@ public final class AdmissionRefusedException extends RuntimeException { public int limit() { return limit; } + + /** {@link WebAdvancedError#ADMISSION_REFUSED}; see the leaf README for the client contract. */ + @Override + public ApiErrorCode errorCode() { + return WebAdvancedError.ADMISSION_REFUSED; + } } diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java new file mode 100644 index 00000000..6e810ebf --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/error/WebAdvancedErrorMappingTest.java @@ -0,0 +1,140 @@ +package dev.caskeleton.adapter.inbound.web.advanced.error; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import dev.caskeleton.adapter.inbound.web.advanced.admin.route.RouteInventoryMismatchException; +import dev.caskeleton.adapter.inbound.web.advanced.patch.JsonPatchRejectedException; +import dev.caskeleton.adapter.inbound.web.advanced.patch.JsonPatchTestFailedException; +import dev.caskeleton.adapter.inbound.web.advanced.patch.PatchAuthorizationException; +import dev.caskeleton.adapter.inbound.web.advanced.security.UntrustedTenantInputException; +import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamItemTooLargeException; +import dev.caskeleton.adapter.inbound.web.advanced.stream.replay.ReplayCursorExpiredException; +import dev.caskeleton.adapter.inbound.web.advanced.stream.replay.WebStreamResumeCursor; +import dev.caskeleton.adapter.inbound.web.advanced.versioning.SunsetViolationException; +import dev.caskeleton.adapter.inbound.web.advanced.versioning.UnsupportedApiVersionException; +import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.AdmissionRefusedException; +import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.shared.tracing.SpanErrorRecorder; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import java.util.stream.Stream; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +/** + * Every exception this leaf throws reaches the client as the status and code the README table + * promises, through the web adapter's one carrier branch — never as {@code 500 INTERNAL_ERROR}. + */ +@Tag("web-advanced") +class WebAdvancedErrorMappingTest { + + private static final Map> FAILURES = + Map.of( + "admission", () -> new AdmissionRefusedException(8), + "patch-test", () -> new JsonPatchTestFailedException("/version"), + "patch-rejected", () -> new JsonPatchRejectedException("too many operations"), + "patch-forbidden", () -> new PatchAuthorizationException(List.of("/role")), + "version", () -> UnsupportedApiVersionException.unknownMajor(9), + "sunset", () -> new SunsetViolationException("sunset in the past"), + "tenant", UntrustedTenantInputException::new, + "cursor", () -> new ReplayCursorExpiredException(new WebStreamResumeCursor("42")), + "item", () -> new StreamItemTooLargeException(2048, 1024), + "inventory", () -> new RouteInventoryMismatchException("undeclared GET /x")); + + private final MockMvc mvc = + MockMvcBuilders.standaloneSetup(new Probe()) + .setControllerAdvice(new GlobalExceptionHandler(SpanErrorRecorder.NOOP)) + .build(); + + static Stream documentedMappings() { + return Stream.of( + Arguments.of("admission", 503, "ADMISSION_REFUSED", "TRANSIENT_DEPENDENCY", true), + Arguments.of("patch-test", 409, "PATCH_TEST_FAILED", "CONFLICT", false), + Arguments.of("patch-rejected", 400, "PATCH_REJECTED", "VALIDATION", false), + Arguments.of("patch-forbidden", 403, "PATCH_PATH_FORBIDDEN", "AUTHZ", false), + Arguments.of("version", 404, "API_VERSION_UNSUPPORTED", "NOT_FOUND", false), + Arguments.of("sunset", 500, "API_DEPRECATION_INVALID", "INTERNAL", false), + Arguments.of("tenant", 403, "TENANT_INPUT_UNTRUSTED", "AUTHZ", false), + Arguments.of("cursor", 410, "STREAM_RESNAPSHOT_REQUIRED", "NOT_FOUND", false), + Arguments.of("item", 500, "STREAM_ITEM_TOO_LARGE", "INTERNAL", false), + Arguments.of("inventory", 500, "ROUTE_INVENTORY_MISMATCH", "INTERNAL", false)); + } + + @ParameterizedTest(name = "{0} -> {1} {2}") + @MethodSource("documentedMappings") + @DisplayName("web-advanced 예외는 문서에 적힌 상태·코드·재시도 여부로 나간다") + void eachExceptionLeavesWithItsDocumentedStatusAndCode( + String failure, int status, String code, String category, boolean retryable) + throws Exception { + // when + var result = mvc.perform(get("/fail/" + failure)); + + // then + result + .andExpect(status().is(status)) + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.error.code").value(code)) + .andExpect(jsonPath("$.error.category").value(category)) + .andExpect(jsonPath("$.error.retryable").value(retryable)); + } + + @Test + @DisplayName("동시성 한도 거절은 503에 Retry-After를 단다") + void anAdmissionRefusalCarriesRetryAfter() throws Exception { + // when + var result = mvc.perform(get("/fail/admission")); + + // then + result + .andExpect(status().isServiceUnavailable()) + .andExpect(header().string("Retry-After", "1")); + } + + @Test + @DisplayName("patch test 실패는 실패한 pointer를 알려 주고 서버 값은 알려 주지 않는다") + void aFailedPatchTestNamesThePointerAndNotTheServerValue() throws Exception { + // when + var result = mvc.perform(get("/fail/patch-test")); + + // then + result + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error.details.pointer").value("/version")) + .andExpect(jsonPath("$.error.details.value").doesNotExist()); + } + + @Test + @DisplayName("patch 권한 거절은 거절된 경로 목록을 알려 준다") + void aRefusedPatchNamesTheRefusedPaths() throws Exception { + // when + var result = mvc.perform(get("/fail/patch-forbidden")); + + // then + result + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.error.details.refusedPaths", Matchers.contains("/role"))); + } + + @RestController + static class Probe { + + @GetMapping("/fail/{failure}") + Map fail(@PathVariable String failure) { + throw FAILURES.get(failure).get(); + } + } +} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java index 3249b9cc..569f66c5 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java @@ -1,13 +1,19 @@ package dev.caskeleton.adapter.inbound.web.fileserver.config; +import dev.caskeleton.adapter.inbound.web.auth.CorsExposedHeaders; import dev.caskeleton.adapter.inbound.web.fileserver.controller.FileDownloadController; import dev.caskeleton.adapter.inbound.web.fileserver.controller.FileUploadController; +import dev.caskeleton.adapter.inbound.web.fileserver.draft12.Draft12Headers; import dev.caskeleton.adapter.inbound.web.fileserver.draft12.Draft12UploadController; import dev.caskeleton.adapter.inbound.web.fileserver.lifecycle.FileLifecycleController; import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverExceptionHandler; import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusController; +import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusHeaders; +import java.util.List; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; +import org.springframework.http.HttpHeaders; /** * The public Fileserver HTTP surface, as one importable unit. @@ -26,4 +32,27 @@ import org.springframework.context.annotation.Import; FileserverExceptionHandler.class, MvcTransferExecutorConfiguration.class }) -public class FileserverHttpSurfaceConfiguration {} +public class FileserverHttpSurfaceConfiguration { + + /** + * The response headers the upload and download routes write that a cross-origin browser must be + * allowed to read: without {@code Upload-Offset} a tus or draft-12 client cannot resume. + */ + @Bean + CorsExposedHeaders fileserverCorsExposedHeaders() { + return new CorsExposedHeaders( + List.of( + TusHeaders.RESUMABLE, + TusHeaders.VERSION, + TusHeaders.EXTENSION, + TusHeaders.MAX_SIZE, + TusHeaders.UPLOAD_OFFSET, + TusHeaders.UPLOAD_LENGTH, + TusHeaders.UPLOAD_DEFER_LENGTH, + TusHeaders.UPLOAD_EXPIRES, + Draft12Headers.UPLOAD_COMPLETE, + Draft12Headers.UPLOAD_LIMIT, + HttpHeaders.CONTENT_DISPOSITION, + HttpHeaders.ACCEPT_RANGES)); + } +} diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java new file mode 100644 index 00000000..78d58122 --- /dev/null +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverCorsExposedHeadersTest.java @@ -0,0 +1,28 @@ +package dev.caskeleton.adapter.inbound.web.fileserver.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.web.auth.CorsExposedHeaders; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class FileserverCorsExposedHeadersTest { + + @Test + @DisplayName("fileserver HTTP 표면은 업로드 재개에 필요한 헤더를 CORS 노출 목록에 기여한다") + void theSurfaceContributesTheHeadersAResumingClientMustRead() { + // when + CorsExposedHeaders contributed = + new FileserverHttpSurfaceConfiguration().fileserverCorsExposedHeaders(); + + // then + assertThat(contributed.headerNames()) + .contains( + "Tus-Resumable", + "Upload-Offset", + "Upload-Length", + "Upload-Expires", + "Upload-Complete", + "Content-Disposition"); + } +} diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 24540436..881276ff 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -103,6 +103,13 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML - `AUTHZ_TENANT_MISMATCH` 는 여기서 추론 불가 — application-layer 의 cross-tenant 결정이며, 일반 `AccessDeniedException` 에는 `AUTHZ_INSUFFICIENT_PERMISSION` 만 방출한다. +### EnvelopeResponseWriter +- 컨버터 밖에서 본문을 직접 쓰는 거부 응답(보안 entry point·access-denied handler·rate-limit + interceptor)이 쓰는 하나의 writer. status·`application/json`·**UTF-8**·`ErrorResponseFactory` 본문을 + 정한다. Tomcat 의 기본 응답 문자셋은 ISO-8859-1 이라 문자셋을 빠뜨리면 한국어 문구가 `???` 가 된다 + (리뷰 02-04 — rate-limit 이 그랬다). 거부별 헤더(`WWW-Authenticate`, `Retry-After`, `X-RateLimit-*`)는 + 호출자가 본문을 쓰기 전에 붙인다. GraphQL body limit filter 는 다른 leaf 라 자기 writer 를 쓴다(UTF-8 지정). + ### AuthErrorResponseWriter - **토큰/PII 리댁션.** 응답 본문엔 해당 코드의 일반 `client_safe_message` 만 담고, 원시 예외 텍스트·`Authorization` 헤더·issuer·audience 는 @@ -201,8 +208,14 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML 하나로 매핑한다. 5xx 는 원인과 함께 로그를 남기고(persistence 는 분류만), retryable 코드는 `RetryAfterAdvisor`로 `Retry-After`를 붙인다. - 개별 override 가 없는 Spring MVC 예외(필수 파라미터·헤더·part 누락, binding 실패 등)는 - `handleExceptionInternal` override 가 상태 코드 → `OperationalError`로 바꿔 같은 Envelope 로 보낸다. + `handleExceptionInternal` override 가 상태 코드 → 코드로 바꿔 같은 Envelope 로 보낸다. 503(Spring 의 + async 요청 시간 초과)은 `INTERNAL_ERROR` 가 아니라 `REQUEST_TIMEOUT`(503, retryable) 이다(리뷰 02-08). `application/problem+json`은 나가지 않는다(I-3a). +- carrier 가 `ClientSafeErrorDetails` 도 구현하면 그 값이 `error.details` 가 된다(web-advanced 의 patch + pointer·거절 경로). 코드가 `RetryAfterHint` 를 구현하면 `Retry-After` 값은 그 코드가 정한다. +- **등록은 한 곳이다.** `WebMvcPlatformAutoConfiguration` 의 `@ConditionalOnMissingBean` bean 하나뿐이다. + `app.web.mvc.enabled=false` 면 이 핸들러·요청 id 필터·JSON 본문 상한·중복 키 거부가 함께 빠지고, + 서비스가 셋을 직접 준다. 같은 타입 bean 을 주면 그것만 쓰인다(리뷰 02-10, `WebMvcPlatformAutoConfigurationTest`). - `adapter-web` 에 위치하는 이유: 실행 앱이 어떤 sample 모듈에도 의존하지 않고 envelope 형식 에러 응답을 제공하도록. - **`spanErrorRecorder`.** 프로덕션 코드를 특정 트레이서 @@ -220,6 +233,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML | `IllegalArgumentException` | `BAD_PARAMETER` | 400 | B3: 매퍼가 아닌 호출자의 일반 예외 | | `ConstraintViolationException` | `VALIDATION_FAILED` | 400 | 정규화된 field + allowlisted reason code/fixed message 리스트를 details 로. interpolated message와 iterable key/index는 미노출 | | `MethodArgumentTypeMismatchException` | `BAD_PARAMETER` | 400 | parameter·expectedType 을 details 로 | +| `HandlerMethodValidationException` | `VALIDATION_FAILED` | 400 | 컨트롤러 파라미터 제약(`@RequestParam @Max(10)`) 위반. 요청 본문 위반과 같은 코드·같은 details 모양(field=파라미터 이름, code=제약). 거절된 값은 미노출(리뷰 02-08) | +| `InvalidIdempotencyKeyException` | `IDEMPOTENCY_KEY_INVALID` | 400 | `IdempotencyKeyHeader.parse` 가 헤더 누락·문법 밖을 거부. `details.reason` = `MISSING`/`MALFORMED`, 키 원문 미노출(리뷰 02-12) | | `InvalidBearerTokenException` | `INVALID_TOKEN` | 코드 상태 | | | `AuthenticationException` | `UNAUTHENTICATED` | 코드 상태 | | | `AccessDeniedException` | `SecurityErrorClassifier` 결정(예: `AUTHZ_INSUFFICIENT_PERMISSION`) | 분류기 결정 | 메서드-시큐리티 거부가 컨트롤러를 빠져나오면 여기 도달. 필터 계층 `EnvelopeAccessDeniedHandler` 와 **동일한 세분화 코드**를 내도록 무상태 classifier 에 위임 | @@ -238,7 +253,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML | `MethodArgumentNotValidException` | `VALIDATION_FAILED` | 코드 상태 | 정규화된 field + allowlisted reason code/fixed message 리스트를 details 로. rejectedValue/defaultMessage/iterable key/index는 secret/PII 가능성이 있어 미노출 | | `HttpMessageNotReadableException` | `VALIDATION_FAILED` | 코드 상태 | cause 클래스명을 details 로 | | `NoHandlerFoundException`, `NoResourceFoundException` | `ROUTE_NOT_FOUND` | 코드 상태 | controller/static-resource 어느 404 경로도 같은 Envelope를 사용하고 raw request URL을 echo하지 않음 | -| 그 밖의 Spring MVC 예외(`MissingServletRequestParameterException`, `MissingRequestHeaderException`, `MissingServletRequestPartException`, `ServletRequestBindingException` …) | 상태 → `OperationalError`(4xx 는 대개 `BAD_PARAMETER`) | 코드 상태 | `handleExceptionInternal` override. problem+json 이 새지 않게 | +| `AsyncRequestTimeoutException` | `REQUEST_TIMEOUT` | 503 (retryable=true) | Spring 이 503 으로 분류한 일시적 시간 초과. 이전에는 `INTERNAL_ERROR` 500 이었다(리뷰 02-08) | +| 그 밖의 Spring MVC 예외(`MissingServletRequestParameterException`, `MissingRequestHeaderException`, `MissingServletRequestPartException`, `ServletRequestBindingException` …) | 상태 → 코드(4xx 는 대개 `BAD_PARAMETER`, 나머지 5xx 는 `INTERNAL_ERROR`) | 코드 상태 | `handleExceptionInternal` override. problem+json 이 새지 않게 | | `ApiErrorCarrier` (위에 없는 adopter 예외 포함) | `errorCode()` | 코드 결정 | `handleCarrier` 한 분기 | | `Exception` (catch-all) | `INTERNAL_ERROR` | 500 | span 에러 기록 + 불투명 문구(`ClientErrorMessages.OPAQUE`) | @@ -258,6 +274,16 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML Boot `JsonMapper` 에 등록한다(shared-contract 는 Jackson 에 의존하지 않으므로 타입에 애너테이션을 달지 않는다). 키 목록과 근거는 `docs/web/http-contract.md` §1, 원문 키 집합 단언은 `EnvelopeWireShapeTest`. +- **이미 직렬화된 `byte[]` 본문은 감싸지 않는다.** 그 본문을 쓰는 converter 는 받은 값을 그대로 복사하므로 + envelope 객체를 받으면 500 으로 끝난다. springdoc 이 OpenAPI 문서를 `byte[]` 로 돌려주어, 감싸던 시절에는 + 실행 중인 앱의 `/api/v3/api-docs` 가 항상 500 이었다(리뷰 09-04). `String` 반환은 감싸되 JSON 문자열로 + 직렬화해 넘긴다(리뷰 02-06). 단언은 `EnvelopeBodyAdviceTest`, 샘플 전체 조합의 `SampleApiDocsSystemTest`. +- **`String` 반환도 JSON 클라이언트에게는 Envelope 다.** `String` 은 `StringHttpMessageConverter` 가 + Jackson 보다 먼저 고른다. 예전에는 그 컨버터에 `Envelope` 객체를 넘겨 `Accept: application/json` 이면 + `ClassCastException` 500, `*/*` 면 200 text 였다(리뷰 02-06). 지금은 String 컨버터가 JSON 을 쓰게 될 때 + advice 가 같은 mapper 로 Envelope 를 문자열로 직렬화해 넘긴다. 텍스트를 요청한 클라이언트는 그대로 + 문자열을 받는다. ArchUnit 으로 `String` 반환을 금지하는 안은 버렸다: `text/plain` 엔드포인트의 정당한 + 용도를 막고, 규칙을 돌리지 않는 서비스에는 함정이 그대로 남는다. - 위치: sample 모듈이 아니라 adapter-web. 실행 앱은 adapter-web 에 의존하지만 sample-portfolio 에는 의존하지 않으므로, 응답 래핑이 실제로 동작하려면 여기 있어야 한다. @@ -280,7 +306,11 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML `WebMvcRequestIdFilter` 의 것이다. - **MDC 키 정책(D11/D19).** `MdcKeys` 의 snake_case 키 사용. - **인바운드 id 헤더(D14/D15).** `X-Request-Id` 는 기본적으로 받지 않고 서버가 만든다(신뢰 설정 시 안전 문자만). - `X-Correlation-Id` 는 사용 전 sanitize(CR/LF + control 제거) 및 길이 제한. 부재/공백은 서버 생성. + `X-Correlation-Id` 는 요청 id 와 같은 규칙(`[A-Za-z0-9._-]{1,128}`, 앞뒤 공백 제거)을 통과하면 그대로 + 잇고, 아니면 서버가 새로 만든다. 예전에는 제어문자만 지우고 200자까지 그대로 내보내 공백·유니코드·DEL 이 + 응답 헤더와 `meta.correlationId` 에 실렸고, 짝 프론트의 envelope 검증(`[A-Za-z0-9._:-]{1,128}`)이 그 + 응답 전체를 거절했다(리뷰 02-11). 고친 값을 쓰지 않고 바꾸는 이유: 고친 값은 더 이상 호출자의 값이 아니라 + 상관관계를 잇지 못한다. - **W3C `traceparent`(D5/D7/D4).** 유효한 인바운드 traceparent 가 있으면 채택해 그 `traceId`→MDC `trace_id`, `spanId`→`span_id`. 부재/공백/무효면 fresh ROOT traceparent 생성(32-hex traceId, 16-hex spanId, sampled=false)하여 MDC `trace_id` 가 **항상** 의미 있는 W3C id 이고 절대 null 이 아니게 한다(D4: 추적 비활성 @@ -351,6 +381,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML `X-RateLimit-*` 헤더를 포함한다(generated_if_missing=true). - 한도 초과 거부 응답의 세 보장(RATE_LIMIT category + retryable + `Retry-After`)이 클라이언트가 이를 retryable 의존성 장애로 오분류하는 것을 막는다. +- 본문은 `EnvelopeResponseWriter` 로 쓴다(UTF-8). --- @@ -369,6 +400,18 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML 는 `Access-Control-Allow-Credentials: true` 와 함께 보낼 수 없다. Spring 런타임 검사에 의존하지 않고 기동 시점에 fail-fast 거부. +### CorsExposedHeaders +- 브라우저는 CORS 안전 목록 밖의 응답 헤더를 `Access-Control-Expose-Headers` 에 없으면 숨긴다. 예전에는 + 노출 목록이 비어 cross-origin 클라이언트가 `Retry-After`·`X-Request-Id`·`Location`·tus offset 을 못 + 읽었다(리뷰 02-05). +- `SecurityConfig` 는 `CorsExposedHeaders.PLATFORM`(이 leaf 가 쓰는 `Retry-After`, `X-Request-Id`, + `X-Correlation-Id`, `traceparent`, `Location`, `ETag`, `X-RateLimit-*`)에 모든 `CorsExposedHeaders` bean 을 + 더해 노출한다. 헤더를 쓰는 모듈이 기여한다(`RestrictedPathRule` 과 같은 방식). web-fileserver 는 tus·draft-12 + 헤더와 `Content-Disposition`·`Accept-Ranges` 를 기여한다. +- 설정 키(env)로 열지 않은 이유: 노출할 헤더는 코드가 쓰는 헤더라 운영자가 고를 값이 아니다. env 로 두면 + 기본 배포가 계속 깨지거나 모듈과 목록이 따로 논다. `*` 는 credentials 모드에서 리터럴 이름으로 취급돼 + 쓰지 않는다. 노출 헤더는 실제 응답에만 붙는다(preflight 에는 의미가 없다). + ### EdgeRateLimitTransportSettings - `app.rate-limit.*`은 HTTP enforcement, default policy ID, pseudonymization key version, @@ -389,6 +432,16 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML Jackson 이 역직렬화하지 못해 absent / explicit-null 구분이 조용히 붕괴된다. - 스켈레톤 전역 web 관심사(공유 `Patch` 타입과 짝)라 도메인 샘플 모듈이 아니라 adapter-web 에 위치. +### IdempotencyKeyHeader +- KEYED 엔드포인트가 헤더를 키로 바꾸는 유일한 지점(리뷰 02-12). 문법: 보이는 ASCII(`0x21`–`0x7E`) + 1~256자, trim·재작성 없음 — 짝 프론트의 `isValidIdempotencyKey` 와 같은 규칙. +- 누락과 형식 오류는 둘 다 `400 IDEMPOTENCY_KEY_INVALID`(`details.reason` = `MISSING`/`MALFORMED`). + 헤더는 `required = false` 로 받고 `IdempotencyKeyHeader.parse` 를 부른다. `required = true` 면 누락이 + `BAD_PARAMETER` 로 먼저 나간다. +- 공용으로 만든 것은 추출뿐이다. claim·fingerprint·replay 는 use case 와 `IdempotencyExecutor` 가 소유한다 + (아래 idempotency 절). 대안 — 엔드포인트마다 검증(현상 유지)은 복사본이 갈라지고, 모든 POST 에 강제하는 + 필터는 KEYED 가 아닌 엔드포인트까지 막아 버렸다. + ### ApiHeaders - 인바운드 web 어댑터 전역의 HTTP 헤더명 상수 — `docs/registries/headers.yaml`의 코드 미러. 리터럴을 중앙집중해 controller/filter/advice 가 casing 으로 drift 하지 않게 하고, 레지스트리 @@ -415,6 +468,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML 참조하지 않고 event-id fallback 정책만 소유한다. ### HeaderSanitizer +- 이제 `X-Correlation-Id` 는 쓰지 않는다(요청 id 규칙으로 바뀜, 리뷰 02-11). 공개 유틸리티로 남아 있다. - 인바운드 헤더 값을 MDC/로그 도달 전에 무해화(D14, OWASP-LOG-C3/C5, CWE-117). 스켈레톤은 구조화 JSON 로깅을 가정하므로 위협은 CR/LF/제어문자를 통한 로그 라인 위조 — 값은 보존하되 `\r`/`\n`/ASCII 제어문자(`< 0x20`)를 제거 후 길이 제한. @@ -436,6 +490,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML - 필드 `RETRY_AFTER_SECONDS` 는 error-codes.yaml 의 `retry_after_seconds` 컬럼 미러. 이 advisor 가 유일한 Retry-After 노출 지점이라 여기 중앙화한다. `DEPENDENCY_4XX_CLIENT` 는 비재시도(retryable=false)라 `shouldAdvise` 가드로 empty 반환. +- 다른 leaf 가 소유한 코드는 이 표에 이름으로 넣지 않고 `RetryAfterHint` 를 구현해 값을 스스로 말한다 + (web-advanced `ADMISSION_REFUSED` = 1초). - `IDEMPOTENT_IN_FLIGHT` 는 2초: 기본 processing lease(30s)보다 짧아 첫 시도가 끝날 수 있는 동안 같은 키로 다시 묻게 한다. 근거와 클라이언트 행동은 `docs/web/http-contract.md` §2. @@ -482,6 +538,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML replay / in-flight arbitration은 application use case가 소유**한다. - web leaf에는 별도 DB replay 엔진을 두지 않는다. 같은 요청 의미를 web/application 두 계층이 서로 다른 fingerprint로 판정하면 동일 key의 의미가 endpoint마다 달라지기 때문이다. +- 헤더 → 키 변환은 `IdempotencyKeyHeader` 하나로 한다(위 settings / config / http 절). - production 예시는 sample의 poster image publication 경로다. controller는 key를 받기만 하고, `PublishPosterImageUseCase`가 application `IdempotencyExecutor`를 사용한다. - response-loss system fixture도 동일한 application executor를 사용해, 연결이 끊긴 뒤 같은 key 재시도에서 diff --git a/src/adapter/inbound/web/build.gradle b/src/adapter/inbound/web/build.gradle index f38b936d..b343225e 100644 --- a/src/adapter/inbound/web/build.gradle +++ b/src/adapter/inbound/web/build.gradle @@ -12,6 +12,9 @@ plugins { // HTTP / web adapters. Depends on application and shared operational contracts. dependencies { implementation project(':application-core') + // A controller turns a path segment into the domain identifier the query carries + // (registry edge `adapter:inbound:web -> domain-core`); docs/manual/02-new-feature.md step 4. + implementation project(':domain-core') // No `application-notification`. The notification HTTP surface is // `adapter:inbound:web-notification`, which depends on this leaf rather than living inside it. // `PresentationWebConfigTest` names the capability controllers as the examples of an absolute @@ -38,6 +41,11 @@ dependencies { // The operation controller's contract test drives the real use cases over the port owners' // fakes (operation store, outbox, transaction port). testImplementation testFixtures(project(':application-core')) + // The operation-id test runs the controller with the real UUIDv7 generator: the id is also the + // event id, and only the generator's output proves the platform will accept it. + testImplementation project(':adapter:outbound:identifier') + // A feature controller's contract test drives its use cases over the domain ports' fakes. + testImplementation testFixtures(project(':domain-core')) } tasks.named('test') { @@ -139,21 +147,18 @@ strictTestLanes { system() sourceSet = 'systemTest' description = 'Runs the Stable HTTP system contract against the default Tomcat runtime.' - jvmArgs '-Duser.timezone=UTC' } lane('performanceTest') { performance() sourceSet = 'performanceTest' description = 'Runs Tomcat load, resource-bound, slow-client and graceful-shutdown checks.' - jvmArgs '-Duser.timezone=UTC' } lane('webJettyPerformanceTest') { performance() sourceSet = 'jettyCompatTest' description = 'Runs Jetty load, resource-bound, slow-client and graceful-shutdown checks.' - jvmArgs '-Duser.timezone=UTC' requires('dev.caskeleton.adapter.inbound.web.testkit.performance.JettyLoadAndShutdownIT') } @@ -161,7 +166,6 @@ strictTestLanes { system() sourceSet = 'jettyCompatTest' description = 'Runs the Stable HTTP system contract against a real Jetty instead of Tomcat.' - jvmArgs '-Duser.timezone=UTC' requires( 'dev.caskeleton.adapter.inbound.web.testkit.fault.JettyCommitThenConnectionResetIT', 'dev.caskeleton.adapter.inbound.web.testkit.mvc.JettyWebContractIT', @@ -184,7 +188,6 @@ strictTestLanes { tag = 'security-boundary' description = 'Runs hermetic JWT/JWKS and CORS filter-boundary contracts with no skips.' shouldRunAfter 'test' - jvmArgs '-Duser.timezone=UTC' rejectSkipped = true } } diff --git a/src/adapter/inbound/web/gradle.lockfile b/src/adapter/inbound/web/gradle.lockfile index 490d6cee..f9e7daf3 100644 --- a/src/adapter/inbound/web/gradle.lockfile +++ b/src/adapter/inbound/web/gradle.lockfile @@ -12,6 +12,7 @@ com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=compileClasspath,j com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath com.fasterxml:classmate:1.7.3=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.github.f4b6a3:uuid-creator:6.1.1=jettyCompatTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs com.github.spotbugs:spotbugs:4.10.2=spotbugs diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java index 78901bde..79068f66 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java @@ -1,21 +1,18 @@ package dev.caskeleton.adapter.inbound.web.auth; -import dev.caskeleton.adapter.inbound.web.error.ErrorResponseFactory; +import dev.caskeleton.adapter.inbound.web.error.EnvelopeResponseWriter; import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor; import dev.caskeleton.shared.error.OperationalError; -import dev.caskeleton.shared.response.Envelope; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; -import java.nio.charset.StandardCharsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; import tools.jackson.databind.ObjectMapper; /** - * Writes a classified security failure to the servlet response as the skeleton-wide {@link + * Writes a classified security failure to the servlet response as the skeleton-wide {@code * Envelope} (same shape as every other error), and logs it safely. The response body and log line * carry only redacted, client-safe metadata. See README for the design rationale. */ @@ -39,10 +36,6 @@ class AuthErrorResponseWriter { request.getMethod(), request.getRequestURI()); - response.setStatus(code.httpStatus()); - response.setContentType(MediaType.APPLICATION_JSON_VALUE); - response.setCharacterEncoding(StandardCharsets.UTF_8.name()); - // A 401 response carries a minimal WWW-Authenticate header (no issuer / token detail). if (code.httpStatus() == 401) { response.setHeader( @@ -55,7 +48,6 @@ class AuthErrorResponseWriter { .ifPresent( seconds -> response.setHeader(HttpHeaders.RETRY_AFTER, Integer.toString(seconds))); - Envelope body = ErrorResponseFactory.body(code, null); - objectMapper.writeValue(response.getWriter(), body); + EnvelopeResponseWriter.write(response, code, objectMapper); } } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/CorsExposedHeaders.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/CorsExposedHeaders.java new file mode 100644 index 00000000..6af22a5c --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/CorsExposedHeaders.java @@ -0,0 +1,54 @@ +package dev.caskeleton.adapter.inbound.web.auth; + +import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; +import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; +import java.util.List; +import java.util.Objects; + +/** + * Response headers a cross-origin browser client may read. + * + *

      A browser hides every response header outside the CORS safelist unless the response names it + * in {@code Access-Control-Expose-Headers}. Without that, a client on another origin sees {@code + * Retry-After}, {@code X-Request-Id}, {@code Location} and the tus offsets as {@code null}: it + * cannot back off, quote a request id, follow a 202 or resume an upload. + * + *

      The list is code, not configuration: these are headers this code writes, so the module that + * writes one contributes it, the same way {@link RestrictedPathRule} is contributed. {@link + * #PLATFORM} is what this leaf writes; a capability that writes more (the fileserver's tus and + * draft-12 headers) registers its own bean, and {@link SecurityConfig} exposes the union. A {@code + * *} would not do: with credentials the browser reads it as a header literally named {@code *}. + * + * @param headerNames header names to expose; never empty + */ +public record CorsExposedHeaders(List headerNames) { + + /** The headers {@code adapter:inbound:web} itself writes on a response. */ + public static final CorsExposedHeaders PLATFORM = + new CorsExposedHeaders( + List.of( + ApiHeaders.RETRY_AFTER, + WebMvcRequestIdFilter.REQUEST_ID_HEADER, + WebMvcRequestIdFilter.CORRELATION_ID_HEADER, + WebMvcRequestIdFilter.TRACEPARENT_HEADER, + ApiHeaders.LOCATION, + ApiHeaders.ETAG, + ApiHeaders.X_RATELIMIT_LIMIT, + ApiHeaders.X_RATELIMIT_REMAINING, + ApiHeaders.X_RATELIMIT_RESET)); + + public CorsExposedHeaders { + Objects.requireNonNull(headerNames, "headerNames"); + if (headerNames.isEmpty()) { + throw new IllegalArgumentException("headerNames must not be empty"); + } + headerNames.forEach( + name -> { + if (name == null || name.isBlank() || "*".equals(name.strip())) { + throw new IllegalArgumentException( + "an exposed header is a concrete header name, not blank or \"*\""); + } + }); + headerNames = List.copyOf(headerNames); + } +} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java index 81eced3c..0ca348d0 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java @@ -70,11 +70,12 @@ public class SecurityConfig { AccessDeniedHandler accessDeniedHandler, org.springframework.beans.factory.ObjectProvider sessionSecurityContextRepository, - org.springframework.beans.factory.ObjectProvider restrictedPaths) + org.springframework.beans.factory.ObjectProvider restrictedPaths, + CorsConfigurationSource corsConfigurationSource) throws Exception { String[] publicPaths = securitySettings.publicPaths().toArray(new String[0]); java.util.List restricted = restrictedPaths.orderedStream().toList(); - http.cors(c -> c.configurationSource(corsConfigurationSource())) + http.cors(c -> c.configurationSource(corsConfigurationSource)) // Disable Spring Security's default Cache-Control writer; CacheControlFilter // owns the cache header policy. See README for the design rationale. .headers(headers -> headers.cacheControl(cache -> cache.disable())) @@ -141,8 +142,14 @@ public class SecurityConfig { return http.build(); } + /** + * The CORS policy. Exposed headers are {@link CorsExposedHeaders#PLATFORM} plus every contributed + * {@link CorsExposedHeaders} bean; the browser applies them to actual responses, not preflights. + */ @Bean - public CorsConfigurationSource corsConfigurationSource() { + public CorsConfigurationSource corsConfigurationSource( + org.springframework.beans.factory.ObjectProvider + contributedExposedHeaders) { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); if (!corsSettings.enabled()) { return source; // no patterns registered -> Spring uses null config -> CORS inactive @@ -153,6 +160,10 @@ public class SecurityConfig { cfg.setAllowedHeaders(corsSettings.allowedHeaders()); cfg.setAllowCredentials(corsSettings.allowCredentials()); cfg.setMaxAge(corsSettings.maxAgeSeconds()); + java.util.Set exposed = + new java.util.LinkedHashSet<>(CorsExposedHeaders.PLATFORM.headerNames()); + contributedExposedHeaders.orderedStream().forEach(c -> exposed.addAll(c.headerNames())); + cfg.setExposedHeaders(java.util.List.copyOf(exposed)); source.registerCorsConfiguration("/**", cfg); return source; } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java index 61c06223..d454781c 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java @@ -3,29 +3,58 @@ package dev.caskeleton.adapter.inbound.web.envelope; import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; import dev.caskeleton.shared.response.BulkEnvelope; import dev.caskeleton.shared.response.Envelope; +import java.util.Objects; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; +import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; /** * Wraps every JSON controller response in {@link Envelope} unless it is already an envelope - * variant, so the wire shape is always {@code {success, data | error, traceId}}. See README for the + * variant, so the wire shape is always {@code {success, data | error, meta}}. See README for the * design rationale. * *

      Skipped: already-{@link Envelope}/{@link BulkEnvelope} bodies, null/void (DELETE 204), - * non-JSON content types. + * non-JSON content types, and {@code byte[]} bodies. A {@code byte[]} body is already serialized + * and {@link ByteArrayHttpMessageConverter} copies it verbatim; handed an envelope object it fails + * the request with a 500. springdoc returns its OpenAPI document this way, so wrapping it broke + * {@code /v3/api-docs} on every composition that carries this advice (review 2026-11-01 09-04). + * + *

      A {@code String} return value is written by {@link StringHttpMessageConverter}, which Spring + * picks before Jackson. Handing that converter an {@link Envelope} object is a {@code + * ClassCastException} and a 500 for every JSON client, while {@code curl} with {@code *}{@code /*} + * still sees {@code 200 text/plain}. So when the String converter is about to write JSON, the + * envelope is serialised here, with the same mapper and wire rules, and the converter writes that + * text (review 2026-11-01 02-06). A text client still gets the plain string. */ @RestControllerAdvice public class EnvelopeBodyAdvice implements ResponseBodyAdvice { + private final ObjectMapper objectMapper; + + /** Spring entry point: Boot's mapper, which already carries the envelope wire rules. */ + @Autowired + public EnvelopeBodyAdvice(ObjectMapper objectMapper) { + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + } + + /** For standalone MockMvc and explicit wiring: a mapper with only the envelope wire rules. */ + public EnvelopeBodyAdvice() { + this(JsonMapper.builder().addModule(EnvelopeWireFormatConfig.module()).build()); + } + @Override public boolean supports( MethodParameter returnType, Class> converterType) { - return true; + return !ByteArrayHttpMessageConverter.class.isAssignableFrom(converterType); } @Override @@ -45,6 +74,10 @@ public class EnvelopeBodyAdvice implements ResponseBodyAdvice { if (selectedContentType != null && !MediaType.APPLICATION_JSON.includes(selectedContentType)) { return body; } - return Envelope.ok(body, ResponseMetaFactory.fromMdc()); + Envelope envelope = Envelope.ok(body, ResponseMetaFactory.fromMdc()); + if (StringHttpMessageConverter.class.isAssignableFrom(selectedConverterType)) { + return objectMapper.writeValueAsString(envelope); + } + return envelope; } } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java index 19c75caa..4ed63d8f 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java @@ -25,6 +25,11 @@ public class EnvelopeWireFormatConfig { @Bean public SimpleModule envelopeWireFormatModule() { + return module(); + } + + /** The module itself, for a writer that has no Boot mapper to take it from. */ + static SimpleModule module() { SimpleModule module = new SimpleModule("EnvelopeWireFormatModule"); module.setMixInAnnotation(Envelope.class, OmitNullFields.class); module.setMixInAnnotation(BulkEnvelope.class, OmitNullFields.class); diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeErrorDetails.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeErrorDetails.java new file mode 100644 index 00000000..763ee618 --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeErrorDetails.java @@ -0,0 +1,15 @@ +package dev.caskeleton.adapter.inbound.web.error; + +/** + * An {@link dev.caskeleton.shared.error.ApiErrorCarrier} that has bounded, client-safe structure to + * put in {@code error.details} — a JSON pointer the client sent, field names from a server + * allowlist. {@link GlobalExceptionHandler#handleCarrier(Exception)} copies it to the wire. + * + *

      Never the exception message, a server value, or anything the caller may not read: what this + * returns is published verbatim. + */ +public interface ClientSafeErrorDetails { + + /** The value of {@code error.details}: a map or list of plain values. */ + Object clientDetails(); +} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeValidationDetails.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeValidationDetails.java index 28a2d4ec..33b27706 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeValidationDetails.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeValidationDetails.java @@ -6,6 +6,7 @@ import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.springframework.context.MessageSourceResolvable; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; @@ -57,6 +58,16 @@ final class ClientSafeValidationDetails { return detail(field, ruleFor(error.getCode())); } + /** + * A violation of a constraint on a controller parameter. The last resolvable code is the bare + * constraint name ({@code Max}); the more specific ones name the controller method. + */ + static Map from(String parameter, MessageSourceResolvable error) { + String[] codes = error.getCodes(); + String rawCode = codes == null || codes.length == 0 ? null : codes[codes.length - 1]; + return detail(normalize(parameter), ruleFor(rawCode)); + } + private static Map detail(String field, Rule rule) { return Map.of("field", field, "code", rule.code(), "message", rule.message()); } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeResponseWriter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeResponseWriter.java new file mode 100644 index 00000000..09c663b5 --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeResponseWriter.java @@ -0,0 +1,42 @@ +package dev.caskeleton.adapter.inbound.web.error; + +import dev.caskeleton.shared.error.ApiErrorCode; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import org.springframework.http.MediaType; +import tools.jackson.databind.ObjectMapper; + +/** + * Writes a failure {@code Envelope} straight to the servlet response, for the paths that refuse a + * request before a message converter exists to do it: the security entry point, the access-denied + * handler and the rate-limit interceptor. + * + *

      The charset is the reason this is one class. A converter-written response is UTF-8 because the + * converter says so; a hand-written one is whatever the container defaults to, and Tomcat's default + * is ISO-8859-1, which turns the Korean client message into question marks. Each writer used to + * remember that on its own, and one forgot (review 2026-11-01 02-04). + * + *

      Headers that belong to one refusal — {@code WWW-Authenticate}, {@code Retry-After}, {@code + * X-RateLimit-*} — stay with the caller and must be set before this writes the body. + */ +public final class EnvelopeResponseWriter { + + private EnvelopeResponseWriter() {} + + /** + * Sets the code's status and writes its envelope as UTF-8 JSON. + * + * @param response the response, not yet committed + * @param code the failure to answer with + * @param objectMapper Boot's mapper, so the envelope's wire rules apply + */ + public static void write( + HttpServletResponse response, ApiErrorCode code, ObjectMapper objectMapper) + throws IOException { + response.setStatus(code.httpStatus()); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + objectMapper.writeValue(response.getWriter(), ErrorResponseFactory.body(code, null)); + } +} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java index 0115f97b..8d67834e 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java @@ -13,6 +13,7 @@ import dev.caskeleton.shared.error.PersistenceFailureException; import dev.caskeleton.shared.response.Envelope; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import jakarta.validation.ConstraintViolationException; +import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -20,6 +21,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.MethodParameter; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; @@ -27,14 +29,20 @@ import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; +import org.springframework.validation.method.ParameterErrors; +import org.springframework.validation.method.ParameterValidationResult; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.WebRequest; +import org.springframework.web.method.annotation.HandlerMethodValidationException; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.servlet.NoHandlerFoundException; @@ -72,11 +80,18 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { this.spanErrorRecorder = spanErrorRecorder; } + /** + * An {@link IllegalArgumentException} is read as "the request was wrong" and answered 400. One + * WARN line names the exception type, so a 400 that is really a misassembled server — code that + * should have thrown {@link IllegalStateException} — still leaves a trace. The message is not + * logged: it may echo request input. + */ @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity> handleIllegalArgument(IllegalArgumentException ex) { if (ex instanceof ApiErrorCarrier) { return handleCarrier(ex); } + log.warn("request refused as BAD_PARAMETER by {}", ex.getClass().getName()); return ErrorResponseFactory.envelope(OperationalError.BAD_PARAMETER, null); } @@ -178,7 +193,8 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { ResponseEntity.BodyBuilder builder = ResponseEntity.status(code.httpStatus()); RetryAfterAdvisor.retryAfterSeconds(code) .ifPresent(seconds -> builder.header(ApiHeaders.RETRY_AFTER, String.valueOf(seconds))); - return builder.body(ErrorResponseFactory.body(code, null)); + Object details = failure instanceof ClientSafeErrorDetails safe ? safe.clientDetails() : null; + return builder.body(ErrorResponseFactory.body(code, details)); } private static PersistenceFailureException sanitizedPersistenceFailure(ApiErrorCode code) { @@ -320,6 +336,53 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { HttpStatusCode.valueOf(OperationalError.ROUTE_NOT_FOUND.httpStatus())); } + /** + * A Bean Validation constraint on a controller parameter ({@code @RequestParam @Max(10) int + * limit}) is the same violation as one on a request body, so it answers the same way: {@code + * VALIDATION_FAILED} with one bounded detail per violated parameter, never the rejected value. + */ + @Override + protected ResponseEntity handleHandlerMethodValidationException( + HandlerMethodValidationException ex, + HttpHeaders headers, + HttpStatusCode status, + WebRequest request) { + List> violations = new ArrayList<>(); + for (ParameterValidationResult result : ex.getParameterValidationResults()) { + if (result instanceof ParameterErrors errors) { + errors.getAllErrors().stream() + .map(ClientSafeValidationDetails::from) + .forEach(violations::add); + } else { + String parameter = parameterName(result.getMethodParameter()); + result.getResolvableErrors().stream() + .map(error -> ClientSafeValidationDetails.from(parameter, error)) + .forEach(violations::add); + } + } + return new ResponseEntity<>( + ErrorResponseFactory.body(OperationalError.VALIDATION_FAILED, violations), + HttpStatusCode.valueOf(OperationalError.VALIDATION_FAILED.httpStatus())); + } + + /** The name the client used for the parameter: the binding annotation's, else the Java name. */ + private static String parameterName(MethodParameter parameter) { + RequestParam param = parameter.getParameterAnnotation(RequestParam.class); + if (param != null && !param.name().isBlank()) { + return param.name(); + } + RequestHeader header = parameter.getParameterAnnotation(RequestHeader.class); + if (header != null && !header.name().isBlank()) { + return header.name(); + } + PathVariable path = parameter.getParameterAnnotation(PathVariable.class); + if (path != null && !path.name().isBlank()) { + return path.name(); + } + String name = parameter.getParameterName(); + return name == null ? "request" : name; + } + /** * Every Spring MVC exception this class does not override individually — a missing required * parameter, header or multipart part, a binding or conversion failure, an async timeout — @@ -341,7 +404,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { && servletRequest.getResponse().isCommitted()) { return null; } - OperationalError code = operationalErrorFor(statusCode); + ApiErrorCode code = errorCodeFor(statusCode); if (code.httpStatus() >= 500) { log.error("spring mvc failure classified as {}", code.code(), ex); spanErrorRecorder.recordException(ex, code.code()); @@ -350,7 +413,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { ErrorResponseFactory.body(code, null), headers, HttpStatusCode.valueOf(code.httpStatus())); } - private static OperationalError operationalErrorFor(HttpStatusCode status) { + private static ApiErrorCode errorCodeFor(HttpStatusCode status) { return switch (status.value()) { case 401 -> OperationalError.UNAUTHENTICATED; case 403 -> OperationalError.FORBIDDEN; @@ -362,6 +425,8 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { case 414 -> OperationalError.URI_TOO_LONG; case 415 -> OperationalError.UNSUPPORTED_MEDIA_TYPE; case 429 -> OperationalError.RATE_LIMIT_EXCEEDED; + // Spring answers its async request timeout with 503: transient, not an internal fault. + case 503 -> WebTransportError.REQUEST_TIMEOUT; default -> status.is4xxClientError() ? OperationalError.BAD_PARAMETER diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebTransportError.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebTransportError.java new file mode 100644 index 00000000..4fd5b28c --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebTransportError.java @@ -0,0 +1,55 @@ +package dev.caskeleton.adapter.inbound.web.error; + +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.Category; + +/** + * HTTP-only failure codes this adapter answers with, beside the skeleton-wide {@code + * OperationalError}. Like {@code RateLimitTransportError} they are not in {@code + * docs/registries/error-codes.yaml} (that registry is the {@code OperationalError} SSOT); their + * contract is {@code docs/web/http-contract.md} §4. + */ +public enum WebTransportError implements ApiErrorCode { + + /** + * The servlet container's async timeout fired before the handler produced a result. Spring + * reports it as 503; it is transient, and the same request may finish next time. + */ + REQUEST_TIMEOUT(Category.TRANSIENT_DEPENDENCY, 503, true), + + /** + * A KEYED endpoint got no {@code Idempotency-Key}, or one outside its grammar. Its own code so a + * client can tell "fix the key" from any other bad parameter. + */ + IDEMPOTENCY_KEY_INVALID(Category.VALIDATION, 400, false); + + private final Category category; + private final int httpStatus; + private final boolean retryable; + + WebTransportError(Category category, int httpStatus, boolean retryable) { + this.category = category; + this.httpStatus = httpStatus; + this.retryable = retryable; + } + + @Override + public String code() { + return name(); + } + + @Override + public Category category() { + return category; + } + + @Override + public int httpStatus() { + return httpStatus; + } + + @Override + public boolean retryable() { + return retryable; + } +} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/IdempotencyKeyHeader.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/IdempotencyKeyHeader.java new file mode 100644 index 00000000..460cea43 --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/IdempotencyKeyHeader.java @@ -0,0 +1,51 @@ +package dev.caskeleton.adapter.inbound.web.http; + +import java.util.regex.Pattern; + +/** + * A validated {@code Idempotency-Key} header value — the one place a KEYED endpoint turns the + * header into a key. + * + *

      Grammar: 1 to 256 visible ASCII characters ({@code 0x21}–{@code 0x7E}), not trimmed or + * rewritten. It is the paired frontend's rule ({@code isValidIdempotencyKey}): fetch strips + * surrounding whitespace and refuses non-ByteString values, so anything outside it could not have + * been sent on purpose, and two keys differing only in whitespace would collide on the wire. + * + *

      A missing header and a malformed one fail the same way, as {@link + * InvalidIdempotencyKeyException} — {@code 400 IDEMPOTENCY_KEY_INVALID} with {@code details.reason} + * — so a client can tell "fix the key" from any other bad parameter. Bind the header with {@code + * required = false} and call {@link #parse(String)}; a required binding would answer a missing key + * as a generic {@code BAD_PARAMETER} before this runs. + * + *

      Only the extraction is shared. Claim, fingerprint and replay stay with the use case and {@code + * IdempotencyExecutor} (docs/web/http-contract.md §2). + * + * @param value the key exactly as the client sent it + */ +public record IdempotencyKeyHeader(String value) { + + /** Longest key accepted, in characters (= bytes, the grammar being ASCII). */ + public static final int MAX_LENGTH = 256; + + private static final Pattern GRAMMAR = Pattern.compile("[\\x21-\\x7E]{1," + MAX_LENGTH + "}"); + + public IdempotencyKeyHeader { + if (value == null) { + throw InvalidIdempotencyKeyException.missing(); + } + if (!GRAMMAR.matcher(value).matches()) { + throw InvalidIdempotencyKeyException.malformed(); + } + } + + /** + * Parses a header value as the request carried it. + * + * @param header the raw {@code Idempotency-Key} value, {@code null} when absent + * @return the validated key + * @throws InvalidIdempotencyKeyException when the header is absent or outside the grammar + */ + public static IdempotencyKeyHeader parse(String header) { + return new IdempotencyKeyHeader(header); + } +} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/InvalidIdempotencyKeyException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/InvalidIdempotencyKeyException.java new file mode 100644 index 00000000..14a8cd76 --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/InvalidIdempotencyKeyException.java @@ -0,0 +1,48 @@ +package dev.caskeleton.adapter.inbound.web.http; + +import dev.caskeleton.adapter.inbound.web.error.ClientSafeErrorDetails; +import dev.caskeleton.adapter.inbound.web.error.WebTransportError; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; +import java.util.Map; + +/** + * A KEYED request without a usable {@code Idempotency-Key}. Answered as {@code 400 + * IDEMPOTENCY_KEY_INVALID}; {@code details.reason} is {@code MISSING} or {@code MALFORMED}. The key + * itself is never echoed. + */ +public final class InvalidIdempotencyKeyException extends IllegalArgumentException + implements ApiErrorCarrier, ClientSafeErrorDetails { + + private static final long serialVersionUID = 1L; + + private final String reason; + + private InvalidIdempotencyKeyException(String reason, String message) { + super(message); + this.reason = reason; + } + + static InvalidIdempotencyKeyException missing() { + return new InvalidIdempotencyKeyException( + "MISSING", "the Idempotency-Key header is required on this endpoint"); + } + + static InvalidIdempotencyKeyException malformed() { + return new InvalidIdempotencyKeyException( + "MALFORMED", + "the Idempotency-Key header must be 1.." + + IdempotencyKeyHeader.MAX_LENGTH + + " visible ASCII characters"); + } + + @Override + public ApiErrorCode errorCode() { + return WebTransportError.IDEMPOTENCY_KEY_INVALID; + } + + @Override + public Map clientDetails() { + return Map.of("reason", reason); + } +} 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 7ee65f38..f6118a4d 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 @@ -20,18 +20,23 @@ import org.springframework.context.annotation.Import; import org.springframework.core.Ordered; /** - * The HTTP adapter this leaf ships, minus its security posture: error envelope, filters, health - * endpoint, rate limiting and their settings. The JWT security chain is {@link - * WebSecurityAutoConfiguration}, a separate root an application can exclude on its own; method - * security is {@link WebMethodSecurityAutoConfiguration}, which stays when the chain is replaced. + * The HTTP adapter this leaf ships, minus its security posture: success envelope, filters, health + * endpoint, rate limiting and their settings. The error handler is not here: {@link + * WebMvcPlatformAutoConfiguration} defines it, once, behind {@code app.web.mvc.enabled}. The JWT + * security chain is {@link WebSecurityAutoConfiguration}, a separate root an application can + * exclude on its own; method security is {@link WebMethodSecurityAutoConfiguration}, which stays + * when the chain is replaced. * *

      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: - * {@link GlobalExceptionHandler} has to be defined before {@link WebMvcPlatformAutoConfiguration} - * offers its default. + *

      First among auto-configurations, which is where a scanned user configuration used to sit. + * + *

      {@link GlobalExceptionHandler} used to be imported here as well. That second, unconditional + * registration made {@code app.web.mvc.enabled=false} leave the handler in place while the request + * id filter and the JSON body ceiling went away, and it meant an adopter's handler of the same type + * sat beside this one rather than replacing it (review 2026-11-01 02-10). */ @AutoConfiguration @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @@ -47,7 +52,6 @@ import org.springframework.core.Ordered; HealthcheckController.class, EnvelopeBodyAdvice.class, EnvelopeWireFormatConfig.class, - GlobalExceptionHandler.class, CacheControlFilter.class, RequestLoggingFilter.class, MdcCorrelationIdPortAdapter.class, diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java index 60fc52df..5d8328ad 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java @@ -24,7 +24,9 @@ import tools.jackson.core.StreamReadFeature; * *

      The {@code Envelope} error handler, the request-id filter and the request-body boundary (JSON * size ceiling and duplicate-key refusal). HTTP errors are the {@code Envelope} this handler - * writes; {@code spring.mvc.problemdetails.enabled} stays false. + * writes; {@code spring.mvc.problemdetails.enabled} stays false. This is the only place the handler + * is registered, so {@code app.web.mvc.enabled=false} removes all four together: a service that + * turns the platform off supplies its own error handler, request ids and body ceiling. * *

      Every bean is {@link ConditionalOnMissingBean}: the platform supplies the one that would * otherwise be missing rather than the one that must be used. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/JsonBodyLimitFilter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/JsonBodyLimitFilter.java index a4102a61..8745e343 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/JsonBodyLimitFilter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/JsonBodyLimitFilter.java @@ -27,8 +27,17 @@ import org.springframework.web.multipart.MaxUploadSizeExceededException; * or understated body fails the read that crosses the ceiling. * *

      The refusal is {@link MaxUploadSizeExceededException}, which the error handler already answers - * as {@code 413 PAYLOAD_TOO_LARGE} in the envelope. Other media types keep their own ceilings - * (multipart, form posts, upload protocols) and pass through untouched. + * as {@code 413 PAYLOAD_TOO_LARGE} in the envelope. {@code JsonBodyLimitFilterTest} pins both + * checks and the {@code +json} suffix types, so removing either one fails a test. + * + *

      Only JSON is bounded here. Multipart and form posts have their container ceilings, and + * the upload protocols (tus, draft-12, the raw file upload) and the notification callback read the + * stream themselves under their own limits. Every other body — {@code text/plain}, {@code + * application/octet-stream}, XML — has no platform ceiling: an endpoint that binds one with + * {@code @RequestBody String} or {@code byte[]} reads it to the end. Such an endpoint must bound + * the body itself. Bounding every media type except a list of exemptions was considered and not + * done: the raw upload accepts any content type on one path, so the exemption list would have to be + * per path and would turn a forgotten entry into a broken upload (review 2026-11-01 02-09). */ public final class JsonBodyLimitFilter extends OncePerRequestFilter implements Ordered { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java index 845e8091..8b39f266 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java @@ -2,7 +2,6 @@ package dev.caskeleton.adapter.inbound.web.mvc.filter; import dev.caskeleton.adapter.inbound.web.core.WebRequestId; import dev.caskeleton.adapter.inbound.web.core.WebTraceId; -import dev.caskeleton.adapter.inbound.web.observability.HeaderSanitizer; import dev.caskeleton.shared.observability.MdcKeys; import dev.caskeleton.shared.tracing.ActiveTrace; import dev.caskeleton.shared.tracing.TraceParent; @@ -53,7 +52,10 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements /** The header a client may propose a request id in. */ public static final String REQUEST_ID_HEADER = "X-Request-Id"; - /** The header a caller correlates its own requests by; sanitized, never trusted as an id. */ + /** + * The header a caller correlates its own requests by. Kept when it matches the request id rule, + * replaced with a server-minted value when it does not. + */ public static final String CORRELATION_ID_HEADER = "X-Correlation-Id"; /** The W3C trace context header. */ @@ -65,8 +67,6 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements /** Printable, bounded, no separators a log parser would act on. */ private static final Pattern SAFE_IDENTIFIER = Pattern.compile("[A-Za-z0-9._-]{1,128}"); - private static final int MAX_CORRELATION_ID_LENGTH = 200; - private final boolean trustInboundRequestId; private final int order; private final ActiveTrace activeTrace; @@ -179,11 +179,16 @@ public final class WebMvcRequestIdFilter extends OncePerRequestFilter implements false)); } + /** + * The same rule as a request id, and replaced rather than repaired when it fails. Stripping + * control characters and cutting at 200 used to let spaces, Unicode and {@code DEL} through to + * the response header and {@code meta.correlationId}, where the paired frontend's envelope check + * ({@code [A-Za-z0-9._:-]{1,128}}) refuses the whole response (review 2026-11-01 02-11). A + * repaired value would also no longer be the caller's, so it could not correlate anything. + */ private static String resolveCorrelationId(HttpServletRequest request) { - String clean = - HeaderSanitizer.sanitize( - request.getHeader(CORRELATION_ID_HEADER), MAX_CORRELATION_ID_LENGTH); - return clean == null || clean.isBlank() ? UUID.randomUUID().toString() : clean; + return sanitized(request.getHeader(CORRELATION_ID_HEADER)) + .orElseGet(() -> UUID.randomUUID().toString()); } private static Optional sanitized(String candidate) { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java index 3cbc483c..e46ec3d6 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java @@ -40,6 +40,9 @@ public final class RetryAfterAdvisor { if (!shouldAdvise(code)) { return OptionalInt.empty(); } + if (code instanceof RetryAfterHint hint) { + return OptionalInt.of(hint.retryAfterSeconds()); + } Integer seconds = RETRY_AFTER_SECONDS.get(code.code()); return seconds == null ? OptionalInt.empty() : OptionalInt.of(seconds); } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterHint.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterHint.java new file mode 100644 index 00000000..db305cd8 --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterHint.java @@ -0,0 +1,14 @@ +package dev.caskeleton.adapter.inbound.web.observability; + +/** + * An {@link dev.caskeleton.shared.error.ApiErrorCode} that names its own {@code Retry-After}. + * + *

      {@link RetryAfterAdvisor}'s table covers the skeleton-wide codes. A code owned by another leaf + * (web-advanced's admission refusal) states its delay here instead of being written into this + * leaf's table by name. Only consulted when the code is retryable. + */ +public interface RetryAfterHint { + + /** Seconds a client should wait before sending the same request again; positive. */ + int retryAfterSeconds(); +} 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 8b829dee..69df34c4 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 @@ -7,6 +7,7 @@ import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.operation.CancelDurableOperationCommand; import dev.caskeleton.application.operation.CancelDurableOperationUseCase; import dev.caskeleton.application.operation.DurableOperationId; +import dev.caskeleton.application.operation.DurableOperationIdFactory; import dev.caskeleton.application.operation.GetDurableOperationQuery; import dev.caskeleton.application.operation.GetDurableOperationUseCase; import dev.caskeleton.application.operation.OperationAcceptance; @@ -18,7 +19,6 @@ import jakarta.validation.Valid; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Objects; -import java.util.UUID; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; @@ -51,6 +51,7 @@ public class DurableOperationController { private final SubmitDurableOperationUseCase submit; private final GetDurableOperationUseCase get; private final CancelDurableOperationUseCase cancel; + private final DurableOperationIdFactory operationIds; /** * A controller over the three operation use cases. @@ -58,12 +59,15 @@ public class DurableOperationController { * @param submit accepts work * @param get reads one operation * @param cancel requests cancellation + * @param operationIds mints the id of a new operation (a UUIDv7: it is also the event id) */ public DurableOperationController( SubmitDurableOperationUseCase submit, GetDurableOperationUseCase get, - CancelDurableOperationUseCase cancel) { + CancelDurableOperationUseCase cancel, + DurableOperationIdFactory operationIds) { this.submit = Objects.requireNonNull(submit, "submit"); + this.operationIds = Objects.requireNonNull(operationIds, "operationIds"); this.get = Objects.requireNonNull(get, "get"); this.cancel = Objects.requireNonNull(cancel, "cancel"); } @@ -71,9 +75,10 @@ public class DurableOperationController { /** * Accepts an operation. * - *

      {@code 202} with the operation's {@code Location}. The id is minted here; a resubmission of - * the same work by the same caller is recognised by its payload fingerprint and answered with the - * operation that already exists, {@code alreadyAccepted} true and the same {@code Location}. + *

      {@code 202} with the operation's {@code Location}. The id is minted here, by {@link + * DurableOperationIdFactory}; a resubmission of the same work by the same caller is recognised by + * its payload fingerprint and answered with the operation that already exists, {@code + * alreadyAccepted} true and the same {@code Location}. */ @PostMapping public ResponseEntity> submit( @@ -83,7 +88,7 @@ public class DurableOperationController { OperationAcceptance acceptance = submit.handle( new OperationCommand( - new DurableOperationId(UUID.randomUUID().toString()), + operationIds.newOperationId(), request.operationName(), principalId(principal), tenantOf(principal), 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 dd9be4c0..42c8f2ff 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 @@ -1,18 +1,16 @@ package dev.caskeleton.adapter.inbound.web.ratelimit; -import dev.caskeleton.adapter.inbound.web.error.ErrorResponseFactory; +import dev.caskeleton.adapter.inbound.web.error.EnvelopeResponseWriter; import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; import dev.caskeleton.shared.error.ApiErrorCode; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.ratelimit.RateLimitDecision; import dev.caskeleton.shared.ratelimit.RateLimitOutcome; -import dev.caskeleton.shared.response.Envelope; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.time.Duration; import java.time.format.DateTimeFormatter; import java.util.Objects; -import org.springframework.http.MediaType; import org.springframework.web.servlet.HandlerInterceptor; import tools.jackson.databind.ObjectMapper; @@ -75,10 +73,7 @@ public final class RateLimitInterceptor implements HandlerInterceptor { } private void reject(HttpServletResponse response, ApiErrorCode error) throws Exception { - response.setStatus(error.httpStatus()); - response.setContentType(MediaType.APPLICATION_JSON_VALUE); - Envelope body = ErrorResponseFactory.body(error, null); - objectMapper.writeValue(response.getWriter(), body); + EnvelopeResponseWriter.write(response, error, objectMapper); } private static String retryAfterSeconds(Duration retryAfter) { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java index 526bdde3..28f04d62 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java @@ -27,6 +27,15 @@ public record SecuritySettings( List publicPaths, SessionCookieSettings session) { this.authMode = authMode == null ? AuthenticationMode.JWT : authMode; + // An environment variable that is not set at all leaves `${APP_SECURITY_JWT_ISSUER}` behind: + // Boot binds an unresolvable placeholder as its literal text rather than failing. Read as a + // value it would pass the blank check and become the issuer (and the audience) every token is + // compared against, so it is treated as what it is — the value was never supplied. + issuerUri = unresolvedAsMissing(issuerUri); + audience = + audience == null + ? null + : audience.stream().map(SecuritySettings::unresolvedAsMissing).toList(); if (this.authMode == AuthenticationMode.JWT && (issuerUri == null || issuerUri.isBlank())) { throw new IllegalArgumentException( "APP_SECURITY_JWT_ISSUER (app.security.issuer-uri) is required"); @@ -35,7 +44,11 @@ public record SecuritySettings( this.audience = audience == null ? List.of() - : audience.stream().map(String::trim).filter(value -> !value.isEmpty()).toList(); + : audience.stream() + .filter(value -> value != null) + .map(String::trim) + .filter(value -> !value.isEmpty()) + .toList(); if (this.authMode == AuthenticationMode.JWT && this.audience.isEmpty()) { // No "skip the check" default: a token minted for another client of the same issuer must // not authenticate here. @@ -50,6 +63,11 @@ public record SecuritySettings( this.session = session == null ? SessionCookieSettings.defaults() : session; } + /** A value still holding a {@code ${...}} placeholder was never resolved, so it is absent. */ + private static String unresolvedAsMissing(String value) { + return value != null && value.contains("${") ? null : value; + } + public SecuritySettings(String issuerUri, List audience, List publicPaths) { this(AuthenticationMode.JWT, issuerUri, audience, publicPaths, null); } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/CorsSecurityFilterIntegrationTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/CorsSecurityFilterIntegrationTest.java index 4e2c1acc..104b5651 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/CorsSecurityFilterIntegrationTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/CorsSecurityFilterIntegrationTest.java @@ -9,6 +9,7 @@ import dev.caskeleton.adapter.inbound.web.settings.CorsSettings; import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; import jakarta.servlet.Filter; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -163,6 +164,75 @@ class CorsSecurityFilterIntegrationTest { }); } + @Test + @DisplayName("cross-origin 실제 응답은 클라이언트가 읽어야 하는 플랫폼 계약 헤더를 노출한다") + void anActualCrossOriginResponseExposesThePlatformContractHeaders() { + // given: CORS on for one origin, with credentials + withCors( + true, + ALLOWED_ORIGIN, + true, + mvc -> { + // when + MvcResult result = + mvc.perform(get("/public").header(HttpHeaders.ORIGIN, ALLOWED_ORIGIN)) + .andExpect(status().isOk()) + .andReturn(); + + // then: a browser hides every response header outside the CORS safelist unless named + assertThat(exposedHeaders(result)) + .contains( + "Retry-After", + "X-Request-Id", + "X-Correlation-Id", + "traceparent", + "Location", + "ETag", + "X-RateLimit-Limit", + "X-RateLimit-Remaining", + "X-RateLimit-Reset"); + }); + } + + @Test + @DisplayName("모듈이 기여한 노출 헤더는 플랫폼 목록에 더해진다") + void aContributedExposedHeaderIsAddedToThePlatformList() { + // given: a capability that writes its own response header contributes it + runner + .withBean( + "uploadHeaders", + CorsExposedHeaders.class, + () -> new CorsExposedHeaders(List.of("Upload-Offset"))) + .withPropertyValues( + "app.security.auth-mode=jwt", + "app.security.issuer-uri=https://issuer.example.test", + "app.security.audience=ca-skeleton-api", + "app.security.public-paths=/public", + "app.cors.enabled=true", + "app.cors.allowed-origins[0]=" + ALLOWED_ORIGIN) + .run( + context -> { + MockMvc mvc = + MockMvcBuilders.standaloneSetup(new ProbeController()) + .addFilters(context.getBean("springSecurityFilterChain", Filter.class)) + .build(); + + // when + MvcResult result = + mvc.perform(get("/public").header(HttpHeaders.ORIGIN, ALLOWED_ORIGIN)) + .andReturn(); + + // then + assertThat(exposedHeaders(result)).contains("Upload-Offset", "Retry-After"); + }); + } + + private static List exposedHeaders(MvcResult result) { + String exposed = result.getResponse().getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS); + assertThat(exposed).as("Access-Control-Expose-Headers").isNotNull(); + return java.util.Arrays.stream(exposed.split(",")).map(String::trim).toList(); + } + private void withCors( boolean enabled, String origin, boolean credentials, ThrowingConsumer assertion) { runner diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java index 8dcbc3a4..68a457f6 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java @@ -10,8 +10,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import dev.caskeleton.shared.response.BulkEnvelope; import dev.caskeleton.shared.response.Envelope; import dev.caskeleton.shared.response.ResponseMeta; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; @@ -20,6 +22,8 @@ import org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.json.JsonCompareMode; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -49,6 +53,17 @@ class EnvelopeBodyAdviceTest { return Envelope.ok(Map.of("k", "v"), new ResponseMeta("r", "t", "c")); } + @GetMapping("/probe/text") + public String text() { + return "안녕"; + } + + /** Already-serialized JSON, the way springdoc returns its OpenAPI document. */ + @GetMapping(value = "/probe/serialized", produces = MediaType.APPLICATION_JSON_VALUE) + public byte[] serialized() { + return "{\"openapi\":\"3.1.0\"}".getBytes(StandardCharsets.UTF_8); + } + @GetMapping("/probe/bulk") public BulkEnvelope> bulk() { return BulkEnvelope.allOk(List.of(Map.of("k", "v")), new ResponseMeta("r", "t", "c")); @@ -89,6 +104,51 @@ class EnvelopeBodyAdviceTest { .andExpect(content().string(not(containsString("\"data\"")))); } + @Test + @DisplayName("String을 반환하는 엔드포인트도 JSON을 요청하면 200 Envelope로 답한다") + void aStringReturningEndpointAnswersAJsonClientWithAnEnvelope() throws Exception { + // when + var result = mvc.perform(get("/probe/text").accept(MediaType.APPLICATION_JSON)); + + // then + result + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data").value("안녕")) + .andExpect(jsonPath("$.meta").exists()) + .andExpect(content().string(not(containsString("\"error\"")))); + } + + @Test + @DisplayName("String을 반환하는 엔드포인트는 텍스트를 요청한 클라이언트에게 텍스트로 답한다") + void aStringReturningEndpointAnswersATextClientWithText() throws Exception { + // when + var result = mvc.perform(get("/probe/text").accept(MediaType.TEXT_PLAIN)); + + // then + result + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)) + .andExpect(content().string("안녕")); + } + + /** + * A body that is already JSON bytes cannot be put inside an envelope: the byte converter the + * response was negotiated for would receive the envelope object and fail with a 500. + */ + @Test + @DisplayName("이미 직렬화된 byte[] JSON 본문은 감싸지 않고 그대로 쓴다") + void alreadySerializedJsonIsWrittenAsItIs() throws Exception { + // given: 컨트롤러가 이미 직렬화된 JSON 바이트를 돌려준다(springdoc 방식) + // when + var result = mvc.perform(get("/probe/serialized")); + // then + result + .andExpect(status().isOk()) + .andExpect(content().json("{\"openapi\":\"3.1.0\"}", JsonCompareMode.STRICT)); + } + @SpringBootConfiguration @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) static class TestBootstrap {} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java index 664e9ad8..571a2323 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java @@ -13,9 +13,11 @@ import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedExceptio import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException; import dev.caskeleton.shared.tracing.SpanErrorRecorder; +import jakarta.validation.constraints.Max; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; @@ -27,6 +29,7 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.async.AsyncRequestTimeoutException; import org.springframework.web.multipart.MaxUploadSizeExceededException; /** @@ -118,9 +121,48 @@ class TransportErrorHandlingTest { .andExpect(jsonPath("$.error.code").value("BAD_PARAMETER")); } + @Test + @DisplayName("비동기 요청 시간 초과는 500이 아니라 재시도 가능한 503 REQUEST_TIMEOUT이다") + void anAsyncTimeoutIsARetryable503NotAnInternalError() throws Exception { + // when + var result = mvc.perform(get("/t/async-timeout")); + + // then + result + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("REQUEST_TIMEOUT")) + .andExpect(jsonPath("$.error.category").value("TRANSIENT_DEPENDENCY")) + .andExpect(jsonPath("$.error.retryable").value(true)); + } + + @Test + @DisplayName("컨트롤러 파라미터 제약 위반은 VALIDATION_FAILED와 위반한 파라미터 details로 나간다") + void aViolatedParameterConstraintIsValidationFailedNamingTheParameter() throws Exception { + // when + var result = mvc.perform(get("/t/bounded").param("limit", "99")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")) + .andExpect(jsonPath("$.error.details[0].field").value("limit")) + .andExpect(jsonPath("$.error.details[0].code").value("MAX")) + .andExpect(jsonPath("$.error.details[0].rejectedValue").doesNotExist()); + } + @RestController static class Probe { + @GetMapping("/t/async-timeout") + Map asyncTimeout() { + throw new AsyncRequestTimeoutException(); + } + + @GetMapping("/t/bounded") + Map bounded(@RequestParam("limit") @Max(10) int limit) { + return Map.of("limit", limit); + } + @PostMapping("/t/needs-header") Map needsHeader(@RequestHeader("Idempotency-Key") String key) { return Map.of("ok", key); diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/IdempotencyKeyHeaderTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/IdempotencyKeyHeaderTest.java new file mode 100644 index 00000000..b08783dc --- /dev/null +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/IdempotencyKeyHeaderTest.java @@ -0,0 +1,113 @@ +package dev.caskeleton.adapter.inbound.web.http; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.tracing.SpanErrorRecorder; +import java.util.Map; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; + +class IdempotencyKeyHeaderTest { + + private final MockMvc mvc = + MockMvcBuilders.standaloneSetup(new KeyedProbe()) + .setControllerAdvice(new GlobalExceptionHandler(SpanErrorRecorder.NOOP)) + .build(); + + @Test + @DisplayName("보이는 ASCII 1~256자 키는 받은 그대로 쓰인다") + void aKeyInsideTheGrammarIsKeptExactly() { + // given + String key = "0190bd6e-7c3e:retry/1" + "x".repeat(235); + + // when + IdempotencyKeyHeader parsed = IdempotencyKeyHeader.parse(key); + + // then + assertThat(parsed.value()).isEqualTo(key).hasSize(256); + } + + static Stream keysOutsideTheGrammar() { + return Stream.of("", " ", " padded", "with space", "키", "tab\tkey", "x".repeat(257)); + } + + @ParameterizedTest(name = "[{index}] <{0}>") + @MethodSource("keysOutsideTheGrammar") + @DisplayName("문법 밖의 키는 MALFORMED로 거부된다") + void aKeyOutsideTheGrammarIsMalformed(String key) { + // when + Throwable thrown = catchThrowable(() -> IdempotencyKeyHeader.parse(key)); + + // then + assertThat(thrown).isInstanceOf(InvalidIdempotencyKeyException.class); + assertThat(((InvalidIdempotencyKeyException) thrown).clientDetails()) + .isEqualTo(Map.of("reason", "MALFORMED")); + } + + @Test + @DisplayName("헤더가 없으면 MISSING으로 거부된다") + void anAbsentHeaderIsMissing() { + // when + Throwable thrown = catchThrowable(() -> IdempotencyKeyHeader.parse(null)); + + // then + assertThat(((ApiErrorCarrier) thrown).errorCode().code()).isEqualTo("IDEMPOTENCY_KEY_INVALID"); + assertThat(((InvalidIdempotencyKeyException) thrown).clientDetails()) + .isEqualTo(Map.of("reason", "MISSING")); + } + + @Test + @DisplayName("키가 없는 KEYED 요청은 400 IDEMPOTENCY_KEY_INVALID와 reason으로 답한다") + void aKeyedRequestWithoutAKeyIsAnswered400WithItsOwnCode() throws Exception { + // when + var result = mvc.perform(post("/keyed")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("IDEMPOTENCY_KEY_INVALID")) + .andExpect(jsonPath("$.error.category").value("VALIDATION")) + .andExpect(jsonPath("$.error.retryable").value(false)) + .andExpect(jsonPath("$.error.details.reason").value("MISSING")); + } + + @Test + @DisplayName("형식이 틀린 키는 응답에 되돌려 쓰지 않는다") + void aMalformedKeyIsNotEchoed() throws Exception { + // when + var result = mvc.perform(post("/keyed").header(ApiHeaders.IDEMPOTENCY_KEY, "SECRET KEY")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.details.reason").value("MALFORMED")) + .andExpect(content().string(not(containsString("SECRET")))); + } + + @RestController + static class KeyedProbe { + + @PostMapping("/keyed") + Map keyed( + @RequestHeader(name = ApiHeaders.IDEMPOTENCY_KEY, required = false) String key) { + return Map.of("key", IdempotencyKeyHeader.parse(key).value()); + } + } +} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java index c3d971f2..88c5a075 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java @@ -3,10 +3,14 @@ package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.adapter.inbound.web.mvc.filter.JsonBodyLimitFilter; import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; +import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort; +import dev.caskeleton.shared.tracing.SpanErrorRecorder; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.jackson.autoconfigure.JacksonAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; @@ -66,6 +70,62 @@ class WebMvcPlatformAutoConfigurationTest { .doesNotHaveBean(WebMvcRequestIdFilter.class)); } + /** Both roots this leaf registers, as a deployment that ships the leaf processes them. */ + private final WebApplicationContextRunner shipped = + new WebApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + JacksonAutoConfiguration.class, + WebAdapterAutoConfiguration.class, + WebMvcPlatformAutoConfiguration.class)) + // The access-log filter's one collaborator, which the application supplies. + .withBean(UserPrincipalPseudonymizerPort.class, () -> raw -> raw); + + @Test + @DisplayName("leaf를 그대로 실으면 오류 핸들러는 하나만 등록된다") + void theShippedLeafRegistersExactlyOneErrorHandler() { + // when + shipped.run( + context -> + // then + assertThat(context).hasNotFailed().hasSingleBean(GlobalExceptionHandler.class)); + } + + @Test + @DisplayName("app.web.mvc.enabled=false면 leaf를 실어도 오류 핸들러·요청 id 필터·본문 상한이 모두 없다") + void switchingThePlatformOffRemovesTheErrorHandlerWithTheFilters() { + // when + shipped + .withPropertyValues("app.web.mvc.enabled=false") + .run( + context -> + // then + assertThat(context) + .hasNotFailed() + .doesNotHaveBean(GlobalExceptionHandler.class) + .doesNotHaveBean(WebMvcRequestIdFilter.class) + .doesNotHaveBean(JsonBodyLimitFilter.class)); + } + + @Test + @DisplayName("서비스가 같은 타입의 오류 핸들러를 주면 그것 하나만 쓰인다") + void anAdopterErrorHandlerIsTheOnlyOne() { + // given + var withAdopterHandler = + shipped.withBean( + "adopterErrorHandler", + GlobalExceptionHandler.class, + () -> new GlobalExceptionHandler(SpanErrorRecorder.NOOP)); + + // when + withAdopterHandler.run( + context -> { + // then + assertThat(context).hasNotFailed().hasSingleBean(GlobalExceptionHandler.class); + assertThat(context).hasBean("adopterErrorHandler"); + }); + } + @Test @DisplayName("the request id is not trusted from a caller by default") void theRequestIdIsNotTrustedByDefault() { diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/JsonBodyLimitFilterTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/JsonBodyLimitFilterTest.java index 56407a02..1ab4624e 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/JsonBodyLimitFilterTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/JsonBodyLimitFilterTest.java @@ -4,7 +4,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletInputStream; +import java.io.IOException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -39,6 +43,63 @@ class JsonBodyLimitFilterTest { .hasMessageContaining("16"); } + @Test + @DisplayName("선언 길이가 상한을 넘는 JSON 본문은 본문 스트림을 열기 전에 거부된다") + void aDeclaredOversizeIsRefusedBeforeTheBodyStreamIsOpened() { + // given: a container stream that records whether anybody opened it + AtomicBoolean streamOpened = new AtomicBoolean(); + MockHttpServletRequest request = + new MockHttpServletRequest("POST", "/probe") { + @Override + public ServletInputStream getInputStream() { + streamOpened.set(true); + return super.getInputStream(); + } + }; + request.setContentType("application/json"); + request.setContent(new byte[64]); + FilterChain opensTheStream = (req, res) -> req.getInputStream(); + + // when + Throwable thrown = + catchThrowable( + () -> filter.doFilter(request, new MockHttpServletResponse(), opensTheStream)); + + // then + assertThat(thrown).isInstanceOf(MaxUploadSizeExceededException.class); + assertThat(streamOpened) + .as("the declared length is refused without the container reading a byte") + .isFalse(); + } + + @Test + @DisplayName("+json 미디어 타입(merge-patch 등) 본문도 JSON 상한을 받는다") + void aStructuredJsonSuffixBodyIsBoundedToo() { + // given: an undeclared merge-patch body larger than the ceiling + MockHttpServletRequest request = + new MockHttpServletRequest("PATCH", "/probe") { + @Override + public long getContentLengthLong() { + return -1; + } + }; + request.setContentType("application/merge-patch+json"); + request.setContent(new byte[64]); + FilterChain readsEverything = (req, res) -> readAll(req.getInputStream()); + + // when + Throwable thrown = + catchThrowable( + () -> filter.doFilter(request, new MockHttpServletResponse(), readsEverything)); + + // then + assertThat(thrown).isInstanceOf(MaxUploadSizeExceededException.class); + } + + private static void readAll(ServletInputStream stream) throws IOException { + stream.readAllBytes(); + } + @Test void nonJsonBodyReachesTheChainUnwrapped() throws Exception { // given diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java index 2e0aea33..578eb0bf 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilterTest.java @@ -8,9 +8,11 @@ import jakarta.servlet.DispatcherType; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.slf4j.MDC; import org.springframework.mock.web.MockFilterChain; @@ -183,7 +185,8 @@ class WebMvcRequestIdFilterTest { } @Test - void inboundCorrelationIdLosesLineBreaksBeforeReachingMdc() throws Exception { + @DisplayName("줄바꿈을 담은 correlation id는 MDC에 닿기 전에 서버가 만든 값으로 바뀐다") + void inboundCorrelationIdWithLineBreaksNeverReachesMdc() throws Exception { // given MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(CORRELATION_ID_HEADER, "foo\r\nFAKE LOG"); @@ -194,7 +197,49 @@ class WebMvcRequestIdFilterTest { .doFilter(request, new MockHttpServletResponse(), (rq, rs) -> duringChain.putAll(mdc())); // then - assertThat(duringChain.get(MdcKeys.CORRELATION_ID)).isEqualTo("fooFAKE LOG"); + assertThat(duringChain.get(MdcKeys.CORRELATION_ID)) + .doesNotContain("FAKE") + .matches(SAFE_IDENTIFIER); + } + + @ParameterizedTest(name = "[{index}] {0}") + @MethodSource("correlationIdsOutsideTheRule") + @DisplayName("요청 id 규칙 밖의 correlation id는 응답·MDC 어디에도 그대로 나가지 않는다") + void aCorrelationIdOutsideTheRequestIdRuleIsReplaced(String proposed) throws Exception { + // given + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(CORRELATION_ID_HEADER, proposed); + MockHttpServletResponse response = new MockHttpServletResponse(); + Map duringChain = new HashMap<>(); + + // when + new WebMvcRequestIdFilter().doFilter(request, response, (rq, rs) -> duringChain.putAll(mdc())); + + // then + String echoed = response.getHeader(CORRELATION_ID_HEADER); + assertThat(echoed).isNotEqualTo(proposed).matches(SAFE_IDENTIFIER); + assertThat(duringChain.get(MdcKeys.CORRELATION_ID)).isEqualTo(echoed); + } + + static Stream correlationIdsOutsideTheRule() { + return Stream.of( + "has space", "유니코드", "del" + (char) 0x7f + "char", "colon:is:outside", "x".repeat(129)); + } + + @Test + @DisplayName("요청 id 규칙 안의 correlation id는 그대로 이어진다") + void aCorrelationIdInsideTheRuleIsKept() throws Exception { + // given + String proposed = "order-42_retry.1"; + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(CORRELATION_ID_HEADER, proposed); + MockHttpServletResponse response = new MockHttpServletResponse(); + + // when + new WebMvcRequestIdFilter().doFilter(request, response, new MockFilterChain()); + + // then + assertThat(response.getHeader(CORRELATION_ID_HEADER)).isEqualTo(proposed); } @Test @@ -238,5 +283,6 @@ class WebMvcRequestIdFilterTest { } private static final String NEWLINE = "\n"; + private static final String SAFE_IDENTIFIER = "[A-Za-z0-9._-]{1,128}"; private static final String CORRELATION_ID_HEADER = "X-Correlation-Id"; } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java index 28683a00..4039ff1a 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationControllerTest.java @@ -12,6 +12,7 @@ import com.jayway.jsonpath.JsonPath; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.adapter.outbound.identifier.UuidV7DurableOperationIdFactory; import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.operation.CancelDurableOperationUseCase; import dev.caskeleton.application.operation.DurableOperationSubmittedContract; @@ -65,9 +66,14 @@ class DurableOperationControllerTest { DurableOperationController controller = new DurableOperationController( new SubmitDurableOperationUseCase( - operations, outbox, new FakeIntegrationEventEncoder(), transactions, clock), + operations, + outbox, + new FakeIntegrationEventEncoder(new DurableOperationSubmittedContract()), + transactions, + clock), new GetDurableOperationUseCase(operations, transactions, clock), - new CancelDurableOperationUseCase(operations, transactions, clock)); + new CancelDurableOperationUseCase(operations, transactions, clock), + new UuidV7DurableOperationIdFactory()); mvc = MockMvcBuilders.standaloneSetup(controller) .setControllerAdvice( @@ -98,6 +104,63 @@ class DurableOperationControllerTest { .andExpect(jsonPath("$.data.alreadyAccepted").value(false)); } + /** + * The operation id becomes the submission event's id, and the messaging platform carries an event + * id only as a UUIDv7 message id. A v4 id was accepted here and refused at publish time, so every + * submission's event ended DEAD in the outbox (review 2026-11-01 06-06, found by the Kafka relay + * lane). + */ + @Test + @DisplayName("제출이 만든 operation id와 그 이벤트 id는 platform이 받는 정규 소문자 UUIDv7이다") + void aSubmissionMintsACanonicalUuidV7ThatIsAlsoItsEventId() throws Exception { + // given + signIn("alice"); + + // when + String operationId = operationIdOf(submit(REPORT).andReturn()); + + // then + java.util.UUID uuid = java.util.UUID.fromString(operationId); + assertThat(List.of(uuid.version(), uuid.variant(), uuid.toString())) + .containsExactly(7, 2, operationId); + assertThat(outbox.appended()) + .singleElement() + .extracting(event -> event.eventId().value()) + .isEqualTo(operationId); + } + + /** + * The composition registered the use case but not its event contract. No request can fix that, so + * the client must not be told 400 "fix your request" — it is a 500 the server logs. + */ + @Test + void aSubmissionWhoseEventContractIsNotRegisteredIsAServerError() throws Exception { + // given + signIn("alice"); + MockMvc unregistered = + MockMvcBuilders.standaloneSetup( + new DurableOperationController( + new SubmitDurableOperationUseCase( + operations, outbox, new FakeIntegrationEventEncoder(), transactions, clock), + new GetDurableOperationUseCase(operations, transactions, clock), + new CancelDurableOperationUseCase(operations, transactions, clock), + new UuidV7DurableOperationIdFactory())) + .setControllerAdvice( + new GlobalExceptionHandler(SpanErrorRecorder.NOOP), new EnvelopeBodyAdvice()) + .setCustomArgumentResolvers(new AuthenticationPrincipalArgumentResolver()) + .build(); + + // when + ResultActions response = + unregistered.perform( + post("/operations").contentType(MediaType.APPLICATION_JSON).content(REPORT)); + + // then + response + .andExpect(status().isInternalServerError()) + .andExpect(jsonPath("$.error.code").value("INTERNAL_ERROR")); + } + @Test void anIdenticalResubmissionPointsAtTheFirstOperation() throws Exception { // given 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 1d767521..560f3927 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,13 +3,17 @@ 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.error.ClientErrorMessages; +import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.ratelimit.RateLimitDecision; import dev.caskeleton.shared.ratelimit.RateLimitOutcome; import dev.caskeleton.shared.ratelimit.RateLimitSubjectDigest; +import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -56,6 +60,28 @@ class RateLimitInterceptorTest { .contains("\"retryable\":true"); } + @Test + @DisplayName("거부 본문은 UTF-8로 나가 한국어 문구가 ClientErrorMessages와 같다") + void theRefusalBodyIsUtf8SoTheKoreanMessageSurvives() throws Exception { + // given: a response that writes ISO-8859-1 unless told otherwise, as Tomcat's does + RateLimitOutcome outcome = + evaluated(false, 1, 0, Duration.ofMillis(1500), Instant.parse("2026-06-09T12:00:02Z")); + ContainerDefaultCharsetResponse response = new ContainerDefaultCharsetResponse(); + + // when + interceptor(outcome).preHandle(request(), response, new Object()); + + // then + assertThat(response.getCharacterEncoding()).isEqualToIgnoringCase("UTF-8"); + assertThat( + objectMapper + .readTree(response.getContentAsString(StandardCharsets.UTF_8)) + .path("error") + .path("message") + .asString()) + .isEqualTo(ClientErrorMessages.of(OperationalError.RATE_LIMIT_EXCEEDED)); + } + @Test void unavailableAndIndeterminateOutcomesMapTo503WithTheirOwnRetryHints() throws Exception { MockHttpServletResponse unavailableResponse = new MockHttpServletResponse(); @@ -102,6 +128,40 @@ class RateLimitInterceptorTest { .contains("\"retryable\":false"); } + /** + * Tomcat's writer is ISO-8859-1 until {@code setCharacterEncoding} or a {@code charset} content + * type parameter says otherwise; Spring's mock is more forgiving for JSON, so it would hide the + * defect this guards. + */ + private static final class ContainerDefaultCharsetResponse extends MockHttpServletResponse { + + private String explicitEncoding; + private java.io.PrintWriter writer; + + @Override + public void setCharacterEncoding(String encoding) { + explicitEncoding = encoding; + super.setCharacterEncoding(encoding); + } + + @Override + public String getCharacterEncoding() { + return explicitEncoding == null ? StandardCharsets.ISO_8859_1.name() : explicitEncoding; + } + + @Override + public java.io.PrintWriter getWriter() { + if (writer == null) { + writer = + new java.io.PrintWriter( + new java.io.OutputStreamWriter( + getOutputStream(), java.nio.charset.Charset.forName(getCharacterEncoding())), + true); + } + return writer; + } + } + private RateLimitInterceptor interceptor(RateLimitOutcome outcome) { EdgeRateLimitTransportBridge bridge = new EdgeRateLimitTransportBridge( diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java index 2ee531e1..287feb42 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java @@ -15,6 +15,44 @@ class SecuritySettingsTest { private final ApplicationContextRunner runner = new ApplicationContextRunner().withUserConfiguration(EnableProperties.class); + @Test + @DisplayName("issuer env가 아예 없어 자리표시자가 그대로 남으면 issuer 값으로 받지 않고 기동을 거부한다") + void anUnresolvedIssuerPlaceholderIsRefusedNotBound() { + // given + var unresolved = + runner.withPropertyValues( + "app.security.issuer-uri=${APP_SECURITY_JWT_ISSUER_UNSET_FOR_TEST}", + "app.security.audience=ca-skeleton-api"); + + // when + unresolved.run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasStackTraceContaining("APP_SECURITY_JWT_ISSUER"); + }); + } + + @Test + @DisplayName("audience env가 아예 없어 자리표시자가 그대로 남으면 audience 값으로 받지 않고 기동을 거부한다") + void anUnresolvedAudiencePlaceholderIsRefusedNotBound() { + // given + var unresolved = + runner.withPropertyValues( + "app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton", + "app.security.audience=${APP_SECURITY_JWT_AUDIENCE_UNSET_FOR_TEST}"); + + // when + unresolved.run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasStackTraceContaining("APP_SECURITY_JWT_AUDIENCE"); + }); + } + @Test void issuerUriMissingFailsStartup() { runner.run( diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureController.java index 8e374439..507841c6 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureController.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureController.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.inbound.web.testkit.fault; import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; +import dev.caskeleton.adapter.inbound.web.http.IdempotencyKeyHeader; import jakarta.servlet.http.HttpServletResponse; import java.util.concurrent.atomic.AtomicInteger; import org.springframework.boot.test.context.TestComponent; @@ -42,7 +43,7 @@ public class FaultFixtureController { public ResponseEntity create( HttpServletResponse servletResponse, @RequestBody Transfer transfer, - @RequestHeader(name = ApiHeaders.IDEMPOTENCY_KEY) String idempotencyKey, + @RequestHeader(name = ApiHeaders.IDEMPOTENCY_KEY, required = false) String idempotencyKey, @RequestHeader(name = FaultFixtureProtocol.FAULT_POINT_HEADER, required = false) String faultPoint) throws java.io.IOException { @@ -54,7 +55,7 @@ public class FaultFixtureController { Receipt receipt = idempotency.execute( - idempotencyKey, + IdempotencyKeyHeader.parse(idempotencyKey).value(), transfer, Receipt.class, () -> { diff --git a/src/adapter/inbound/websocket/CLAUDE.md b/src/adapter/inbound/websocket/CLAUDE.md index df16edfd..3b4163e6 100644 --- a/src/adapter/inbound/websocket/CLAUDE.md +++ b/src/adapter/inbound/websocket/CLAUDE.md @@ -63,6 +63,11 @@ values matter only in a composition that adopts it. | `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 channel (client inbound, client outbound, broker) queues before rejecting | +| `app.websocket.message-size-limit` | `APP_WEBSOCKET_MESSAGE_SIZE_LIMIT` | `64KB` (Spring default, now explicit) | +| `app.websocket.send-buffer-size-limit` | `APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT` | `512KB` (Spring default, now explicit) | +| `app.websocket.send-time-limit` | `APP_WEBSOCKET_SEND_TIME_LIMIT` | `10s` (Spring default, now explicit) | +| `app.websocket.time-to-first-message` | `APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE` | `60s` (Spring default, now explicit) | +| `app.websocket.max-connections` | `APP_WEBSOCKET_MAX_CONNECTIONS` | `1000`; STOMP sessions per node, the next is closed with 1013 | `WebSocketSettings` is `@Validated`. Invalid enabled settings fail context startup. diff --git a/src/adapter/inbound/websocket/README.md b/src/adapter/inbound/websocket/README.md index f758e432..79bef041 100644 --- a/src/adapter/inbound/websocket/README.md +++ b/src/adapter/inbound/websocket/README.md @@ -21,6 +21,15 @@ 해석하지 않는다. - SUBSCRIBE는 설정된 broadcast destination 하나만, SEND는 `/app/**`만 허용한다. 클라이언트가 `/topic/**`으로 직접 보내는 것은 거부한다. +- 세션 하나에 구독은 하나다. 같은 세션의 두 번째 SUBSCRIBE는 id가 달라도 ERROR 프레임으로 + 거부한다(UNSUBSCRIBE·DISCONNECT로 풀린다). simple broker는 subscription id마다 한 번씩 보내므로, + 막지 않으면 한 클라이언트가 같은 destination을 N번 구독해 broadcast 한 건을 N번 받고 broker 큐를 + N배로 차지한다. 이 채널에는 구독할 destination이 하나뿐이라 정상 클라이언트에는 비용이 없다. +- 노드 연결 상한(`APP_WEBSOCKET_MAX_CONNECTIONS`). 상한을 넘는 연결은 STOMP handler에 닿기 전에 + 1013(Try Again Later)으로 닫는다. handshake에서 503으로 거부하지 않은 이유: 자리를 돌려주는 것은 + 세션 종료 콜백뿐이고, 통과한 SockJS handshake가 세션이 되지 않을 수도 있어 두 곳에서 세면 자리가 + 샌다. 1008이 아니라 1013인 이유: 거부 사유가 클라이언트가 아니라 지금 이 노드의 부하라서, 일반 + 클라이언트가 물러났다가(가능하면 다른 노드로) 다시 붙게 한다. - 처리 실패는 모두 빈 본문의 ERROR 프레임이 되고 `message` 헤더는 고정값 `WEBSOCKET_REQUEST_REJECTED`다. `error-code` 헤더는 원인 사슬에 `ApiErrorCarrier`가 있으면 그 코드, `IllegalArgumentException`이면 `BAD_PARAMETER`, 나머지는 `WEBSOCKET_REQUEST_REJECTED`다. @@ -47,6 +56,16 @@ runtimeOnly project(':adapter:inbound:websocket') // WebSocket (STOMP push) | `APP_WEBSOCKET_ALLOWED_ORIGINS` | `http://localhost:3000` | 쉼표 구분 origin 목록. wildcard 금지 | | `APP_WEBSOCKET_BROADCAST_DESTINATION` | `/topic/events` | 서버 push 대상. `/topic/` 아래 경로 하나 | | `APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY` | `10000` | STOMP 인바운드·아웃바운드 채널 executor 큐 상한. 가득 차면 메시지를 거부한다(스레드 수는 CPU×2 고정) | +| `APP_WEBSOCKET_MESSAGE_SIZE_LIMIT` | `64KB` | 수신 STOMP 메시지 상한. 넘으면 세션을 닫는다 | +| `APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT` | `512KB` | 세션 하나의 미전송 버퍼 상한. 넘으면 느린 소비자로 보고 닫는다 | +| `APP_WEBSOCKET_SEND_TIME_LIMIT` | `10s` | 송신 한 번이 막혀 있을 수 있는 시간. 넘으면 닫는다 | +| `APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE` | `60s` | 새 세션이 첫 프레임을 보내기까지 기다리는 시간 | +| `APP_WEBSOCKET_MAX_CONNECTIONS` | `1000` | 노드 하나가 동시에 여는 STOMP 세션 수. 다음 연결은 1013으로 닫는다 | + +전송 한도 네 개의 기본값은 Spring 기본값(`WebSocketTransportRegistration`) 그대로다. 예전에도 이 +값으로 돌았지만 코드에 없었다. 키로 꺼내 지금 어떤 상한이 걸려 있는지 보이게 하고, 라이브러리 +업그레이드가 기본값을 바꿔도 조용히 따라가지 않게 했다. 연결 상한 기본값 1000은 +1000 × 512 KiB(send buffer) ≈ 512 MiB를 최악의 송신 버퍼로 잡은 값이다. 노드 heap에 맞춰 조정한다. 켠 상태에서 값이 잘못되면(wildcard origin, 정규화되지 않은 경로) 기동이 실패한다. @@ -56,6 +75,12 @@ simple broker는 한 프로세스 안의 best-effort 전달이다. 영속·트 없고, 발행이 트랜잭션 rollback보다 먼저 일어날 수 있다. 이런 전달이 필요하면 outbox/relay로 설계한다. +- **principal별 연결 상한 없음.** 상한은 노드 단위다. 인증된 사용자 한 명(또는 탈취된 토큰)이 한 + 노드의 자리를 모두 차지할 수 있다. principal별 상한은 모든 노드가 공유하는 카운터(Redis 등)가 + 필요해 이 leaf 범위를 넘는다. 필요하면 서비스가 프록시나 공유 카운터로 막는다. +- **연결 수명 동안 토큰을 다시 확인하지 않는다.** 인증은 handshake 한 번이다. 토큰이 만료되거나 + 폐기돼도 열린 연결은 유지된다. 연결 수명은 프록시 read timeout이나 서비스의 세션 정책으로 끊는다. + ## 라이브러리 API — 서비스의 어댑터 leaf에서 직접 조립 설정 키도 자동 설정도 없다. 서비스의 어댑터 leaf가 `implementation project(':adapter:inbound:websocket')`로 @@ -63,7 +88,7 @@ simple broker는 한 프로세스 안의 best-effort 전달이다. 영속·트 | 진입점 | 역할 | | --- | --- | -| `servlet.PlatformWebSocketHandler` | 텍스트 메시지 하나를 받아 `BiFunction>`에 넘기고, 응답을 연결별 큐로 보낸다. `SmartLifecycle`이라 context 종료 시 열린 연결을 1001로 닫는다 | +| `servlet.PlatformWebSocketHandler(budget, globalBudget, maxConnections, application)` | 텍스트 메시지 하나를 받아 `BiFunction>`에 넘기고, 응답을 연결별 큐로 보낸다. `maxConnections`(필수)를 넘는 연결은 1013으로 닫는다. `SmartLifecycle`이라 context 종료 시 열린 연결을 1001로 닫고, `stop()` 뒤 들어온 연결도 즉시 1001로 닫는다 | | `budget.WebSocketConnectionBudget(maxMessageBytes, maxBufferedOutboundBytes)` | 연결 하나의 수신 메시지 상한(UTF-8 바이트)과 미전송 버퍼 상한 | | `outbound.GlobalBufferBudget(maxBufferedBytes)` | 노드 전체 미전송 바이트 상한. 모든 연결이 공유한다 | | `outbound.OutboundQueue`, `outbound.SerializedOutboundWriter` | 우선순위·conflation·drop 정책을 가진 bounded 큐와 연결당 단일 writer. handler 없이 따로 쓸 수 있다 | @@ -71,6 +96,9 @@ simple broker는 한 프로세스 안의 best-effort 전달이다. 영속·트 동작: ```text +client ──connect──> PlatformWebSocketHandler.afterConnectionEstablished + ├─ stop() 뒤 → close 1001 + └─ maxConnections 도달 → close 1013 client ──text──> container(whole message) ──> PlatformWebSocketHandler ├─ > maxMessageBytes → close 1009 └─ application.apply(id, text) @@ -97,6 +125,7 @@ class LiveSocketConfig implements WebSocketConfigurer { return new PlatformWebSocketHandler( new WebSocketConnectionBudget(64 * 1024, 1024 * 1024), new GlobalBufferBudget(64L * 1024 * 1024), + 1_000, // 노드 연결 상한. 넘는 연결은 1013 (connection, text) -> useCase.handle(text)); // Optional: 응답 또는 empty } @@ -125,6 +154,9 @@ class LiveSocketConfig implements WebSocketConfigurer { - **수신 크기**: servlet API는 애플리케이션에 frame을 보여주지 않는다. 컨테이너가 메시지를 자기 버퍼(Tomcat 기본 8 KiB)에 모으고, 그보다 크면 컨테이너가 1009로 닫는다. 컨테이너 버퍼를 `maxMessageBytes`와 같게 두면 두 상한이 일치한다. +- **연결 수 상한(필수)**: 생성자의 `maxConnections`. 1013(Try Again Later)으로 닫는 이유는 거부 + 사유가 노드 부하라서 클라이언트가 물러났다 다시 붙게 하기 위해서다. upgrade 전에 503으로 막고 + 싶으면 서비스의 `HandshakeInterceptor`에서 따로 한다. principal별 상한은 없다(공유 카운터 필요). - **idle timeout·연결 수명**: handler에는 없다. 컨테이너(`setMaxSessionIdleTimeout`)와 프록시의 read timeout으로 정한다. - **서버 주도 push 없음**: handler는 받은 메시지에 대한 응답만 보낸다. 임의 시점 push가 필요하면 diff --git a/src/adapter/inbound/websocket/build.gradle b/src/adapter/inbound/websocket/build.gradle index 541e3d08..158a8a2e 100644 --- a/src/adapter/inbound/websocket/build.gradle +++ b/src/adapter/inbound/websocket/build.gradle @@ -102,14 +102,12 @@ strictTestLanes { system() sourceSet = 'systemTest' description = 'Runs the WebSocket transport and abuse contracts against real Tomcat sockets.' - jvmArgs '-Duser.timezone=UTC' } lane('websocketNginxTest') { integration() sourceSet = 'nginxWebSocketTest' description = 'Runs the upgrade and forwarded-header contract behind a real Nginx.' - jvmArgs '-Duser.timezone=UTC' } // The real-container lane. Upgrade negotiation, close-frame handling and idle behaviour are @@ -118,7 +116,6 @@ strictTestLanes { system() sourceSet = 'jettyWebSocketTest' description = 'Runs the WebSocket system contract against a real Jetty instead of Tomcat.' - jvmArgs '-Duser.timezone=UTC' } lane('websocketTransportQualificationTest') { @@ -126,6 +123,5 @@ strictTestLanes { description = 'Runs exact no-skip WebSocket conditional transport wire evidence.' requires 'dev.caskeleton.adapter.inbound.websocket.stomp.WebSocketBoundaryQualificationTest' rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' } } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java index 962130ba..fbd61dd1 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java @@ -92,6 +92,14 @@ public final class SerializedOutboundWriter { // stalled socket cannot block a producer from queueing. queueLock.lock(); try { + // Checked again under the lock. The check above is only a fast path: a close() that runs + // between it and this lock has already discarded the queue, and a message queued now would + // reserve node-wide bytes that no one releases — the writer is gone from the handler's map + // and drain() writes nothing once closed. close() discards under this same lock, so either + // it sees this message and releases it, or this offer sees `closed` and reserves nothing. + if (closed.get()) { + return OutboundEnqueueResult.CONNECTION_MUST_CLOSE; + } result = queue.offer(message); } finally { queueLock.unlock(); @@ -181,7 +189,9 @@ public final class SerializedOutboundWriter { return; } // The queue lock, not the write lock: a stalled sink still holds the write lock, and taking it - // here would make close() wait for the very peer it is giving up on. + // here would make close() wait for the very peer it is giving up on. It is also the lock under + // which offer() re-reads `closed`, which is what makes this discard final: no offer can queue + // after it. queueLock.lock(); try { // Released explicitly: the node-wide buffer budget would otherwise keep counting bytes for a diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java index 366ff318..84addfad 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java @@ -36,38 +36,93 @@ import org.springframework.web.socket.handler.TextWebSocketHandler; */ public class PlatformWebSocketHandler extends TextWebSocketHandler implements SmartLifecycle { + private static final String SHUTTING_DOWN = "server is shutting down"; + private final WebSocketConnectionBudget budget; private final GlobalBufferBudget globalBudget; private final BiFunction> application; private final Map writers = new ConcurrentHashMap<>(); private final Map sessions = new ConcurrentHashMap<>(); + private final int maxConnections; + + /** + * Makes "count, then register" one step, so two upgrades at once cannot both take the last slot. + */ + private final Object admission = new Object(); + private volatile boolean running; + /** + * False from {@link #stop()} until the next {@link #start()}. Separate from {@link #running} + * because a handler that has not been started yet — a container can complete an upgrade before + * the lifecycle reaches this phase — is not shutting down and should serve. + */ + private volatile boolean accepting = true; + /** * A handler over one budget. * + *

      The connection ceiling is a required argument rather than an optional one. {@link + * GlobalBufferBudget} bounds unsent bytes, but every open connection also costs a container + * session, a queue and a writer whether or not anything is sent, and "how many connections" is + * chosen by whoever connects. A handler without the bound would accept until the heap or the + * file-descriptor table ran out. + * * @param budget what a connection may consume * @param globalBudget the node-wide outbound ceiling + * @param maxConnections the most connections this handler holds at once; the next one is closed + * with 1013 * @param application handles one decoded message and optionally answers */ public PlatformWebSocketHandler( WebSocketConnectionBudget budget, GlobalBufferBudget globalBudget, + int maxConnections, BiFunction> application) { this.budget = Objects.requireNonNull(budget, "budget"); this.globalBudget = Objects.requireNonNull(globalBudget, "globalBudget"); + if (maxConnections <= 0) { + throw new IllegalArgumentException("a handler that admits no connection serves nothing"); + } + this.maxConnections = maxConnections; this.application = Objects.requireNonNull(application, "application"); } @Override public void afterConnectionEstablished(WebSocketSession session) { - sessions.put(session.getId(), session); - writers.put( - session.getId(), - new SerializedOutboundWriter( - connectionId(session), - new OutboundQueue(budget, 256, globalBudget), - new ServletFrameSink(session))); + if (!accepting) { + close(session, CloseStatus.GOING_AWAY, SHUTTING_DOWN); + return; + } + boolean admitted; + synchronized (admission) { + admitted = writers.size() < maxConnections; + if (admitted) { + sessions.put(session.getId(), session); + writers.put( + session.getId(), + new SerializedOutboundWriter( + connectionId(session), + new OutboundQueue(budget, 256, globalBudget), + new ServletFrameSink(session))); + } + } + if (!admitted) { + // 1013 "try again later" rather than 1008 "policy violation": the refusal is about this + // node's load at this moment, not about the client, and 1013 is the code a generic client + // backs off on and retries — ideally against another node. The upgrade has already + // happened by the time a WebSocketHandler sees the session; refusing earlier (503 at the + // handshake) belongs to the service's HandshakeInterceptor, which this library does not own. + close(session, CloseStatus.SERVICE_OVERLOAD, "connection limit reached"); + return; + } + if (!accepting) { + // stop() ran between the check above and the registration, and its sweep may have missed + // this session. Re-read after registering: either stop() saw the session in the map, or this + // thread sees `accepting == false` — closing twice is harmless, closing never is the 1006. + afterConnectionClosed(session, CloseStatus.GOING_AWAY); + close(session, CloseStatus.GOING_AWAY, SHUTTING_DOWN); + } } @Override @@ -113,6 +168,7 @@ public class PlatformWebSocketHandler extends TextWebSocketHandler implements Sm @Override public void start() { + accepting = true; running = true; } @@ -131,17 +187,11 @@ public class PlatformWebSocketHandler extends TextWebSocketHandler implements Sm */ @Override public void stop() { + // First, so a connection the container upgrades after this point — the web server keeps + // accepting until its own graceful phase runs — is told 1001 too instead of dying as a 1006. + accepting = false; running = false; - sessions.forEach( - (id, session) -> { - try { - if (session.isOpen()) { - session.close(CloseStatus.GOING_AWAY); - } - } catch (Exception alreadyGone) { - // The peer beat us to it. Nothing left to tell it. - } - }); + sessions.forEach((id, session) -> closeGoingAway(session)); writers.values().forEach(SerializedOutboundWriter::close); sessions.clear(); writers.clear(); @@ -180,6 +230,16 @@ public class PlatformWebSocketHandler extends TextWebSocketHandler implements Sm } } + private static void closeGoingAway(WebSocketSession session) { + try { + if (session.isOpen()) { + session.close(CloseStatus.GOING_AWAY); + } + } catch (Exception alreadyGone) { + // The peer beat us to it. Nothing left to tell it. + } + } + private static void close(WebSocketSession session, CloseStatus status, String reason) { try { // The reason is truncated because RFC 6455 caps the close frame's reason at 123 bytes, and a diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompConnectionLimit.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompConnectionLimit.java new file mode 100644 index 00000000..c7b47bf8 --- /dev/null +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompConnectionLimit.java @@ -0,0 +1,106 @@ +package dev.caskeleton.adapter.inbound.websocket.stomp; + +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.WebSocketHandler; +import org.springframework.web.socket.WebSocketMessage; +import org.springframework.web.socket.WebSocketSession; +import org.springframework.web.socket.handler.WebSocketHandlerDecorator; +import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory; + +/** + * The STOMP channel's per-node connection ceiling ({@code app.websocket.max-connections}). + * + *

      Applied as a decorator around Spring's {@code SubProtocolWebSocketHandler} because that is the + * one place both raw WebSocket and SockJS sessions open and close. A refused session is closed + * before the STOMP handler ever sees it, so it holds no STOMP session state and no broker + * subscription. + * + *

      Refused after the upgrade, with 1013 "try again later", rather than at the handshake with 503. + * A handshake interceptor could count, but only a session's close callback can give the slot back, + * and a SockJS handshake that passes may never become a session — counting in two places would leak + * slots. 1013 rather than 1008: the refusal is about this node's load now, not about the client, + * and 1013 is what a generic client backs off on and retries, ideally on another node. + * + *

      Per node, not per principal. One authenticated user can still take every slot on a node; a + * per-principal bound needs a counter shared by all nodes (Redis or similar) and is left to the + * service — the module README states it as a limit. + */ +final class StompConnectionLimit implements WebSocketHandlerDecoratorFactory { + + private final int maxConnections; + private final Set admitted = ConcurrentHashMap.newKeySet(); + + /** Makes "count, then admit" one step, so two upgrades at once cannot both take the last slot. */ + private final Object admission = new Object(); + + StompConnectionLimit(int maxConnections) { + if (maxConnections <= 0) { + throw new IllegalArgumentException("a channel that admits no connection serves nothing"); + } + this.maxConnections = maxConnections; + } + + @Override + public WebSocketHandler decorate(WebSocketHandler handler) { + return new LimitedHandler(handler); + } + + /** How many STOMP sessions currently hold a slot. */ + int openConnections() { + return admitted.size(); + } + + private boolean admit(String sessionId) { + synchronized (admission) { + if (admitted.size() >= maxConnections) { + return false; + } + return admitted.add(sessionId); + } + } + + private final class LimitedHandler extends WebSocketHandlerDecorator { + + LimitedHandler(WebSocketHandler delegate) { + super(delegate); + } + + @Override + public void afterConnectionEstablished(WebSocketSession session) throws Exception { + if (!admit(session.getId())) { + session.close(CloseStatus.SERVICE_OVERLOAD.withReason("connection limit reached")); + return; + } + super.afterConnectionEstablished(session); + } + + @Override + public void handleMessage(WebSocketSession session, WebSocketMessage message) + throws Exception { + // A refused session can still deliver a frame that was in flight before its close; the STOMP + // handler never registered it, so the frame goes nowhere. + if (admitted.contains(session.getId())) { + super.handleMessage(session, message); + } + } + + @Override + public void handleTransportError(WebSocketSession session, Throwable exception) + throws Exception { + if (admitted.contains(session.getId())) { + super.handleTransportError(session, exception); + } + } + + @Override + public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) + throws Exception { + // Only an admitted session gives a slot back; a refused one never took one. + if (admitted.remove(session.getId())) { + super.afterConnectionClosed(session, closeStatus); + } + } + } +} 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 f08eec43..3243f0a1 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 @@ -14,6 +14,7 @@ import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; +import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; /** * WebSocket (STOMP over SockJS) driving-adapter configuration. @@ -52,10 +53,29 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { new SafeStompSubProtocolErrorHandler(); private final WebSocketInboundAuthorizationInterceptor inboundAuthorization; private final WebSocketCorrelationInterceptor correlation = new WebSocketCorrelationInterceptor(); + private final StompConnectionLimit connectionLimit; public WebSocketConfig(WebSocketSettings properties) { this.properties = properties; this.inboundAuthorization = new WebSocketInboundAuthorizationInterceptor(properties); + this.connectionLimit = new StompConnectionLimit(properties.getMaxConnections()); + } + + /** + * Every transport bound written down. The four limits used to be Spring's defaults by omission; + * the values have not changed, but they are now {@code app.websocket.*} keys, so the bound in + * force is visible and an upgrade that changes a default cannot change it silently. The + * connection ceiling is new: without it, the number of sessions — each with its own send buffer + * of up to {@code send-buffer-size-limit} — is chosen by whoever connects. + */ + @Override + public void configureWebSocketTransport(WebSocketTransportRegistration registration) { + registration + .setMessageSizeLimit(Math.toIntExact(properties.getMessageSizeLimit().toBytes())) + .setSendBufferSizeLimit(Math.toIntExact(properties.getSendBufferSizeLimit().toBytes())) + .setSendTimeLimit(Math.toIntExact(properties.getSendTimeLimit().toMillis())) + .setTimeToFirstMessage(Math.toIntExact(properties.getTimeToFirstMessage().toMillis())) + .addDecoratorFactory(connectionLimit); } @Override @@ -108,6 +128,12 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { registry.setApplicationDestinationPrefixes("/app"); } + /** The connection ceiling, as a bean so its current count can be read. */ + @Bean + StompConnectionLimit stompConnectionLimit() { + return connectionLimit; + } + @Bean LiveEventStompBroadcaster liveEventStompBroadcaster( SimpMessagingTemplate messaging, diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java index 186b1226..82a9c004 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java @@ -1,6 +1,9 @@ package dev.caskeleton.adapter.inbound.websocket.stomp; import java.security.Principal; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.simp.stomp.StompCommand; @@ -8,13 +11,27 @@ import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.messaging.support.ChannelInterceptor; import org.springframework.messaging.support.MessageHeaderAccessor; -/** Enforces the authenticated STOMP destination allowlist on the client inbound channel. */ +/** + * Enforces the authenticated STOMP destination allowlist on the client inbound channel, and one + * subscription per session. + * + *

      One subscription, because the channel has exactly one subscribable destination. The simple + * broker sends a broadcast once per subscription id, so a session that subscribes to the same + * destination N times under N ids receives every event N times and grows the broker's registry by N + * — one authenticated client multiplying its share of the broker queue every other user's live + * events go through. A second SUBSCRIBE gets the same fixed ERROR frame as any other policy + * refusal; UNSUBSCRIBE of the held id or DISCONNECT (Spring sends one through this channel when a + * transport closes, too) frees the slot. + */ final class WebSocketInboundAuthorizationInterceptor implements ChannelInterceptor { private static final String APPLICATION_PREFIX = "/app/"; private final WebSocketSettings properties; + /** Session id to the id of its one subscription. Bounded by the number of open sessions. */ + private final Map subscriptions = new ConcurrentHashMap<>(); + WebSocketInboundAuthorizationInterceptor(WebSocketSettings properties) { this.properties = properties; } @@ -35,6 +52,15 @@ final class WebSocketInboundAuthorizationInterceptor implements ChannelIntercept && !properties.getBroadcastDestination().equals(accessor.getDestination())) { throw new WebSocketPolicyViolationException(); } + if (command == StompCommand.SUBSCRIBE && !holdSubscription(accessor)) { + throw new WebSocketPolicyViolationException(); + } + if (command == StompCommand.UNSUBSCRIBE && accessor.getSessionId() != null) { + subscriptions.remove(accessor.getSessionId(), subscriptionId(accessor)); + } + if (command == StompCommand.DISCONNECT && accessor.getSessionId() != null) { + subscriptions.remove(accessor.getSessionId()); + } if (command == StompCommand.SEND && (accessor.getDestination() == null || !accessor.getDestination().startsWith(APPLICATION_PREFIX))) { @@ -43,6 +69,36 @@ final class WebSocketInboundAuthorizationInterceptor implements ChannelIntercept return message; } + /** + * Gives the slot back when a SUBSCRIBE this interceptor admitted never reached the broker — a + * full channel queue rejects it after {@code preSend} — so the client can subscribe again. + */ + @Override + public void afterSendCompletion( + Message message, MessageChannel channel, boolean sent, Exception failure) { + if (sent && failure == null) { + return; + } + StompHeaderAccessor accessor = + MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); + if (accessor != null + && accessor.getCommand() == StompCommand.SUBSCRIBE + && accessor.getSessionId() != null) { + subscriptions.remove(accessor.getSessionId(), subscriptionId(accessor)); + } + } + + /** Fails closed: a SUBSCRIBE with no session id cannot be counted, so it is not admitted. */ + private boolean holdSubscription(StompHeaderAccessor accessor) { + String sessionId = accessor.getSessionId(); + return sessionId != null + && subscriptions.putIfAbsent(sessionId, subscriptionId(accessor)) == null; + } + + private static String subscriptionId(StompHeaderAccessor accessor) { + return Objects.toString(accessor.getSubscriptionId(), ""); + } + private static boolean requiresAuthentication(StompCommand command) { return command != StompCommand.DISCONNECT; } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettings.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettings.java index 752e3f25..f936c372 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettings.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettings.java @@ -4,8 +4,10 @@ import jakarta.validation.constraints.AssertTrue; import jakarta.validation.constraints.Positive; import java.net.URI; import java.net.URISyntaxException; +import java.time.Duration; import java.util.Arrays; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.util.unit.DataSize; import org.springframework.validation.annotation.Validated; /** WebSocket (STOMP) settings bound from {@code app.websocket.*}. */ @@ -31,6 +33,29 @@ public class WebSocketSettings { /** Messages each STOMP client channel (inbound, outbound) may queue before rejecting. */ @Positive private int channelQueueCapacity = 10_000; + // The four transport limits below are Spring's own defaults + // (WebSocketTransportRegistration). They were in force before they were keys; they are keys + // now so that the bound an operator is running with is written down and changeable, not + // inherited silently from a library version. + + /** Largest inbound STOMP message after reassembly; a larger one closes the session. */ + private DataSize messageSizeLimit = DataSize.ofKilobytes(64); + + /** Unsent bytes one session may hold before it is closed as a slow consumer. */ + private DataSize sendBufferSizeLimit = DataSize.ofKilobytes(512); + + /** How long one send may block before the session is closed as a slow consumer. */ + private Duration sendTimeLimit = Duration.ofSeconds(10); + + /** How long a new session may stay silent before its first frame; then it is closed. */ + private Duration timeToFirstMessage = Duration.ofSeconds(60); + + /** + * STOMP sessions this node holds at once; the next one is closed with 1013. A per-node count, not + * per principal: a per-principal bound needs a counter shared across nodes. + */ + @Positive private int maxConnections = 1_000; + public boolean isEnabled() { return enabled; } @@ -71,6 +96,46 @@ public class WebSocketSettings { this.channelQueueCapacity = channelQueueCapacity; } + public DataSize getMessageSizeLimit() { + return messageSizeLimit; + } + + public void setMessageSizeLimit(DataSize messageSizeLimit) { + this.messageSizeLimit = messageSizeLimit; + } + + public DataSize getSendBufferSizeLimit() { + return sendBufferSizeLimit; + } + + public void setSendBufferSizeLimit(DataSize sendBufferSizeLimit) { + this.sendBufferSizeLimit = sendBufferSizeLimit; + } + + public Duration getSendTimeLimit() { + return sendTimeLimit; + } + + public void setSendTimeLimit(Duration sendTimeLimit) { + this.sendTimeLimit = sendTimeLimit; + } + + public Duration getTimeToFirstMessage() { + return timeToFirstMessage; + } + + public void setTimeToFirstMessage(Duration timeToFirstMessage) { + this.timeToFirstMessage = timeToFirstMessage; + } + + public int getMaxConnections() { + return maxConnections; + } + + public void setMaxConnections(int maxConnections) { + this.maxConnections = maxConnections; + } + /** Split the comma-separated {@link #allowedOrigins} into patterns for the handshake registry. */ public String[] allowedOriginPatterns() { return Arrays.stream(allowedOrigins.split(",", -1)).map(String::trim).toArray(String[]::new); @@ -96,6 +161,31 @@ public class WebSocketSettings { return origins.length > 0 && Arrays.stream(origins).allMatch(WebSocketSettings::validOrigin); } + @AssertTrue( + message = + "websocket message-size-limit and send-buffer-size-limit must be positive and at most" + + " 2147483647 bytes") + public boolean isTransportSizeLimitsValid() { + return !enabled || (fitsInt(messageSizeLimit) && fitsInt(sendBufferSizeLimit)); + } + + @AssertTrue( + message = + "websocket send-time-limit and time-to-first-message must be positive and at most" + + " 2147483647 ms") + public boolean isTransportTimeLimitsValid() { + return !enabled || (fitsIntMillis(sendTimeLimit) && fitsIntMillis(timeToFirstMessage)); + } + + // Spring's transport registration takes int bytes and int milliseconds. + private static boolean fitsInt(DataSize size) { + return size != null && size.toBytes() > 0 && size.toBytes() <= Integer.MAX_VALUE; + } + + private static boolean fitsIntMillis(Duration duration) { + return duration != null && duration.toMillis() > 0 && duration.toMillis() <= Integer.MAX_VALUE; + } + private static boolean validPath(String value, String requiredPrefix) { if (value == null || value.isBlank() diff --git a/src/adapter/inbound/websocket/src/nginxWebSocketTest/java/dev/caskeleton/adapter/inbound/websocket/proxy/NginxWebSocketHarness.java b/src/adapter/inbound/websocket/src/nginxWebSocketTest/java/dev/caskeleton/adapter/inbound/websocket/proxy/NginxWebSocketHarness.java index 2db85fb6..70c8859b 100644 --- a/src/adapter/inbound/websocket/src/nginxWebSocketTest/java/dev/caskeleton/adapter/inbound/websocket/proxy/NginxWebSocketHarness.java +++ b/src/adapter/inbound/websocket/src/nginxWebSocketTest/java/dev/caskeleton/adapter/inbound/websocket/proxy/NginxWebSocketHarness.java @@ -17,7 +17,8 @@ import org.testcontainers.utility.DockerImageName; */ public final class NginxWebSocketHarness implements AutoCloseable { - private static final DockerImageName IMAGE = DockerImageName.parse("nginx:1.27-alpine"); + private static final DockerImageName IMAGE = + DockerImageName.parse(System.getProperty("ca.test.image.nginx")); private final GenericContainer nginx; diff --git a/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/runtime/TomcatWebSocketAbuseIT.java b/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/runtime/TomcatWebSocketAbuseIT.java index 693e1701..4d4b11da 100644 --- a/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/runtime/TomcatWebSocketAbuseIT.java +++ b/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/runtime/TomcatWebSocketAbuseIT.java @@ -8,8 +8,11 @@ import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; @@ -18,8 +21,11 @@ import org.springframework.boot.test.web.server.LocalServerPort; * Abuse and graceful shutdown on the servlet default. * *

      Shutdown is asserted here rather than in the shared contract because it is destructive: the - * container serves nothing afterwards, so it has to run last and own its own class. + * container serves nothing afterwards, so it has to run last and own its own class. "Last" is + * declared, not left to JUnit's default method order: a stopped handler closes every later + * connection with 1001, so the inherited contract tests would fail if this one ran first. */ +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) @SpringBootTest( classes = WebSocketFixtureApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, @@ -37,6 +43,7 @@ class TomcatWebSocketAbuseIT extends WebSocketAbuseContract { } @Test + @Order(Integer.MAX_VALUE) @Tag("websocket-shutdown") @DisplayName("shutting down closes live connections rather than dropping them") void shutdownClosesLiveConnections() throws Exception { diff --git a/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/runtime/TomcatWebSocketShutdownIT.java b/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/runtime/TomcatWebSocketShutdownIT.java index 6925cf2f..d00f34c4 100644 --- a/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/runtime/TomcatWebSocketShutdownIT.java +++ b/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/runtime/TomcatWebSocketShutdownIT.java @@ -2,11 +2,13 @@ package dev.caskeleton.adapter.inbound.websocket.runtime; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.inbound.websocket.servlet.PlatformWebSocketHandler; import dev.caskeleton.adapter.inbound.websocket.testkit.runtime.WebSocketFixtureApplication; import java.net.URI; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.server.context.WebServerApplicationContext; @@ -56,4 +58,46 @@ class TomcatWebSocketShutdownIT { // A 1006 here means the server stopped before the handler could send its close frame. assertThat(closed.await(20, TimeUnit.SECONDS) ? observedCode.get() : -1).isEqualTo(1001); } + + @Test + @DisplayName("handler가 멈춘 뒤 서버가 아직 받아 준 재접속은 1006이 아니라 1001로 닫힌다") + void aReconnectAcceptedAfterTheHandlerStoppedIsClosedWith1001() throws Exception { + // given + // The window under test: the handler's stop (DEFAULT_PHASE) has run, the web server's graceful + // stop (DEFAULT_PHASE - 1024) has not, so the container still completes upgrades. A client that + // was just told 1001 and reconnects at once — with the load balancer still routing here — + // lands in it. + ConfigurableApplicationContext context = + new SpringApplicationBuilder(WebSocketFixtureApplication.class) + .properties("server.port=0", "server.shutdown=graceful") + .run(); + try { + int port = ((WebServerApplicationContext) context).getWebServer().getPort(); + PlatformWebSocketHandler handler = context.getBean(PlatformWebSocketHandler.class); + handler.stop(); + AtomicInteger observedCode = new AtomicInteger(); + CountDownLatch closed = new CountDownLatch(1); + + // when + new StandardWebSocketClient() + .execute( + new TextWebSocketHandler() { + @Override + public void afterConnectionClosed(WebSocketSession peer, CloseStatus status) { + observedCode.set(status.getCode()); + closed.countDown(); + } + }, + new WebSocketHttpHeaders(), + URI.create("ws://localhost:" + port + WebSocketFixtureApplication.PATH)) + .get(10, TimeUnit.SECONDS); + + // then + // Without the check the connection stays open until the server is torn down: a 1006 later. + assertThat(closed.await(10, TimeUnit.SECONDS) ? observedCode.get() : -1).isEqualTo(1001); + assertThat(handler.openConnections()).isZero(); + } finally { + context.close(); + } + } } diff --git a/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketBoundaryQualificationTest.java b/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketBoundaryQualificationTest.java index 64ad5671..b6780815 100644 --- a/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketBoundaryQualificationTest.java +++ b/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketBoundaryQualificationTest.java @@ -20,11 +20,12 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import org.awaitility.Awaitility; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; @@ -59,17 +60,21 @@ import org.springframework.web.socket.sockjs.client.WebSocketTransport; "app.websocket.enabled=true", "app.websocket.endpoint=/ws", "app.websocket.allowed-origins=https://allowed.example", - "app.websocket.broadcast-destination=/topic/events" + "app.websocket.broadcast-destination=/topic/events", + // Small enough to cross in a test. Every other test here holds one connection at a time. + "app.websocket.max-connections=" + WebSocketBoundaryQualificationTest.MAX_CONNECTIONS }) class WebSocketBoundaryQualificationTest { + static final int MAX_CONNECTIONS = 2; + private static final String AUTHORIZATION = "Bearer qualification-token"; private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(WebSocketConfig.class)); - private final AtomicReference openSession = new AtomicReference<>(); + private final List openSessions = new CopyOnWriteArrayList<>(); private final List openClients = new CopyOnWriteArrayList<>(); @LocalServerPort int port; @@ -78,6 +83,8 @@ class WebSocketBoundaryQualificationTest { @Autowired WireProbe wireProbe; + @Autowired StompConnectionLimit connectionLimit; + @BeforeEach void resetWireProbe() { wireProbe.reset(); @@ -85,16 +92,23 @@ class WebSocketBoundaryQualificationTest { @AfterEach void closeClient() { - StompSession session = openSession.getAndSet(null); - if (session != null && session.isConnected()) { - try { - session.disconnect(); - } catch (RuntimeException ignored) { - // An ERROR frame closes the transport before the client session flips its connected flag. + for (StompSession session : openSessions) { + if (session.isConnected()) { + try { + session.disconnect(); + } catch (RuntimeException ignored) { + // An ERROR frame closes the transport before the client session flips its connected + // flag. + } } } + openSessions.clear(); openClients.forEach(WebSocketStompClient::stop); openClients.clear(); + // The next test must start with every slot free, or the connection ceiling refuses it. + Awaitility.await() + .atMost(Duration.ofSeconds(10)) + .until(() -> connectionLimit.openConnections() == 0); } @Test @@ -138,7 +152,7 @@ class WebSocketBoundaryQualificationTest { ErrorCapturingHandler sessionHandler = new ErrorCapturingHandler(); StompSession session = connect("https://allowed.example", true, sessionHandler).get(5, TimeUnit.SECONDS); - openSession.set(session); + openSessions.add(session); CompletableFuture frame = new CompletableFuture<>(); session.subscribe("/topic/events", bytesHandler(frame)); @@ -159,7 +173,7 @@ class WebSocketBoundaryQualificationTest { ErrorCapturingHandler sessionHandler = new ErrorCapturingHandler(); StompSession session = connect("https://allowed.example", true, sessionHandler).get(5, TimeUnit.SECONDS); - openSession.set(session); + openSessions.add(session); CompletableFuture frame = new CompletableFuture<>(); session.subscribe("/topic/events", bytesHandler(frame)); @@ -179,7 +193,7 @@ class WebSocketBoundaryQualificationTest { ErrorCapturingHandler sessionHandler = new ErrorCapturingHandler(); StompSession session = connect("https://allowed.example", true, sessionHandler).get(5, TimeUnit.SECONDS); - openSession.set(session); + openSessions.add(session); session.send("/app/qualification", new byte[0]); wireProbe.applicationSend().get(5, TimeUnit.SECONDS); @@ -194,6 +208,51 @@ class WebSocketBoundaryQualificationTest { assertThat(error.toString()).doesNotContain("SECRET_SENTINEL"); } + @Test + @DisplayName("같은 세션의 두 번째 SUBSCRIBE는 고정 코드 ERROR 프레임으로 거부된다") + void aSecondSubscribeOnTheSameSessionGetsAnErrorFrame() throws Exception { + // given + ErrorCapturingHandler sessionHandler = new ErrorCapturingHandler(); + StompSession session = + connect("https://allowed.example", true, sessionHandler).get(5, TimeUnit.SECONDS); + openSessions.add(session); + session.subscribe("/topic/events", bytesHandler(new CompletableFuture<>())); + wireProbe.subscription().get(5, TimeUnit.SECONDS); + + // when + session.subscribe("/topic/events", bytesHandler(new CompletableFuture<>())); + + // then + ErrorFrame error = sessionHandler.errorFrame().get(5, TimeUnit.SECONDS); + assertThat(error.headers().getFirst("message")) + .isEqualTo(SafeStompSubProtocolErrorHandler.SAFE_ERROR_CODE); + assertThat(error.payload()).isEmpty(); + } + + @Test + @DisplayName("노드 연결 상한+1번째 연결은 STOMP 세션이 되지 못하고 거부된다") + void theConnectionBeyondTheNodeCeilingIsRefused() throws Exception { + // given + Awaitility.await() + .atMost(Duration.ofSeconds(10)) + .until(() -> connectionLimit.openConnections() == 0); + for (int index = 0; index < MAX_CONNECTIONS; index++) { + openSessions.add( + connect("https://allowed.example", true, new ErrorCapturingHandler()) + .get(5, TimeUnit.SECONDS)); + } + + // when + CompletableFuture overflow = + connect("https://allowed.example", true, new ErrorCapturingHandler()); + + // then + // Closed with 1013 before the STOMP handler sees it, so CONNECTED never arrives. + assertThatThrownBy(() -> openSessions.add(overflow.get(5, TimeUnit.SECONDS))) + .isInstanceOf(ExecutionException.class); + assertThat(connectionLimit.openConnections()).isEqualTo(MAX_CONNECTIONS); + } + private CompletableFuture connect( String origin, boolean authenticated, ErrorCapturingHandler sessionHandler) { SockJsClient sockJsClient = diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriterTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriterTest.java index f4f53379..c54562f1 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriterTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriterTest.java @@ -5,6 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; +import java.lang.reflect.Field; +import java.time.Duration; import java.util.List; import java.util.Optional; import java.util.concurrent.CopyOnWriteArrayList; @@ -14,6 +16,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.ReentrantLock; +import org.awaitility.Awaitility; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -204,4 +208,48 @@ class SerializedOutboundWriterTest { assertThat(shared.buffered()).isZero(); } + + @Test + @DisplayName("closed 확인 뒤 queue lock 앞에서 close에 추월당한 offer는 노드 버퍼 예산을 남기지 않는다") + void anOfferOvertakenByCloseLeavesNoNodeBudgetReserved() throws Exception { + // given + // The race in production is a producer that read `closed == false` and is about to take the + // queue lock when another thread closes the writer. Made deterministic by holding the writer's + // own queue lock from this thread: the producer parks on it after its closed check, and close() + // runs on this thread through the reentrant lock — exactly "close overtook the producer". + // Read by reflection rather than through a test-only seam in production code. + GlobalBufferBudget shared = new GlobalBufferBudget(10_000); + OutboundQueue queue = new OutboundQueue(BUDGET, 1000, shared); + SerializedOutboundWriter writer = + new SerializedOutboundWriter( + new WebSocketConnectionId("c-01H8XQ2N4K"), queue, payload -> {}); + ReentrantLock queueLock = queueLockOf(writer); + OutboundEnqueueResult result; + try (ExecutorService producer = Executors.newSingleThreadExecutor()) { + Future offered; + queueLock.lock(); + try { + offered = producer.submit(() -> writer.offer(message("m-late", "x".repeat(500)))); + Awaitility.await().atMost(Duration.ofSeconds(5)).until(queueLock::hasQueuedThreads); + + // when + writer.close(); + } finally { + queueLock.unlock(); + } + result = offered.get(5, TimeUnit.SECONDS); + } + + // then + assertThat(shared.buffered()) + .as("bytes reserved for a closed writer have no owner left to release them") + .isZero(); + assertThat(result).isEqualTo(OutboundEnqueueResult.CONNECTION_MUST_CLOSE); + } + + private static ReentrantLock queueLockOf(SerializedOutboundWriter writer) throws Exception { + Field field = SerializedOutboundWriter.class.getDeclaredField("queueLock"); + field.setAccessible(true); + return (ReentrantLock) field.get(writer); + } } diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandlerTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandlerTest.java index 16e888db..39f11302 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandlerTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandlerTest.java @@ -15,6 +15,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.boot.web.server.context.WebServerApplicationContext; @@ -24,6 +25,8 @@ import org.springframework.web.socket.WebSocketSession; class PlatformWebSocketHandlerTest { + private static final int MAX_CONNECTIONS = 16; + @Test void stopRunsBeforeTheWebServerGracefulShutdown() { // Spring stops the highest phase first; below this the server is gone before 1001 is sent. @@ -31,6 +34,7 @@ class PlatformWebSocketHandlerTest { new PlatformWebSocketHandler( new WebSocketConnectionBudget(64, 10), new GlobalBufferBudget(1_024), + MAX_CONNECTIONS, (connection, request) -> Optional.empty()); assertThat(handler.getPhase()) @@ -45,6 +49,7 @@ class PlatformWebSocketHandlerTest { new PlatformWebSocketHandler( new WebSocketConnectionBudget(64, 1_024), new GlobalBufferBudget(1_024), + MAX_CONNECTIONS, (connection, request) -> Optional.of("unexpected")); WebSocketSession session = mock(WebSocketSession.class); when(session.getId()).thenReturn("session-02"); @@ -67,6 +72,7 @@ class PlatformWebSocketHandlerTest { new PlatformWebSocketHandler( budget, new GlobalBufferBudget(1_024), + MAX_CONNECTIONS, (connection, request) -> Optional.of("0123456789")); WebSocketSession session = mock(WebSocketSession.class); @@ -129,4 +135,81 @@ class PlatformWebSocketHandlerTest { handler.afterConnectionClosed(session, CloseStatus.NORMAL); } } + + @Test + @DisplayName("stop() 뒤에 맺어진 연결은 등록되지 않고 즉시 1001로 닫힌다") + void aConnectionEstablishedAfterStopIsClosedWith1001() throws Exception { + // given + // Between this handler's stop (DEFAULT_PHASE) and the web server's graceful stop the container + // still accepts upgrades. A client told 1001 that reconnects at once lands in that window. + PlatformWebSocketHandler handler = + new PlatformWebSocketHandler( + new WebSocketConnectionBudget(64, 1_024), + new GlobalBufferBudget(1_024), + MAX_CONNECTIONS, + (connection, request) -> Optional.empty()); + handler.start(); + handler.stop(); + WebSocketSession late = mock(WebSocketSession.class); + when(late.getId()).thenReturn("session-late"); + + // when + handler.afterConnectionEstablished(late); + + // then + ArgumentCaptor closed = ArgumentCaptor.forClass(CloseStatus.class); + verify(late).close(closed.capture()); + assertThat(closed.getValue().getCode()).isEqualTo(1001); + assertThat(handler.openConnections()).isZero(); + } + + @Test + @DisplayName("연결 상한에 닿으면 다음 연결은 등록되지 않고 1013으로 닫힌다") + void aConnectionBeyondTheCeilingIsClosedWith1013() throws Exception { + // given + PlatformWebSocketHandler handler = + new PlatformWebSocketHandler( + new WebSocketConnectionBudget(64, 1_024), + new GlobalBufferBudget(1_024), + 1, + (connection, request) -> Optional.empty()); + WebSocketSession admitted = mock(WebSocketSession.class); + when(admitted.getId()).thenReturn("session-admitted"); + handler.afterConnectionEstablished(admitted); + WebSocketSession overflow = mock(WebSocketSession.class); + when(overflow.getId()).thenReturn("session-overflow"); + + // when + handler.afterConnectionEstablished(overflow); + + // then + ArgumentCaptor closed = ArgumentCaptor.forClass(CloseStatus.class); + verify(overflow).close(closed.capture()); + assertThat(closed.getValue().getCode()).isEqualTo(1013); + assertThat(handler.openConnections()).isOne(); + } + + @Test + @DisplayName("상한에 걸려 닫힌 연결의 종료 콜백은 받아들인 연결 수를 줄이지 않는다") + void closingARefusedConnectionDoesNotFreeAnAdmittedSlot() throws Exception { + // given + PlatformWebSocketHandler handler = + new PlatformWebSocketHandler( + new WebSocketConnectionBudget(64, 1_024), + new GlobalBufferBudget(1_024), + 1, + (connection, request) -> Optional.empty()); + WebSocketSession admitted = mock(WebSocketSession.class); + when(admitted.getId()).thenReturn("session-admitted"); + WebSocketSession overflow = mock(WebSocketSession.class); + when(overflow.getId()).thenReturn("session-overflow"); + handler.afterConnectionEstablished(admitted); + handler.afterConnectionEstablished(overflow); + + // when + handler.afterConnectionClosed(overflow, CloseStatus.SERVICE_OVERLOAD); + + // then + assertThat(handler.openConnections()).isOne(); + } } diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompConnectionLimitTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompConnectionLimitTest.java new file mode 100644 index 00000000..8d5da264 --- /dev/null +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompConnectionLimitTest.java @@ -0,0 +1,65 @@ +package dev.caskeleton.adapter.inbound.websocket.stomp; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.WebSocketHandler; +import org.springframework.web.socket.WebSocketSession; + +class StompConnectionLimitTest { + + private final WebSocketHandler stomp = mock(WebSocketHandler.class); + + @Test + @DisplayName("상한+1번째 연결은 STOMP handler에 넘어가지 않고 1013으로 닫힌다") + void aConnectionBeyondTheCeilingIsClosedWith1013BeforeStompSeesIt() throws Exception { + // given + StompConnectionLimit limit = new StompConnectionLimit(1); + WebSocketHandler handler = limit.decorate(stomp); + handler.afterConnectionEstablished(session("admitted")); + WebSocketSession overflow = session("overflow"); + + // when + handler.afterConnectionEstablished(overflow); + + // then + ArgumentCaptor closed = ArgumentCaptor.forClass(CloseStatus.class); + verify(overflow).close(closed.capture()); + assertThat(closed.getValue().getCode()).isEqualTo(1013); + verify(stomp, never()).afterConnectionEstablished(overflow); + assertThat(limit.openConnections()).isOne(); + } + + @Test + @DisplayName("받아들인 연결이 닫히면 자리가 돌아오고 거부된 연결의 종료는 자리를 돌려주지 않는다") + void onlyAnAdmittedConnectionGivesItsSlotBack() throws Exception { + // given + StompConnectionLimit limit = new StompConnectionLimit(1); + WebSocketHandler handler = limit.decorate(stomp); + WebSocketSession admitted = session("admitted"); + WebSocketSession overflow = session("overflow"); + handler.afterConnectionEstablished(admitted); + handler.afterConnectionEstablished(overflow); + handler.afterConnectionClosed(overflow, CloseStatus.SERVICE_OVERLOAD); + + // when + handler.afterConnectionClosed(admitted, CloseStatus.NORMAL); + + // then + assertThat(limit.openConnections()).isZero(); + verify(stomp, never()).afterConnectionClosed(overflow, CloseStatus.SERVICE_OVERLOAD); + } + + private static WebSocketSession session(String id) { + WebSocketSession session = mock(WebSocketSession.class); + when(session.getId()).thenReturn(id); + return session; + } +} 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 0d6bd600..c8cdfeea 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 @@ -7,11 +7,14 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.stream.Stream; +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.WebApplicationContextRunner; import org.springframework.messaging.support.ExecutorSubscribableChannel; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.web.socket.messaging.StompSubProtocolHandler; +import org.springframework.web.socket.messaging.SubProtocolWebSocketHandler; /** The STOMP channel reaches an application through this module's own auto-configuration entry. */ class WebSocketAutoConfigurationTest { @@ -83,6 +86,37 @@ class WebSocketAutoConfigurationTest { }); } + @Test + @DisplayName("app.websocket 전송 한도 키가 STOMP 전송 계층 설정에 그대로 들어간다") + void transportLimitsComeFromTheConfiguredKeys() { + // given + WebApplicationContextRunner configured = + runner.withPropertyValues( + "app.websocket.message-size-limit=32KB", + "app.websocket.send-buffer-size-limit=256KB", + "app.websocket.send-time-limit=5s", + "app.websocket.time-to-first-message=30s"); + + // when + configured.run( + context -> { + // then + SubProtocolWebSocketHandler transport = + context.getBean("subProtocolWebSocketHandler", SubProtocolWebSocketHandler.class); + assertThat(transport) + .extracting( + SubProtocolWebSocketHandler::getSendBufferSizeLimit, + SubProtocolWebSocketHandler::getSendTimeLimit, + SubProtocolWebSocketHandler::getTimeToFirstMessage) + .containsExactly(256 * 1024, 5_000, 30_000); + assertThat(transport.getProtocolHandlers()) + .singleElement() + .isInstanceOfSatisfying( + StompSubProtocolHandler.class, + stomp -> assertThat(stomp.getMessageSizeLimit()).isEqualTo(32 * 1024)); + }); + } + @Test void switchedOffHoldsNothing() { runner diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketEnvironmentBindingTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketEnvironmentBindingTest.java index 74d16439..21a54ef4 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketEnvironmentBindingTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketEnvironmentBindingTest.java @@ -2,12 +2,14 @@ package dev.caskeleton.adapter.inbound.websocket.stomp; import static org.assertj.core.api.Assertions.assertThat; +import java.time.Duration; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.env.SystemEnvironmentPropertySource; +import org.springframework.util.unit.DataSize; class WebSocketEnvironmentBindingTest { @@ -25,7 +27,12 @@ class WebSocketEnvironmentBindingTest { "APP_WEBSOCKET_ENDPOINT", "/live/ws", "APP_WEBSOCKET_ALLOWED_ORIGINS", "https://client.example", "APP_WEBSOCKET_BROADCAST_DESTINATION", "/topic/live", - "APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY", "512"))); + "APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY", "512", + "APP_WEBSOCKET_MESSAGE_SIZE_LIMIT", "32KB", + "APP_WEBSOCKET_SEND_BUFFER_SIZE_LIMIT", "256KB", + "APP_WEBSOCKET_SEND_TIME_LIMIT", "5s", + "APP_WEBSOCKET_TIME_TO_FIRST_MESSAGE", "30s", + "APP_WEBSOCKET_MAX_CONNECTIONS", "200"))); // when WebSocketSettings stomp = @@ -40,7 +47,22 @@ class WebSocketEnvironmentBindingTest { WebSocketSettings::getEndpoint, WebSocketSettings::getAllowedOrigins, WebSocketSettings::getBroadcastDestination, - WebSocketSettings::getChannelQueueCapacity) - .containsExactly(true, "/live/ws", "https://client.example", "/topic/live", 512); + WebSocketSettings::getChannelQueueCapacity, + WebSocketSettings::getMessageSizeLimit, + WebSocketSettings::getSendBufferSizeLimit, + WebSocketSettings::getSendTimeLimit, + WebSocketSettings::getTimeToFirstMessage, + WebSocketSettings::getMaxConnections) + .containsExactly( + true, + "/live/ws", + "https://client.example", + "/topic/live", + 512, + DataSize.ofKilobytes(32), + DataSize.ofKilobytes(256), + Duration.ofSeconds(5), + Duration.ofSeconds(30), + 200); } } diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java index a725311d..a4243e1a 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import java.security.Principal; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -57,6 +58,88 @@ class WebSocketInboundAuthorizationInterceptorTest { .hasMessageNotContaining("SECRET_SENTINEL"); } + @Test + @DisplayName("같은 세션의 두 번째 SUBSCRIBE는 id가 달라도 거부된다") + void aSecondSubscribeFromTheSameSessionIsRejected() { + // given + interceptor.preSend(subscribe("session-1", "sub-0"), channel); + + // when / then + assertRejected(subscribe("session-1", "sub-1")); + } + + @Test + @DisplayName("다른 세션의 SUBSCRIBE는 서로의 구독 수에 들어가지 않는다") + void subscriptionsAreCountedPerSession() { + // given + interceptor.preSend(subscribe("session-1", "sub-0"), channel); + + // when / then + assertThatCode(() -> interceptor.preSend(subscribe("session-2", "sub-0"), channel)) + .doesNotThrowAnyException(); + } + + @Test + @DisplayName("UNSUBSCRIBE로 구독을 풀면 같은 세션이 다시 구독할 수 있다") + void unsubscribingFreesTheSessionsSubscription() { + // given + interceptor.preSend(subscribe("session-1", "sub-0"), channel); + interceptor.preSend(unsubscribe("session-1", "sub-0"), channel); + + // when / then + assertThatCode(() -> interceptor.preSend(subscribe("session-1", "sub-1"), channel)) + .doesNotThrowAnyException(); + } + + @Test + @DisplayName("DISCONNECT 뒤에는 같은 세션 id의 구독 기록이 남지 않는다") + void disconnectFreesTheSessionsSubscription() { + // given + interceptor.preSend(subscribe("session-1", "sub-0"), channel); + interceptor.preSend(withSession(StompCommand.DISCONNECT, null, "session-1", null), channel); + + // when / then + assertThatCode(() -> interceptor.preSend(subscribe("session-1", "sub-0"), channel)) + .doesNotThrowAnyException(); + } + + @Test + @DisplayName("broker에 닿지 못한 SUBSCRIBE는 구독 자리를 돌려준다") + void aSubscribeTheChannelRejectedFreesTheSlot() { + // given + Message first = subscribe("session-1", "sub-0"); + interceptor.preSend(first, channel); + interceptor.afterSendCompletion( + first, channel, false, new IllegalStateException("channel queue full")); + + // when / then + assertThatCode(() -> interceptor.preSend(subscribe("session-1", "sub-0"), channel)) + .doesNotThrowAnyException(); + } + + private static Message subscribe(String sessionId, String subscriptionId) { + return withSession(StompCommand.SUBSCRIBE, "/topic/events", sessionId, subscriptionId); + } + + private static Message unsubscribe(String sessionId, String subscriptionId) { + return withSession(StompCommand.UNSUBSCRIBE, null, sessionId, subscriptionId); + } + + private static Message withSession( + StompCommand command, String destination, String sessionId, String subscriptionId) { + StompHeaderAccessor accessor = StompHeaderAccessor.create(command); + if (destination != null) { + accessor.setDestination(destination); + } + accessor.setSessionId(sessionId); + if (subscriptionId != null) { + accessor.setSubscriptionId(subscriptionId); + } + accessor.setUser(AUTHENTICATED); + accessor.setLeaveMutable(true); + return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()); + } + private void assertRejected(Message message) { assertThatThrownBy(() -> interceptor.preSend(message, channel)) .isInstanceOf(WebSocketPolicyViolationException.class) @@ -69,6 +152,8 @@ class WebSocketInboundAuthorizationInterceptorTest { if (destination != null) { accessor.setDestination(destination); } + // Spring stamps every client frame with its session id; a frame without one is not admitted. + accessor.setSessionId("session-0"); accessor.setUser(principal); accessor.setLeaveMutable(true); return MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()); diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettingsTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettingsTest.java index 7d0a8ad5..821f6fbc 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettingsTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettingsTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.websocket.stomp; import static org.assertj.core.api.Assertions.assertThat; +import java.time.Duration; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -11,6 +12,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.validation.autoconfigure.ValidationAutoConfiguration; import org.springframework.context.annotation.Configuration; +import org.springframework.util.unit.DataSize; import org.springframework.validation.annotation.Validated; class WebSocketSettingsTest { @@ -43,6 +45,28 @@ class WebSocketSettingsTest { }); } + @Test + @DisplayName("전송 한도 기본값은 Spring 기본값(64 KiB·512 KiB·10초·60초)과 같고 연결 상한은 1000이다") + void transportDefaultsEqualSpringsAndTheConnectionCeilingIsSet() { + // when + WebSocketSettings properties = new WebSocketSettings(); + + // then + assertThat(properties) + .extracting( + WebSocketSettings::getMessageSizeLimit, + WebSocketSettings::getSendBufferSizeLimit, + WebSocketSettings::getSendTimeLimit, + WebSocketSettings::getTimeToFirstMessage, + WebSocketSettings::getMaxConnections) + .containsExactly( + DataSize.ofKilobytes(64), + DataSize.ofKilobytes(512), + Duration.ofSeconds(10), + Duration.ofSeconds(60), + 1_000); + } + @Test void enabledSafeSettingsBind() { runner @@ -73,7 +97,12 @@ class WebSocketSettingsTest { "app.websocket.broadcast-destination=/queue/events", "app.websocket.broadcast-destination=/topic/", "app.websocket.broadcast-destination=/topic/events?raw=true", - "app.websocket.channel-queue-capacity=0" + "app.websocket.channel-queue-capacity=0", + "app.websocket.max-connections=0", + "app.websocket.message-size-limit=0B", + "app.websocket.send-buffer-size-limit=3GB", + "app.websocket.send-time-limit=0s", + "app.websocket.time-to-first-message=0s" }) void enabledUnsafeSettingFailsBinding(String invalidSetting) { runner diff --git a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketFixtureApplication.java b/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketFixtureApplication.java index 50167983..6d91f2aa 100644 --- a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketFixtureApplication.java +++ b/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketFixtureApplication.java @@ -35,10 +35,17 @@ public class WebSocketFixtureApplication implements WebSocketConfigurer { /** The message bound this lane tests against. */ public static final int MAX_MESSAGE_BYTES = 1024; + /** + * The connection ceiling. Above the abuse contract's burst (24) so the burst is served, and low + * enough that a leaked slot would show up in a long run. + */ + public static final int MAX_CONNECTIONS = 64; + private final PlatformWebSocketHandler handler = new PlatformWebSocketHandler( new WebSocketConnectionBudget(MAX_MESSAGE_BYTES, 8 * 1024), new GlobalBufferBudget(1024 * 1024), + MAX_CONNECTIONS, // Echoes with a prefix, so a test can tell an answer from its own request and can prove // the whole message arrived. (connectionId, message) -> Optional.of("echo:" + message)); diff --git a/src/adapter/outbound/cache-redis/CLAUDE.md b/src/adapter/outbound/cache-redis/CLAUDE.md index 494a02c9..61f3823b 100644 --- a/src/adapter/outbound/cache-redis/CLAUDE.md +++ b/src/adapter/outbound/cache-redis/CLAUDE.md @@ -15,8 +15,11 @@ Package root: `dev.caskeleton.adapter.outbound.cache`. - Implement semantic cache ports from `application-core` without exposing Redis concepts to core. - Own canonical physical keys, digesting, codec/envelope, program catalog, typed Redis atomic facades, runtime client adaptation, and capability-specific failure semantics. -- Implement absolute soft/hard expiry and deterministic bounded jitter behind the semantic cache - port (`CacheRegionPort`). +- Implement absolute soft/hard expiry, write conditions and key invalidation markers behind the + semantic cache port (`CacheRegionPort`). There is no TTL jitter and no stampede protection; + single-flight is the caller's. The revision order is the port's `CacheSourceRevisionOrder`; the + Lua copy is held to it by `CacheRegionContract` (application-core testFixtures), which + `RedisCacheRegionContractTest` and `LiveRedisCacheRegionContractTest` extend. - Implement the provider-neutral `EdgeRateLimitPort` with dedicated coordination Redis settings, connection/admission, private keys and versioned atomic programs. - Keep the legacy cache router isolated while consumers migrate to semantic ports. @@ -171,6 +174,14 @@ from the watched keys (or an explicit `RedisSlotTag`) and borrows `RedisSdkLane. is pinned to its key's owner, on the node that owns that slot. Routed leases are never pooled: a pooled connection is pinned to the previous caller's node. +Settings binding is a recorded exception to capability criterion 4 (one prefix, `StrictSettingsBinder`, +review finding 05-18): `app.redis.*` is bound by `redis-runtime` with setters and `validate()`, +because that leaf has no project dependencies and cannot reach `StrictSettingsBinder` (support); +`app.capabilities.*` (cache, lease, rate-limit provider) is bound strictly by this leaf under the +shared capability-selector root; `app.rate-limit.*` is the HTTP boundary's switch that this leaf only +reads. Renaming the keys would break every deployment's environment for no behavioural gain, so the +three trees stay; a new Redis setting goes into one of them, never a fourth. + `RedisRuntimeSettings` must never carry a class-level `@ConfigurationProperties`: `RedisRuntimeAutoConfiguration` binds it, so `APP_REDIS_ENABLED=false` binds no Redis configuration at all. A properties scan that reached this diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 4478b3f2..e3457087 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -122,10 +122,13 @@ Redis checks a script's inner commands against the ACL only when they run, so a nothing proved `EVALSHA` and nothing else: an account granted by category (`@read`/`@write`) lacks `TIME` and failed every rate-limit and idempotency request after a clean start. A deployment whose effective Redis account lacks script permissions fails during startup rather than at the first -request. Cache-only deployments do not run this probe, although the cache's conditional intents -(`ONLY_IF_OBSERVED`, `ONLY_IF_SOURCE_REVISION_NEWER`) also run on the SCRIPT lane: a cache-only -deployment whose script-lane account lacks `EVALSHA` finds out as `INDETERMINATE` conditional -writes, not at startup. +request. + +A cache-only deployment (`app.capabilities.cache.bindings.default=redis`, no correctness role) runs +a narrower probe: a program that calls only `SET`/`GET`, the commands the cache's conditional-write +programs use. A server that answers and refuses it fails startup — every conditional record would +otherwise come back degraded while plain reads looked healthy. A Redis that cannot be reached at +startup is logged as a warning and the pod starts: a cache outage degrades, it never stops a pod. At runtime, `redisRequired` (redis-runtime) probes the SCRIPT lane too when a script role is selected, so a broken advanced-account credential makes the pod unready instead of leaving the @@ -147,7 +150,13 @@ Important contracts: `ONLY_IF_OBSERVED` is an atomic server-side compare-and-replace. -The lookup returns an opaque SHA-1 observation token over the stored bytes. SHA-1 here is **not a +Every lookup returns a `CacheWriteCondition` naming the state it saw — `absent`, `vacant:` +(an invalidation marker, an entry of an older region generation, an expired entry) or +`present:`. A record that carries the condition applies only while the key is still in that +state (registered program, SCRIPT lane). This is what rejects a source load that began before an +invalidation and finished after it. + +A hit also returns an opaque SHA-1 observation token over the stored bytes. SHA-1 here is **not a security primitive**; it is used only because Redis Lua exposes `redis.sha1hex`, allowing the script to perform: @@ -156,10 +165,12 @@ script to perform: inside one Redis execution. A stale source load therefore cannot overwrite a value written between observation and replacement. -`ONLY_IF_SOURCE_REVISION_NEWER` is an atomic server-side revision comparison. The source revision -must be a non-negative decimal integer without leading zeros (a row version, an offset, epoch -millis); any other revision is refused with `IllegalArgumentException` before anything is sent, -because text order would rank revision `10` below `9`. The script reads the stored envelope's +`ONLY_IF_SOURCE_REVISION_NEWER` is an atomic server-side revision comparison. The order is the +port's `CacheSourceRevisionOrder` (application-core): a non-negative decimal integer without leading +zeros (a row version, an offset, epoch millis), compared numerically at any length. Any other +revision is refused by `CacheRecordMetadata` itself, for every provider, because text order would +rank revision `10` below `9`. The Lua program reimplements the order (the comparison and the write +must be one step); `CacheRegionContract`, run over the fixture and a real server, keeps it equal. The script reads the stored envelope's schema version, revision and generation and writes only when: - nothing is stored, or the stored entry is from an older region generation (already invalidated); @@ -169,10 +180,25 @@ Everything else — an equal or smaller revision, a stored revision with no nume example one written by `UPSERT` as `rev-1`), another schema version, a generation newer than the writer knows — is `NOT_RECORDED_CONDITION`. -Both conditional intents run registered scripts, so they borrow the SCRIPT lane (the advanced -account when one is configured, the application account otherwise). The application account is not -granted `EVALSHA`; on the REGULAR lane every conditional write came back `INDETERMINATE`. `UPSERT` -and `ONLY_IF_ABSENT` stay on the REGULAR lane. +Both conditional intents, and any record carrying a write condition, run registered scripts, so +they borrow the SCRIPT lane (the advanced account when one is configured, the application account +otherwise). The application account is not granted `EVALSHA`; on the REGULAR lane every conditional +write came back `INDETERMINATE`. Unconditioned `UPSERT` and `ONLY_IF_ABSENT` stay on the REGULAR +lane. + +### Key invalidation + +`invalidate(key)` writes a short-lived marker (`GET`, then `SET … PX softTtl` on the REGULAR lane) +instead of deleting the key. While the marker lives, a record whose condition came from an earlier +lookup, an unconditioned `ONLY_IF_ABSENT`, and an unconditioned `ONLY_IF_SOURCE_REVISION_NEWER` are +`NOT_RECORDED_CONDITION`; a fresh lookup returns a `vacant:` condition that records normally; +unconditioned `UPSERT` overwrites it. Limit: the marker lives for the soft TTL, so a source load +slower than that, carrying an `absent` condition, can still land after it. + +### Stampede + +There is no stampede protection and no TTL jitter. Concurrent misses on one key each load from the +source. Single-flight, where a source cannot take the burst, is the caller's. ### Region invalidation @@ -195,7 +221,14 @@ Script TTLs are computed as integer milliseconds in Java and passed as exact Lua `cleanup-grace` is part of the physical state TTL. There is no exposed `maximum-clock-regression` knob because Redis is the time authority for this state. -Rate-limit failures remain fail-closed according to the application contract. +Rate-limit failures remain fail-closed according to the application contract. A connection that +could not be opened is `UNAVAILABLE_BEFORE_SEND` (nothing was sent). The caller's remaining +deadline bounds the lane wait and the reply wait; opening a new connection is still bounded only by +the driver's connect timeout. + +Evaluation deduplication is **not implemented**: `RateLimitRequest.evaluationId` is ignored, so a +retry after `NO_MUTATION_CONFIRMED` is charged again. Policies default to +`RateLimitEvaluationDedupPolicy.disabled()`, and the adapter refuses a policy that enables it. ## Idempotency semantics diff --git a/src/adapter/outbound/cache-redis/build.gradle b/src/adapter/outbound/cache-redis/build.gradle index 4b66c1b5..71342859 100644 --- a/src/adapter/outbound/cache-redis/build.gradle +++ b/src/adapter/outbound/cache-redis/build.gradle @@ -52,7 +52,7 @@ dependencies { // of its lanes exists to run. Sentinel and TLS are qualified by redis-runtime and redis-sdk. redisTopologyLane { requiredClasses 'standalone', 'LiveRedisSemanticPortsTest', 'LiveRedisSemanticScriptAclProbeTest', - 'LiveRedisDistributedLeaseContractTest' + 'LiveRedisDistributedLeaseContractTest', 'LiveRedisCacheRegionContractTest' requiredClasses 'cluster', 'LiveRedisSemanticPortsTest', 'LiveRedisSemanticScriptAclProbeTest', - 'LiveRedisDistributedLeaseContractTest' + 'LiveRedisDistributedLeaseContractTest', 'LiveRedisCacheRegionContractTest' } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/SemanticRedisCall.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/SemanticRedisCall.java index 59d38f78..e8d46475 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/SemanticRedisCall.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/SemanticRedisCall.java @@ -31,6 +31,11 @@ import java.util.function.Supplier; * adapters, and the difference between their two answers was re-derived in each. Every failure is * reported to {@link RedisSemanticFailureLogger} except an interrupt, which is the caller's own * doing. + * + *

      A lease whose call failed after it was borrowed is {@linkplain RedisLease#invalidate() + * invalidated}, never pooled. The local wait gives up before the driver does, so a timed-out + * command can still be queued on the connection; the next borrower of that connection would read + * the previous caller's reply as its own. */ public final class SemanticRedisCall { @@ -59,9 +64,10 @@ public final class SemanticRedisCall { * Runs a call whose command may take effect as soon as it is sent. * *

      For the registered programs: the call counts as sent from the start, so anything but the - * runtime's own refusal — a connection that could not be opened included — is an unknown outcome. - * A caller told "unavailable" after a failure it cannot rule out having reached the server would - * retry an effect that may already have landed. + * runtime's own refusal is an unknown outcome. The refusal includes a connection that could not + * be opened (review 05-17): no command exists before the connection does. A caller told + * "unavailable" after a failure it cannot rule out having reached the server would retry an + * effect that may already have landed. * * @param operation the semantic operation, for the failure log * @param body what to send, and how to read the reply @@ -71,7 +77,28 @@ public final class SemanticRedisCall { * @return the body's answer, or one of the two failure answers */ public R effect(String operation, Body body, Supplier notSent, Supplier unknown) { - return call(operation, body, notSent, unknown, true); + return call(operation, null, body, notSent, unknown, true); + } + + /** + * Runs an effect call that must finish within what the caller has left. + * + *

      The budget bounds the wait for a lane connection and every awaited reply, whichever of the + * budget and the frame's own ceilings is shorter. Opening a new connection is bounded by the + * driver's connect timeout, which no per-call budget can shorten. + * + * @param operation the semantic operation, for the failure log + * @param budget how long the caller has left + * @param body what to send, and how to read the reply + * @param notSent the answer when nothing can have happened + * @param unknown the answer when the command may have run + * @param the answer type + * @return the body's answer, or one of the two failure answers + */ + public R effectWithin( + String operation, Duration budget, Body body, Supplier notSent, Supplier unknown) { + Objects.requireNonNull(budget, "budget must be non-null"); + return call(operation, budget, body, notSent, unknown, true); } /** @@ -86,29 +113,46 @@ public final class SemanticRedisCall { * @return the body's answer, or one of the two failure answers */ public R run(String operation, Body body, Supplier notSent, Supplier unknown) { - return call(operation, body, notSent, unknown, false); + return call(operation, null, body, notSent, unknown, false); } private R call( String operation, + Duration budget, Body body, Supplier notSent, Supplier unknown, boolean sentFromStart) { Session session = new Session(); session.sent = sentFromStart; - try (RedisLease lease = owner.borrow(lane)) { - session.lease = lease; - return body.apply(session); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return session.sent ? unknown.get() : notSent.get(); + session.deadlineNanos = budget == null ? Long.MAX_VALUE : System.nanoTime() + budget.toNanos(); + RedisLease lease; + try { + // Nothing exists yet that could have reached the server: every refusal here — a full lane, + // a closing runtime, a connection that could not be opened — is "not sent", even for an + // effect call that counts as sent from the start. + lease = + budget == null + ? owner.borrow(lane) + : owner.borrow(lane, java.util.Optional.empty(), session.remaining()); } catch (RedisLaneUnavailableException refused) { RedisSemanticFailureLogger.report(capability, operation, refused); return notSent.get(); + } + try { + session.lease = lease; + return body.apply(session); + } catch (InterruptedException interrupted) { + lease.invalidate(); + Thread.currentThread().interrupt(); + return session.sent ? unknown.get() : notSent.get(); } catch (Exception failure) { + // The reply this call stopped waiting for may still arrive on this connection. + lease.invalidate(); RedisSemanticFailureLogger.report(capability, operation, failure); return session.sent ? unknown.get() : notSent.get(); + } finally { + lease.close(); } } @@ -131,9 +175,16 @@ public final class SemanticRedisCall { private RedisLease lease; private boolean sent; + private long deadlineNanos; private Session() {} + private Duration remaining() { + return deadlineNanos == Long.MAX_VALUE + ? timeout + : Duration.ofNanos(Math.max(0L, deadlineNanos - System.nanoTime())); + } + /** * Returns the commands of the borrowed connection. * @@ -152,7 +203,9 @@ public final class SemanticRedisCall { * @throws Exception the reply's failure, a timeout, or an interrupt */ public V await(CompletionStage reply) throws Exception { - return reply.toCompletableFuture().get(timeout.toNanos(), TimeUnit.NANOSECONDS); + Duration remaining = remaining(); + Duration wait = remaining.compareTo(timeout) < 0 ? remaining : timeout; + return reply.toCompletableFuture().get(wait.toNanos(), TimeUnit.NANOSECONDS); } /** diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScripts.java index 0964afde..982e779f 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScripts.java @@ -9,10 +9,19 @@ import java.util.concurrent.CompletionStage; /** Atomic cache mutations that cannot be expressed as one ordinary Redis command. */ final class CacheScripts { + /** + * Replaces the entry only while it is exactly what the caller observed: the same bytes, by + * digest, or — when the caller observed an empty key, {@code ARGV[1] == "absent"} — still nothing + * at all. + */ private static final String REPLACE_IF_OBSERVED = """ local current = redis.call('GET', KEYS[1]) if current == false then + if ARGV[1] == 'absent' then + redis.call('SET', KEYS[1], ARGV[2], 'PX', ARGV[3]) + return 1 + end return 0 end if redis.sha1hex(current) ~= ARGV[1] then @@ -26,15 +35,23 @@ final class CacheScripts { * Replaces the entry only when the caller's source revision is strictly newer than the stored * one. * - *

      Revisions are canonical non-negative decimal integers, compared by length and then digit by - * digit, so the order is numeric at any length (no 2^53 limit, no locale collation). The stored - * envelope header is {@code digest|version|revision|generation|...}; the digest is not - * re-verified here, the reader does that on lookup. + *

      Revisions are ordered by the port's {@code CacheSourceRevisionOrder}, reimplemented here + * because the comparison and the replacement must be one atomic step: canonical non-negative + * decimal integers, compared by length and then digit by digit, so the order is numeric at any + * length (no 2^53 limit, no locale collation). The cache contract keeps this copy equal to the + * port's. The stored envelope header is {@code digest|version|revision|generation|...}; the + * digest is not re-verified here, the reader does that on lookup. * *

      The write applies when nothing is stored, or when the stored entry belongs to an older * region generation (semantically invalidated). It is refused when the stored entry has another * schema version, a newer generation than the writer knows, or a revision that has no numeric - * order: nothing proves the caller's revision is newer than any of those. + * order: nothing proves the caller's revision is newer than any of those. An invalidation marker + * fails the header parse and refuses the write too. + * + *

      With a write condition ({@code ARGV[6]}: {@code "absent"} or the digest the caller observed) + * the stored state must still be the observed one. When what the caller observed was vacant — an + * invalidation marker, an entry of an older generation, an expired entry ({@code ARGV[7] == "1"}) + * — the write applies without a revision comparison: the caller's load began after it. */ private static final String REPLACE_IF_REVISION_NEWER = """ @@ -56,6 +73,18 @@ final class CacheScripts { return false end local current = redis.call('GET', KEYS[1]) + if ARGV[6] ~= '' then + if current == false then + if ARGV[6] ~= 'absent' then + return 0 + end + elseif redis.sha1hex(current) ~= ARGV[6] then + return 0 + elseif ARGV[7] == '1' then + redis.call('SET', KEYS[1], ARGV[2], 'PX', ARGV[3]) + return 1 + end + end if current ~= false then if string.sub(current, 65, 65) ~= '|' then return 0 @@ -94,16 +123,6 @@ final class CacheScripts { private final RegisteredLuaScript replaceIfRevisionNewer = new RegisteredLuaScript(REPLACE_IF_REVISION_NEWER); - /** - * Whether a revision has the numeric order {@link #replaceIfRevisionNewer} compares by. - * - * @param revision the source revision - * @return true for a canonical non-negative decimal integer - */ - static boolean hasNumericOrder(String revision) { - return revision.matches("0|[1-9][0-9]*"); - } - CompletionStage replaceIfObserved( SemanticRedisCommands commands, byte[] key, @@ -127,14 +146,18 @@ final class CacheScripts { byte[] replacement, long ttlMillis, int schemaVersion, - long writerGeneration) { + long writerGeneration, + String expected, + boolean observedVacant) { List arguments = List.of( sourceRevision.getBytes(StandardCharsets.US_ASCII), replacement, Long.toString(ttlMillis).getBytes(StandardCharsets.US_ASCII), Integer.toString(schemaVersion).getBytes(StandardCharsets.US_ASCII), - Long.toString(writerGeneration).getBytes(StandardCharsets.US_ASCII)); + Long.toString(writerGeneration).getBytes(StandardCharsets.US_ASCII), + expected.getBytes(StandardCharsets.US_ASCII), + (observedVacant ? "1" : "0").getBytes(StandardCharsets.US_ASCII)); return replaceIfRevisionNewer .evaluateForLong(commands, key, arguments) .thenApply(applied -> applied != null && applied == 1L); diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java index c0c25158..95b3a6e3 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java @@ -15,6 +15,8 @@ import dev.caskeleton.application.cache.CacheRecordMetadata; import dev.caskeleton.application.cache.CacheRecordOutcome; import dev.caskeleton.application.cache.CacheRegionPort; import dev.caskeleton.application.cache.CacheWriteCondition; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -44,6 +46,16 @@ import java.util.function.Function; * absence of one, and collapsing it into a miss defeats the negative caching it exists for. * * + *

      Key invalidation writes a short-lived marker instead of deleting the key, and every lookup + * returns a {@link CacheWriteCondition} naming the state it saw: {@code absent}, {@code vacant:} (a + * marker, an entry of an older region generation, an expired entry) or {@code present:}, each with + * the digest of the stored bytes. A record that carries the condition applies only while the key is + * still in that state, so a source load that began before an invalidation cannot put the old value + * back after it. The marker lives for the soft TTL — the freshness this region promises; a load + * slower than that, carrying an {@code absent} condition, can still land once the marker is gone. + * There is no stampede protection: concurrent misses each load from the source, and single-flight + * is the caller's. + * *

      The physical TTL equals the hard expiry, always. A cache whose Redis TTL outlives its own * notion of usability accumulates entries nothing will ever read; one whose TTL is shorter throws * away entries that are still valid. @@ -79,6 +91,16 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort implements CacheRegionPort( - CacheLookup.MissReason.ABSENT, CacheWriteCondition.unavailable()); + CacheLookup.MissReason.ABSENT, new CacheWriteCondition(ABSENT)); + } + if (isTombstone(stored)) { + return new CacheLookup.Miss<>(CacheLookup.MissReason.INVALIDATED, vacant(stored)); } return interpret(stored, now); }, @@ -174,12 +199,10 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort( - CacheLookup.MissReason.INVALIDATED, CacheWriteCondition.unavailable()); + return new CacheLookup.Miss<>(CacheLookup.MissReason.INVALIDATED, vacant(stored)); } if (!envelope.hardExpiresAt().isAfter(now)) { - return new CacheLookup.Miss<>( - CacheLookup.MissReason.EXPIRED, CacheWriteCondition.unavailable()); + return new CacheLookup.Miss<>(CacheLookup.MissReason.EXPIRED, vacant(stored)); } if (!envelope.absence().isEmpty()) { try { @@ -202,7 +225,7 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort implements CacheRegionPort 0 ? ttl : softTtl; byte[] physicalKey = keys.entryKey(keyDigest.apply(key)); boolean scripted = intent == CacheRecordIntent.ONLY_IF_OBSERVED - || intent == CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER; + || intent == CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER + || observed != null; // The write is marked sent only when the write command itself is handed to the driver. A // failure before that point — lane refusal, connection, the generation read — wrote nothing. return (scripted ? scriptCall : call) @@ -279,17 +302,33 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort - session.await( - session - .commands() - .set(physicalKey, envelope.encode(), WritePresence.IF_ABSENT, ttl)); - case UPSERT -> - session.await( - session - .commands() - .set(physicalKey, envelope.encode(), WritePresence.ALWAYS, ttl)); + keys.generation(), + observed == null ? "" : observed.expected(), + observed != null && observed.vacant())); + case ONLY_IF_ABSENT, UPSERT -> + observed != null + // A condition: the key must still be in the state the caller's lookup + // saw. + ? session.await( + scripts.replaceIfObserved( + session.commands(), + physicalKey, + observed.expected(), + envelope.encode(), + ttl.toMillis())) + // No condition: an invalidation marker occupies the key, so IF_ABSENT + // refuses while it lives — nothing proves this load began after the + // invalidation. UPSERT is unconditional and overwrites it. + : session.await( + session + .commands() + .set( + physicalKey, + envelope.encode(), + intent == CacheRecordIntent.UPSERT + ? WritePresence.ALWAYS + : WritePresence.IF_ABSENT, + ttl)); }; return Boolean.TRUE.equals(applied) ? CacheRecordOutcome.RECORDED @@ -306,9 +345,16 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort { byte[] physicalKey = keys.entryKey(keyDigest.apply(key)); + // A marker, not a delete. A delete leaves the key absent, and a source load that read the + // old value before this call would find "absent" still true and put it back. The marker + // carries a nonce so that two invalidations are two different states. GET then SET, not + // one script: a write landing between them is overwritten, which is what an invalidation + // means, and the regular lane needs no script permission to invalidate. + byte[] previous = session.await(session.commands().get(physicalKey)); session.markSent(); - byte[] removed = session.await(session.commands().getAndDelete(physicalKey)); - return removed == null + session.await( + session.commands().set(physicalKey, tombstone(), WritePresence.ALWAYS, softTtl)); + return previous == null || isTombstone(previous) ? CacheInvalidationOutcome.ALREADY_ABSENT : CacheInvalidationOutcome.INVALIDATED; }, @@ -360,6 +406,52 @@ public final class RedisCacheRegionAdapter implements CacheRegionPortStatic: the guard is a startup rule and reads the contributions before any ordinary + * singleton exists, which must not create this configuration class. + * * @return the contribution */ @Bean - RedisProductionSecrets redisProductionSecrets() { + static RedisProductionSecrets redisProductionSecrets() { return new RedisProductionSecrets(); } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeys.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeys.java index b7fd09c3..8379a3e9 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeys.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeys.java @@ -5,7 +5,9 @@ import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; import dev.caskeleton.application.outbound.SecretReference; import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.shared.digest.HmacSha256; import java.nio.charset.StandardCharsets; +import java.util.HexFormat; /** * Namespace construction and the keyed digest every Redis capability derives its key material from. @@ -35,7 +37,13 @@ final class RedisKeys { * everyone who can run {@code SCAN}. The key comes from the deployment's secret backend, so the * keyspace is only correlatable by something that already holds the secret. */ - record KeyDigest(javax.crypto.Mac prototype) { + static final class KeyDigest { + + private final byte[] key; + + private KeyDigest(byte[] key) { + this.key = key; + } static KeyDigest of( SecretSourcePort secretSource, @@ -55,26 +63,18 @@ final class RedisKeys { + name + "' resolved to nothing. Without it the keyspace would carry" + " identifiers in a form anybody who can read it could reverse.")); - try { - javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256"); - mac.init( - new javax.crypto.spec.SecretKeySpec( - // Namespace-bound: the same identifier in staging and production must not digest - // to the same key, or a keyspace dump from the softer environment would map - // one-for-one onto the harder one. - (material - + '|' - + redis.getNamespace().getEnvironment() - + ':' - + redis.getNamespace().getService() - + ':' - + redis.getNamespace().getDomain()) - .getBytes(StandardCharsets.UTF_8), - "HmacSHA256")); - return new KeyDigest(mac); - } catch (java.security.GeneralSecurityException failure) { - throw new IllegalStateException("HmacSHA256 must be available", failure); - } + // Namespace-bound: the same identifier in staging and production must not digest to the + // same key, or a keyspace dump from the softer environment would map one-for-one onto the + // harder one. + return new KeyDigest( + (material + + '|' + + redis.getNamespace().getEnvironment() + + ':' + + redis.getNamespace().getService() + + ':' + + redis.getNamespace().getDomain()) + .getBytes(StandardCharsets.UTF_8)); } private static String secretName(String reference, String capability) { @@ -94,14 +94,8 @@ final class RedisKeys { } } - String of(String key) { - try { - javax.crypto.Mac mac = (javax.crypto.Mac) prototype.clone(); - return "hv1:" - + java.util.HexFormat.of().formatHex(mac.doFinal(key.getBytes(StandardCharsets.UTF_8))); - } catch (CloneNotSupportedException failure) { - throw new IllegalStateException("a Mac must be cloneable", failure); - } + String of(String semanticKey) { + return "hv1:" + HexFormat.of().formatHex(HmacSha256.sign(key, semanticKey)); } } } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbe.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbe.java index f8a4179c..dd88d831 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbe.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbe.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLaneUnavailableException; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLease; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; @@ -9,6 +10,9 @@ import java.time.Duration; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.SmartInitializingSingleton; /** @@ -22,6 +26,13 @@ import org.springframework.beans.factory.SmartInitializingSingleton; * rate-limit and idempotency request failed with {@code NOPERM} after a clean start. The probe runs * the commands the scripts depend on, on the probe key, and cleans up after itself; it answers * {@code {1}} only when the value it wrote reads back. + * + *

      A cache-only deployment is probed too: its conditional writes and revision-ordered writes are + * registered programs on the same lane, and without the permission every one of them would come + * back degraded while plain reads looked healthy. Its probe runs only what the cache programs call + * ({@code GET}, {@code SET}), and a Redis it cannot reach at startup is logged, not fatal — a cache + * outage degrades, it never stops a pod from starting. A server that answers and refuses the + * scripts is a configuration error and fails startup as it does for the correctness roles. */ final class RedisSemanticScriptAclProbe implements SmartInitializingSingleton { @@ -39,6 +50,19 @@ final class RedisSemanticScriptAclProbe implements SmartInitializingSingleton { """ .getBytes(StandardCharsets.UTF_8); + /** The commands the cache's conditional-write programs call, and nothing else. */ + private static final byte[] CACHE_PROBE_SCRIPT = + """ + redis.call('SET', KEYS[1], 'probe', 'PX', 10000) + if redis.call('GET', KEYS[1]) == 'probe' then + return {1} + end + return {0} + """ + .getBytes(StandardCharsets.UTF_8); + + private static final Logger LOG = LoggerFactory.getLogger(RedisSemanticScriptAclProbe.class); + private final RedisRuntimeOwner owner; private final RedisCapabilitySettings capabilities; private final byte[] probeKey; @@ -57,14 +81,40 @@ final class RedisSemanticScriptAclProbe implements SmartInitializingSingleton { @Override public void afterSingletonsInstantiated() { - if (!scriptCapabilitySelected()) { + if (scriptCapabilitySelected()) { + probe(PROBE_SCRIPT); return; } + if (capabilities.getCache().redisSelected()) { + try { + probe(CACHE_PROBE_SCRIPT); + } catch (CapabilityStartupValidationException failure) { + if (!unreachable(failure.getCause())) { + throw new CapabilityStartupValidationException( + "Redis cache is selected but its account cannot run the cache's conditional-write" + + " scripts (SCRIPT LOAD/EVALSHA, GET, SET); every conditional record would" + + " degrade. Configure the ADVANCED Redis credential role or grant the effective" + + " account the script permissions", + failure.getCause()); + } + LOG.warn( + "Redis cache is selected but Redis was unreachable at startup; the cache script" + + " permission is unverified and the cache runs degraded until Redis answers", + failure.getCause()); + } + } + } + + private static boolean unreachable(Throwable cause) { + return cause instanceof RedisLaneUnavailableException || cause instanceof TimeoutException; + } + + private void probe(byte[] script) { try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { String digest = lease .commands() - .loadScript(PROBE_SCRIPT) + .loadScript(script) .toCompletableFuture() .get(timeout.toNanos(), TimeUnit.NANOSECONDS); List reply = diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicy.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicy.java index 212b2826..cad1be53 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicy.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicy.java @@ -9,6 +9,10 @@ import java.util.Objects; *

      The byte limit covers the logical evaluation-ID and decision payload retained by the Redis * program. Redis allocator overhead remains deployment/version evidence, not a portable byte * contract. + * + *

      Not implemented by any program yet. {@code RedisEdgeRateLimitAdapter} refuses a policy + * that enables it, and policies default to {@link #disabled()}. Until an implementation exists, a + * caller that retries after an unknown outcome ({@code NO_MUTATION_CONFIRMED}) is charged twice. */ public record RateLimitEvaluationDedupPolicy( boolean enabled, Duration timeToLive, int maximumEntries, int maximumStoredBytes) { diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicy.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicy.java index 413c9b26..fbcd0cc3 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicy.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicy.java @@ -33,7 +33,9 @@ public record RateLimitPolicy( cleanupGrace, maximumClockRegression, failurePolicy, - RateLimitEvaluationDedupPolicy.enabledDefaults()); + // Off: no adapter implements evaluation deduplication (review 05-23f). A default that said + // "on" let a caller believe a retry after an unknown outcome would not be charged twice. + RateLimitEvaluationDedupPolicy.disabled()); } public RateLimitPolicy { diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapter.java index 4599a531..47b6982f 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapter.java @@ -73,6 +73,20 @@ public final class RedisEdgeRateLimitAdapter implements EdgeRateLimitPort { "rate-limit"); this.keys = Objects.requireNonNull(keys, "keys must be non-null"); this.policies = Map.copyOf(Objects.requireNonNull(policies, "policies must be non-null")); + // Evaluation deduplication is not implemented: RateLimitRequest.evaluationId is not sent to + // Redis, so a retry after NO_MUTATION_CONFIRMED is charged again. A policy that asks for it is + // refused at composition rather than silently ignored. + this.policies.values().stream() + .filter(policy -> policy.evaluationDedupPolicy().enabled()) + .findFirst() + .ifPresent( + policy -> { + throw new IllegalArgumentException( + "rate-limit policy " + + policy.policyId() + + " enables evaluation dedup, which this adapter does not implement; a" + + " retry after an unknown outcome is charged again"); + }); this.scripts = Objects.requireNonNull(scripts, "scripts must be non-null"); this.clock = Objects.requireNonNull(clock, "clock must be non-null"); this.failureRetryAfter = @@ -106,8 +120,14 @@ public final class RedisEdgeRateLimitAdapter implements EdgeRateLimitPort { // The distinction that matters: a command refused before it was sent consumed no budget, while // one that may have run has consumed one the caller will never know about. Reporting them the // same way would make a retry either free or double-charged. - return call.effect( + // The caller's remaining time bounds the lane wait and the reply wait, not only the check + // above: a lane that stays full for the runtime's acquire timeout would otherwise hold a + // request + // for seconds past the deadline it asked for. Opening a new connection is still bounded by the + // driver's connect timeout, which no per-call budget can shorten. + return call.effectWithin( "evaluate", + Duration.between(now, request.callerDeadline()), session -> new RateLimitOutcome.Evaluated( decisionOf( diff --git a/src/adapter/outbound/cache-redis/src/main/resources/config/module-defaults/cache-redis.yml b/src/adapter/outbound/cache-redis/src/main/resources/config/module-defaults/cache-redis.yml index a09b3a3e..eab2668f 100644 --- a/src/adapter/outbound/cache-redis/src/main/resources/config/module-defaults/cache-redis.yml +++ b/src/adapter/outbound/cache-redis/src/main/resources/config/module-defaults/cache-redis.yml @@ -75,6 +75,16 @@ app: maximum-cost: ${APP_RATE_LIMIT_MAXIMUM_COST:10} cleanup-grace: ${APP_RATE_LIMIT_CLEANUP_GRACE:5s} +# redis-runtime 의 redisOptional 은 Redis 에 닿지 못하면 DEGRADED 를 보고한다. Boot 기본 순서 +# (DOWN, OUT_OF_SERVICE, UP, UNKNOWN)에 없는 상태는 DOWN 보다 앞에 정렬돼, 다른 contributor 가 DOWN +# 이어도 전체 health 가 HTTP 200 DEGRADED 로 보였다(리뷰 05-23e). DEGRADED 를 DOWN 뒤, UP 앞에 둔다. +# 이 키를 정하는 module-defaults 는 이 파일 하나뿐이다. 서비스가 순서를 바꾸면 DEGRADED 를 넣어야 한다. +management: + endpoint: + health: + status: + order: DOWN,OUT_OF_SERVICE,DEGRADED,UP,UNKNOWN + # /actuator/info 에 싣는 이 모듈의 상태(management.info.env). compose smoke 가 lane 이 실제로 켠 # capability 를 이 값으로 확인한다. 위 스위치를 해석한 값이고, 기본값은 RedisCapabilityConfig 의 # 조건과 같다(matchIfMissing 없음 = false). diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/SemanticRedisCallTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/SemanticRedisCallTest.java new file mode 100644 index 00000000..d366d09d --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/SemanticRedisCallTest.java @@ -0,0 +1,105 @@ +package dev.caskeleton.adapter.outbound.cache.redis; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.InMemorySemanticRedisCommands; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.StubRedisRuntimeClient; +import java.lang.reflect.Proxy; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** The call frame's handling of the connection a failed call leaves behind. */ +class SemanticRedisCallTest { + + private static RedisRuntimeOwner owner(StubRedisRuntimeClient client, Duration acquireTimeout) { + Map limits = new LinkedHashMap<>(); + for (RedisConnectionKind kind : RedisConnectionKind.values()) { + limits.put(kind, 1); + } + return new RedisRuntimeOwner(client, limits, acquireTimeout, Duration.ofSeconds(1)); + } + + /** Commands whose first PING never answers, the way a reply the driver still owes looks. */ + private static SemanticRedisCommands firstPingHangs() { + InMemorySemanticRedisCommands real = new InMemorySemanticRedisCommands(); + AtomicBoolean hung = new AtomicBoolean(); + return (SemanticRedisCommands) + Proxy.newProxyInstance( + SemanticRedisCommands.class.getClassLoader(), + new Class[] {SemanticRedisCommands.class}, + (proxy, method, arguments) -> + method.getName().equals("ping") && hung.compareAndSet(false, true) + ? new CompletableFuture() + : method.invoke(real, arguments)); + } + + @Test + @DisplayName("시간 초과로 끝난 호출의 연결은 pool로 돌아가지 않아 다음 호출은 새 연결을 연다") + void aConnectionWhoseCallTimedOutIsNotHandedToTheNextCaller() { + // given + StubRedisRuntimeClient client = StubRedisRuntimeClient.serving(firstPingHangs()); + try (RedisRuntimeOwner owner = owner(client, Duration.ofSeconds(1))) { + SemanticRedisCall call = + new SemanticRedisCall(owner, RedisConnectionKind.REGULAR, Duration.ofMillis(20), "test"); + String first = + call.run( + "ping", + session -> session.await(session.commands().ping()), + () -> "not-sent", + () -> "unknown"); + + // when + String second = + call.run( + "ping", + session -> session.await(session.commands().ping()), + () -> "not-sent", + () -> "unknown"); + + // then + assertThat(first).isEqualTo("not-sent"); + assertThat(second).isEqualTo("PONG"); + assertThat(client.opened()) + .as( + "the timed-out connection may still deliver the first PING's reply to the next caller") + .isEqualTo(2); + } + } + + @Test + @DisplayName("lane이 가득 차면 호출자 예산 안에서 포기하고 보낸 적 없음으로 답한다") + void aFullLaneIsGivenUpWithinTheCallersBudgetAsNotSent() throws Exception { + // given + StubRedisRuntimeClient client = + StubRedisRuntimeClient.serving(new InMemorySemanticRedisCommands()); + try (RedisRuntimeOwner owner = owner(client, Duration.ofSeconds(5))) { + SemanticRedisCall call = + new SemanticRedisCall(owner, RedisConnectionKind.SCRIPT, Duration.ofSeconds(1), "test"); + var held = owner.borrow(RedisConnectionKind.SCRIPT); + long started = System.nanoTime(); + + // when + String answer = + call.effectWithin( + "evaluate", + Duration.ofMillis(20), + session -> "evaluated", + () -> "not-sent", + () -> "unknown"); + + // then + assertThat(answer).isEqualTo("not-sent"); + assertThat(Duration.ofNanos(System.nanoTime() - started)).isLessThan(Duration.ofSeconds(2)); + held.close(); + } + } +} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/LiveRedisCacheRegionContractTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/LiveRedisCacheRegionContractTest.java new file mode 100644 index 00000000..efc9274b --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/LiveRedisCacheRegionContractTest.java @@ -0,0 +1,53 @@ +package dev.caskeleton.adapter.outbound.cache.redis.cache; + +import dev.caskeleton.adapter.outbound.cache.redis.LiveRedisRuntime; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; +import dev.caskeleton.application.cache.CacheRegionPort; +import dev.caskeleton.application.cache.testkit.CacheRegionContract; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Tag; + +/** + * The cache contract against a real server: the Lua programs, not the fixture's emulation of them, + * decide every conditional write here. + */ +@Tag("redis-topology") +@Tag("lane-standalone") +@Tag("lane-cluster") +class LiveRedisCacheRegionContractTest extends CacheRegionContract { + + private static final RedisNamespace NAMESPACE = new RedisNamespace("prod", "order", "shared"); + + private RedisRuntimeOwner owner; + + @AfterEach + void closeOwner() { + if (owner != null) { + owner.close(); + owner = null; + } + } + + @Override + protected CacheRegionPort region() { + owner = LiveRedisRuntime.open(NAMESPACE, true); + // A region of its own per test, so one test's entries and markers are never another's. + String region = "contract-" + UUID.randomUUID(); + return new RedisCacheRegionAdapter<>( + owner, + new RedisCacheRegionAdapter.CacheKeys(NAMESPACE, region, 1), + key -> "digest-" + key, + value -> value.getBytes(StandardCharsets.UTF_8), + bytes -> new String(bytes, StandardCharsets.UTF_8), + Clock.systemUTC(), + Duration.ofSeconds(30), + Duration.ofMinutes(5), + Duration.ofSeconds(10), + Duration.ofSeconds(2)); + } +} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java index 52cc6e8b..e83d72d9 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java @@ -472,11 +472,12 @@ class RedisCacheRegionAdapterTest { } @Test - @DisplayName("보낸 뒤 응답을 잃은 invalidate는 지워졌을 수 있으므로 INDETERMINATE다") + @DisplayName("보낸 뒤 응답을 잃은 invalidate는 무효화 표시가 써졌을 수 있으므로 INDETERMINATE다") void anInvalidationWhoseReplyWasLostIsIndeterminate() { // given + // The marker is the invalidation's effect, so the lost reply is the marker's SET. RedisCacheRegionAdapter cache = - cache(T0, StubRedisRuntimeClient.serving(losingReplyOf("getAndDelete"))); + cache(T0, StubRedisRuntimeClient.serving(losingReplyOf("set"))); // when CacheInvalidationOutcome outcome = cache.invalidate("order-1"); diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionContractTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionContractTest.java new file mode 100644 index 00000000..d3a996dc --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionContractTest.java @@ -0,0 +1,43 @@ +package dev.caskeleton.adapter.outbound.cache.redis.cache; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.InMemorySemanticRedisCommands; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.StubRedisRuntimeClient; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; +import dev.caskeleton.application.cache.CacheRegionPort; +import dev.caskeleton.application.cache.testkit.CacheRegionContract; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; + +/** The Redis cache region keeps the port's contract, over the runtime's command fake. */ +class RedisCacheRegionContractTest extends CacheRegionContract { + + @Override + protected CacheRegionPort region() { + Map limits = new LinkedHashMap<>(); + for (RedisConnectionKind kind : RedisConnectionKind.values()) { + limits.put(kind, 4); + } + return new RedisCacheRegionAdapter<>( + new RedisRuntimeOwner( + StubRedisRuntimeClient.serving(new InMemorySemanticRedisCommands()), + limits, + Duration.ofSeconds(1), + Duration.ofSeconds(1)), + new RedisCacheRegionAdapter.CacheKeys( + new RedisNamespace("test", "ca-skeleton", "shared"), "contract", 1), + key -> "digest-" + key, + value -> value.getBytes(StandardCharsets.UTF_8), + bytes -> new String(bytes, StandardCharsets.UTF_8), + Clock.systemUTC(), + Duration.ofSeconds(30), + Duration.ofMinutes(5), + Duration.ofSeconds(10), + Duration.ofSeconds(2)); + } +} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeysTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeysTest.java new file mode 100644 index 00000000..beccb380 --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeysTest.java @@ -0,0 +1,33 @@ +package dev.caskeleton.adapter.outbound.cache.redis.capability; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; +import java.util.Optional; +import org.junit.jupiter.api.Test; + +class RedisKeysTest { + + /** + * Pinned: the digest is part of every key already in Redis, so a change of implementation that + * changed it would orphan the whole keyspace. + */ + @Test + void aKeyDigestIsTheNamespaceBoundHmacSha256InHexWithItsVersionPrefix() { + // given + RedisRuntimeSettings redis = new RedisRuntimeSettings(); + redis.getNamespace().setEnvironment("test"); + redis.getNamespace().setService("orders-api"); + redis.getNamespace().setDomain("cache"); + RedisKeys.KeyDigest digest = + RedisKeys.KeyDigest.of( + name -> Optional.of("digest-secret"), "secret://env/cache-key", "cache", redis); + + // when + String key = digest.of("orders:42"); + + // then + assertThat(key) + .isEqualTo("hv1:1c40a175a9cae0b5c5633bd9c83c3e58d05f3500ee4ff6794858ed1ce57f6ad2"); + } +} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessorTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessorTest.java index b8a5af2a..737c094d 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessorTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessorTest.java @@ -18,12 +18,14 @@ import org.springframework.boot.autoconfigure.availability.ApplicationAvailabili import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.health.actuate.endpoint.HealthEndpointGroup; import org.springframework.boot.health.actuate.endpoint.HealthEndpointGroups; +import org.springframework.boot.health.actuate.endpoint.StatusAggregator; import org.springframework.boot.health.autoconfigure.actuate.endpoint.HealthEndpointAutoConfiguration; import org.springframework.boot.health.autoconfigure.application.AvailabilityHealthContributorAutoConfiguration; import org.springframework.boot.health.autoconfigure.contributor.HealthContributorAutoConfiguration; import org.springframework.boot.health.autoconfigure.registry.HealthContributorRegistryAutoConfiguration; import org.springframework.boot.health.contributor.Health; import org.springframework.boot.health.contributor.HealthIndicator; +import org.springframework.boot.health.contributor.Status; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -128,6 +130,28 @@ class RedisReadinessGroupPostProcessorTest { } } + @Test + @DisplayName("다른 contributor가 DOWN이면 Redis의 DEGRADED가 있어도 전체 health는 DOWN이다") + void aDownContributorOutranksADegradedRedis() throws IOException { + // given + Map properties = redisOn(); + properties.put("app.capabilities.cache.bindings.default", "redis"); + try (ConfigurableApplicationContext context = boot(properties)) { + StatusAggregator aggregator = context.getBean(StatusAggregator.class); + + // when + Status overall = + aggregator.getAggregateStatus(Status.UP, new Status("DEGRADED"), Status.DOWN); + + // then + // A status missing from the order sorts before DOWN, so an unreachable cache used to turn a + // real outage into an HTTP 200 "DEGRADED". + assertThat(overall).isEqualTo(Status.DOWN); + assertThat(aggregator.getAggregateStatus(Status.UP, new Status("DEGRADED")).getCode()) + .isEqualTo("DEGRADED"); + } + } + @Test @DisplayName("a correctness role: the contributor exists and readiness gates on it") void correctnessRoleGatesReadiness() throws IOException { diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java index 4b237800..c1909150 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java @@ -105,6 +105,92 @@ class RedisSemanticScriptAclProbeTest { .hasMessageContaining("SCRIPT LOAD/EVALSHA is unavailable"); } + @Test + @DisplayName("cache만 고른 배포도 조건부 기록이 쓰는 script 권한이 없으면 기동에서 실패한다") + void aCacheOnlyDeploymentWithoutScriptPermissionFailsStartup() { + // given + RedisCapabilitySettings capabilities = new RedisCapabilitySettings(); + capabilities.getCache().getBindings().put("default", "redis"); + RedisSemanticScriptAclProbe probe = + new RedisSemanticScriptAclProbe( + owner(gateway(true), new AtomicInteger()), + capabilities, + "prod:svc:shared:probe".getBytes(StandardCharsets.UTF_8), + Duration.ofSeconds(1)); + + // when + Throwable failure = catchThrowable(probe::afterSingletonsInstantiated); + + // then + assertThat(failure) + .isInstanceOf(CapabilityStartupValidationException.class) + .hasMessageContaining("cache"); + } + + @Test + @DisplayName("cache만 고른 배포의 script probe는 cache 스크립트가 부르는 GET·SET만 요구한다") + void aCacheOnlyProbeRequiresOnlyTheCommandsTheCacheScriptsCall() { + // given + RedisCapabilitySettings capabilities = new RedisCapabilitySettings(); + capabilities.getCache().getBindings().put("default", "redis"); + RedisSemanticScriptAclProbe probe = + new RedisSemanticScriptAclProbe( + owner(gatewayDenying("HSET"), new AtomicInteger()), + capabilities, + "prod:svc:shared:probe".getBytes(StandardCharsets.UTF_8), + Duration.ofSeconds(1)); + + // when + Throwable failure = catchThrowable(probe::afterSingletonsInstantiated); + + // then + assertThat(failure).isNull(); + } + + @Test + @DisplayName("cache만 고른 배포는 기동 때 Redis에 닿지 못해도 기동하고 확인하지 못했음을 남긴다") + void aCacheOnlyDeploymentStartsWhenRedisIsUnreachable() { + // given + RedisCapabilitySettings capabilities = new RedisCapabilitySettings(); + capabilities.getCache().getBindings().put("default", "redis"); + Map limits = new java.util.LinkedHashMap<>(); + for (RedisConnectionKind kind : RedisConnectionKind.values()) { + limits.put(kind, 1); + } + RedisRuntimeOwner unreachable = + new RedisRuntimeOwner( + new RedisRuntimeClient() { + @Override + public RedisDeploymentMode mode() { + return RedisDeploymentMode.STANDALONE; + } + + @Override + public RedisLaneConnection openLane(RedisLane kind, Optional routingKey) { + throw new IllegalStateException("connection refused"); + } + + @Override + public void close() {} + }, + limits, + Duration.ofSeconds(1), + Duration.ofSeconds(1)); + RedisSemanticScriptAclProbe probe = + new RedisSemanticScriptAclProbe( + unreachable, + capabilities, + "prod:svc:shared:probe".getBytes(StandardCharsets.UTF_8), + Duration.ofSeconds(1)); + + // when + Throwable failure = catchThrowable(probe::afterSingletonsInstantiated); + + // then + // A cache outage degrades; it never stops a pod from starting. + assertThat(failure).isNull(); + } + private static RedisRuntimeOwner owner(SemanticRedisCommands gateway, AtomicInteger opened) { RedisRuntimeClient client = new RedisRuntimeClient() { diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java index 68129ffa..48d09e4a 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java @@ -403,18 +403,53 @@ class RedisIdempotencyStoreAdapterTest { } @Test - @DisplayName("an unreachable Redis is indeterminate, never a clean failure") - void anUnreachableRedisIsIndeterminate() { + @DisplayName("연결을 열지 못한 claim은 아무것도 보내지 않았으므로 Indeterminate가 아니라 Unavailable이다") + void aClaimWhoseConnectionCouldNotBeOpenedIsUnavailable() { + // given RedisIdempotencyStoreAdapter broken = store(T0, new BrokenClient()); IdempotencyClaimAttempt attempt = broken.newClaimAttempt(OPERATION); + // when IdempotencyClaimOutcome outcome = broken.claim(claim(attempt)); + // then + // No connection, no command: sending the caller to reconciliation for an effect that cannot + // have happened turned every Redis outage into a recovery queue. + assertThat(outcome).isInstanceOf(IdempotencyClaimOutcome.Unavailable.class); + } + + @Test + @DisplayName("보낸 뒤 응답을 잃은 claim은 적용됐을 수 있으므로 Indeterminate다") + void aClaimWhoseReplyWasLostIsIndeterminate() { + // given + RedisIdempotencyStoreAdapter lost = store(T0, StubRedisRuntimeClient.serving(repliesLost())); + IdempotencyClaimAttempt attempt = lost.newClaimAttempt(OPERATION); + + // when + IdempotencyClaimOutcome outcome = lost.claim(claim(attempt)); + + // then // A caller told "failed" retries and duplicates the effect. A caller told "indeterminate" // inspects with the same attempt and finds out. assertThat(outcome).isInstanceOf(IdempotencyClaimOutcome.Indeterminate.class); } + /** A connection that opens, then loses the reply to every command it sends. */ + private static dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands + repliesLost() { + return (dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands) + java.lang.reflect.Proxy.newProxyInstance( + dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands.class + .getClassLoader(), + new Class[] { + dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands + .class + }, + (proxy, method, arguments) -> + java.util.concurrent.CompletableFuture.failedFuture( + new IllegalStateException("reply lost"))); + } + @Test @DisplayName("스크립트 lane이 포화돼 보내지도 못한 claim은 Indeterminate가 아니라 Unavailable이다") void aSaturatedScriptLaneRefusesTheClaimAsUnavailable() { diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreContractTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreContractTest.java new file mode 100644 index 00000000..072cba1b --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreContractTest.java @@ -0,0 +1,37 @@ +package dev.caskeleton.adapter.outbound.cache.redis.idempotency; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.InMemorySemanticRedisCommands; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.StubRedisRuntimeClient; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; +import dev.caskeleton.application.idempotency.IdempotencyStorePort; +import dev.caskeleton.application.idempotency.testkit.IdempotencyStoreContract; +import java.time.Clock; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; + +/** The Redis idempotency store keeps the port's contract, over the runtime's command fake. */ +class RedisIdempotencyStoreContractTest extends IdempotencyStoreContract { + + @Override + protected IdempotencyStorePort store() { + Map limits = new LinkedHashMap<>(); + for (RedisConnectionKind kind : RedisConnectionKind.values()) { + limits.put(kind, 4); + } + return new RedisIdempotencyStoreAdapter( + new RedisRuntimeOwner( + StubRedisRuntimeClient.serving(new InMemorySemanticRedisCommands()), + limits, + Duration.ofSeconds(1), + Duration.ofSeconds(1)), + new RedisIdempotencyStoreAdapter.IdempotencyKeys( + new RedisNamespace("test", "ca-skeleton", "shared"), 1), + new IdempotencyScripts(), + Clock.systemUTC(), + Duration.ofSeconds(2)); + } +} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapterTest.java index 249554b2..bbf6f7f0 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapterTest.java @@ -259,19 +259,54 @@ class RedisDistributedLeaseAdapterTest { } @Test - @DisplayName("an unreachable Redis is indeterminate, never a clean failure") - void anUnreachableRedisIsIndeterminate() { + @DisplayName("연결을 열지 못한 acquire는 아무것도 보내지 않았으므로 보내기 전 Unavailable이다") + void anAcquireWhoseConnectionCouldNotBeOpenedIsUnavailableBeforeSend() { + // given RedisDistributedLeaseAdapter broken = adapter(new BrokenClient()); LeaseAttempt attempt = broken.newAttempt(OPERATION_A); + // when LeaseAcquireOutcome outcome = broken.tryAcquire(request(attempt, Duration.ofSeconds(30))); + // then + assertThat(outcome) + .isEqualTo( + new LeaseAcquireOutcome.Unavailable(LeaseUnavailableCategory.UNAVAILABLE_BEFORE_SEND)); + } + + @Test + @DisplayName("보낸 뒤 응답을 잃은 acquire는 lease를 잡았을 수 있으므로 Indeterminate다") + void anAcquireWhoseReplyWasLostIsIndeterminate() { + // given + RedisDistributedLeaseAdapter lost = adapter(StubRedisRuntimeClient.serving(repliesLost())); + LeaseAttempt attempt = lost.newAttempt(OPERATION_A); + + // when + LeaseAcquireOutcome outcome = lost.tryAcquire(request(attempt, Duration.ofSeconds(30))); + + // then // The acquire may have taken the lease. A clean failure would let the caller retry under a new // attempt and hold it twice; Indeterminate tells them to inspect with the same one. assertThat(outcome).isInstanceOf(LeaseAcquireOutcome.Indeterminate.class); assertThat(((LeaseAcquireOutcome.Indeterminate) outcome).operationId()).isEqualTo(OPERATION_A); } + /** A connection that opens, then loses the reply to every command it sends. */ + private static dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands + repliesLost() { + return (dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands) + java.lang.reflect.Proxy.newProxyInstance( + dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands.class + .getClassLoader(), + new Class[] { + dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands + .class + }, + (proxy, method, arguments) -> + java.util.concurrent.CompletableFuture.failedFuture( + new IllegalStateException("reply lost"))); + } + @Test @DisplayName("스크립트 lane이 포화돼 보내지도 못한 acquire는 Indeterminate가 아니라 보내기 전 Unavailable이다") void aSaturatedScriptLaneRefusesAcquireBeforeSend() { diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyTest.java index 760976eb..bec3982c 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.shared.ratelimit.RateParameters; import java.time.Duration; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class RateLimitPolicyTest { @@ -145,6 +146,19 @@ class RateLimitPolicyTest { .hasMessageContaining("maximumClockRegression"); } + @Test + @DisplayName("dedup policy를 지정하지 않은 policy는 evaluation dedup이 꺼져 있다") + void aPolicyWithoutAnExplicitDedupPolicyDoesNotClaimDeduplication() { + // given + RateParameters parameters = new RateParameters.FixedWindow(5, Duration.ofSeconds(60)); + + // when + RateLimitPolicy policy = policy(RateLimitAlgorithm.FIXED_WINDOW, parameters, 5); + + // then + assertThat(policy.evaluationDedupPolicy()).isEqualTo(RateLimitEvaluationDedupPolicy.disabled()); + } + private static RateLimitPolicy policy( RateLimitAlgorithm algorithm, RateParameters parameters, long maximumCost) { return new RateLimitPolicy( diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapterTest.java index f6529eb9..c8e9780a 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapterTest.java @@ -192,6 +192,54 @@ class RedisEdgeRateLimitAdapterTest { assertThat(((RateLimitOutcome.Unavailable) outcome).retryAfter()).isPositive(); } + @Test + @DisplayName("연결을 열지 못한 평가는 차감했을 수 없으므로 UNAVAILABLE_BEFORE_SEND다") + void anEvaluationWhoseConnectionCouldNotBeOpenedConsumedNothing() { + // given + RateLimitPolicy policy = + policy( + new RateParameters.FixedWindow(5, Duration.ofSeconds(60)), + RateLimitAlgorithm.FIXED_WINDOW); + RedisEdgeRateLimitAdapter adapter = + adapter(policy, Clock.fixed(T0, ZoneOffset.UTC), new BrokenClient()); + + // when + RateLimitOutcome outcome = adapter.evaluate(request(1)); + + // then + assertThat(((RateLimitOutcome.Unavailable) outcome).category()) + .isEqualTo(RateLimitOutcome.UnavailableCategory.UNAVAILABLE_BEFORE_SEND); + } + + @Test + @DisplayName("구현되지 않은 evaluation dedup을 켠 policy로는 adapter를 만들 수 없다") + void aPolicyAskingForEvaluationDedupIsRefusedBecauseNothingImplementsIt() { + // given + RateLimitPolicy asksForDedup = + new RateLimitPolicy( + "api-default", + "v1", + RateLimitAlgorithm.FIXED_WINDOW, + new RateParameters.FixedWindow(5, Duration.ofSeconds(60)), + 5, + Duration.ofSeconds(5), + Duration.ofMillis(250), + RateLimitFailurePolicy.FAIL_CLOSED, + RateLimitEvaluationDedupPolicy.enabledDefaults()); + + // when + Throwable refused = + org.assertj.core.api.Assertions.catchThrowable( + () -> adapter(asksForDedup, Clock.fixed(T0, ZoneOffset.UTC))); + + // then + // A retry after NO_MUTATION_CONFIRMED is charged again. A policy that claimed otherwise would + // let a caller rely on a deduplication no code performs. + assertThat(refused) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("evaluation dedup"); + } + @Test @DisplayName("an unknown policy is a deployment error, not an allowance") void anUnknownPolicyIsIncompatible() { diff --git a/src/adapter/outbound/httpclient/README.md b/src/adapter/outbound/httpclient/README.md index e061ed39..faa4f02a 100644 --- a/src/adapter/outbound/httpclient/README.md +++ b/src/adapter/outbound/httpclient/README.md @@ -39,8 +39,9 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d - **Time.** One effective deadline covers pool acquire, DNS, connect, TLS, write, read, and every retry backoff. It is checked before each attempt and also ends an attempt still in flight: Apache cancels the request at the deadline, the JDK transport bounds its exchange timeout by the time - left, and the caller gets `HttpDeadlineExceededException`. Streaming splits setup, idle, and total - lifetime. + left, the experimental Jetty HTTP/3 transport aborts the request, and the caller gets + `HttpDeadlineExceededException`. A streaming download's setup (up to the response headers) runs + inside the same deadline; after hand-over each body gap is bounded by `read-idle`. - **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or `PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it. - **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline, @@ -48,9 +49,11 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d raises `HttpAmbiguousExecutionException` instead of being retried or reported as a plain failure. - **Order.** Every physical attempt passes Circuit Breaker → Rate Limiter → Bulkhead, and holds no permit while a backoff waits. -- **Circuit.** The breaker counts transport failures and 5xx, 408, and 429 against the upstream. - Any other 4xx (404, 409, 422 …) is a healthy answer, even when it reaches the caller as - `HttpRemoteErrorException`. +- **Circuit.** The breaker counts transport failures and 5xx, 408, and 429 against the upstream, + whether the call throws them or returns them as a result (`RETURN_RESULT`). Any other 4xx (404, + 409, 422 …) is a healthy answer, even when it reaches the caller as `HttpRemoteErrorException`. + Window, threshold and open-state wait are per profile under `clients[N].circuit-breaker.*` + (defaults are Resilience4j's; see `docs/httpclient/configuration-reference.md`). - **Resources.** Connections and buffers are reclaimed after success, error, decode failure, size rejection, and cancellation alike. - **Secrets.** No URL, query value, path variable, token, cookie, or idempotency key reaches a log, diff --git a/src/adapter/outbound/httpclient/build.gradle b/src/adapter/outbound/httpclient/build.gradle index bfda230a..220ab3a3 100644 --- a/src/adapter/outbound/httpclient/build.gradle +++ b/src/adapter/outbound/httpclient/build.gradle @@ -137,11 +137,17 @@ dependencies { jmhImplementation testFixtures(project) } -tasks.named('test', Test) { +// Which transports the contract suites cover and whether the HTTP/3 opt-in runs: the same two +// properties for every Test task of this leaf, declared once (review 2026-11-01 O-10a). Values a +// single lane needs (the performance assertions, the httpbin image) stay in that lane. +tasks.withType(Test).configureEach { systemProperty 'httpclient.contract.transports', providers.gradleProperty('httpclient.contract.transports').orElse('apache,jdk').get() systemProperty 'httpclient.http3.tests.enabled', providers.gradleProperty('http3.tests.enabled').orElse('false').get() +} + +tasks.named('test', Test) { // The tagged suites run in their own lanes below, so the default run does not repeat them. useJUnitPlatform { excludeTags 'httpclient-contract', 'httpclient-security', 'httpclient-spring62-surface' @@ -159,10 +165,6 @@ strictTestLanes { lane('httpClientStableContractTest') { tag = 'httpclient-contract' description = 'Runs the cross-transport stable contract suite (design §28.2, §33).' - systemProperty 'httpclient.contract.transports', - providers.gradleProperty('httpclient.contract.transports').orElse('apache,jdk').get() - systemProperty 'httpclient.http3.tests.enabled', - providers.gradleProperty('http3.tests.enabled').orElse('false').get() } // The same contract suite, run under the name the release gate and the support matrix quote for // the repository's Spring 7 baseline. It used to be a hand-written `tasks.register(..., Test)` @@ -173,18 +175,10 @@ strictTestLanes { lane('spring70CompatibilityTest') { tag = 'httpclient-contract' description = 'Runs the contract suite on the repository Spring 7 baseline (design §29).' - systemProperty 'httpclient.contract.transports', - providers.gradleProperty('httpclient.contract.transports').orElse('apache,jdk').get() - systemProperty 'httpclient.http3.tests.enabled', - providers.gradleProperty('http3.tests.enabled').orElse('false').get() } lane('httpClientSecurityTest') { tag = 'httpclient-security' description = 'Runs the SSRF, credential-leak, and cardinality suite (design §28.5, §28.7).' - systemProperty 'httpclient.contract.transports', - providers.gradleProperty('httpclient.contract.transports').orElse('apache,jdk').get() - systemProperty 'httpclient.http3.tests.enabled', - providers.gradleProperty('http3.tests.enabled').orElse('false').get() } // Spring 6.2 / 7.0 compatibility lanes. This repository's Spring Boot 4.0 baseline pins Spring // Framework 7, so the 6.2 lane verifies the *API surface* the common packages compile against @@ -199,10 +193,6 @@ strictTestLanes { performance() sourceSet = 'httpClientPerformanceTest' description = 'Certifies pool, streaming, retry, and rotation resource bounds (design §28.8).' - systemProperty 'httpclient.contract.transports', - providers.gradleProperty('httpclient.contract.transports').orElse('apache,jdk').get() - systemProperty 'httpclient.http3.tests.enabled', - providers.gradleProperty('http3.tests.enabled').orElse('false').get() systemProperty 'performance.assertions.enabled', providers.gradleProperty('performance.assertions.enabled').orElse('false').get() } @@ -212,16 +202,11 @@ strictTestLanes { tag = 'httpclient-fault' description = 'Runs the Toxiproxy fault-injection suite; fails closed without Docker ' + '(design §28.3).' - systemProperty 'httpclient.contract.transports', - providers.gradleProperty('httpclient.contract.transports').orElse('apache,jdk').get() - systemProperty 'httpclient.http3.tests.enabled', - providers.gradleProperty('http3.tests.enabled').orElse('false').get() - // The upstream image is mutable by default. A digest here is what makes a red fault run - // attributable to this repository rather than to someone else's image push. + // The digest-pinned default is config/testing/container-images.properties' `httpbin`; + // -Phttpclient.fault.httpbin.image overrides it for a one-off run. systemProperty 'httpclient.fault.httpbin.image', providers.gradleProperty('httpclient.fault.httpbin.image').orElse( - 'kennethreitz/httpbin@sha256:' + - '599fe5e5073102dbb0ee3dbb65f049dab44fa9fc251f6835c9990f8fb196a72b').get() + testContainerImages['httpbin']).get() } } @@ -241,8 +226,15 @@ strictTestLanes { // `check`, under the name the release gate and the support matrix quote. The main stage runs it so the // name's fail-closed selection is proven before a release tag, not first on one (review 2026-11-01 // 08-01). +// +// httpClientFailureInjectionTest joins the main stage too (review 2026-11-01 05-06, 05-16). It is +// the only lane that proves the deadline and evidence contracts against real TCP faults — a slow +// drip, a cut stream, a refused connect — and it was reachable only through integrationCheck, so a +// main-branch build could go green with those contracts broken. The main stage already runs Docker +// lanes (MinIO), so the lane's fail-closed Docker requirement costs that stage nothing new; it stays +// out of `check` for the reason above. tasks.named('mainCheck') { - dependsOn 'spring70CompatibilityTest' + dependsOn 'spring70CompatibilityTest', 'httpClientFailureInjectionTest' } tasks.named('check') { diff --git a/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PoolSaturationPerformanceTest.java b/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PoolSaturationPerformanceTest.java index c826541a..89f8ffad 100644 --- a/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PoolSaturationPerformanceTest.java +++ b/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PoolSaturationPerformanceTest.java @@ -41,8 +41,6 @@ class PoolSaturationPerformanceTest { Duration.ofSeconds(30), Duration.ofMinutes(5), Duration.ofSeconds(5), - Duration.ofSeconds(15), - Duration.ofSeconds(5), false, false)) .build(); diff --git a/src/adapter/outbound/httpclient/src/integrationTest/java/dev/caskeleton/adapter/outbound/httpclient/contract/FailureInjectionContractTest.java b/src/adapter/outbound/httpclient/src/integrationTest/java/dev/caskeleton/adapter/outbound/httpclient/contract/FailureInjectionContractTest.java index 24cad835..0bf00d98 100644 --- a/src/adapter/outbound/httpclient/src/integrationTest/java/dev/caskeleton/adapter/outbound/httpclient/contract/FailureInjectionContractTest.java +++ b/src/adapter/outbound/httpclient/src/integrationTest/java/dev/caskeleton/adapter/outbound/httpclient/contract/FailureInjectionContractTest.java @@ -1,12 +1,16 @@ package dev.caskeleton.adapter.outbound.httpclient.contract; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpClientException; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException; import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType; +import dev.caskeleton.adapter.outbound.httpclient.profile.TimeoutSettings; +import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType; import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; import dev.caskeleton.adapter.outbound.httpclient.testkit.ToxiproxyFixture; @@ -14,10 +18,13 @@ import eu.rekawek.toxiproxy.Proxy; import java.net.InetAddress; import java.net.ServerSocket; import java.net.URI; +import java.time.Duration; import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.utility.DockerImageName; @@ -35,9 +42,12 @@ import org.testcontainers.utility.DockerImageName; @Tag("httpclient-fault") class FailureInjectionContractTest { + private static final Duration SLOW_DRIP_BUDGET = Duration.ofSeconds(1); + private static final DockerImageName UPSTREAM_IMAGE = DockerImageName.parse( - System.getProperty("httpclient.fault.httpbin.image", "kennethreitz/httpbin:latest")) + System.getProperty( + "httpclient.fault.httpbin.image", System.getProperty("ca.test.image.httpbin"))) .asCompatibleSubstituteFor("kennethreitz/httpbin"); /** @@ -93,6 +103,75 @@ class FailureInjectionContractTest { } } + /** + * The total budget ends an attempt an upstream keeps alive one slice at a time (finding 05-06). + * + *

      Toxiproxy re-slices the upstream's response into 16-byte pieces 50 ms apart. No gap comes + * near the read-idle (3 s) or response-header (2 s) timeout and the whole 4 KiB response would + * take over twelve seconds, so only the one-second total budget can end the call on time. Run on + * both stable transports because each enforces the deadline by its own mechanism. + */ + @ParameterizedTest(name = "{0}") + @EnumSource( + value = TransportType.class, + names = {"APACHE", "JDK"}) + @DisplayName("Toxiproxy로 조금씩 흘린 응답이라도 호출은 전체 시간 예산 안에 deadline 초과로 끝난다") + @SuppressWarnings("resource") + void aSlowDripThroughToxiproxyEndsAtTheTotalDeadline(TransportType transport) throws Exception { + ToxiproxyFixture.requireAvailable(); + try (Network network = Network.newNetwork(); + GenericContainer upstream = + new GenericContainer<>(UPSTREAM_IMAGE) + .withNetwork(network) + .withNetworkAliases("upstream") + .withExposedPorts(80)) { + upstream.start(); + try (ToxiproxyFixture toxiproxy = ToxiproxyFixture.start(network)) { + // given + Proxy proxy = toxiproxy.proxyTo("slow-drip", "upstream", 80); + toxiproxy.slowDrip(proxy, 16, Duration.ofMillis(50)); + TimeoutSettings base = ClientProfiles.timeouts(); + URI baseUrl = + URI.create("http://" + toxiproxy.proxiedHost() + ":" + toxiproxy.proxiedPort() + "/"); + long started; + Throwable failure; + + // when + try (TestGateways.Harness harness = + TestGateways.forProfile( + ClientProfiles.builder("slow-drip") + .baseUrl(baseUrl) + .transport(transport) + .timeout( + new TimeoutSettings( + base.dns(), + base.connect(), + base.tlsHandshake(), + base.responseHeader(), + base.readIdle(), + SLOW_DRIP_BUDGET)) + .build())) { + started = System.nanoTime(); + failure = + catchThrowable( + () -> + harness + .gateway() + .exchange( + harness.profile().name(), + HttpOperation.get( + new OperationName("fault-probe"), "/bytes/4096", Map.of()), + ResponseType.of(byte[].class))); + } + + // then + Duration elapsed = Duration.ofNanos(System.nanoTime() - started); + assertThat(failure).isInstanceOf(HttpDeadlineExceededException.class); + assertThat(elapsed).isLessThan(SLOW_DRIP_BUDGET.plus(Duration.ofMillis(500))); + } + } + } + private static HttpClientException callThrough( ToxiproxyFixture toxiproxy, String path, ResponseType responseType) throws Exception { return call( diff --git a/src/adapter/outbound/httpclient/src/integrationTest/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ToxiproxyFixture.java b/src/adapter/outbound/httpclient/src/integrationTest/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ToxiproxyFixture.java index cc671754..3e455024 100644 --- a/src/adapter/outbound/httpclient/src/integrationTest/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ToxiproxyFixture.java +++ b/src/adapter/outbound/httpclient/src/integrationTest/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ToxiproxyFixture.java @@ -22,9 +22,7 @@ public final class ToxiproxyFixture implements AutoCloseable { public static final int PROXY_PORT = 8666; private static final DockerImageName IMAGE = - DockerImageName.parse( - "ghcr.io/shopify/toxiproxy@sha256:" - + "9378ed52a28bc50edc1350f936f518f31fa95f0d15917d6eb40b8e376d1a214e") + DockerImageName.parse(System.getProperty("ca.test.image.toxiproxy")) .asCompatibleSubstituteFor("shopify/toxiproxy"); private final Network network; @@ -95,6 +93,19 @@ public final class ToxiproxyFixture implements AutoCloseable { proxy.toxics().resetPeer("reset", ToxicDirection.DOWNSTREAM, after.toMillis()); } + /** + * Delivers the downstream stream in slices of {@code sliceBytes} with {@code gap} between them. + * + *

      A slow drip: every gap stays below any idle timeout, so only a whole-call budget can end the + * exchange before the response is complete. + */ + public void slowDrip(Proxy proxy, long sliceBytes, Duration gap) throws IOException { + proxy + .toxics() + .slicer("slow-drip", ToxicDirection.DOWNSTREAM, sliceBytes, gap.toNanos() / 1_000L) + .setSizeVariation(0); + } + /** Cuts the downstream TCP stream after an exact byte budget. */ public void limitDownstreamData(Proxy proxy, long bytes) throws IOException { proxy.toxics().limitData("limit-data", ToxicDirection.DOWNSTREAM, bytes); diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheBlockingTransportProvider.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheBlockingTransportProvider.java index 2ac93ca4..89b40fe3 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheBlockingTransportProvider.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheBlockingTransportProvider.java @@ -71,6 +71,12 @@ public final class ApacheBlockingTransportProvider implements BlockingTransportP return BlockingTransportCapabilities.apacheClassic(); } + /** Apache's request executor signals the write; see {@link SignallingRequestExecutor}. */ + @Override + public boolean reportsRequestWrite() { + return true; + } + @Override public ClientHttpRequestFactory create( ClientProfile profile, RuntimeGeneration generation, TransportLifecycleListener listener) { diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheClientFactory.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheClientFactory.java index f3ce2eec..8a12e87a 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheClientFactory.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheClientFactory.java @@ -103,6 +103,7 @@ public final class ApacheClientFactory { HttpClients.custom() .setConnectionManager(pool) .setConnectionManagerShared(false) + .setRequestExecutor(new SignallingRequestExecutor()) .disableAutomaticRetries() .disableRedirectHandling() .setProxySelector(ProxySelector.of(null)) diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/SignallingRequestExecutor.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/SignallingRequestExecutor.java new file mode 100644 index 00000000..febef636 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/SignallingRequestExecutor.java @@ -0,0 +1,38 @@ +package dev.caskeleton.adapter.outbound.httpclient.apache; + +import dev.caskeleton.adapter.outbound.httpclient.transport.RequestWriteSignal; +import java.io.IOException; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.HttpException; +import org.apache.hc.core5.http.impl.io.HttpRequestExecutor; +import org.apache.hc.core5.http.io.HttpClientConnection; +import org.apache.hc.core5.http.io.HttpResponseInformationCallback; +import org.apache.hc.core5.http.protocol.HttpContext; + +/** + * Apache's request executor, announcing when a request is about to be written (finding 05-14). + * + *

      The classic client runs this executor only after the route is established — pool lease, DNS, + * TCP connect, TLS handshake and any proxy tunnel are done — and it is the executor that writes the + * request line, headers and entity. So the moment it is entered is exactly the boundary between + * "nothing left the process" and "the upstream may have seen it", on the caller's thread. + * + *

      A proxy {@code CONNECT} goes through the same executor while establishing a tunnel. That is + * still route setup, not the request, so it is not announced. + */ +final class SignallingRequestExecutor extends HttpRequestExecutor { + + @Override + public ClassicHttpResponse execute( + ClassicHttpRequest request, + HttpClientConnection connection, + HttpResponseInformationCallback informationCallback, + HttpContext context) + throws IOException, HttpException { + if (!"CONNECT".equalsIgnoreCase(request.getMethod())) { + RequestWriteSignal.requestWriteStarting(); + } + return super.execute(request, connection, informationCallback, context); + } +} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettings.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettings.java index 0a9fe458..94c895b6 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettings.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettings.java @@ -142,7 +142,8 @@ public record HttpClientPlatformSettings( @DefaultValue Observability observability, @DefaultValue Tls tls, @DefaultValue Proxy proxy, - String experimentalAcknowledgement) {} + String experimentalAcknowledgement, + @DefaultValue CircuitBreaker circuitBreaker) {} /** * One Dynamic Target policy (design §22). @@ -173,8 +174,6 @@ public record HttpClientPlatformSettings( @DefaultValue("30s") Duration maxIdleTime, @DefaultValue("5m") Duration maxLifeTime, @DefaultValue("5s") Duration validateAfterInactivity, - @DefaultValue("15s") Duration evictionInterval, - @DefaultValue("5s") Duration shutdownTimeout, @DefaultValue("false") boolean requiresRoutePool, @DefaultValue("false") boolean requiresBoundedPendingQueue) {} @@ -183,8 +182,6 @@ public record HttpClientPlatformSettings( @DefaultValue("300ms") Duration dns, @DefaultValue("500ms") Duration connect, @DefaultValue("1s") Duration tlsHandshake, - @DefaultValue("500ms") Duration proxyConnect, - @DefaultValue("1s") Duration requestWriteIdle, @DefaultValue("2s") Duration responseHeader, @DefaultValue("3s") Duration readIdle, @DefaultValue("4s") Duration totalCall) {} @@ -227,7 +224,6 @@ public record HttpClientPlatformSettings( /** Per-profile observability switches (design §25). */ public record Observability( - @DefaultValue("true") boolean operationNameRequired, @DefaultValue("false") boolean fullUrlRecording, @DefaultValue("false") boolean bodyLogging) {} @@ -253,6 +249,19 @@ public record HttpClientPlatformSettings( @DefaultValue("0") int port, @DefaultValue("HTTP") ProxyType type, String credentialProvider, - @DefaultValue("500ms") Duration connectTimeout, @DefaultValue("false") boolean importAmbientNoProxy) {} + + /** + * Per-profile circuit breaker thresholds (design §18.1, finding 05-05). + * + *

      Defaults are Resilience4j's own, which every profile ran with before these keys existed. + * What counts as a failure (5xx, 408, 429, transport failures) is fixed by the platform, not + * here. + */ + public record CircuitBreaker( + @DefaultValue("50") int failureRateThreshold, + @DefaultValue("100") int minimumNumberOfCalls, + @DefaultValue("100") int slidingWindowSize, + @DefaultValue("60s") Duration waitDurationInOpenState, + @DefaultValue("10") int permittedCallsInHalfOpenState) {} } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsBinder.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsBinder.java index 308b58a5..ffa75946 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsBinder.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsBinder.java @@ -18,7 +18,12 @@ final class HttpClientPlatformSettingsBinder { private HttpClientPlatformSettingsBinder() {} static HttpClientPlatformSettings bind(Environment environment) { - return StrictSettingsBinder.bind( - environment, HttpClientPlatformSettings.PREFIX, HttpClientPlatformSettings.class); + HttpClientPlatformSettings settings = + StrictSettingsBinder.bind( + environment, HttpClientPlatformSettings.PREFIX, HttpClientPlatformSettings.class); + // The shared binder's unbound-key check stops at the first level of a list element; see + // ListElementKeyGuard for why, and why that matters for removed settings. + ListElementKeyGuard.requireKnownKeys(environment); + return settings; } } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileFactory.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileFactory.java index a4e89a3e..13562007 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileFactory.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileFactory.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.httpclient.autoconfigure; import dev.caskeleton.adapter.outbound.httpclient.api.ClientProfileName; import dev.caskeleton.adapter.outbound.httpclient.profile.AuthenticationSettings; +import dev.caskeleton.adapter.outbound.httpclient.profile.CircuitBreakerSettings; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientObservabilitySettings; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; import dev.caskeleton.adapter.outbound.httpclient.profile.PoolSettings; @@ -61,10 +62,9 @@ public final class HttpClientProfileFactory { Set.copyOf(client.response().allowedContentTypes())), authentication(client.authentication()), retry(client.retry()), + circuitBreaker(client.circuitBreaker()), new ClientObservabilitySettings( - client.observability().operationNameRequired(), - client.observability().fullUrlRecording(), - client.observability().bodyLogging()), + client.observability().fullUrlRecording(), client.observability().bodyLogging()), tls(client.tls()), proxy(client.proxy()), Optional.ofNullable(client.experimentalAcknowledgement())); @@ -79,8 +79,6 @@ public final class HttpClientProfileFactory { pool.maxIdleTime(), pool.maxLifeTime(), pool.validateAfterInactivity(), - pool.evictionInterval(), - pool.shutdownTimeout(), pool.requiresRoutePool(), pool.requiresBoundedPendingQueue()); } @@ -90,8 +88,6 @@ public final class HttpClientProfileFactory { timeout.dns(), timeout.connect(), timeout.tlsHandshake(), - timeout.proxyConnect(), - timeout.requestWriteIdle(), timeout.responseHeader(), timeout.readIdle(), timeout.totalCall()); @@ -119,6 +115,19 @@ public final class HttpClientProfileFactory { Optional.ofNullable(retry.budget())); } + private CircuitBreakerSettings circuitBreaker( + HttpClientPlatformSettings.CircuitBreaker circuitBreaker) { + if (circuitBreaker == null) { + return CircuitBreakerSettings.defaults(); + } + return new CircuitBreakerSettings( + circuitBreaker.failureRateThreshold(), + circuitBreaker.minimumNumberOfCalls(), + circuitBreaker.slidingWindowSize(), + circuitBreaker.waitDurationInOpenState(), + circuitBreaker.permittedCallsInHalfOpenState()); + } + private TlsSettings tls(HttpClientPlatformSettings.Tls tls) { return new TlsSettings( Optional.ofNullable(tls.profileId()), @@ -137,7 +146,6 @@ public final class HttpClientProfileFactory { proxy.port(), proxy.type(), Optional.ofNullable(proxy.credentialProvider()), - proxy.connectTimeout(), proxy.importAmbientNoProxy()); } } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/ListElementKeyGuard.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/ListElementKeyGuard.java new file mode 100644 index 00000000..b9989a83 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/ListElementKeyGuard.java @@ -0,0 +1,111 @@ +package dev.caskeleton.adapter.outbound.httpclient.autoconfigure; + +import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.RecordComponent; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.TreeSet; +import org.springframework.boot.context.properties.source.ConfigurationPropertyName; +import org.springframework.boot.context.properties.source.ConfigurationPropertyName.Form; +import org.springframework.boot.context.properties.source.ConfigurationPropertySource; +import org.springframework.boot.context.properties.source.ConfigurationPropertySources; +import org.springframework.boot.context.properties.source.IterableConfigurationPropertySource; +import org.springframework.core.env.Environment; +import org.springframework.core.env.SystemEnvironmentPropertySource; + +/** + * Refuses a property under {@code clients[n]} or {@code dynamic-targets[n]} that names no setting. + * + *

      The strict binder cannot see these. Spring's {@code NoUnboundElementsBindHandler} treats every + * key beneath an element of a bound list as "an overridden collection element" once the element's + * first-level group was attempted, so {@code clients[0].timeout.request-wirte-idle} — or a key this + * platform removed, such as {@code clients[0].pool.shutdown-timeout} — bound nothing and failed + * nothing. Only a misspelt first-level group ({@code clients[0].timeuot}) was refused. Removing an + * inert setting is honest only if setting it afterwards fails, so the per-element key set is + * checked here against the record tree (finding 05-15). + * + *

      The system environment is not checked here: the strict binder already refuses an {@code + * APP_HTTPCLIENT_*} variable that bound nothing, and environment names cannot be split back into + * property paths unambiguously. + */ +final class ListElementKeyGuard { + + private static final String INDEX = "[]"; + + private ListElementKeyGuard() {} + + static void requireKnownKeys(Environment environment) { + check( + environment, + HttpClientPlatformSettings.PREFIX + ".clients", + knownPaths(HttpClientPlatformSettings.ClientSettings.class)); + check( + environment, + HttpClientPlatformSettings.PREFIX + ".dynamic-targets", + knownPaths(HttpClientPlatformSettings.DynamicTargetSettings.class)); + } + + private static void check(Environment environment, String listPrefix, Set known) { + ConfigurationPropertyName list = ConfigurationPropertyName.of(listPrefix); + Set unknown = new TreeSet<>(); + for (ConfigurationPropertySource source : ConfigurationPropertySources.get(environment)) { + if (source.getUnderlyingSource() instanceof SystemEnvironmentPropertySource + || !(source instanceof IterableConfigurationPropertySource iterable)) { + continue; + } + for (ConfigurationPropertyName name : iterable) { + if (!list.isAncestorOf(name) || !name.isNumericIndex(list.getNumberOfElements())) { + continue; + } + String path = relativePath(name, list.getNumberOfElements() + 1); + if (!path.isEmpty() && !known.contains(path)) { + unknown.add(name.toString()); + } + } + } + if (!unknown.isEmpty()) { + throw new CapabilityStartupValidationException( + "HTTPCLIENT_UNKNOWN_SETTING: " + unknown + " name no setting and would be ignored"); + } + } + + /** The key below the list index, uniform form, with every further index written as []. */ + private static String relativePath(ConfigurationPropertyName name, int from) { + List parts = new ArrayList<>(); + for (int i = from; i < name.getNumberOfElements(); i++) { + parts.add(name.isNumericIndex(i) ? INDEX : name.getElement(i, Form.UNIFORM)); + } + return String.join(".", parts); + } + + /** Every leaf path of a settings record, in the same form {@link #relativePath} produces. */ + static Set knownPaths(Class recordType) { + Set paths = new HashSet<>(); + collect(recordType, "", paths); + return Set.copyOf(paths); + } + + private static void collect(Class recordType, String prefix, Set out) { + for (RecordComponent component : recordType.getRecordComponents()) { + String path = prefix + component.getName().toLowerCase(Locale.ROOT); + Class type = component.getType(); + if (type.isRecord()) { + collect(type, path + ".", out); + } else if (List.class.isAssignableFrom(type)) { + Type element = ((ParameterizedType) component.getGenericType()).getActualTypeArguments()[0]; + if (element instanceof Class elementType && elementType.isRecord()) { + collect(elementType, path + "." + INDEX + ".", out); + } else { + out.add(path + "." + INDEX); + } + } else { + out.add(path); + } + } + } +} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/http3/JettyHttp3TransportProvider.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/http3/JettyHttp3TransportProvider.java index 3d9a4cfa..8bf18d5b 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/http3/JettyHttp3TransportProvider.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/http3/JettyHttp3TransportProvider.java @@ -6,6 +6,7 @@ import dev.caskeleton.adapter.outbound.httpclient.profile.ClientMode; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; import dev.caskeleton.adapter.outbound.httpclient.profile.HttpProtocol; import dev.caskeleton.adapter.outbound.httpclient.profile.RuntimeGeneration; +import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline; import dev.caskeleton.adapter.outbound.httpclient.transport.BlockingTransportCapabilities; import dev.caskeleton.adapter.outbound.httpclient.transport.BlockingTransportProvider; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureClassifier; @@ -102,15 +103,45 @@ public final class JettyHttp3TransportProvider implements BlockingTransportProvi * are absent; never a downgrade to TCP */ static HttpClient newHttp3Client(ClientProfile profile) { - HttpClient client = new HttpClient(newHttp3Transport(profile)); + return configure(new HttpClient(newHttp3Transport(profile)), profile); + } + + /** + * Applies the profile's limits to a Jetty client, whatever its wire transport. + * + *

      Separate from {@link #newHttp3Client} so the behaviour it installs can be exercised over a + * plain TCP transport: a test cannot stand up a QUIC server, and the deadline and limits here do + * not depend on the wire. + * + * @param client a client not yet started + * @param profile the profile whose timeouts and pool bounds configure the client + * @return the same client + */ + static HttpClient configure(HttpClient client, ClientProfile profile) { client.setFollowRedirects(false); client.setConnectTimeout(profile.timeout().connect().toMillis()); client.setIdleTimeout(profile.timeout().readIdle().toMillis()); client.setMaxConnectionsPerDestination(profile.pool().maxConnectionsPerRoute()); client.setMaxRequestsQueuedPerDestination(Math.max(1, profile.pool().maxPendingAcquires())); + // Ends an exchange that is still in flight when the attempt deadline passes (finding 05-06). + // Jetty's connect and idle timeouts are per gap, so an upstream dripping a byte at a time was + // bounded by nothing. Jetty notifies "queued" on the thread that calls send(), which is the + // caller's thread inside the attempt scope, so the abort is registered with the right deadline; + // aborting fails the response listener Spring is blocked on and the body stream it hands out. + client + .getRequestListeners() + .addQueuedListener( + request -> AttemptDeadline.abortOnExpiry(() -> abortAtDeadline(request))); return client; } + private static void abortAtDeadline(org.eclipse.jetty.client.Request request) { + // The future says whether this abort won against a completing exchange. Either answer is fine: + // past the deadline nothing is left in flight, which is all the abort is for. + java.util.concurrent.Future unused = + request.abort(new java.util.concurrent.TimeoutException("attempt deadline reached")); + } + /** * The QUIC-backed transport, or a refusal. * diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/CircuitBreakerSettings.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/CircuitBreakerSettings.java new file mode 100644 index 00000000..c2c22582 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/CircuitBreakerSettings.java @@ -0,0 +1,48 @@ +package dev.caskeleton.adapter.outbound.httpclient.profile; + +import java.time.Duration; +import java.util.Objects; + +/** + * When a profile's circuit breaker opens and how long it stays open (design §18.1). + * + *

      The defaults are Resilience4j's own, which is what every profile ran with before these + * settings existed: a count-based window of the last 100 calls, opening once at least 100 calls + * were recorded and half of them failed, then rejecting for 60 seconds before letting 10 trial + * calls through. Keeping them means introducing the settings changes no deployment's behaviour. + * + *

      What counts as a failure is not configurable here: {@code CircuitBreakerStatusPolicy} owns + * that (5xx, 408, 429 and transport failures). These settings only say how many failures, out of + * how many calls, open the circuit. + * + *

      Ranges are checked by {@link ClientProfileValidator} so a bad value is reported with the + * others under one stable code instead of as an exception from the breaker library at runtime + * assembly. + * + * @param failureRateThreshold percentage of failed calls in the window that opens the circuit, 1 to + * 100 + * @param minimumNumberOfCalls calls the window must hold before the rate is evaluated, at least 1 + * and no more than the window + * @param slidingWindowSize how many of the most recent calls the rate is computed over + * @param waitDurationInOpenState how long an open circuit rejects before trial calls, positive + * @param permittedCallsInHalfOpenState trial calls allowed while half-open, at least 1 + */ +public record CircuitBreakerSettings( + int failureRateThreshold, + int minimumNumberOfCalls, + int slidingWindowSize, + Duration waitDurationInOpenState, + int permittedCallsInHalfOpenState) { + + private static final CircuitBreakerSettings LIBRARY_DEFAULTS = + new CircuitBreakerSettings(50, 100, 100, Duration.ofSeconds(60), 10); + + public CircuitBreakerSettings { + Objects.requireNonNull(waitDurationInOpenState, "wait duration in open state"); + } + + /** Resilience4j's defaults, the behaviour every profile had before these settings existed. */ + public static CircuitBreakerSettings defaults() { + return LIBRARY_DEFAULTS; + } +} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientObservabilitySettings.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientObservabilitySettings.java index a24610e1..971fb649 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientObservabilitySettings.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientObservabilitySettings.java @@ -1,11 +1,16 @@ package dev.caskeleton.adapter.outbound.httpclient.profile; -/** Per-profile observability switches (design §11.1, §25). */ -public record ClientObservabilitySettings( - boolean operationNameRequired, boolean fullUrlRecording, boolean bodyLogging) { +/** + * Per-profile observability switches (design §11.1, §25). + * + *

      {@code operation-name-required} was removed (finding 05-15). An operation name is not optional + * anywhere: {@code HttpOperation} refuses to exist without one, so the switch could only be true, + * and false was a promise nothing could keep. + */ +public record ClientObservabilitySettings(boolean fullUrlRecording, boolean bodyLogging) { private static final ClientObservabilitySettings SAFE = - new ClientObservabilitySettings(true, false, false); + new ClientObservabilitySettings(false, false); public static ClientObservabilitySettings safeDefaults() { return SAFE; diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfile.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfile.java index e99bb1c8..9934ed17 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfile.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfile.java @@ -32,6 +32,7 @@ public record ClientProfile( ResponseLimits response, AuthenticationSettings authentication, RetrySettings retry, + CircuitBreakerSettings circuitBreaker, ClientObservabilitySettings observability, TlsSettings tls, ProxySettings proxy, @@ -51,6 +52,7 @@ public record ClientProfile( Objects.requireNonNull(response, "response limits"); Objects.requireNonNull(authentication, "authentication settings"); Objects.requireNonNull(retry, "retry settings"); + Objects.requireNonNull(circuitBreaker, "circuit breaker settings"); Objects.requireNonNull(observability, "observability settings"); Objects.requireNonNull(tls, "tls settings"); Objects.requireNonNull(proxy, "proxy settings"); diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfileValidator.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfileValidator.java index cc34eb1b..af40bff6 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfileValidator.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfileValidator.java @@ -25,6 +25,7 @@ public final class ClientProfileValidator { validateCredentials(profile, violations); validateTls(profile, environment, violations); validateRetry(profile, violations); + validateCircuitBreaker(profile, violations); validateObservability(profile, environment, violations); validateProductionCompleteness(profile, environment, violations); violations.sort(ClientProfileViolation::compareTo); @@ -115,6 +116,27 @@ public final class ClientProfileValidator { if (timeout.totalCall().isZero() || timeout.totalCall().isNegative()) { out.add(violation("INVALID_TIMEOUT_BUDGET", profile, "timeout.total-call")); } + // Every enforced timeout must be positive. Both engines read zero as "no timeout": Apache's + // Timeout.of(Duration.ZERO) is infinite, and the JDK client never times out a zero budget. Only + // total-call used to be checked, so `connect: 0s` was accepted and meant "wait forever" — the + // opposite of what anyone writing a zero means (finding 05-15). + requirePositive(timeout.connect(), "timeout.connect", profile, out); + requirePositive(timeout.tlsHandshake(), "timeout.tls-handshake", profile, out); + requirePositive(timeout.responseHeader(), "timeout.response-header", profile, out); + requirePositive(timeout.readIdle(), "timeout.read-idle", profile, out); + requirePositive(timeout.totalCall(), "timeout.total-call", profile, out); + requirePositive( + profile.pool().pendingAcquireTimeout(), "pool.pending-acquire-timeout", profile, out); + } + + private static void requirePositive( + java.time.Duration value, + String setting, + ClientProfile profile, + List out) { + if (value.isZero() || value.isNegative()) { + out.add(violation("TIMEOUT_NOT_POSITIVE", profile, setting)); + } } private void validateLimits(ClientProfile profile, List out) { @@ -232,7 +254,20 @@ public final class ClientProfileValidator { } } + /** + * The most attempts a profile may declare, the first included. + * + *

      Five is gRPC's ceiling for the same knob (its service config caps {@code maxAttempts} at + * five), and the reasoning carries over: past a handful of attempts, more retries add load to an + * upstream that is already failing and do not raise the success rate. Without a ceiling a typo of + * {@code 30} multiplied every failing call thirty-fold, bounded only by the deadline. + */ + public static final int MAX_ATTEMPTS_CEILING = 5; + private void validateRetry(ClientProfile profile, List out) { + if (profile.retry().maxAttempts() > MAX_ATTEMPTS_CEILING) { + out.add(violation("RETRY_MAX_ATTEMPTS_EXCEEDED", profile, "retry.max-attempts")); + } if (profile.retry().enabled() && profile.retry().baseBackoff().isZero() && profile.retry().jitter() == JitterStrategy.NONE) { @@ -252,6 +287,52 @@ public final class ClientProfileValidator { } } + /** + * Breaker thresholds the breaker library would refuse, refused here first with stable codes. + * + *

      A minimum above the window could never be reached in a count-based window, so the rate would + * never be evaluated and the breaker could never open — accepted silently, that is a breaker + * switched off by a typo. + */ + private void validateCircuitBreaker(ClientProfile profile, List out) { + CircuitBreakerSettings breaker = profile.circuitBreaker(); + if (breaker.failureRateThreshold() < 1 || breaker.failureRateThreshold() > 100) { + out.add( + violation( + "CIRCUIT_BREAKER_SETTING_INVALID", + profile, + "circuit-breaker.failure-rate-threshold")); + } + if (breaker.slidingWindowSize() < 1) { + out.add( + violation( + "CIRCUIT_BREAKER_SETTING_INVALID", profile, "circuit-breaker.sliding-window-size")); + } + if (breaker.minimumNumberOfCalls() < 1 + || breaker.minimumNumberOfCalls() > breaker.slidingWindowSize()) { + out.add( + violation( + "CIRCUIT_BREAKER_SETTING_INVALID", + profile, + "circuit-breaker.minimum-number-of-calls")); + } + if (breaker.waitDurationInOpenState().isZero() + || breaker.waitDurationInOpenState().isNegative()) { + out.add( + violation( + "CIRCUIT_BREAKER_SETTING_INVALID", + profile, + "circuit-breaker.wait-duration-in-open-state")); + } + if (breaker.permittedCallsInHalfOpenState() < 1) { + out.add( + violation( + "CIRCUIT_BREAKER_SETTING_INVALID", + profile, + "circuit-breaker.permitted-calls-in-half-open-state")); + } + } + private void validateProductionCompleteness( ClientProfile profile, RuntimeEnvironment environment, List out) { if (!environment.production()) { diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/PoolSettings.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/PoolSettings.java index c869e6d9..05ec1211 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/PoolSettings.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/PoolSettings.java @@ -8,6 +8,11 @@ import java.util.Objects; * *

      Pool size, pending-acquire queue, and attempt bulkhead are independent knobs: HTTP/2 * multiplexes many streams onto one connection, so connection count is not a concurrency limit. + * + *

      {@code eviction-interval} and {@code shutdown-timeout} were removed (finding 05-15). Both + * bound and reached nothing: Apache's idle evictor runs at {@code max-idle-time}, and a retired + * runtime drains for {@code app.httpclient.rotation-drain-timeout}. The strict binder refuses + * either key by name if a deployment still sets it. */ public record PoolSettings( int maxTotalConnections, @@ -17,8 +22,6 @@ public record PoolSettings( Duration maxIdleTime, Duration maxLifeTime, Duration validateAfterInactivity, - Duration evictionInterval, - Duration shutdownTimeout, boolean requiresRoutePool, boolean requiresBoundedPendingQueue) { @@ -27,8 +30,6 @@ public record PoolSettings( Objects.requireNonNull(maxIdleTime, "max idle time"); Objects.requireNonNull(maxLifeTime, "max life time"); Objects.requireNonNull(validateAfterInactivity, "validate after inactivity"); - Objects.requireNonNull(evictionInterval, "eviction interval"); - Objects.requireNonNull(shutdownTimeout, "shutdown timeout"); if (maxTotalConnections < 1 || maxConnectionsPerRoute < 1 || maxPendingAcquires < 0) { throw new IllegalArgumentException("pool limits must be positive"); } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ProxySettings.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ProxySettings.java index 5c7380a6..a68c2a6a 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ProxySettings.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ProxySettings.java @@ -1,6 +1,5 @@ package dev.caskeleton.adapter.outbound.httpclient.profile; -import java.time.Duration; import java.util.Objects; import java.util.Optional; @@ -9,6 +8,9 @@ import java.util.Optional; * *

      Proxy authentication is a separate credential from target authentication, and the ambient * {@code NO_PROXY} environment variable never widens a validated production profile. + * + *

      {@code connect-timeout} was removed (finding 05-15): it was bound and reached no transport, + * and the TCP connect to the proxy is governed by {@code timeout.connect} like any other connect. */ public record ProxySettings( boolean enabled, @@ -16,18 +18,15 @@ public record ProxySettings( int port, ProxyType type, Optional credentialProvider, - Duration connectTimeout, boolean importAmbientNoProxy) { private static final ProxySettings DISABLED = - new ProxySettings( - false, "", 0, ProxyType.HTTP, Optional.empty(), Duration.ofMillis(500), false); + new ProxySettings(false, "", 0, ProxyType.HTTP, Optional.empty(), false); public ProxySettings { Objects.requireNonNull(host, "proxy host"); Objects.requireNonNull(type, "proxy type"); Objects.requireNonNull(credentialProvider, "proxy credential provider"); - Objects.requireNonNull(connectTimeout, "proxy connect timeout"); if (enabled && (host.isBlank() || port < 1 || port > 65535)) { throw new IllegalArgumentException("an enabled proxy requires a host and a valid port"); } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/TimeoutSettings.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/TimeoutSettings.java index 643ed7c4..478b1e80 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/TimeoutSettings.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/TimeoutSettings.java @@ -8,6 +8,13 @@ import java.util.Objects; * *

      {@link #totalCall()} is the upper budget for everything, including pool acquire and retry * backoff. + * + *

      The design lists two more stage timeouts, proxy-connect and request-write-idle. They were + * bound and reached no transport: neither engine can bound a blocking socket write, and the TCP + * connect to a proxy is the connect timeout. They were removed rather than refused (finding 05-15): + * the strict settings binder already refuses an unknown key by name at startup, so a deployment + * that still sets one fails loudly, and a field that only exists to be refused is a setting that + * documents a capability the platform does not have. */ public record TimeoutSettings( // Hostname resolution budget. Currently unenforced: neither the Apache classic client nor the @@ -16,8 +23,6 @@ public record TimeoutSettings( Duration dns, Duration connect, Duration tlsHandshake, - Duration proxyConnect, - Duration requestWriteIdle, Duration responseHeader, Duration readIdle, Duration totalCall) { @@ -34,8 +39,6 @@ public record TimeoutSettings( Objects.requireNonNull(dns, "dns timeout"); Objects.requireNonNull(connect, "connect timeout"); Objects.requireNonNull(tlsHandshake, "tls handshake timeout"); - Objects.requireNonNull(proxyConnect, "proxy connect timeout"); - Objects.requireNonNull(requestWriteIdle, "request write idle timeout"); Objects.requireNonNull(responseHeader, "response header timeout"); Objects.requireNonNull(readIdle, "read idle timeout"); Objects.requireNonNull(totalCall, "total call timeout"); diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DefaultRetryEligibilityEngine.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DefaultRetryEligibilityEngine.java index 2ad13a74..1feec2af 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DefaultRetryEligibilityEngine.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DefaultRetryEligibilityEngine.java @@ -8,14 +8,30 @@ import java.util.Optional; /** * The complete ordered retry decision table (design §17.3). * - *

      The order is the point. Cheap absolute blockers come first (attempts, budget, replayability, - * first byte, deadline, draining), then ambiguity, then status- and failure-specific rules. A later - * rule can never re-enable something an earlier rule forbade. + *

      The order is the point. An unanswered unsafe request is ambiguous before anything else is + * asked; then the cheap absolute blockers (attempts, budget, replayability, first byte, deadline, + * draining), then partial-response ambiguity, then status- and failure-specific rules. A later rule + * can never re-enable something an earlier rule forbade. */ public final class DefaultRetryEligibilityEngine implements RetryEligibilityEngine { + /** + * The reason a 401 replay is granted under. The gateway refreshes the credential only when a + * retry is granted with this reason, so the refresh and the replay cannot be decided apart. + */ + public static final String UNAUTHORIZED_REFRESH = "UNAUTHORIZED_REFRESH"; + @Override public RetryDecision decide(RetryContext context) { + // Ambiguity first. "Sent, no answer, and repeating is not safe" is a fact about this attempt's + // outcome, not a retry eligibility rule, so no "no more retries" rule may answer before it. It + // used to sit below the attempt, budget and replayability checks, and with the default of one + // attempt a POST that timed out after it was sent reached the caller as an ordinary timeout + // instead of HttpAmbiguousExecutionException — the one exception that tells the caller to + // reconcile before doing anything else (finding 05-14). + if (context.evidence() == ExecutionEvidence.SENT_NO_RESPONSE && !context.safelyIdempotent()) { + return AmbiguousFailure.remoteOutcomeUnknown(); + } if (context.attempt() >= context.maxAttempts()) { return RetryDenied.maxAttempts(); } @@ -44,9 +60,6 @@ public final class DefaultRetryEligibilityEngine implements RetryEligibilityEngi ? RetryAllowed.of("PARTIAL_RESPONSE") : AmbiguousFailure.remoteOutcomeUnknown(); } - if (context.evidence() == ExecutionEvidence.SENT_NO_RESPONSE && !context.safelyIdempotent()) { - return AmbiguousFailure.remoteOutcomeUnknown(); - } return statusOrFailureDecision(context); } @@ -86,7 +99,7 @@ public final class DefaultRetryEligibilityEngine implements RetryEligibilityEngi context.credentialRefreshAvailable() && context.attempt() == 1 && context.safelyIdempotent() - ? RetryAllowed.of("UNAUTHORIZED_REFRESH") + ? RetryAllowed.of(UNAUTHORIZED_REFRESH) : RetryDenied.notRetryableStatus(status); case 500 -> context.transientServerErrorStatuses().contains(500) && context.safelyIdempotent() diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/ResilienceRegistry.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/ResilienceRegistry.java index e64aa49e..10f2d9dc 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/ResilienceRegistry.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/ResilienceRegistry.java @@ -1,6 +1,8 @@ package dev.caskeleton.adapter.outbound.httpclient.resilience; import dev.caskeleton.adapter.outbound.httpclient.api.ClientProfileName; +import dev.caskeleton.adapter.outbound.httpclient.profile.CircuitBreakerSettings; +import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig; import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; import io.github.resilience4j.ratelimiter.RateLimiterConfig; import io.github.resilience4j.ratelimiter.RateLimiterRegistry; @@ -54,8 +56,29 @@ public final class ResilienceRegistry { .build(); } - public AttemptCircuitBreaker circuitBreaker(ClientProfileName profileName) { - return AttemptCircuitBreaker.resilience4j(circuitBreakers.circuitBreaker(profileName.value())); + /** + * The profile's breaker, configured from its settings the first time the profile asks. + * + *

      A breaker is per profile, not per runtime generation: a certificate rotation builds a new + * runtime for the same upstream, and its failure history must carry over. The registry returns + * the existing breaker for a name, so a rotation keeps both the state and the configuration the + * profile started with. + */ + public AttemptCircuitBreaker circuitBreaker( + ClientProfileName profileName, CircuitBreakerSettings settings) { + return AttemptCircuitBreaker.resilience4j( + circuitBreakers.circuitBreaker(profileName.value(), circuitBreakerConfig(settings))); + } + + static CircuitBreakerConfig circuitBreakerConfig(CircuitBreakerSettings settings) { + return CircuitBreakerConfig.from(CircuitBreakerConfig.ofDefaults()) + .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED) + .failureRateThreshold(settings.failureRateThreshold()) + .minimumNumberOfCalls(settings.minimumNumberOfCalls()) + .slidingWindowSize(settings.slidingWindowSize()) + .waitDurationInOpenState(settings.waitDurationInOpenState()) + .permittedNumberOfCallsInHalfOpenState(settings.permittedCallsInHalfOpenState()) + .build(); } public AttemptRateLimiter rateLimiter(ClientProfileName profileName) { diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java index 09ee5c05..3b6df73f 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java @@ -6,6 +6,7 @@ import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceeded import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpFailureMetadata; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException; import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType; import dev.caskeleton.adapter.outbound.httpclient.auth.RequestCredentials; @@ -18,6 +19,7 @@ import dev.caskeleton.adapter.outbound.httpclient.resilience.ProtocolEvidence; import dev.caskeleton.adapter.outbound.httpclient.security.PreparedOperation; import dev.caskeleton.adapter.outbound.httpclient.security.PreparedTarget; import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline; +import dev.caskeleton.adapter.outbound.httpclient.transport.RequestWriteSignal; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure; import java.net.URI; import java.time.Duration; @@ -144,7 +146,7 @@ public final class BlockingAttemptExecutor { tracker.firstByteDelivered()); } }, - BlockingAttemptExecutor::upstreamFailure); + outcome -> upstreamFailure(outcome, baseMetadata)); return finish(observation, scope, attemptOutcome); } catch (HttpClientException stable) { return finish( @@ -162,21 +164,46 @@ public final class BlockingAttemptExecutor { // frame, so the classification of everything else is unchanged. ProtocolEvidence protocolEvidence = support.http2EvidenceMapper().map(support.protocolEvidenceReader().read(engineFailure)); + TransportFailure effective = + withMoreSpecificEvidence( + classified, + protocolEvidence, + support.evidenceClassifier().classify(tracker.snapshot(), protocolEvidence)); HttpFailureMetadata metadata = - baseMetadata - .withEvidence( - support.evidenceClassifier().classify(tracker.snapshot(), protocolEvidence)) - .withStage(classified.stage()); + baseMetadata.withEvidence(effective.evidence()).withStage(effective.stage()); HttpClientException mapped = - support.exceptionMapper().map(classified, metadata, engineFailure); + support.exceptionMapper().map(effective, metadata, engineFailure); return finish( observation, scope, AttemptOutcome.failed( - mapped, classified.category(), Optional.empty(), tracker.firstByteDelivered())); + mapped, effective.category(), Optional.empty(), tracker.firstByteDelivered())); } } + /** + * The evidence the caller is told, choosing the more specific of the two observations. + * + *

      Two parties classify a failed attempt. The transport classifier reads the engine's exception + * type against the stage reached — a {@code ConnectException} proves nothing left even when the + * stage says the write had begun. The progress classifier reads protocol frames — an HTTP/2 + * REFUSED_STREAM proves the peer processed nothing even though the request was written. Frame + * proof is the stronger statement and wins; otherwise the transport's reading stands. The + * executor used to compute the progress evidence into the metadata and hand both to the exception + * mapper, which then wrote the transport's evidence over it, so the REFUSED_STREAM promotion was + * computed on every failure and reached no caller (finding 05-14). + */ + private static TransportFailure withMoreSpecificEvidence( + TransportFailure classified, + ProtocolEvidence protocolEvidence, + ExecutionEvidence progressEvidence) { + if (!protocolEvidence.peerDidNotProcess() || classified.evidence() == progressEvidence) { + return classified; + } + return new TransportFailure( + classified.stage(), progressEvidence, classified.category(), classified.safeReason()); + } + /** * Stops the observation with the attempt's outcome, naming the deadline when it ended the * attempt. @@ -212,11 +239,30 @@ public final class BlockingAttemptExecutor { /** * The failure the circuit breaker records for a returned outcome, if any. * - *

      Only a remote status that {@link CircuitBreakerStatusPolicy} counts against the upstream is - * a breaker failure. A 404 thrown to the caller as {@code HttpRemoteErrorException} is still a + *

      Only a status that {@link CircuitBreakerStatusPolicy} counts against the upstream is a + * breaker failure. A 404 thrown to the caller as {@code HttpRemoteErrorException} is still a * healthy answer for the breaker. + * + *

      The status decides, not the shape the caller asked for. Under {@link + * StatusHandlingPolicy#RETURN_RESULT} a 503 comes back as a successful outcome carrying the + * status, and reading only failed outcomes recorded every one of those as a success — an upstream + * answering nothing but 503 never opened the circuit for a caller that had chosen to receive + * statuses as data (finding 05-05). */ - private static Optional upstreamFailure(AttemptOutcome outcome) { + private static Optional upstreamFailure( + AttemptOutcome outcome, HttpFailureMetadata baseMetadata) { + if (outcome.successful()) { + return outcome + .status() + .filter(CircuitBreakerStatusPolicy::countsAsUpstreamFailure) + .map( + status -> + new HttpRemoteErrorException( + "upstream returned an error status as a result", + baseMetadata + .withStatus(status) + .withEvidence(ExecutionEvidence.RESPONSE_RECEIVED))); + } if (outcome.failureCategory() != FailureCategory.REMOTE_STATUS) { return Optional.empty(); } @@ -309,12 +355,32 @@ public final class BlockingAttemptExecutor { .uri(uri); headers.forEach((name, values) -> values.forEach(value -> spec.header(name, value))); - tracker.enter(AttemptStage.REQUEST_HEADERS); RestClient.RequestHeadersSpec request = runtime.support().bodyWriter().write(spec, body, runtime.bodyLimitPolicy(), metadata); - tracker.enter(AttemptStage.REQUEST_BODY); - tracker.requestWriteStarted(); + Runnable writeStarting = + () -> { + tracker.enter(AttemptStage.REQUEST_HEADERS); + tracker.enter(AttemptStage.REQUEST_BODY); + tracker.requestWriteStarted(); + }; + // A transport that reports the moment it starts writing advances the stage then, so a failure + // while connecting stays provably unsent. One that cannot is advanced here, before the engine + // runs: without an observation the only safe assumption is that the request may have left + // (finding 05-14, RequestWriteSignal). + if (!runtime.reportsRequestWrite()) { + writeStarting.run(); + } + try (RequestWriteSignal.Scope signal = RequestWriteSignal.listen(writeStarting)) { + return exchange(request, runtime, tracker, limiter); + } + } + + private RestClientResponseReader.RawResponse exchange( + RestClient.RequestHeadersSpec request, + BlockingClientRuntime runtime, + AttemptProgressTracker tracker, + ResponseSizeLimiter limiter) { return request.exchange( (httpRequest, httpResponse) -> { tracker.enter(AttemptStage.RESPONSE_HEADERS); diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingClientRuntime.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingClientRuntime.java index ba4ebaf0..9b9a91bd 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingClientRuntime.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingClientRuntime.java @@ -29,6 +29,7 @@ public final class BlockingClientRuntime extends ClientRuntime { private final RestClient restClient; private final TransportId transportId; private final TransportFailureClassifier failureClassifier; + private final boolean reportsRequestWrite; private final TrustedTargetPolicy targetPolicy; private final BodyLimitPolicy bodyLimitPolicy; private final RedirectPolicy redirectPolicy; @@ -46,6 +47,7 @@ public final class BlockingClientRuntime extends ClientRuntime { RestClient restClient, TransportId transportId, TransportFailureClassifier failureClassifier, + boolean reportsRequestWrite, AttemptResiliencePipeline resiliencePipeline, LogicalAdmissionLimiter admissionLimiter, RetryBudget retryBudget, @@ -56,6 +58,7 @@ public final class BlockingClientRuntime extends ClientRuntime { this.restClient = Objects.requireNonNull(restClient, "rest client"); this.transportId = Objects.requireNonNull(transportId, "transport id"); this.failureClassifier = Objects.requireNonNull(failureClassifier, "failure classifier"); + this.reportsRequestWrite = reportsRequestWrite; this.resiliencePipeline = Objects.requireNonNull(resiliencePipeline, "resilience pipeline"); this.admissionLimiter = Objects.requireNonNull(admissionLimiter, "admission limiter"); this.retryBudget = Objects.requireNonNull(retryBudget, "retry budget"); @@ -90,6 +93,11 @@ public final class BlockingClientRuntime extends ClientRuntime { return transportId; } + /** Whether the transport signals the start of the request write; see RequestWriteSignal. */ + public boolean reportsRequestWrite() { + return reportsRequestWrite; + } + public TransportFailureClassifier failureClassifier() { return failureClassifier; } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingGateway.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingGateway.java index 919528d4..9fabdca1 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingGateway.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingGateway.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.httpclient.restclient; import dev.caskeleton.adapter.outbound.httpclient.api.ClientProfileName; import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpFailureMetadata; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException; import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; @@ -11,6 +12,7 @@ import dev.caskeleton.adapter.outbound.httpclient.auth.RequestCredentials; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientRuntimeLease; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientRuntimeRegistry; import dev.caskeleton.adapter.outbound.httpclient.security.PreparedOperation; +import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -71,7 +73,15 @@ public final class BlockingStreamingGateway { // the limiter blind to exactly the calls that hold resources longest. AutoCloseable admission = setup.admit(); BlockingStreamingResponse response; - try { + // The total budget bounds the setup — connect, send, and the wait for response headers — and + // nothing after it (design §15.3). The scope closes when the exchange hands the stream over, + // which deregisters the transport's abort, so the body is then bounded by read-idle per gap + // and a long download is not cut at an arbitrary total. Without the scope a setup was bounded + // only by per-gap stage timeouts, and an upstream that held or dripped its headers kept the + // caller past its deadline (finding 05-06). + AttemptDeadline.Scope setupDeadline = + AttemptDeadline.open(setup.deadline().remaining(runtime.support().clock())); + try (setupDeadline) { response = spec.exchange( (request, rawResponse) -> { @@ -101,6 +111,10 @@ public final class BlockingStreamingGateway { false); } catch (RuntimeException failure) { closeQuietly(admission); + if (setupDeadline.expired() && !(failure instanceof HttpRemoteErrorException)) { + throw new HttpDeadlineExceededException( + "effective deadline reached before the stream was set up", metadata, failure); + } throw failure; } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGateway.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGateway.java index 670b2a49..40699975 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGateway.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGateway.java @@ -20,6 +20,7 @@ import dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptOutcome; import dev.caskeleton.adapter.outbound.httpclient.resilience.BlockingLogicalCall; import dev.caskeleton.adapter.outbound.httpclient.resilience.Deadline; import dev.caskeleton.adapter.outbound.httpclient.resilience.DeadlineGuard; +import dev.caskeleton.adapter.outbound.httpclient.resilience.DefaultRetryEligibilityEngine; import dev.caskeleton.adapter.outbound.httpclient.resilience.RetryAllowed; import dev.caskeleton.adapter.outbound.httpclient.resilience.RetryContext; import dev.caskeleton.adapter.outbound.httpclient.resilience.RetryCoordinator; @@ -191,11 +192,10 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway { prepared.operation().body().replayability(), credentialRefreshes, true)); - if (refreshAllowed) { - runtime.credentialProvider().invalidate(setup.credentialRequest(false)); - credentials = resolveCredentials(true); - credentialRefreshes++; - } + // Only whether a refresh would be allowed. The refresh itself waits for the retry engine: + // a 401 the engine will not replay — one attempt configured, budget spent, deadline gone — + // used to invalidate the token cache and fetch a new token anyway, a token-endpoint call per + // rejected request for a credential nothing would send (finding 05-23g). return new RetryContext( prepared.operation().idempotency(), prepared.operation().idempotencyKey(), @@ -255,6 +255,11 @@ public final class DefaultGenericHttpGateway implements GenericHttpGateway { @Override public void onRetryGranted(RetryAllowed allowed, int attemptNumber) { observation.recordRetry(allowed.reason()); + if (DefaultRetryEligibilityEngine.UNAUTHORIZED_REFRESH.equals(allowed.reason())) { + runtime.credentialProvider().invalidate(setup.credentialRequest(false)); + credentials = resolveCredentials(true); + credentialRefreshes++; + } } private RequestCredentials resolveCredentials(boolean forceRefresh) { diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/RestClientRuntimeFactory.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/RestClientRuntimeFactory.java index b9da3431..be59f5ff 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/RestClientRuntimeFactory.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/RestClientRuntimeFactory.java @@ -33,6 +33,12 @@ import org.springframework.web.client.RestClient; */ public final class RestClientRuntimeFactory implements ClientRuntimeFactory { + /** + * Prefix of the budget a retrying profile gets when it names none. The colon cannot be confused + * with an operator-chosen budget name that happens to equal a profile name. + */ + static final String PROFILE_SCOPED_BUDGET_PREFIX = "profile:"; + private final Map providers = new EnumMap<>(TransportType.class); private final TransportCapabilityValidator capabilityValidator = @@ -79,15 +85,7 @@ public final class RestClientRuntimeFactory implements ClientRuntimeFactory { AttemptResiliencePipeline pipeline = newResiliencePipeline(profile); - RetryBudget retryBudget = - profile - .retry() - .budget() - .map( - name -> - resilienceRegistry.retryBudget( - name, retryCapacity(profile), Duration.ofMinutes(1))) - .orElseGet(RetryBudget::unlimited); + RetryBudget retryBudget = retryBudget(profile); Supplier backoffFactory = () -> @@ -105,6 +103,7 @@ public final class RestClientRuntimeFactory implements ClientRuntimeFactory { restClient, provider.id(), provider.failureClassifier(), + provider.reportsRequestWrite(), pipeline, resilienceRegistry.admission( profile.name(), @@ -115,6 +114,24 @@ public final class RestClientRuntimeFactory implements ClientRuntimeFactory { support); } + /** + * The retry budget this profile's retries draw from; every retrying profile has a bounded one. + * + *

      A named budget is shared by every profile that names it. A retrying profile that names none + * gets its own, keyed by profile, with the same pool-derived capacity. It used to get an + * unlimited budget, so the per-upstream ceiling on retry traffic was missing exactly where nobody + * had configured one (finding 05-15). A profile that cannot retry keeps the unlimited budget: it + * never asks for a token, and a bucket there would be a counter nothing reads. + */ + private RetryBudget retryBudget(ClientProfile profile) { + if (!profile.retry().enabled()) { + return RetryBudget.unlimited(); + } + String name = + profile.retry().budget().orElse(PROFILE_SCOPED_BUDGET_PREFIX + profile.name().value()); + return resilienceRegistry.retryBudget(name, retryCapacity(profile), Duration.ofMinutes(1)); + } + /** * Retry capacity is derived from the pool budget rather than invented: a retry storm is bounded * by what the upstream can absorb, and the pool is the only declared statement of that. @@ -132,7 +149,7 @@ public final class RestClientRuntimeFactory implements ClientRuntimeFactory { */ private AttemptResiliencePipeline newResiliencePipeline(ClientProfile profile) { dev.caskeleton.adapter.outbound.httpclient.resilience.AttemptCircuitBreaker breaker = - resilienceRegistry.circuitBreaker(profile.name()); + resilienceRegistry.circuitBreaker(profile.name(), profile.circuitBreaker()); return new AttemptResiliencePipeline( breaker, resilienceRegistry.rateLimiter(profile.name()), diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/BlockingTransportProvider.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/BlockingTransportProvider.java index aa3baaf9..67bdd578 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/BlockingTransportProvider.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/BlockingTransportProvider.java @@ -27,6 +27,15 @@ public interface BlockingTransportProvider { TransportFailureClassifier failureClassifier(); + /** + * Whether this transport calls {@link RequestWriteSignal#requestWriteStarting()} before it writes + * a request. Only a transport that does may have its pre-write failures classified as not sent by + * stage; the others keep the conservative classification. + */ + default boolean reportsRequestWrite() { + return false; + } + /** Releases the engine resources created for exactly this profile generation. */ void close(ClientProfile profile, RuntimeGeneration generation); } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/RequestWriteSignal.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/RequestWriteSignal.java new file mode 100644 index 00000000..3dace60c --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/RequestWriteSignal.java @@ -0,0 +1,55 @@ +package dev.caskeleton.adapter.outbound.httpclient.transport; + +import java.util.Objects; + +/** + * Lets a transport say "the request is about to go onto an established connection" (finding 05-14). + * + *

      Whether a failed request was sent is decided from the stage the attempt reached. The executor + * cannot see inside the engine, so it used to mark the attempt as writing just before calling the + * engine — which made every failure inside the engine, including DNS, connect and the TLS + * handshake, look like a failure after the request was written. A failure the engine reports with a + * specific type was still classified correctly by type; one it reports generically (a plain {@code + * SSLException} from a peer that answered the handshake in plaintext) became "sent, outcome + * unknown", and a POST that never left the process was reported as ambiguous. + * + *

      A transport that can observe the moment — Apache, through its request executor — calls {@link + * #requestWriteStarting()} on the caller's thread, and the executor advances the stage then. A + * transport that cannot declares so through {@link + * BlockingTransportProvider#reportsRequestWrite()}, and the executor keeps the conservative early + * advance for it: guessing "not sent" is what turns a timeout into a duplicate payment. + */ +public final class RequestWriteSignal { + + private static final ThreadLocal CURRENT = new ThreadLocal<>(); + + private RequestWriteSignal() {} + + /** Listens on the current thread until the returned scope is closed. */ + public static Scope listen(Runnable onRequestWriteStarting) { + Objects.requireNonNull(onRequestWriteStarting, "request write listener"); + Runnable outer = CURRENT.get(); + CURRENT.set(onRequestWriteStarting); + return () -> { + if (outer == null) { + CURRENT.remove(); + } else { + CURRENT.set(outer); + } + }; + } + + /** Called by a transport immediately before it writes the request onto a connection. */ + public static void requestWriteStarting() { + Runnable listener = CURRENT.get(); + if (listener != null) { + listener.run(); + } + } + + /** Restores the previous listener. */ + public interface Scope extends AutoCloseable { + @Override + void close(); + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java index e352e8b2..ccc2891a 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java @@ -84,8 +84,6 @@ class ApachePoolSaturationTest { Duration.ofSeconds(30), Duration.ofMinutes(5), Duration.ofSeconds(5), - Duration.ofSeconds(15), - Duration.ofSeconds(5), false, false)) .build(); diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientAutoConfigurationTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientAutoConfigurationTest.java index 18720176..18615c33 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientAutoConfigurationTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientAutoConfigurationTest.java @@ -2,15 +2,21 @@ package dev.caskeleton.adapter.outbound.httpclient.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.outbound.httpclient.api.ClientProfileName; import dev.caskeleton.adapter.outbound.httpclient.dynamic.DynamicCredentialBinding; import dev.caskeleton.adapter.outbound.httpclient.dynamic.DynamicTargetGateway; +import dev.caskeleton.adapter.outbound.httpclient.profile.CircuitBreakerSettings; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientRuntimeRegistry; import dev.caskeleton.adapter.outbound.httpclient.restclient.GenericHttpGateway; import dev.caskeleton.adapter.outbound.httpclient.service.HttpServiceRegistry; import java.time.Clock; +import java.time.Duration; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -78,6 +84,72 @@ class HttpClientAutoConfigurationTest { }); } + @Test + @DisplayName("clients[n].circuit-breaker.* 설정이 해당 프로필의 circuit breaker 설정으로 바인딩된다") + void circuitBreakerKeysBindIntoTheProfile() { + runner + .withPropertyValues(paymentClient()) + .withPropertyValues( + "app.httpclient.clients[0].circuit-breaker.failure-rate-threshold=25", + "app.httpclient.clients[0].circuit-breaker.minimum-number-of-calls=10", + "app.httpclient.clients[0].circuit-breaker.sliding-window-size=20", + "app.httpclient.clients[0].circuit-breaker.wait-duration-in-open-state=15s", + "app.httpclient.clients[0].circuit-breaker.permitted-calls-in-half-open-state=2") + .run( + context -> { + // given + ClientRuntimeRegistry registry = context.getBean(ClientRuntimeRegistry.class); + + // when + CircuitBreakerSettings bound = + registry.current(new ClientProfileName("payment")).profile().circuitBreaker(); + + // then + assertThat(bound) + .isEqualTo(new CircuitBreakerSettings(25, 10, 20, Duration.ofSeconds(15), 2)); + }); + } + + @ParameterizedTest + @ValueSource( + strings = { + "timeout.request-write-idle=1s", + "timeout.proxy-connect=1s", + "proxy.connect-timeout=1s", + "pool.eviction-interval=15s", + "pool.shutdown-timeout=5s", + "observability.operation-name-required=true" + }) + @DisplayName("동작하지 않아 지운 설정 키를 적으면 시작이 키 이름과 함께 실패한다") + void aRemovedInertKeyFailsStartupByName(String setting) { + runner + .withPropertyValues(paymentClient()) + .withPropertyValues("app.httpclient.clients[0]." + setting) + .run( + context -> { + // given + String key = setting.substring(0, setting.indexOf('=')); + + // when + Throwable failure = context.getStartupFailure(); + + // then + assertThat(failure).isNotNull(); + assertThat(rootCauseChainMessages(failure)).contains(key); + }); + } + + private static String rootCauseChainMessages(Throwable failure) { + StringBuilder messages = new StringBuilder(); + for (Throwable current = failure; current != null; current = current.getCause()) { + messages.append(current.getMessage()).append('\n'); + if (current.getCause() == current) { + break; + } + } + return messages.toString(); + } + private static String[] dynamicWebhookClient() { return new String[] { "app.httpclient.clients[1].name=webhook", diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsTest.java index bf3eb3c6..afa721b1 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsTest.java @@ -99,7 +99,7 @@ class HttpClientPlatformSettingsTest { /** * A client whose only meaningful field here is its name. * - *

      The aggregate rules read nothing else, and filling in nineteen components would state a + *

      The aggregate rules read nothing else, and filling in twenty components would state a * dependency this test does not have. */ private static HttpClientPlatformSettings.ClientSettings client(String name) { @@ -121,6 +121,7 @@ class HttpClientPlatformSettingsTest { null, null, null, + null, null); } diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/http3/JettyAttemptDeadlineTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/http3/JettyAttemptDeadlineTest.java new file mode 100644 index 00000000..1b81c012 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/http3/JettyAttemptDeadlineTest.java @@ -0,0 +1,67 @@ +package dev.caskeleton.adapter.outbound.httpclient.http3; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; +import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; +import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline; +import java.io.IOException; +import java.time.Duration; +import org.eclipse.jetty.client.HttpClient; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.client.JettyClientHttpRequestFactory; + +/** + * The experimental HTTP/3 transport ends an in-flight exchange at the attempt deadline (finding + * 05-06). + * + *

      Jetty's idle timeouts are per gap, like Apache's, so an upstream that drips a byte every 50 ms + * held the HTTP/3 transport past the total budget for as long as it liked. The configuration under + * test is the one {@link JettyHttp3TransportProvider} applies to its QUIC client; it is exercised + * here over TCP because a test cannot stand up a QUIC server, and the abort it installs does not + * depend on the wire. + */ +class JettyAttemptDeadlineTest { + + private static final Duration DEADLINE = Duration.ofSeconds(1); + private static final Duration TOLERANCE = Duration.ofMillis(500); + + @Test + @DisplayName("Jetty 클라이언트는 바이트를 조금씩 흘리는 응답이라도 attempt deadline에 교환을 끊는다") + void aSlowDripExchangeIsAbortedAtTheAttemptDeadline() throws Exception { + HttpClient client = + JettyHttp3TransportProvider.configure( + new HttpClient(), ClientProfiles.http3Experimental("edge")); + client.start(); + try (MockHttpServer server = MockHttpServer.start()) { + // given + server.enqueueSlowDripBody(200, 100, Duration.ofMillis(50)); + JettyClientHttpRequestFactory factory = new JettyClientHttpRequestFactory(client); + long started = System.nanoTime(); + + // when + Throwable failure; + try (AttemptDeadline.Scope scope = AttemptDeadline.open(DEADLINE)) { + failure = + catchThrowable( + () -> { + try (ClientHttpResponse response = + factory.createRequest(server.uri("/slow"), HttpMethod.GET).execute()) { + response.getBody().readAllBytes(); + } + }); + } + + // then + Duration elapsed = Duration.ofNanos(System.nanoTime() - started); + assertThat(failure).isInstanceOf(IOException.class); + assertThat(elapsed).isLessThan(DEADLINE.plus(TOLERANCE)); + } finally { + client.stop(); + } + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfileValidatorTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfileValidatorTest.java index 8a618011..14436739 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfileValidatorTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientProfileValidatorTest.java @@ -6,7 +6,10 @@ import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; import java.net.URI; import java.time.Duration; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; class ClientProfileValidatorTest { @@ -82,6 +85,141 @@ class ClientProfileValidatorTest { .contains("BASE_URL_USERINFO_FORBIDDEN", "BASE_URL_QUERY_FORBIDDEN"); } + @ParameterizedTest(name = "{0}") + @ValueSource( + strings = { + "connect", + "tls-handshake", + "response-header", + "read-idle", + "total-call", + "pool.pending-acquire-timeout" + }) + @DisplayName("0인 timeout은 엔진에서 무한 대기가 되므로 시작 시 거부한다") + void aZeroTimeoutIsRefusedAtStartup(String setting) { + // given + ClientProfile profile = withZero(setting); + + // when + List violations = + validator.validate(profile, RuntimeEnvironment.NON_PRODUCTION); + + // then + assertThat(violations) + .extracting(ClientProfileViolation::code, ClientProfileViolation::detail) + .contains( + org.assertj.core.groups.Tuple.tuple( + "TIMEOUT_NOT_POSITIVE", + "profile=payment setting=" + + (setting.startsWith("pool.") ? setting : "timeout." + setting))); + } + + @Test + @DisplayName("최대 시도 횟수가 상한 5를 넘으면 시작 시 거부한다") + void maxAttemptsAboveTheCeilingAreRefused() { + // given + ClientProfile profile = ClientProfiles.builder("payment").retryEnabled(6).build(); + + // when + List violations = + validator.validate(profile, RuntimeEnvironment.NON_PRODUCTION); + + // then + assertThat(violations) + .extracting(ClientProfileViolation::code) + .contains("RETRY_MAX_ATTEMPTS_EXCEEDED"); + } + + @Test + @DisplayName("최대 시도 횟수가 상한 5이면 받아들인다") + void maxAttemptsAtTheCeilingAreAccepted() { + // given + ClientProfile profile = ClientProfiles.builder("payment").retryEnabled(5).build(); + + // when + List violations = + validator.validate(profile, RuntimeEnvironment.NON_PRODUCTION); + + // then + assertThat(violations) + .extracting(ClientProfileViolation::code) + .doesNotContain("RETRY_MAX_ATTEMPTS_EXCEEDED"); + } + + @Test + @DisplayName("창보다 큰 최소 호출 수와 0% 실패율 기준은 circuit-breaker 설정 오류로 거부한다") + void incoherentCircuitBreakerSettingsAreRefused() { + // given + ClientProfile profile = + ClientProfiles.builder("payment") + .circuitBreaker(new CircuitBreakerSettings(0, 20, 10, Duration.ofSeconds(30), 1)) + .build(); + + // when + List violations = + validator.validate(profile, RuntimeEnvironment.NON_PRODUCTION); + + // then + assertThat(violations) + .extracting(ClientProfileViolation::code, ClientProfileViolation::detail) + .contains( + org.assertj.core.groups.Tuple.tuple( + "CIRCUIT_BREAKER_SETTING_INVALID", + "profile=payment setting=circuit-breaker.failure-rate-threshold"), + org.assertj.core.groups.Tuple.tuple( + "CIRCUIT_BREAKER_SETTING_INVALID", + "profile=payment setting=circuit-breaker.minimum-number-of-calls")); + } + + @Test + @DisplayName("circuit-breaker 기본값은 라이브러리 기본값과 같고 그대로 받아들인다") + void defaultCircuitBreakerSettingsAreAccepted() { + // given + ClientProfile profile = ClientProfiles.builder("payment").build(); + + // when + List violations = + validator.validate(profile, RuntimeEnvironment.NON_PRODUCTION); + + // then + assertThat(profile.circuitBreaker()) + .isEqualTo(new CircuitBreakerSettings(50, 100, 100, Duration.ofSeconds(60), 10)); + assertThat(violations) + .extracting(ClientProfileViolation::code) + .doesNotContain("CIRCUIT_BREAKER_SETTING_INVALID"); + } + + private static ClientProfile withZero(String setting) { + TimeoutSettings t = ClientProfiles.timeouts(); + Duration zero = Duration.ZERO; + if (setting.equals("pool.pending-acquire-timeout")) { + PoolSettings p = ClientProfiles.pool(); + return ClientProfiles.builder("payment") + .pool( + new PoolSettings( + p.maxTotalConnections(), + p.maxConnectionsPerRoute(), + p.maxPendingAcquires(), + zero, + p.maxIdleTime(), + p.maxLifeTime(), + p.validateAfterInactivity(), + p.requiresRoutePool(), + p.requiresBoundedPendingQueue())) + .build(); + } + return ClientProfiles.builder("payment") + .timeout( + new TimeoutSettings( + t.dns(), + setting.equals("connect") ? zero : t.connect(), + setting.equals("tls-handshake") ? zero : t.tlsHandshake(), + setting.equals("response-header") ? zero : t.responseHeader(), + setting.equals("read-idle") ? zero : t.readIdle(), + setting.equals("total-call") ? zero : t.totalCall())) + .build(); + } + @Test void violationOrderIsDeterministic() { List first = diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/RetryEligibilityEngineTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/RetryEligibilityEngineTest.java index 0906157f..46cd6e99 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/RetryEligibilityEngineTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/RetryEligibilityEngineTest.java @@ -8,6 +8,7 @@ import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; import dev.caskeleton.adapter.outbound.httpclient.api.operation.OperationIdempotency; import dev.caskeleton.adapter.outbound.httpclient.testkit.RetryContexts; import java.util.Set; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -67,6 +68,47 @@ class RetryEligibilityEngineTest { .isEqualTo(RetryDenied.runtimeDraining()); } + @ParameterizedTest + @ValueSource(ints = {1, 3}) + @DisplayName("응답 없이 끊긴 비멱등 요청은 시도 횟수를 다 썼어도 결과 불명으로 판정한다") + void aSentNonIdempotentRequestWithoutAResponseIsAmbiguousEvenWhenAttemptsAreExhausted( + int maxAttempts) { + // given + RetryContext context = + RetryContexts.builder() + .idempotency(OperationIdempotency.NON_IDEMPOTENT) + .evidence(ExecutionEvidence.SENT_NO_RESPONSE) + .failureCategory(FailureCategory.RESPONSE_TIMEOUT) + .attempt(maxAttempts) + .maxAttempts(maxAttempts) + .build(); + + // when + RetryDecision decision = engine.decide(context); + + // then + assertThat(decision).isInstanceOf(AmbiguousFailure.class); + } + + @Test + @DisplayName("응답 없이 끊긴 비멱등 요청은 재시도 예산이 바닥났어도 결과 불명으로 판정한다") + void aSentNonIdempotentRequestWithoutAResponseIsAmbiguousEvenWithoutRetryBudget() { + // given + RetryContext context = + RetryContexts.builder() + .idempotency(OperationIdempotency.NON_IDEMPOTENT) + .evidence(ExecutionEvidence.SENT_NO_RESPONSE) + .failureCategory(FailureCategory.RESPONSE_TIMEOUT) + .budget(RetryBudgetSnapshot.exhausted()) + .build(); + + // when + RetryDecision decision = engine.decide(context); + + // then + assertThat(decision).isInstanceOf(AmbiguousFailure.class); + } + @Test void deniesWhenAttemptsAreExhausted() { assertThat(engine.decide(RetryContexts.builder().attempt(3).maxAttempts(3).build())) diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/AttemptDeadlineEnforcementTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/AttemptDeadlineEnforcementTest.java index 70cba6c5..02e0d264 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/AttemptDeadlineEnforcementTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/AttemptDeadlineEnforcementTest.java @@ -72,8 +72,6 @@ class AttemptDeadlineEnforcementTest { base.dns(), base.connect(), base.tlsHandshake(), - base.proxyConnect(), - base.requestWriteIdle(), base.responseHeader(), base.readIdle(), totalCall); diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingLifecycleTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingLifecycleTest.java index 0f841cd7..ed00ac7a 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingLifecycleTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingLifecycleTest.java @@ -39,8 +39,6 @@ class BlockingStreamingLifecycleTest { Duration.ofSeconds(30), Duration.ofMinutes(5), Duration.ofSeconds(5), - Duration.ofSeconds(15), - Duration.ofSeconds(5), false, false)) .response( diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java index c284d6af..adb33f86 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java @@ -7,9 +7,13 @@ import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpCircuitOpenException; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException; import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; +import dev.caskeleton.adapter.outbound.httpclient.api.result.HttpCallResult; import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType; +import dev.caskeleton.adapter.outbound.httpclient.profile.CircuitBreakerSettings; +import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; +import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -26,6 +30,7 @@ class CircuitBreakerStatusAccountingTest { private static final int CALLS = 200; private static final int LIBRARY_DEFAULT_WINDOW = 100; + private static final int SMALL_WINDOW = 5; @Test @DisplayName("정상 응답인 404가 200번 이어져도 circuit이 열리지 않고 모든 호출이 상대 서버에 닿는다") @@ -78,6 +83,91 @@ class CircuitBreakerStatusAccountingTest { } } + @Test + @DisplayName("결과 반환 정책에서도 503이 창 하나를 채우면 circuit이 열려 다음 호출은 상대 서버에 보내지 않는다") + void aWindowOfServiceUnavailableResultsOpensTheCircuitUnderTheReturnResultPolicy() + throws Exception { + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = TestGateways.apache(server.uri("/"))) { + // given + List windowStatuses = new ArrayList<>(); + for (int i = 0; i < LIBRARY_DEFAULT_WINDOW; i++) { + server.enqueueStatus(503); + windowStatuses.add(getUserAsResult(harness).status().value()); + } + assertThat(windowStatuses).containsOnly(503); + + // when + Throwable next = catchThrowable(() -> getUserAsResult(harness)); + + // then + assertThat(next).isInstanceOf(HttpCircuitOpenException.class); + assertThat(server.requestCount()).isEqualTo(LIBRARY_DEFAULT_WINDOW); + } + } + + @Test + @DisplayName("결과 반환 정책에서 404가 200번 이어져도 circuit이 열리지 않는다") + void aRunOfNotFoundResultsNeverOpensTheCircuitUnderTheReturnResultPolicy() throws Exception { + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = TestGateways.apache(server.uri("/"))) { + // given + for (int i = 0; i < CALLS; i++) { + server.enqueueStatus(404); + } + List failures = new ArrayList<>(); + + // when + for (int i = 0; i < CALLS; i++) { + failures.add(catchThrowable(() -> getUserAsResult(harness))); + } + + // then + assertThat(failures).containsOnlyNulls(); + assertThat(server.requestCount()).isEqualTo(CALLS); + } + } + + @Test + @DisplayName("프로필에 적은 circuit-breaker 창과 최소 호출 수로 circuit이 열린다") + void theProfileBreakerSettingsDecideWhenTheCircuitOpens() throws Exception { + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = + TestGateways.forProfile( + ClientProfiles.builder("small-window") + .baseUrl(server.uri("/")) + .circuitBreaker( + new CircuitBreakerSettings( + 50, SMALL_WINDOW, SMALL_WINDOW, Duration.ofMinutes(1), 1)) + .build())) { + // given + List windowFailures = new ArrayList<>(); + for (int i = 0; i < SMALL_WINDOW; i++) { + server.enqueueStatus(503); + windowFailures.add(catchThrowable(() -> getUser(harness))); + } + assertThat(windowFailures) + .allSatisfy(f -> assertThat(f).isInstanceOf(HttpRemoteErrorException.class)); + + // when + Throwable next = catchThrowable(() -> getUser(harness)); + + // then + assertThat(next).isInstanceOf(HttpCircuitOpenException.class); + assertThat(server.requestCount()).isEqualTo(SMALL_WINDOW); + } + } + + private static HttpCallResult getUserAsResult(TestGateways.Harness harness) { + return harness + .gateway() + .exchange( + harness.profile().name(), + HttpOperation.get(new OperationName("get-user"), "/users/1", Map.of()), + ResponseType.of(String.class), + StatusHandlingPolicy.RETURN_RESULT); + } + private static void getUser(TestGateways.Harness harness) { harness .gateway() diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGatewayTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGatewayTest.java index b1ed53be..9adab8fe 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGatewayTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/DefaultGenericHttpGatewayTest.java @@ -350,8 +350,6 @@ class DefaultGenericHttpGatewayTest { base.maxIdleTime(), base.maxLifeTime(), base.validateAfterInactivity(), - base.evictionInterval(), - base.shutdownTimeout(), false, false); } diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ExecutionEvidenceGatewayTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ExecutionEvidenceGatewayTest.java new file mode 100644 index 00000000..6e236f24 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ExecutionEvidenceGatewayTest.java @@ -0,0 +1,304 @@ +package dev.caskeleton.adapter.outbound.httpclient.restclient; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.httpclient.apache.ApacheFailureClassifier; +import dev.caskeleton.adapter.outbound.httpclient.api.HttpMethod; +import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; +import dev.caskeleton.adapter.outbound.httpclient.api.body.ObjectBody; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpAmbiguousExecutionException; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpClientException; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.OperationIdempotency; +import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType; +import dev.caskeleton.adapter.outbound.httpclient.auth.CredentialProviderRegistry; +import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; +import dev.caskeleton.adapter.outbound.httpclient.profile.RuntimeGeneration; +import dev.caskeleton.adapter.outbound.httpclient.profile.TimeoutSettings; +import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; +import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; +import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; +import dev.caskeleton.adapter.outbound.httpclient.transport.BlockingTransportCapabilities; +import dev.caskeleton.adapter.outbound.httpclient.transport.BlockingTransportProvider; +import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureClassifier; +import dev.caskeleton.adapter.outbound.httpclient.transport.TransportId; +import dev.caskeleton.adapter.outbound.httpclient.transport.TransportLifecycleListener; +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URI; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.apache.hc.core5.http2.H2Error; +import org.apache.hc.core5.http2.H2StreamResetException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpHeaders; +import org.springframework.http.client.AbstractBufferingClientHttpRequest; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.ClientHttpResponse; + +/** + * What the caller is told about whether a failed request reached the upstream (finding 05-14). + * + *

      Asserted at the gateway, through the real executor, because each of the three defects lived in + * the hand-off between two classes that were correct on their own: the retry table decided "out of + * attempts" before "outcome unknown", the executor advanced the attempt stage before the transport + * had connected, and the exception mapper replaced the evidence the executor had just computed. + */ +class ExecutionEvidenceGatewayTest { + + @Test + @DisplayName("응답 없이 끊긴 비멱등 POST는 재시도가 꺼진 기본 프로필에서도 결과 불명 예외로 끝난다") + void aNonIdempotentPostWithoutAResponseIsAmbiguousEvenWithASingleAttempt() throws Exception { + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = + TestGateways.forProfile( + ClientProfiles.builder("orders") + .baseUrl(server.uri("/")) + .timeout(withResponseHeader(Duration.ofMillis(300))) + .build())) { + // given + server.enqueueNoResponse(); + + // when + Throwable failure = + catchThrowable( + () -> + harness + .gateway() + .exchange(harness.profile().name(), createOrder(), ResponseType.empty())); + + // then + assertThat(failure).isInstanceOf(HttpAmbiguousExecutionException.class); + assertThat(((HttpClientException) failure).metadata().evidence()) + .isEqualTo(ExecutionEvidence.SENT_NO_RESPONSE); + assertThat(server.requestCount()).isEqualTo(1); + } + } + + @Test + @DisplayName("TLS handshake가 시간 초과로 끝나면 요청은 보내지 않은 것으로 분류된다") + void aTlsHandshakeTimeoutIsClassifiedAsNotSent() throws Exception { + try (SilentTlsPeer peer = SilentTlsPeer.start(); + TestGateways.Harness harness = + TestGateways.forProfile( + ClientProfiles.builder("silent-tls").baseUrl(peer.uri()).build())) { + // given + HttpOperation post = createOrder(); + + // when + Throwable failure = + catchThrowable( + () -> + harness.gateway().exchange(harness.profile().name(), post, ResponseType.empty())); + + // then + assertThat(failure) + .isInstanceOf(HttpClientException.class) + .isNotInstanceOf(HttpAmbiguousExecutionException.class); + assertThat(((HttpClientException) failure).metadata().evidence()) + .isEqualTo(ExecutionEvidence.NOT_SENT); + } + } + + /** + * A TLS failure the engine reports only as a plain {@code SSLException} is still a pre-send + * failure. The peer answers the ClientHello with plaintext, so the handshake fails before a byte + * of the request exists. The executor used to mark the attempt as writing before it called the + * engine, so the classifier's "TLS failed before the request" branch could not match and the POST + * was reported as sent with its outcome unknown. + */ + @Test + @DisplayName("TLS 대신 평문으로 답하는 상대 때문에 handshake가 실패한 POST는 보내지 않은 것으로 분류된다") + void aHandshakeRejectedWithPlaintextIsClassifiedAsNotSent() throws Exception { + try (SilentTlsPeer peer = SilentTlsPeer.answeringPlaintext(); + TestGateways.Harness harness = + TestGateways.forProfile( + ClientProfiles.builder("plaintext-peer").baseUrl(peer.uri()).build())) { + // given + HttpOperation post = createOrder(); + + // when + Throwable failure = + catchThrowable( + () -> + harness.gateway().exchange(harness.profile().name(), post, ResponseType.empty())); + + // then + assertThat(failure) + .isInstanceOf(HttpClientException.class) + .isNotInstanceOf(HttpAmbiguousExecutionException.class); + assertThat(((HttpClientException) failure).metadata().evidence()) + .isEqualTo(ExecutionEvidence.NOT_SENT); + } + } + + @Test + @DisplayName("HTTP/2 REFUSED_STREAM 증거는 예외 변환 뒤에도 보내지 않음으로 남는다") + void anHttp2RefusedStreamStaysNotSentAfterExceptionMapping() { + // given + ClientProfile profile = ClientProfiles.builder("refusing").build(); + RefusingTransport transport = new RefusingTransport(); + + // when + Throwable failure; + try (TestGateways.Harness harness = + TestGateways.forProfile(profile, CredentialProviderRegistry.withNoAuth(), transport)) { + failure = + catchThrowable( + () -> + harness + .gateway() + .exchange( + profile.name(), + HttpOperation.get(new OperationName("get-user"), "/users/1", Map.of()), + ResponseType.of(String.class))); + } + + // then + assertThat(failure).isInstanceOf(HttpClientException.class); + assertThat(((HttpClientException) failure).metadata().evidence()) + .isEqualTo(ExecutionEvidence.NOT_SENT); + } + + private static HttpOperation createOrder() { + return new HttpOperation( + new OperationName("create-order"), + HttpMethod.POST, + "/orders", + Map.of(), + Map.of(), + ObjectBody.json(Map.of("sku", "a-1")), + OperationIdempotency.NON_IDEMPOTENT, + Optional.empty(), + Optional.empty()); + } + + private static TimeoutSettings withResponseHeader(Duration responseHeader) { + TimeoutSettings base = ClientProfiles.timeouts(); + return new TimeoutSettings( + base.dns(), + base.connect(), + base.tlsHandshake(), + responseHeader, + base.readIdle(), + base.totalCall()); + } + + /** + * Accepts TCP connections and either never says a word, so a TLS client waits for a ServerHello, + * or answers in plaintext, so the client's handshake fails on an unrecognised record. + */ + private static final class SilentTlsPeer implements AutoCloseable { + + private final ServerSocket server; + private final boolean answerPlaintext; + private final List accepted = new ArrayList<>(); + private final Thread acceptor; + + private SilentTlsPeer(ServerSocket server, boolean answerPlaintext) { + this.server = server; + this.answerPlaintext = answerPlaintext; + this.acceptor = Thread.ofVirtual().start(this::acceptForever); + } + + static SilentTlsPeer start() throws IOException { + return new SilentTlsPeer(new ServerSocket(0, 50, InetAddress.getLoopbackAddress()), false); + } + + /** Answers every connection with a plaintext HTTP response instead of a ServerHello. */ + static SilentTlsPeer answeringPlaintext() throws IOException { + return new SilentTlsPeer(new ServerSocket(0, 50, InetAddress.getLoopbackAddress()), true); + } + + URI uri() { + return URI.create("https://localhost:" + server.getLocalPort() + "/"); + } + + private void acceptForever() { + while (!server.isClosed()) { + try { + Socket socket = server.accept(); + synchronized (accepted) { + accepted.add(socket); + } + if (answerPlaintext) { + socket + .getOutputStream() + .write( + "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n" + .getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + socket.getOutputStream().flush(); + } + } catch (IOException closed) { + return; + } + } + } + + @Override + public void close() throws Exception { + server.close(); + acceptor.join(Duration.ofSeconds(1)); + synchronized (accepted) { + for (Socket socket : accepted) { + socket.close(); + } + } + } + } + + /** Fails every exchange the way HC5 reports an HTTP/2 stream the server refused to process. */ + private static final class RefusingTransport implements BlockingTransportProvider { + + @Override + public TransportId id() { + return new TransportId("refusing"); + } + + @Override + public BlockingTransportCapabilities capabilities() { + return BlockingTransportCapabilities.apacheClassic(); + } + + @Override + public ClientHttpRequestFactory create( + ClientProfile profile, RuntimeGeneration generation, TransportLifecycleListener listener) { + return (uri, method) -> + new AbstractBufferingClientHttpRequest() { + @Override + public org.springframework.http.HttpMethod getMethod() { + return method; + } + + @Override + public URI getURI() { + return uri; + } + + @Override + protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] body) + throws IOException { + throw new IOException( + "stream refused", + new H2StreamResetException(H2Error.REFUSED_STREAM, "refused by peer")); + } + }; + } + + @Override + public TransportFailureClassifier failureClassifier() { + return new ApacheFailureClassifier(); + } + + @Override + public void close(ClientProfile profile, RuntimeGeneration generation) {} + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/RetryBudgetAssignmentTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/RetryBudgetAssignmentTest.java new file mode 100644 index 00000000..1f43a8ac --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/RetryBudgetAssignmentTest.java @@ -0,0 +1,58 @@ +package dev.caskeleton.adapter.outbound.httpclient.restclient; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; +import dev.caskeleton.adapter.outbound.httpclient.profile.JitterStrategy; +import dev.caskeleton.adapter.outbound.httpclient.profile.RetryAfterPolicy; +import dev.caskeleton.adapter.outbound.httpclient.profile.RetrySettings; +import dev.caskeleton.adapter.outbound.httpclient.resilience.RetryBudgetSnapshot; +import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; +import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; +import java.net.URI; +import java.time.Duration; +import java.util.Optional; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Every retrying profile has a bounded retry budget (finding 05-15). + * + *

      A profile that named no budget used to get an unlimited one, so the only thing standing + * between a failing upstream and a retry storm was each caller's attempt count — the per-upstream + * ceiling the budget exists to provide was absent exactly when nobody had thought about it. + */ +class RetryBudgetAssignmentTest { + + @Test + @DisplayName("budget 이름을 적지 않은 재시도 프로필도 pool 크기에서 나온 유한한 재시도 예산을 갖는다") + void aRetryingProfileWithoutABudgetNameGetsABoundedBudget() { + // given + ClientProfile profile = + ClientProfiles.builder("unnamed-budget") + .baseUrl(URI.create("https://payment.example.com")) + .retry( + new RetrySettings( + "default", + 3, + Duration.ofMillis(50), + Duration.ofMillis(200), + JitterStrategy.FULL, + RetryAfterPolicy.HONOR, + Optional.empty())) + .build(); + + // when + RetryBudgetSnapshot snapshot; + try (TestGateways.Harness harness = TestGateways.forProfile(profile)) { + snapshot = + ((BlockingClientRuntime) harness.registry().current(profile.name())) + .retryBudget() + .snapshot(); + } + + // then + long poolDerivedCapacity = ClientProfiles.pool().maxTotalConnections() / 10L; + assertThat(snapshot.capacity()).isEqualTo(poolDerivedCapacity); + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingSetupDeadlineTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingSetupDeadlineTest.java new file mode 100644 index 00000000..9c85615e --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingSetupDeadlineTest.java @@ -0,0 +1,93 @@ +package dev.caskeleton.adapter.outbound.httpclient.restclient; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; +import dev.caskeleton.adapter.outbound.httpclient.api.result.BlockingStreamingResponse; +import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; +import dev.caskeleton.adapter.outbound.httpclient.profile.ResponseLimits; +import dev.caskeleton.adapter.outbound.httpclient.profile.TimeoutSettings; +import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType; +import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; +import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; +import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +/** + * A streaming download's setup — everything up to the response headers — runs inside the call's + * total budget (finding 05-06, design §15.3). + * + *

      The design separates a stream's setup from its life: the total budget bounds setup, and once + * the headers arrive the read-idle timeout bounds each gap of the body, because a download may + * legitimately outlast any fixed total. Before this the streaming gateway opened no deadline scope + * at all, so its setup was bounded only by the per-gap stage timeouts. + * + *

      The upstream holds its headers back for 1.8 s: shorter than the 2 s response-header timeout, + * longer than the 1 s total budget, so only the budget can end the setup on time. + */ +class StreamingSetupDeadlineTest { + + private static final Duration TOTAL_CALL = Duration.ofSeconds(1); + private static final Duration HEADERS_DELAY = Duration.ofMillis(1800); + private static final Duration TOLERANCE = Duration.ofMillis(500); + + @ParameterizedTest(name = "{0}") + @EnumSource( + value = TransportType.class, + names = {"APACHE", "JDK"}) + @DisplayName("헤더를 늦게 보내는 상대 서버라도 스트리밍 다운로드 준비는 전체 시간 예산 안에 deadline 초과로 끝난다") + void aStreamingSetupThatOutlastsTheBudgetEndsAtTheDeadline(TransportType transport) + throws Exception { + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = TestGateways.forProfile(profile(server, transport))) { + // given + server.enqueueDelayedHeaders( + 200, "application/octet-stream", "late".getBytes(StandardCharsets.UTF_8), HEADERS_DELAY); + BlockingStreamingGateway gateway = new BlockingStreamingGateway(harness.registry()); + long started = System.nanoTime(); + + // when + Throwable failure = + catchThrowable( + () -> { + try (BlockingStreamingResponse response = + gateway.download( + harness.profile().name(), + HttpOperation.get(new OperationName("download"), "/late", Map.of()))) { + response.body().readAllBytes(); + } + }); + + // then + Duration elapsed = Duration.ofNanos(System.nanoTime() - started); + assertThat(failure).isInstanceOf(HttpDeadlineExceededException.class); + assertThat(elapsed).isLessThan(TOTAL_CALL.plus(TOLERANCE)); + } + } + + private static ClientProfile profile(MockHttpServer server, TransportType transport) { + TimeoutSettings base = ClientProfiles.timeouts(); + return ClientProfiles.builder("streaming-setup") + .baseUrl(server.uri("/")) + .transport(transport) + .timeout( + new TimeoutSettings( + base.dns(), + base.connect(), + base.tlsHandshake(), + base.responseHeader(), + base.readIdle(), + TOTAL_CALL)) + .response(new ResponseLimits(1024, 1024, Set.of("application/octet-stream"))) + .build(); + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/UnauthorizedRefreshTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/UnauthorizedRefreshTest.java new file mode 100644 index 00000000..3fc162be --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/UnauthorizedRefreshTest.java @@ -0,0 +1,108 @@ +package dev.caskeleton.adapter.outbound.httpclient.restclient; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; +import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType; +import dev.caskeleton.adapter.outbound.httpclient.auth.CredentialProviderRegistry; +import dev.caskeleton.adapter.outbound.httpclient.auth.NoAuthCredentialProvider; +import dev.caskeleton.adapter.outbound.httpclient.profile.AuthenticationSettings; +import dev.caskeleton.adapter.outbound.httpclient.profile.AuthenticationType; +import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; +import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; +import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; +import dev.caskeleton.adapter.outbound.httpclient.testkit.RecordingCredentialProvider; +import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * A 401 refreshes the credential only when the refreshed credential will be used (finding 05-23g). + * + *

      The refresh used to run while the retry context was being assembled, before the retry engine + * had decided anything. A profile that cannot retry at all (the default, one attempt) still + * invalidated its token cache and fetched a new token on every 401 — a token-endpoint call per + * rejected request, for a token nothing would send. + */ +class UnauthorizedRefreshTest { + + @Test + @DisplayName("다시 보낼 수 없는 프로필은 401을 받아도 토큰을 새로 받지 않는다") + void aProfileThatCannotRetryDoesNotRefreshItsTokenOnUnauthorized() throws Exception { + RecordingCredentialProvider credentials = new RecordingCredentialProvider(); + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = + TestGateways.forProfile(bearerProfile(server, 1), registry(credentials))) { + // given + server.enqueueStatus(401); + + // when + Throwable failure = catchThrowable(() -> getUser(harness)); + + // then + assertThat(failure).isInstanceOf(HttpRemoteErrorException.class); + assertThat(server.requestCount()).isEqualTo(1); + assertThat(credentials.invalidations()).isZero(); + assertThat(credentials.resolves()).isEqualTo(1); + } + } + + @Test + @DisplayName("다시 보낼 수 있는 프로필은 401 뒤에 토큰을 한 번 새로 받아 다시 보낸다") + void aProfileThatCanRetryRefreshesItsTokenOnceBeforeTheReplay() throws Exception { + RecordingCredentialProvider credentials = new RecordingCredentialProvider(); + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = + TestGateways.forProfile(bearerProfile(server, 2), registry(credentials))) { + // given + server.enqueueStatus(401); + server.enqueueJson(200, "\"ok\""); + + // when + String body = getUser(harness); + + // then + assertThat(body).contains("ok"); + assertThat(server.requestCount()).isEqualTo(2); + assertThat(credentials.invalidations()).isEqualTo(1); + assertThat(credentials.resolves()).isEqualTo(2); + } + } + + private static ClientProfile bearerProfile(MockHttpServer server, int maxAttempts) { + ClientProfiles.Builder builder = + ClientProfiles.builder("bearer") + .baseUrl(server.uri("/")) + .authentication( + new AuthenticationSettings( + AuthenticationType.STATIC_BEARER, + Optional.empty(), + Set.of(), + Optional.empty(), + Optional.empty(), + Optional.of("secret://token"))); + return maxAttempts > 1 ? builder.retryEnabled(maxAttempts).build() : builder.build(); + } + + private static CredentialProviderRegistry registry(RecordingCredentialProvider credentials) { + return new CredentialProviderRegistry() + .register(new NoAuthCredentialProvider()) + .register(credentials); + } + + private static String getUser(TestGateways.Harness harness) { + return harness + .gateway() + .exchange( + harness.profile().name(), + HttpOperation.get(new OperationName("get-user"), "/users/1", Map.of()), + ResponseType.of(String.class)) + .body(); + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ForwardProxyContractTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ForwardProxyContractTest.java index 40aa30ab..e76ec37a 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ForwardProxyContractTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ForwardProxyContractTest.java @@ -9,7 +9,6 @@ import dev.caskeleton.adapter.outbound.httpclient.profile.ProxySettings; import dev.caskeleton.adapter.outbound.httpclient.profile.ProxyType; import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType; import java.nio.charset.StandardCharsets; -import java.time.Duration; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.Test; @@ -49,7 +48,6 @@ class ForwardProxyContractTest { proxy.port(), ProxyType.HTTP, Optional.empty(), - Duration.ofSeconds(1), false)) .build())) { upstream.enqueueJson(200, "{\"id\":7,\"name\":\"proxied\"}"); diff --git a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ClientProfiles.java b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ClientProfiles.java index f6407361..fecbdf8b 100644 --- a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ClientProfiles.java +++ b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ClientProfiles.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.httpclient.testkit; import dev.caskeleton.adapter.outbound.httpclient.api.ClientProfileName; import dev.caskeleton.adapter.outbound.httpclient.profile.AuthenticationSettings; import dev.caskeleton.adapter.outbound.httpclient.profile.AuthenticationType; +import dev.caskeleton.adapter.outbound.httpclient.profile.CircuitBreakerSettings; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientMode; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientObservabilitySettings; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; @@ -37,8 +38,6 @@ public final class ClientProfiles { Duration.ofSeconds(30), Duration.ofMinutes(5), Duration.ofSeconds(5), - Duration.ofSeconds(15), - Duration.ofSeconds(5), false, false); } @@ -48,8 +47,6 @@ public final class ClientProfiles { Duration.ofMillis(300), Duration.ofMillis(500), Duration.ofSeconds(1), - Duration.ofMillis(500), - Duration.ofSeconds(1), Duration.ofSeconds(2), Duration.ofSeconds(3), Duration.ofSeconds(4)); @@ -105,8 +102,6 @@ public final class ClientProfiles { base.dns(), connect, base.tlsHandshake(), - base.proxyConnect(), - base.requestWriteIdle(), Duration.ofMillis(200), base.readIdle(), totalCall)) @@ -126,8 +121,6 @@ public final class ClientProfiles { base.maxIdleTime(), base.maxLifeTime(), base.validateAfterInactivity(), - base.evictionInterval(), - base.shutdownTimeout(), true, true)) .build(); @@ -180,6 +173,7 @@ public final class ClientProfiles { private ResponseLimits response = ClientProfiles.responseLimits(); private AuthenticationSettings authentication = AuthenticationSettings.none(); private RetrySettings retry = RetrySettings.none(); + private CircuitBreakerSettings circuitBreaker = CircuitBreakerSettings.defaults(); private ClientObservabilitySettings observability = ClientObservabilitySettings.safeDefaults(); private TlsSettings tls = new TlsSettings( @@ -281,6 +275,11 @@ public final class ClientProfiles { return this; } + public Builder circuitBreaker(CircuitBreakerSettings value) { + this.circuitBreaker = value; + return this; + } + public Builder observability(ClientObservabilitySettings value) { this.observability = value; return this; @@ -317,6 +316,7 @@ public final class ClientProfiles { response, authentication, retry, + circuitBreaker, observability, tls, proxy, diff --git a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/MockHttpServer.java b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/MockHttpServer.java index ec333e96..918a93b6 100644 --- a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/MockHttpServer.java +++ b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/MockHttpServer.java @@ -151,6 +151,21 @@ public final class MockHttpServer implements AutoCloseable { .setBodyDelay(delay.toMillis(), TimeUnit.MILLISECONDS)); } + /** + * Holds the status line and headers back for {@code delay}; drives setup-deadline tests. + * + *

      The delay is one gap, so a test profile whose response-header timeout is longer than the + * delay sees only its total budget end the exchange. + */ + public void enqueueDelayedHeaders(int status, String contentType, byte[] body, Duration delay) { + server.enqueue( + new MockResponse() + .setResponseCode(status) + .setHeader("Content-Type", contentType) + .setBody(new okio.Buffer().write(body)) + .setHeadersDelay(delay.toMillis(), TimeUnit.MILLISECONDS)); + } + /** * Sends headers at once, then the body one byte per {@code gap}; drives total-deadline tests. * diff --git a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ResourceLifecycleContract.java b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ResourceLifecycleContract.java index fc962f6a..a53cc0f9 100644 --- a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ResourceLifecycleContract.java +++ b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ResourceLifecycleContract.java @@ -40,8 +40,6 @@ public final class ResourceLifecycleContract { Duration.ofSeconds(30), Duration.ofMinutes(5), Duration.ofSeconds(5), - Duration.ofSeconds(15), - Duration.ofSeconds(5), false, false)) .response( diff --git a/src/adapter/outbound/identifier/CLAUDE.md b/src/adapter/outbound/identifier/CLAUDE.md index b33f69b0..f89d9805 100644 --- a/src/adapter/outbound/identifier/CLAUDE.md +++ b/src/adapter/outbound/identifier/CLAUDE.md @@ -5,7 +5,7 @@ - Module ID: `adapter-outbound-identifier` - Gradle path: `:adapter:outbound:identifier` - Focused test (derived from Gradle path): `./gradlew :adapter:outbound:identifier:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. +- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.8. - Registry SSOT: `src/config/architecture/modules.json`. Package root: `dev.caskeleton.adapter.outbound.identifier`. @@ -15,13 +15,14 @@ build choices) live in [README.md](README.md). ## Responsibility -- Driven adapters for capabilities with **no external-system integration**: - identifier generation/encoding today, and clock / crypto/random sources by the - same rationale (feature-resource-identifier-contract §4 taxonomy). -- `HmacUserPrincipalPseudonymizer` — `UserPrincipalPseudonymizerPort` implementation. -- Kept out of `adapter-outbound` on purpose: a UUID id/codec capability is - infrastructure, not an outbound integration point, so `adapter-outbound` keeps its - documented meaning (external HTTP / messaging / cache / notifications). +- `HmacUserPrincipalPseudonymizer` — the `UserPrincipalPseudonymizerPort` implementation + (HMAC-SHA-256 of the UTF-8 principal, lowercase hex). +- `UuidV7DurableOperationIdFactory` — `DurableOperationIdFactory` implementation (UUIDv7 via + `uuid-creator`). The operation id is also the submission event's id, and the messaging platform's + message id accepts only UUIDv7 (review 2026-11-01 06-06). Wired by `composition:durable-operation`. +- The leaf name says "identifier"; general identifier generation, clock and random sources are not here. + The name is kept because Gradle paths and consumers use it (README, review 05-21). +- Wiring is `composition/service-runtime` (`PseudonymizationConfig`), not this leaf. ## Allowed @@ -38,7 +39,8 @@ build choices) live in [README.md](README.md). ## Test -Pure unit tests, no Spring context (`HmacUserPrincipalPseudonymizerTest`). +Pure unit tests, no Spring context (`HmacUserPrincipalPseudonymizerTest`, including the RFC 4231 +known-answer vector). ```bash cd src diff --git a/src/adapter/outbound/identifier/README.md b/src/adapter/outbound/identifier/README.md index b9d9f4d6..f63eca2f 100644 --- a/src/adapter/outbound/identifier/README.md +++ b/src/adapter/outbound/identifier/README.md @@ -1,50 +1,51 @@ -# adapter-identifier — 설계 결정 참조 +# adapter:outbound:identifier — 사용자 principal 가명화, durable operation id -비-IO 인프라 능력(capability) 어댑터 모듈. 패키지 루트: `dev.caskeleton.adapter.identifier`. +이 leaf의 main 코드는 `HmacUserPrincipalPseudonymizer`와 `UuidV7DurableOperationIdFactory` 두 클래스다. 패키지 루트: +`dev.caskeleton.adapter.outbound.identifier`. -허용/금지 의존과 테스트 명령 같은 **모듈 규칙**은 [CLAUDE.md](CLAUDE.md) 가 SSOT 다. -이 문서는 코드 주석에서 덜어낸 **설계 결정의 근거**를 모아둔 참조용 기록이다 — 코드를 읽다 -"왜 이렇게 했나"가 궁금할 때 본다. +허용·금지 의존과 테스트 명령 같은 **모듈 규칙**은 [CLAUDE.md](CLAUDE.md)가 기준이다. 이 문서는 +설계 결정의 근거를 모은다. -## 왜 별도 모듈인가 (adapter-outbound 와의 구분) +## 이름과 내용이 다른 이유 (review 05-21) -`adapter-outbound` 처럼 도메인 포트를 구현하는 driven/secondary 어댑터지만, **외부 시스템 연동이 -없는**(no external-system integration) 능력만 담는다: 식별자 생성/인코딩(UUIDv7), 같은 근거로 clock· -crypto/random 소스. UUID id/코덱 능력은 인프라이지 아웃바운드 연동 지점이 아니므로, 이것을 -`adapter-outbound` 밖에 둬야 그 모듈의 문서화된 의미("외부 HTTP / messaging / cache / notifications")가 -유지된다. +leaf 이름은 `identifier`지만 범용 식별자 생성기·clock·random 소스는 여기 없다. 식별자 생성은 +durable operation id(UUIDv7) 하나뿐이다(아래). 예전 문서가 범용 생성기 계획을 현재 내용처럼 적었다. 이름은 바꾸지 않았다: Gradle 경로·registry id·소비자 +(`composition:service-runtime`, `app-bootstrap`, `sample-portfolio`)의 의존 선언이 모두 이 이름을 +쓰고, 바꿔서 얻는 것은 이름 하나뿐이다. 외부 연동이 없는 crypto 능력을 새로 둘 곳이 필요하면 이 +leaf에 둔다. 그때 이 절을 고친다. ## HmacUserPrincipalPseudonymizer -`UserPrincipalPseudonymizerPort`(application-core) 의 HMAC-SHA-256 구현. +`UserPrincipalPseudonymizerPort`(application-core)의 HMAC-SHA-256 구현이다. 로그의 +`user_principal` 값을 원래 값 대신 이 토큰으로 남긴다. -### 알고리즘 SSOT -구체 알고리즘은 90일 회전 salt 로 키잉한 HMAC-SHA-256 이다. 이 클래스가 유일한 구현이며, -비-IO crypto 능력 어댑터로 이 모듈에 있고 `app-bootstrap` -이 싱글톤 빈으로 와이어링한다. +- 출력: 비어 있지 않은 `rawPrincipal`을 UTF-8 바이트로 서명한 256-bit HMAC을 64자 소문자 hex로 + 돌려준다. `null`이나 blank면 `null`. +- 정답 값: 테스트가 RFC 4231 test case 2와 non-ASCII(UTF-8) 벡터를 고정한다. 알고리즘·charset·hex + 대소문자를 바꾸면 테스트가 실패한다. +- Salt: `APP_PRIVACY_PSEUDONYMIZATION_SALT`(secret, 90일 회전)에서 온다. 이 클래스는 salt를 스스로 + 읽지 않고 생성자로 받는다. 받은 배열은 복사해 둔다. +- Thread safety: `Mac`은 thread-safe하지 않아서 호출마다 새로 만든다. 그래서 싱글톤 bean으로 + 공유해도 된다. `HmacSHA256`은 JDK 필수 알고리즘이라 `NoSuchAlgorithmException`· + `InvalidKeyException`은 사실상 나지 않는다. checked exception을 호출부에 남기지 않으려고 + `IllegalStateException`으로 감싼다. -### 출력 -비어있지 않은 `rawPrincipal` 에 대해 단방향·안정적인 256-bit HMAC 토큰을 64자 소문자 hex 로 반환. -`rawPrincipal` 이 `null` 이거나 blank 면 `null` 반환. +## UuidV7DurableOperationIdFactory -### Salt 출처 -salt 는 `app-bootstrap` 이 `APP_PRIVACY_PSEUDONYMIZATION_SALT` 환경변수에서 공급한다(분류: secret, -회전 주기: 90일). 이 클래스는 salt 를 스스로 조달하지 않는다. +`DurableOperationIdFactory`(application-core) 구현. `UuidCreator.getTimeOrderedEpochPlus1()`로 UUIDv7을 +만든다(샘플 id adapter와 같은 방식). operation id는 제출 이벤트의 event id가 되고, messaging platform +`MessageId`는 UUIDv7만 받는다. 예전에는 web controller가 `UUID.randomUUID()`(v4)로 만들어 모든 제출 +이벤트가 발행 시점에 거부되어 DEAD가 됐다(리뷰 2026-11-01 06-06, Kafka relay lane이 발견). +`composition:durable-operation`이 bean으로 조립한다. -### Thread safety -`Mac` 인스턴스는 thread-safe 하지 않다. 매 `pseudonymize(String)` 호출마다 새 `Mac` 을 생성하므로 -공유 싱글톤 빈으로 안전하다. HmacSHA256 은 JDK 필수 알고리즘(JCA spec)이라 `NoSuchAlgorithmException`· -`InvalidKeyException` 은 사실상 도달 불가능하며, 호출부에 checked exception 잡음을 남기지 않으려고 -`IllegalStateException` 으로 감싼다. +## 조립 -### Spring-free -이 모듈(`adapter-identifier`)은 설계상 Spring-free 다. 어노테이션이 없고, 빈 생성은 -`app-bootstrap` 의 책임이다. +Spring 어노테이션이 없다. bean은 +`composition/service-runtime/.../logging/PseudonymizationConfig.java`가 만든다 +(`@ConditionalOnMissingBean`이라 파생 서비스가 자기 구현으로 바꿀 수 있다). -## 빌드 결정 (build.gradle) +## 빌드 결정 -### implementation vs api -`:application-core` 를 `implementation` 으로 선언한다(`api` 아님). adapter-identifier 가 자신의 public -ABI 에 application-core 타입을 노출하지 않기 때문이다. 유일한 와이어링 소비자인 `app-bootstrap` 은 -이미 자기 classpath 에 application-core 를 갖고 있다. 이 의존 edge 는 `src/build.gradle` 의 -`allowedProjectDependencies['adapter-identifier']` 로 허용된다. +`:application-core`를 `implementation`으로 받는다. 이 leaf의 public 타입 시그니처에 +application-core 타입이 드러나지만, 조립하는 쪽이 application-core를 이미 classpath에 갖고 있다. +허용 edge는 `src/config/architecture/modules.json`이 기준이다. diff --git a/src/adapter/outbound/identifier/build.gradle b/src/adapter/outbound/identifier/build.gradle index bddded3c..138a95cf 100644 --- a/src/adapter/outbound/identifier/build.gradle +++ b/src/adapter/outbound/identifier/build.gradle @@ -7,4 +7,9 @@ plugins { // resolved the Fileserver use cases. It lives with the capability now. dependencies { implementation project(':application-core') + // A feature's server-assigned id adapter implements its domain `*IdFactory` port here + // (registry edge `adapter:outbound:identifier -> domain-core`); docs/manual/02-new-feature.md. + implementation project(':domain-core') + // UUIDv7 ids (UuidV7DurableOperationIdFactory), the generator the sample's id adapters use. + implementation libs.uuid.creator } diff --git a/src/adapter/outbound/identifier/gradle.lockfile b/src/adapter/outbound/identifier/gradle.lockfile index 58357ca2..53be72dc 100644 --- a/src/adapter/outbound/identifier/gradle.lockfile +++ b/src/adapter/outbound/identifier/gradle.lockfile @@ -6,6 +6,7 @@ ch.qos.logback:logback-classic:1.5.38=testCompileClasspath,testRuntimeClasspath ch.qos.logback:logback-core:1.5.38=testCompileClasspath,testRuntimeClasspath com.fasterxml.jackson.core:jackson-annotations:2.21=testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor +com.github.f4b6a3:uuid-creator:6.1.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs com.github.spotbugs:spotbugs:4.10.2=spotbugs @@ -146,4 +147,4 @@ org.yaml:snakeyaml:2.5=testCompileClasspath,testRuntimeClasspath tools.jackson.core:jackson-core:3.1.5=testCompileClasspath,testRuntimeClasspath tools.jackson.core:jackson-databind:3.1.5=testCompileClasspath,testRuntimeClasspath tools.jackson:jackson-bom:3.1.5=testCompileClasspath,testRuntimeClasspath -empty=compileClasspath,runtimeClasspath +empty= diff --git a/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactory.java b/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactory.java new file mode 100644 index 00000000..7e317892 --- /dev/null +++ b/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactory.java @@ -0,0 +1,18 @@ +package dev.caskeleton.adapter.outbound.identifier; + +import com.github.f4b6a3.uuid.UuidCreator; +import dev.caskeleton.application.operation.DurableOperationId; +import dev.caskeleton.application.operation.DurableOperationIdFactory; + +/** + * {@link DurableOperationIdFactory} minting time-ordered UUIDv7 ids, the same mechanism ({@code + * UuidCreator.getTimeOrderedEpochPlus1()}) the sample's identifier adapters use. The id is also the + * submission event's id, and the messaging platform's message id accepts only UUIDv7. + */ +public final class UuidV7DurableOperationIdFactory implements DurableOperationIdFactory { + + @Override + public DurableOperationId newOperationId() { + return new DurableOperationId(UuidCreator.getTimeOrderedEpochPlus1().toString()); + } +} diff --git a/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/package-info.java b/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/package-info.java index 2b35916b..5f6c7d82 100644 --- a/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/package-info.java +++ b/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/package-info.java @@ -1,5 +1,5 @@ /** - * Non-IO infrastructure-capability adapters (identifier generation/codec, clock, crypto/random). - * See README for why these are separate from {@code adapter-outbound}. + * The HMAC-SHA-256 user-principal pseudonymizer. Despite the leaf name, no identifier generation, + * clock or random source lives here; see README for why the name was kept. */ package dev.caskeleton.adapter.outbound.identifier; diff --git a/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizerTest.java b/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizerTest.java index b2833ce2..f5893324 100644 --- a/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizerTest.java +++ b/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizerTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class HmacUserPrincipalPseudonymizerTest { @@ -109,4 +110,37 @@ class HmacUserPrincipalPseudonymizerTest { String token = pseudonymizer.pseudonymize("some-user"); assertThat(token).matches("^[0-9a-f]{64}$"); } + + /** + * RFC 4231 test case 2 pins the algorithm and the hex encoding: determinism tests alone survive a + * swap to another MAC or to upper-case hex (review 05-21). + */ + @Test + @DisplayName("RFC 4231 test case 2의 정답 HMAC-SHA-256 값을 소문자 hex로 낸다") + void producesTheRfc4231TestCase2Digest() { + // given + HmacUserPrincipalPseudonymizer pseudonymizer = + new HmacUserPrincipalPseudonymizer("Jefe".getBytes(StandardCharsets.US_ASCII)); + + // when + String token = pseudonymizer.pseudonymize("what do ya want for nothing?"); + + // then + assertThat(token).isEqualTo("5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"); + } + + /** A non-ASCII principal pins UTF-8: any other charset gives a different digest. */ + @Test + @DisplayName("ASCII가 아닌 principal은 UTF-8 바이트로 서명한다") + void signsANonAsciiPrincipalAsUtf8Bytes() { + // given + HmacUserPrincipalPseudonymizer pseudonymizer = + new HmacUserPrincipalPseudonymizer("salt-for-utf8".getBytes(StandardCharsets.US_ASCII)); + + // when + String token = pseudonymizer.pseudonymize("\uC0AC\uC6A9\uC790-\u00E9"); + + // then + assertThat(token).isEqualTo("44f7ff2e795f37b669a0556c52fabab30de60037efa207701d3b8c07e1a1e63e"); + } } diff --git a/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactoryTest.java b/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactoryTest.java new file mode 100644 index 00000000..28d84f09 --- /dev/null +++ b/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactoryTest.java @@ -0,0 +1,28 @@ +package dev.caskeleton.adapter.outbound.identifier; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class UuidV7DurableOperationIdFactoryTest { + + @Test + @DisplayName("operation id는 정규 소문자 UUIDv7이고 호출마다 다르다") + void everyIdIsADistinctCanonicalUuidV7() { + // given + UuidV7DurableOperationIdFactory factory = new UuidV7DurableOperationIdFactory(); + String first = factory.newOperationId().value(); + + // when + String second = factory.newOperationId().value(); + + // then + UUID uuid = UUID.fromString(second); + assertThat(List.of(uuid.version(), uuid.variant(), uuid.toString())) + .containsExactly(7, 2, second); + assertThat(second).isNotEqualTo(first); + } +} diff --git a/src/adapter/outbound/messaging-kafka/README.md b/src/adapter/outbound/messaging-kafka/README.md index 0fce818a..637372e1 100644 --- a/src/adapter/outbound/messaging-kafka/README.md +++ b/src/adapter/outbound/messaging-kafka/README.md @@ -59,3 +59,22 @@ runtimeOnly project(':adapter:outbound:messaging-kafka') // Kafka 발행 `APP_MESSAGING_BROKER`는 platform이 쓸 broker 선택값이고 기본값이 `kafka`다. 등록된 broker가 Kafka 하나라 바꿀 일이 없다. destination·broker profile·보안 설정은 `docs/messaging/configuration-reference.md`. + +## 실제 broker로 도는 앱 발행 경로 lane (`messagingKafkaRelayIntegrationTest`) + +앱이 실제로 쓰는 발행 경로 — `composition:outbox-relay` relay → `OutboxMessagePublishAdapter` → +platform bridge → `DefaultMessagePublisher` → Kafka — 를 Testcontainers Kafka(`apache/kafka:4.1.0`, +`-PmessagingKafkaImage=`로 교체)로 끝까지 돌린다(리뷰 2026-11-01 06-09). vendored 쪽 broker lane은 +platform 자기 relay와 publisher 직접 호출만 검증하므로 앱 경로의 증거가 아니다. + +- 정상 발행: append한 row를 relay가 보내고, 테스트가 topic에서 읽은 레코드 값이 envelope 바이트와 + 같고 key가 partition key와 같다. +- broker 정지(컨테이너 pause) 중 claim된 row는 DEAD가 아니라 FAILED로 남고, broker가 돌아오면 운영자 + 개입 없이 PUBLISHED가 된다. +- outbox store는 port 소유자의 in-memory fake다. claim SQL·FIFO gate는 persistence-jpa의 PostgreSQL + lane이 따로 검증한다. +- strict lane(`integration()`)이라 `:integrationCheck`에 들어가고 skip을 거부한다. + +```bash +./gradlew :adapter:outbound:messaging-kafka:messagingKafkaRelayIntegrationTest --console=plain +``` diff --git a/src/adapter/outbound/messaging-kafka/build.gradle b/src/adapter/outbound/messaging-kafka/build.gradle index c7323e5f..bba266f8 100644 --- a/src/adapter/outbound/messaging-kafka/build.gradle +++ b/src/adapter/outbound/messaging-kafka/build.gradle @@ -25,6 +25,21 @@ base { archivesName = 'adapter-outbound-messaging-kafka' } +testing { + suites { + // The application's own publish path against a real broker (review 2026-11-01 06-09). + integrationTest(JvmTestSuite) { + dependencies { + implementation project() + } + } + } +} +configurations { + integrationTestImplementation.extendsFrom testImplementation + integrationTestRuntimeOnly.extendsFrom testRuntimeOnly +} + dependencies { // Runtime only: this leaf names none of their types. The bridge publishes the application's // canonical events through the platform's EncodedMessagePublisher, which the Kafka starter @@ -37,3 +52,33 @@ dependencies { testImplementation project(':application-core') testImplementation project(':messaging:messaging-core-api') } + +// Test-only edges of the relay lane: the application relay as the composition root selects it, the +// port owner's in-memory store, and a real Kafka. Test edges are outside the registry gate. +dependencies { + integrationTestImplementation project(':composition:outbox-relay') + integrationTestImplementation testFixtures(project(':application-core')) + integrationTestImplementation 'org.apache.kafka:kafka-clients' + integrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter' + integrationTestImplementation 'org.testcontainers:testcontainers-kafka' +} + +// The publish path the application actually uses — outbox relay -> OutboxMessagePublishAdapter -> +// platform bridge -> DefaultMessagePublisher -> Kafka — run end to end against a real broker. The +// platform's own broker lanes exercise its relay and its publisher directly; this is the only lane +// in which the application's relay meets a broker. It joins :integrationCheck by its category. +strictTestLanes { + lane('messagingKafkaRelayIntegrationTest') { + integration() + sourceSet = 'integrationTest' + description = 'Runs the application outbox relay through the platform bridge against a real Kafka.' + requires 'dev.caskeleton.adapter.outbound.messaging.kafka.relay.ApplicationRelayKafkaIntegrationTest' + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + // Pinned like the platform's certification lane: a red run must name the broker it ran on. + // Not under messaging.*: the platform refuses any property with that old prefix at startup. + systemProperty 'relayLane.kafkaImage', + (project.findProperty('messagingKafkaImage') ?: 'apache/kafka:4.1.0').toString() + shouldRunAfter 'test' + } +} diff --git a/src/adapter/outbound/messaging-kafka/gradle.lockfile b/src/adapter/outbound/messaging-kafka/gradle.lockfile index 7cbc1e5c..03c9677a 100644 --- a/src/adapter/outbound/messaging-kafka/gradle.lockfile +++ b/src/adapter/outbound/messaging-kafka/gradle.lockfile @@ -1,161 +1,177 @@ # 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. -at.yawk.lz4:lz4-java:1.10.1=runtimeClasspath,testRuntimeClasspath -biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath -ch.qos.logback:logback-classic:1.5.38=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -ch.qos.logback:logback-core:1.5.38=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -com.fasterxml.jackson.core:jackson-annotations:2.21=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.luben:zstd-jni:1.5.6-10=runtimeClasspath,testRuntimeClasspath +at.yawk.lz4:lz4-java:1.10.1=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath +biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=integrationTestCompileClasspath,testCompileClasspath +ch.qos.logback:logback-classic:1.5.38=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=integrationTestRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=integrationTestRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=integrationTestRuntimeClasspath +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.github.docker-java:docker-java-api:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath +com.github.docker-java:docker-java-transport-zerodep:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath +com.github.docker-java:docker-java-transport:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.github.luben:zstd-jni:1.5.6-10=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs com.github.spotbugs:spotbugs:4.10.2=spotbugs com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.38.0=testCompileClasspath +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.38.0=integrationTestCompileClasspath,testCompileClasspath com.google.errorprone:error_prone_annotations:2.41.0=spotbugs com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.google.guava:guava:33.6.0-jre=checkstyle -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins -com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath +com.jayway.jsonpath:json-path:2.10.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath +com.vaadin.external.google:android-json:0.0.20131108.vaadin1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-codec:commons-codec:1.19.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle +commons-io:commons-io:2.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath commons-io:commons-io:2.21.0=spotbugs -commons-logging:commons-logging:1.3.6=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +commons-logging:commons-logging:1.3.6=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -io.micrometer:micrometer-commons:1.16.7=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.7=runtimeClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath -jakarta.annotation:jakarta.annotation-api:3.0.0=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=testCompileClasspath,testRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +io.micrometer:micrometer-commons:1.16.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +javax.inject:javax.inject:1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath -net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath -net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy-agent:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath +net.logstash.logback:logstash-logback-encoder:8.0=integrationTestRuntimeClasspath +net.minidev:accessors-smart:2.6.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.minidev:json-smart:2.6.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs +org.apache.commons:commons-compress:1.28.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.apache.commons:commons-lang3:3.20.0=checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle org.apache.httpcomponents:httpclient:4.5.13=checkstyle org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.kafka:kafka-clients:4.1.2=runtimeClasspath,testRuntimeClasspath -org.apache.logging.log4j:log4j-api:2.25.5=runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.kafka:kafka-clients:4.1.2=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-api:2.25.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.logging.log4j:log4j-to-slf4j:2.25.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.maven.doxia:doxia-core:1.12.0=checkstyle org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle -org.apache.tomcat.embed:tomcat-embed-core:11.0.24=testCompileClasspath,testRuntimeClasspath -org.apache.tomcat.embed:tomcat-embed-el:11.0.24=testCompileClasspath,testRuntimeClasspath -org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-core:11.0.24=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-el:11.0.24=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath -org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=integrationTestCompileClasspath,testCompileClasspath +org.assertj:assertj-core:3.27.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.awaitility:awaitility:4.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs -org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath -org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath +org.hamcrest:hamcrest:3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath -org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath +org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-engine:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-params:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-engine:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-launcher:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath +org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs -org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath -org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath -org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath -org.objenesis:objenesis:3.3=testRuntimeClasspath -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath -org.osgi:org.osgi.annotation.bundle:2.0.0=testCompileClasspath -org.osgi:org.osgi.annotation.versioning:1.1.2=testCompileClasspath -org.osgi:org.osgi.resource:1.0.0=testCompileClasspath -org.osgi:org.osgi.service.serviceloader:1.0.0=testCompileClasspath +org.latencyutils:LatencyUtils:2.0.3=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath +org.mockito:mockito-core:5.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,mockitoAgent,testCompileClasspath,testRuntimeClasspath +org.mockito:mockito-junit-jupiter:5.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.objenesis:objenesis:3.3=integrationTestRuntimeClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.osgi:org.osgi.annotation.bundle:2.0.0=integrationTestCompileClasspath,testCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=integrationTestCompileClasspath,testCompileClasspath +org.osgi:org.osgi.resource:1.0.0=integrationTestCompileClasspath,testCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=integrationTestCompileClasspath,testCompileClasspath org.ow2.asm:asm-analysis:9.10.1=spotbugs org.ow2.asm:asm-commons:9.10.1=spotbugs org.ow2.asm:asm-tree:9.10.1=spotbugs org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs -org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.ow2.asm:asm:9.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor org.reflections:reflections:0.10.2=checkstyle -org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath -org.slf4j:jul-to-slf4j:2.0.18=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.slf4j:slf4j-api:2.0.18=runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.rnorth.duct-tape:duct-tape:1.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.skyscreamer:jsonassert:1.5.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springframework.boot:spring-boot-actuator:4.0.8=runtimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-autoconfigure:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-actuator:4.0.8=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-autoconfigure:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor -org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-jackson:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-json:4.0.8=runtimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-logging:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-aop:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-beans:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-context:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-core:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-expression:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-jdbc:7.0.9=runtimeClasspath,testRuntimeClasspath -org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath -org.springframework:spring-tx:7.0.9=runtimeClasspath,testRuntimeClasspath -org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath -org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath -org.xerial.snappy:snappy-java:1.1.10.7=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-http-converter:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-json:4.0.8=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-jdbc:7.0.9=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath +org.springframework:spring-test:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-tx:7.0.9=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-webmvc:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.testcontainers:testcontainers-junit-jupiter:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.testcontainers:testcontainers-kafka:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.testcontainers:testcontainers:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.xerial.snappy:snappy-java:1.1.10.7=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath -org.yaml:snakeyaml:2.5=testCompileClasspath,testRuntimeClasspath -tools.jackson.core:jackson-core:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -tools.jackson.core:jackson-databind:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -tools.jackson:jackson-bom:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.xmlunit:xmlunit-core:2.10.4=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.yaml:snakeyaml:2.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-core:3.1.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson:jackson-bom:3.1.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath empty=compileClasspath diff --git a/src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java b/src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java new file mode 100644 index 00000000..67f7fdd1 --- /dev/null +++ b/src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java @@ -0,0 +1,336 @@ +package dev.caskeleton.adapter.outbound.messaging.kafka.relay; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.OutboxAppendPort; +import dev.caskeleton.application.outbox.OutboxCompletion; +import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxLease; +import dev.caskeleton.application.outbox.OutboxStorePort; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.messaging.api.MessageId; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import org.apache.kafka.clients.admin.Admin; +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.admin.NewTopic; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.serialization.ByteArrayDeserializer; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.testcontainers.DockerClientFactory; +import org.testcontainers.kafka.KafkaContainer; + +/** + * The application's publish path against a real Kafka (review 2026-11-01 06-09). + * + *

      Booted the way an application gets it: this capability module and the outbox relay composition + * on the classpath, auto-configuration on. The relay claims from the outbox, publishes through + * {@code OutboxMessagePublishAdapter} and the platform bridge into the vendored {@code + * DefaultMessagePublisher}, and the platform's Kafka transport writes the record. Nothing on that + * path is a fake; the store is the port owner's in-memory fake, because the claim SQL is covered + * against PostgreSQL by persistence-jpa's own lanes and this lane is about the broker side. + * + *

      Two bugs this would have caught lived exactly between the unit tests of the parts: the bridge + * read the platform's retryable refusal as definite, and the relay parked it (06-01). + */ +class ApplicationRelayKafkaIntegrationTest { + + private static final String DESTINATION = "testkit-events"; + private static final String TOPIC = "app-relay-" + UUID.randomUUID(); + private static final String DLQ_TOPIC = TOPIC + ".dlt"; + + private static KafkaContainer kafka; + + @BeforeAll + static void startBroker() throws Exception { + kafka = new KafkaContainer(System.getProperty("relayLane.kafkaImage", "apache/kafka:4.1.0")); + kafka.start(); + Properties admin = new Properties(); + admin.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers()); + try (Admin client = Admin.create(admin)) { + client + .createTopics( + List.of(new NewTopic(TOPIC, 1, (short) 1), new NewTopic(DLQ_TOPIC, 1, (short) 1))) + .all() + .get(30, TimeUnit.SECONDS); + } + } + + @AfterAll + static void stopBroker() { + if (kafka != null) { + kafka.stop(); + } + } + + @Test + @DisplayName("relay가 outbox 행을 실제 Kafka로 보내고 레코드 값은 append한 envelope 바이트와 같다") + void theRelayPublishesAnAppendedRowToKafkaWithTheExactEnvelopeBytes() { + // given + TestBeans beans = new TestBeans(); + ValidatedIntegrationEvent event = event(); + + try (ConfigurableApplicationContext context = start(beans)) { + // when + beans.store.appendNow(event); + + // then + await() + .atMost(Duration.ofSeconds(60)) + .until(() -> beans.store.statusOf(event) == OutboxEventStatus.PUBLISHED); + ConsumerRecord record = readBack(event); + assertThat(record.value()).isEqualTo(event.envelopeBytes()); + assertThat(record.key()).isEqualTo(event.partitionKeyBytes()); + } + } + + @Test + @DisplayName("broker가 멈춘 동안 claim된 행은 DEAD가 아니라 FAILED로 남고 broker가 돌아오면 운영자 개입 없이 발행된다") + void aRowClaimedWhileTheBrokerIsDownWaitsAsFailedAndIsPublishedOnceItReturns() { + // given: the broker stops answering before the row is appended + TestBeans beans = new TestBeans(); + ValidatedIntegrationEvent event = event(); + + try (ConfigurableApplicationContext context = start(beans)) { + pause(true); + try { + // when + beans.store.appendNow(event); + + // then: the outage leaves the row waiting, not parked + await() + .atMost(Duration.ofSeconds(90)) + .until(() -> beans.store.statusOf(event) == OutboxEventStatus.FAILED); + assertThat(beans.store.deadIds()).isEmpty(); + } finally { + pause(false); + } + beans.clock.advance(Duration.ofMinutes(10)); + await() + .atMost(Duration.ofSeconds(90)) + .until(() -> beans.store.statusOf(event) == OutboxEventStatus.PUBLISHED); + assertThat(readBack(event).value()).isEqualTo(event.envelopeBytes()); + assertThat(beans.store.deadIds()).isEmpty(); + } + } + + /** The event id is a UUIDv7: the platform's message id refuses any other version. */ + private static ValidatedIntegrationEvent event() { + String eventId = MessageId.newId().value().toString(); + return OutboxEvents.event(eventId, "aggregate-" + eventId, 1, Instant.now().minusSeconds(1)); + } + + private static ConfigurableApplicationContext start(TestBeans beans) { + return new SpringApplicationBuilder(Application.class) + .initializers(context -> context.getBeanFactory().registerSingleton("testBeans", beans)) + .web(WebApplicationType.NONE) + .logStartupInfo(false) + .run( + "--APP_MESSAGING_KAFKA_BROKERS=" + kafka.getBootstrapServers(), + "--APP_MESSAGING_PRODUCER_ID=relay-lane", + "--app.outbox.enabled=true", + "--app.outbox.relay-enabled=true", + "--app.outbox.poll-interval=PT0.2S", + "--app.messaging.destinations." + DESTINATION + ".broker=kafka", + "--app.messaging.destinations." + DESTINATION + ".kind=EVENT_STREAM", + "--app.messaging.destinations." + DESTINATION + ".physical.topic=" + TOPIC, + "--app.messaging.destinations." + + DESTINATION + + ".schema.message-types[0]=" + + OutboxEvents.CONTRACT_ID, + "--app.messaging.destinations." + DESTINATION + ".guarantees.delivery=AT_LEAST_ONCE", + "--app.messaging.destinations." + + DESTINATION + + ".dlq.destination=" + + DESTINATION + + "-dlq", + "--app.messaging.destinations." + DESTINATION + "-dlq.broker=kafka", + "--app.messaging.destinations." + DESTINATION + "-dlq.kind=WORK_QUEUE", + "--app.messaging.destinations." + DESTINATION + "-dlq.physical.topic=" + DLQ_TOPIC, + "--app.messaging.destinations." + + DESTINATION + + "-dlq.schema.message-types[0]=" + + OutboxEvents.CONTRACT_ID, + "--app.messaging.destinations." + + DESTINATION + + "-dlq.guarantees.delivery=AT_MOST_ONCE"); + } + + private static void pause(boolean paused) { + var docker = DockerClientFactory.instance().client(); + if (paused) { + docker.pauseContainerCmd(kafka.getContainerId()).exec(); + } else { + docker.unpauseContainerCmd(kafka.getContainerId()).exec(); + } + } + + /** Reads the topic from the start until the record carrying this event's envelope shows up. */ + private static ConsumerRecord readBack(ValidatedIntegrationEvent event) { + Properties config = new Properties(); + config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers()); + config.put(ConsumerConfig.GROUP_ID_CONFIG, "relay-lane-" + UUID.randomUUID()); + config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class); + config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class); + List> seen = new ArrayList<>(); + try (KafkaConsumer consumer = new KafkaConsumer<>(config)) { + consumer.subscribe(List.of(TOPIC)); + Instant deadline = Instant.now().plusSeconds(30); + while (Instant.now().isBefore(deadline)) { + for (ConsumerRecord record : consumer.poll(Duration.ofSeconds(1))) { + seen.add(record); + if (Arrays.equals(record.value(), event.envelopeBytes())) { + return record; + } + } + } + } + throw new AssertionError( + "no record on " + + TOPIC + + " carries the envelope of " + + event.eventId().value() + + "; records read: " + + seen.size()); + } + + /** What the composition root would otherwise contribute: the store, transactions and a clock. */ + static final class TestBeans { + final SynchronizedStore store = new SynchronizedStore(); + final MutableClock clock = new MutableClock(); + } + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration + static class Application { + + @Bean + SynchronizedStore outboxStore(TestBeans beans) { + return beans.store; + } + + @Bean + TransactionPort transactionPort() { + return new DirectTransactionPort(); + } + + @Bean + Clock clock(TestBeans beans) { + return beans.clock; + } + } + + /** The port owner's fake, made safe for the relay thread and the test thread. */ + static final class SynchronizedStore implements OutboxStorePort, OutboxAppendPort { + private final InMemoryOutboxStore delegate = new InMemoryOutboxStore(); + + synchronized void appendNow(ValidatedIntegrationEvent event) { + delegate.append(event); + } + + synchronized OutboxEventStatus statusOf(ValidatedIntegrationEvent event) { + return delegate.status(event.eventId().value()); + } + + synchronized List deadIds() { + return delegate.dead(); + } + + @Override + public synchronized void append(ValidatedIntegrationEvent event) { + delegate.append(event); + } + + @Override + public synchronized List claimBatch( + String owner, int batchSize, Instant now, Duration inFlightTimeout) { + return delegate.claimBatch(owner, batchSize, now, inFlightTimeout); + } + + @Override + public synchronized OutboxCompletion markPublished(OutboxLease lease) { + return delegate.markPublished(lease); + } + + @Override + public synchronized OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { + return delegate.markFailed(lease, nextAttemptAt); + } + + @Override + public synchronized OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt) { + return delegate.markDeferred(lease, nextAttemptAt); + } + + @Override + public synchronized OutboxCompletion releaseLease(OutboxLease lease, Instant claimableAt) { + return delegate.releaseLease(lease, claimableAt); + } + + @Override + public synchronized OutboxCompletion markDead(OutboxLease lease) { + return delegate.markDead(lease); + } + + @Override + public synchronized Map countByStatus() { + return delegate.countByStatus(); + } + + @Override + public synchronized Map oldestUnpublishedAgeSecondsByEventType(Instant now) { + return delegate.oldestUnpublishedAgeSecondsByEventType(now); + } + } + + /** The system clock plus an offset the test can move forward past a retry delay. */ + static final class MutableClock extends Clock { + private volatile Duration offset = Duration.ZERO; + + void advance(Duration by) { + offset = offset.plus(by); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return Instant.now().plus(offset); + } + } +} diff --git a/src/adapter/outbound/messaging/README.md b/src/adapter/outbound/messaging/README.md index bdd68c58..63e6ff03 100644 --- a/src/adapter/outbound/messaging/README.md +++ b/src/adapter/outbound/messaging/README.md @@ -42,6 +42,14 @@ platform `REJECTED` 중 `FailureDescriptor.retryable()`이 true인 것(종료 멈춘다(2026-11-01 리뷰 06-01). `AMBIGUOUS`로 번역하지 않은 이유: 동작은 같지만 "전송됐을 수 있음"이라는 거짓 정보가 남아 중복 경고를 오염시킨다. +### event id → message id + +application `EventId`는 문자열이고 platform `MessageId`는 **UUIDv7**만 받는다. bridge는 event id가 +정규 소문자 UUIDv7 문자열일 때만 같은 값으로 옮기고, 그 밖(대문자·축약 표기·v4 등 다른 버전)은 다른 +문자열의 message id로 바꿔 보내지 않고 `REJECTED_BEFORE_SEND`로 거부한다(relay는 DEAD). 소비자 중복 +제거 키가 event id라서 값을 바꿔 보내면 중복 제거가 깨지기 때문이다(리뷰 2026-11-01 06-06). 이 거부는 +append 시점(`EventId` 문법)에서 먼저 일어나야 한다 — application 쪽 문법 일원화는 별도 작업이다. + ## outbox 발행 포트에는 대역이 없다 `OutboxMessagePublishPort`의 대역(항상 던지는 publisher)은 두지 않는다. 대역도 bean이므로 relay diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java index 7f39a975..49e84155 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java @@ -130,8 +130,37 @@ public final class PlatformIntegrationEventPublishAdapter implements Integration target.put(new HeaderName(name), new HeaderValue(value)); } - private static MessageId canonicalMessageId(String value) { - return new MessageId(UUID.fromString(value)); + /** + * The platform message id for an application event id: the same UUID, spelled the same way. + * + *

      The application's {@code EventId} is a string; the platform's {@code MessageId} is a UUID of + * version 7, and its constructor refuses any other version. So the event ids this bridge can + * carry are exactly the canonical lower-case spellings of UUIDv7 values: + * + *

        + *
      • {@code UUID.fromString} also accepts spellings that do not survive the trip — upper case, + * or the short {@code 1-2-3-4-5} — and the id it yields prints as a different string. + * Consumers deduplicate on the event id, so a message sent under a re-spelled id is one + * their inbox has never seen. Refused here. + *
      • A v4 (or any non-v7) UUID is refused by {@code MessageId}. + *
      + * + *

      Either refusal is {@code REJECTED_BEFORE_SEND}: the same id is refused again, so the relay + * dead-letters it. The append side's {@code EventId} grammar is where such an id should fail + * first, in the writer's transaction; until it does, this is where the mismatch is caught. + * + * @throws IllegalArgumentException when the value is not a canonical lower-case UUIDv7 + */ + static MessageId canonicalMessageId(String value) { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value)) { + throw new IllegalArgumentException( + "integration event id is not a canonical lower-case UUID; mapped to the platform it would" + + " be sent as " + + uuid + + ", a different id from the one consumers deduplicate on"); + } + return new MessageId(uuid); } private static CausationId canonicalCausationId(String value) { diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java index 5787930f..b8f248ac 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java @@ -35,6 +35,8 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; class PlatformIntegrationEventPublishAdapterTest { private static final String EVENT_ID = "0190f4aa-0000-7000-8000-000000000001"; @@ -158,6 +160,35 @@ class PlatformIntegrationEventPublishAdapterTest { assertThat(publisher.calls).isZero(); } + /** + * {@code UUID.fromString} also reads non-canonical spellings — upper case, or {@code 1-2-3-4-5} — + * and the message id it yields prints differently from the event id; and the platform message id + * is a UUIDv7, so a v4 id (the last value) is refused too. Consumers deduplicate on the event id, + * so the bridge must not send a message whose id is a different string. + */ + @ParameterizedTest + @ValueSource( + strings = { + "0190F4AA-0000-7000-8000-000000000001", + "1-2-3-4-5", + "6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b" + }) + @DisplayName("정규 소문자 UUIDv7이 아닌 event id는 다른 id로 바꿔 보내지 않고 송신 전에 거부한다") + void anEventIdThatIsNotACanonicalUuidIsRefusedRatherThanSentUnderAnotherId(String eventId) { + // given + RecordingPublisher publisher = new RecordingPublisher(confirmed()); + PlatformIntegrationEventPublishAdapter bridge = + new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service"); + + // when + OutboxPublishOutcome outcome = + bridge.publish(event(eventId, Optional.empty())).toCompletableFuture().join(); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND); + assertThat(publisher.calls).isZero(); + } + /** * Only an event the platform cannot represent is a definite refusal. * diff --git a/src/adapter/outbound/objectstorage/README.md b/src/adapter/outbound/objectstorage/README.md index 59841f81..dbcd9ba1 100644 --- a/src/adapter/outbound/objectstorage/README.md +++ b/src/adapter/outbound/objectstorage/README.md @@ -107,12 +107,39 @@ release the `status`, `excludedProfiles` and `limitations` beside it were measur `-PobjectStorageMinioImage=/@sha256:`. A value that does not end in the evidence digest is refused: a different build is a new measurement, made by re-running the lanes and rewriting the evidence file (image and findings together). -- The local compose runtime (`docker-compose.infra.yml`, `LOCAL_MINIO_IMAGE`) is a different, later - release and is not evidence; the comment there says why. +- The local compose runtime (`docker-compose.infra.yml`, `LOCAL_MINIO_IMAGE`) uses the same digest. + `ComposeMinioImageMatchesEvidenceTest` (leaf `test`) fails when the compose default and the + evidence disagree; change both together. +- The contract lane also runs `MinioS3ManagedObjectProviderContractTest`: the S3 adapter itself under + the provider contract the local-dev provider inherits, on the production client factory, over TLS + with a certificate made for the run (a binding only accepts HTTPS). Its first run found two adapter + defects the mocked unit tests could not: every create failed because the SDK cancels the request + body once it holds Content-Length bytes (and at once for an empty body), and every read with a + consumer chunk below the network buffer size failed because Netty delivers 8 KiB buffers. Both + are fixed (`S3AsyncRequestBodyBridge`, `S3AsyncResponseBodyBridge.TRANSPORT_BUFFER_CEILING_BYTES`). -As of 2026-11-01 a pull of `minio/minio` from Docker Hub answers "repository does not exist", so -these lanes fail with the message above until a mirror or a re-measured replacement is chosen -(review 05-09; the choice is an open owner decision). +#### Image source (review 05-09, measured 2026-11-02) + +Docker Hub `minio/minio` and `quay.io/minio/minio` stopped serving MinIO, so the measured digest of +the old release (2024-01-16) could not be mirrored. Two maintained builds were pulled and measured +with the same requests (create-only PUT twice, stale and current `If-Match` PUT, create-only +multipart completion onto an existing key, stale `If-Match` DELETE): + +| Candidate | Result | Decision | +| --- | --- | --- | +| `pgsty/minio@sha256:b6bfe723…` (community fork on Docker Hub, `RELEASE.2026-08-04T00-00-00Z`) | 412 / 412, 200 / 412; DELETE ignores `If-Match` | **Chosen.** Named release tags, `pgsty/mc` with a shell for the compose bucket bootstrap, runs as root like the old image | +| `cgr.dev/chainguard/minio@sha256:0a011000…` (`RELEASE.2026-10-23T20-06-51Z`) | Same results | Rejected: the free tier offers only a moving `latest` tag, it runs as uid 65532 (the compose volume would need re-owning), and `cgr.dev/chainguard/minio-client` has no shell | + +The new release refuses create-only overwrites, which the old one accepted. So the evidence is now +`status: SUPPORTED` for the managed create-only profiles (`supportedProfiles`), the direct +(presigned) profiles stay excluded because they were not measured, and the adapter allowlist gained +the provider type `s3-compatible-minio-pgsty-release-2026-08-04t00-00-00z` (version +`release-2026-08-04t00-00-00z-sdk-2.30.0`). Only that release may claim `IMMUTABLE_CREATE`; no MinIO +release may claim `MULTI_NODE_LINEARIZABLE_CAS` or `RESPONSE_LOSS_RESOLUTION`, because the evidence +is one single-node container. The 2024-01-16 type stays for servers that still run it, with its +old restrictions. + +The compose client `minio-init` uses `pgsty/mc` by digest (`LOCAL_MINIO_MC_IMAGE` overrides it). ```bash cd src diff --git a/src/adapter/outbound/objectstorage/build.gradle b/src/adapter/outbound/objectstorage/build.gradle index f0c2a4f3..7ed416a4 100644 --- a/src/adapter/outbound/objectstorage/build.gradle +++ b/src/adapter/outbound/objectstorage/build.gradle @@ -82,10 +82,17 @@ dependencies { def objectStorageReadinessRegistry = rootProject.projectDir.parentFile.toPath() .resolve('docs/registries/object-storage-readiness.yaml').toFile() +// The local compose MinIO must be the image the evidence measured (review 05-09); +// ComposeMinioImageMatchesEvidenceTest compares the two. +def localComposeFile = rootProject.projectDir.parentFile.toPath() + .resolve('docker-compose.infra.yml').toFile() tasks.named('test') { inputs.file(objectStorageReadinessRegistry) .withPathSensitivity(PathSensitivity.RELATIVE) systemProperty 'objectstorage.readiness.registry', objectStorageReadinessRegistry.absolutePath + inputs.file(localComposeFile) + .withPathSensitivity(PathSensitivity.RELATIVE) + systemProperty 'objectstorage.compose.file', localComposeFile.absolutePath } // A mirror of the measured MinIO digest, for when the origin registry stops serving it (review @@ -99,10 +106,11 @@ strictTestLanes { lane('objectStorageMinioContractTest') { integration() sourceSet = 'integrationTest' - description = 'Runs the non-skipping MinIO managed object contract on the evidence-pinned image.' - requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectContractTest' + description = 'Runs the non-skipping MinIO managed object contract and the S3 provider contract on the evidence-pinned image.' + requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectContractTest', + // The S3 adapter itself under the shared provider contract (review 05-16). + 'dev.caskeleton.adapter.outbound.objectstorage.s3.MinioS3ManagedObjectProviderContractTest' rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' if (minioImageOverride) { systemProperty 'objectstorage.minio.image', minioImageOverride } @@ -114,7 +122,6 @@ strictTestLanes { description = 'Runs the non-skipping digest-pinned MinIO/Toxiproxy fault contract.' requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectFaultTest' rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' if (minioImageOverride) { systemProperty 'objectstorage.minio.image', minioImageOverride } @@ -126,7 +133,6 @@ strictTestLanes { description = 'Runs only with explicit protected AWS sandbox authority and exact inputs.' requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.AwsS3QualificationPreconditionsTest' rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' // The protected environment of object-storage-qualification.yml is the only caller that has // the authority. Without it the lane can only fail, so integrationCheck leaves it out and // says so (review NEW-16); naming the task still runs it and still fails closed. diff --git a/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectContractTest.java b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectContractTest.java index 2e37a796..0860cba2 100644 --- a/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectContractTest.java +++ b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/MinioManagedObjectContractTest.java @@ -1,7 +1,6 @@ package dev.caskeleton.adapter.outbound.objectstorage.qualification; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; import java.net.URI; @@ -15,6 +14,7 @@ import java.util.UUID; import java.util.concurrent.CompletionException; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; @@ -40,6 +40,7 @@ import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.model.NoSuchKeyException; import software.amazon.awssdk.services.s3.model.PutBucketVersioningRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.ServerSideEncryption; import software.amazon.awssdk.services.s3.model.UploadPartRequest; @@ -114,49 +115,27 @@ class MinioManagedObjectContractTest { } } + /** + * The managed-single and conditional-control create-only profiles rest on this: a second {@code + * If-None-Match: *} PUT is refused with 412 and the first bytes stay. The 2024-01-16 release the + * lane used to pin accepted it and overwrote (review 05-09); the evidence file records the + * change. + */ @Test - void checksumHeadRangeWorkButConditionalCreateIsIgnoredWhileStaleCasIsRejected() - throws Exception { + @DisplayName("이미 있는 키에 If-None-Match 생성을 다시 보내면 412로 거절되고 처음 바이트가 남는다") + void aSecondCreateOnlyPutIsRejectedAndTheFirstBytesStay() throws Exception { + // given byte[] content = "qualified-minio-content".getBytes(StandardCharsets.UTF_8); - String checksum = sha256(content); String key = "qualification/managed-single"; - var first = - client - .putObject( - PutObjectRequest.builder() - .bucket(BUCKET) - .key(key) - .ifNoneMatch("*") - .contentLength((long) content.length) - .checksumAlgorithm(ChecksumAlgorithm.SHA256) - .checksumSHA256(checksum) - .serverSideEncryption(ServerSideEncryption.AES256) - .metadata(java.util.Map.of("ca-logical-sha256", checksum)) - .build(), - AsyncRequestBody.fromByteBuffer(ByteBuffer.wrap(content))) - .join(); - - assertThat(first.eTag()).isNotBlank(); + var first = createOnlyPut(key, content); byte[] replacement = content.clone(); replacement[0] ^= 1; - String replacementChecksum = sha256(replacement); - var overwrittenDespiteCreateOnlyCondition = - client - .putObject( - PutObjectRequest.builder() - .bucket(BUCKET) - .key(key) - .ifNoneMatch("*") - .contentLength((long) replacement.length) - .checksumAlgorithm(ChecksumAlgorithm.SHA256) - .checksumSHA256(replacementChecksum) - .serverSideEncryption(ServerSideEncryption.AES256) - .metadata(java.util.Map.of("ca-logical-sha256", replacementChecksum)) - .build(), - AsyncRequestBody.fromByteBuffer(ByteBuffer.wrap(replacement))) - .join(); - assertThat(overwrittenDespiteCreateOnlyCondition.eTag()).isNotBlank(); + // when + Throwable second = catchThrowable(() -> createOnlyPut(key, replacement)); + + // then + assertPreconditionFailed(second); var head = client .headObject( @@ -166,79 +145,78 @@ class MinioManagedObjectContractTest { .checksumMode(ChecksumMode.ENABLED) .build()) .join(); - assertThat(head.contentLength()).isEqualTo(replacement.length); - assertThat(head.metadata()).containsEntry("ca-logical-sha256", replacementChecksum); + assertThat(List.of(head.eTag(), head.contentLength(), head.metadata().get("ca-logical-sha256"))) + .containsExactly(first.eTag(), (long) content.length, sha256(content)); assertThat(head.serverSideEncryption()).isEqualTo(ServerSideEncryption.AES256); + } + /** Checksum, SSE and ranged reads under an ETag condition, which every managed profile uses. */ + @Test + @DisplayName("현재 ETag 조건을 건 범위 읽기는 요청한 바이트만 돌려준다") + void aRangedReadUnderTheCurrentEtagReturnsOnlyTheRequestedBytes() throws Exception { + // given + byte[] content = "ranged-read-content".getBytes(StandardCharsets.UTF_8); + String key = "qualification/managed-range"; + var created = createOnlyPut(key, content); + + // when var range = client .getObject( GetObjectRequest.builder() .bucket(BUCKET) .key(key) - .ifMatch(head.eTag()) + .ifMatch(created.eTag()) .range("bytes=2-7") .build(), AsyncResponseTransformer.toBytes()) .join(); - assertThat(range.asByteArray()) - .containsExactly(java.util.Arrays.copyOfRange(replacement, 2, 8)); - byte[] control = "{\"revision\":1}".getBytes(StandardCharsets.UTF_8); - var controlCreate = - client - .putObject( - PutObjectRequest.builder() - .bucket(BUCKET) - .key("qualification/control/exact") - .ifNoneMatch("*") - .contentLength((long) control.length) - .build(), - AsyncRequestBody.fromByteBuffer(ByteBuffer.wrap(control))) - .join(); - byte[] controlTwo = "{\"revision\":2}".getBytes(StandardCharsets.UTF_8); - assertThat(controlCreate.eTag()).isNotBlank(); - var overwrittenControlCreate = - client - .putObject( - PutObjectRequest.builder() - .bucket(BUCKET) - .key("qualification/control/exact") - .ifNoneMatch("*") - .contentLength((long) controlTwo.length) - .build(), - AsyncRequestBody.fromByteBuffer(ByteBuffer.wrap(controlTwo))) - .join(); - assertThat(overwrittenControlCreate.eTag()).isNotBlank(); - assertPreconditionFailed( - () -> - client - .putObject( - PutObjectRequest.builder() - .bucket(BUCKET) - .key("qualification/control/exact") - .ifMatch("\"definitely-stale-etag\"") - .contentLength((long) controlTwo.length) - .build(), - AsyncRequestBody.fromByteBuffer(ByteBuffer.wrap(controlTwo))) - .join()); + // then + assertThat(range.asByteArray()).containsExactly(java.util.Arrays.copyOfRange(content, 2, 8)); } + /** + * The control-record CAS: create-if-absent refuses an existing record, a stale {@code If-Match} + * is refused, and only the current ETag replaces it. + */ @Test - void lowLevelMultipartWorksButCompletionCreateOnlyConditionIsIgnored() throws Exception { + @DisplayName("control 레코드는 없을 때만 생성되고 현재 ETag로만 교체된다") + void aControlRecordIsCreatedOnlyWhenAbsentAndReplacedOnlyUnderItsCurrentEtag() { + // given + String key = "qualification/control/exact"; + byte[] revisionOne = "{\"revision\":1}".getBytes(StandardCharsets.UTF_8); + byte[] revisionTwo = "{\"revision\":2}".getBytes(StandardCharsets.UTF_8); + String current = conditionalPut(key, revisionOne, "*", null).eTag(); + + // when + List refusals = + java.util.stream.Stream.of( + catchThrowable(() -> conditionalPut(key, revisionTwo, "*", null)), + catchThrowable( + () -> conditionalPut(key, revisionTwo, null, "\"definitely-stale-etag\""))) + .map(MinioManagedObjectContractTest::preconditionStatus) + .toList(); + String replaced = conditionalPut(key, revisionTwo, null, current).eTag(); + + // then + assertThat(refusals).containsExactly(412, 412); + assertThat(replaced).isNotBlank().isNotEqualTo(current); + } + + /** + * The managed-multipart create-only profile: completing an upload with {@code If-None-Match: *} + * onto an existing key is refused and the existing object stays. + */ + @Test + @DisplayName("이미 있는 키에 If-None-Match로 multipart를 완료하면 412로 거절되고 기존 객체가 남는다") + void aCreateOnlyMultipartCompletionOntoAnExistingKeyIsRejected() throws Exception { + // given byte[] original = "pre-existing-target".getBytes(StandardCharsets.UTF_8); byte[] content = "final-part-can-be-small".getBytes(StandardCharsets.UTF_8); String checksum = sha256(content); String key = "qualification/managed-multipart"; - client - .putObject( - PutObjectRequest.builder() - .bucket(BUCKET) - .key(key) - .contentLength((long) original.length) - .build(), - AsyncRequestBody.fromByteBuffer(ByteBuffer.wrap(original))) - .join(); + put(BUCKET, key, original); var initiated = client .createMultipartUpload( @@ -263,41 +241,49 @@ class MinioManagedObjectContractTest { .build(), AsyncRequestBody.fromByteBuffer(ByteBuffer.wrap(content))) .join(); - var completed = - client - .completeMultipartUpload( - CompleteMultipartUploadRequest.builder() - .bucket(BUCKET) - .key(key) - .uploadId(initiated.uploadId()) - .multipartUpload( - CompletedMultipartUpload.builder() - .parts( - List.of( - CompletedPart.builder() - .partNumber(1) - .eTag(part.eTag()) - .checksumSHA256(part.checksumSHA256()) - .build())) + + // when + Throwable completion = + catchThrowable( + () -> + client + .completeMultipartUpload( + CompleteMultipartUploadRequest.builder() + .bucket(BUCKET) + .key(key) + .uploadId(initiated.uploadId()) + .multipartUpload( + CompletedMultipartUpload.builder() + .parts( + List.of( + CompletedPart.builder() + .partNumber(1) + .eTag(part.eTag()) + .checksumSHA256(part.checksumSHA256()) + .build())) + .build()) + .ifNoneMatch("*") .build()) - .ifNoneMatch("*") - .build()) - .join(); - assertThat(completed.eTag()).isNotBlank(); - var overwritten = - client - .getObject( - GetObjectRequest.builder().bucket(BUCKET).key(key).build(), - AsyncResponseTransformer.toBytes()) - .join(); - assertThat(overwritten.asByteArray()).containsExactly(content); + .join()); + + // then + assertPreconditionFailed(completion); + assertThat( + client + .getObject( + GetObjectRequest.builder().bucket(BUCKET).key(key).build(), + AsyncResponseTransformer.toBytes()) + .join() + .asByteArray()) + .containsExactly(original); } /** - * Why S3 retirement cannot rest on an ETag: the qualified release ignores {@code If-Match} on - * DELETE, so a stale condition still removes the object. + * Why S3 retirement cannot rest on an ETag: the qualified release still ignores {@code If-Match} + * on DELETE, so a stale condition still removes the object. */ @Test + @DisplayName("오래된 ETag 조건을 건 DELETE도 객체를 지운다") void aStaleEtagConditionOnDeleteIsIgnored() { // given String key = "qualification/etag-delete"; @@ -324,6 +310,7 @@ class MinioManagedObjectContractTest { * version and never an overwrite that landed after the HEAD. */ @Test + @DisplayName("version id로 지우면 확인한 버전만 지워지고 뒤에 덮어쓴 버전은 남는다") void aVersionIdDeleteRemovesOnlyTheVerifiedVersionEvenAfterAnOverwrite() { // given String key = "qualification/version-delete"; @@ -352,6 +339,7 @@ class MinioManagedObjectContractTest { /** A bucket without versioning gives HEAD no version id, which the provider refuses to retire. */ @Test + @DisplayName("버전 관리가 꺼진 bucket의 HEAD는 version id를 주지 않는다") void anUnversionedBucketGivesHeadNoVersionId() { // given String key = "qualification/unversioned-head"; @@ -366,6 +354,7 @@ class MinioManagedObjectContractTest { /** The startup check the S3 contribution runs for a profile that claims retirement. */ @Test + @DisplayName("버전 관리는 켠 bucket에서만 ENABLED로 보고된다") void bucketVersioningIsReportedEnabledOnlyWhereItWasTurnedOn() { // when List statuses = @@ -406,12 +395,47 @@ class MinioManagedObjectContractTest { return Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(value)); } - private static void assertPreconditionFailed( - org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { - assertThatThrownBy(action) + private static PutObjectResponse createOnlyPut(String key, byte[] content) throws Exception { + String checksum = sha256(content); + return client + .putObject( + PutObjectRequest.builder() + .bucket(BUCKET) + .key(key) + .ifNoneMatch("*") + .contentLength((long) content.length) + .checksumAlgorithm(ChecksumAlgorithm.SHA256) + .checksumSHA256(checksum) + .serverSideEncryption(ServerSideEncryption.AES256) + .metadata(java.util.Map.of("ca-logical-sha256", checksum)) + .build(), + AsyncRequestBody.fromByteBuffer(ByteBuffer.wrap(content))) + .join(); + } + + private static PutObjectResponse conditionalPut( + String key, byte[] content, String ifNoneMatch, String ifMatch) { + return client + .putObject( + PutObjectRequest.builder() + .bucket(BUCKET) + .key(key) + .ifNoneMatch(ifNoneMatch) + .ifMatch(ifMatch) + .contentLength((long) content.length) + .build(), + AsyncRequestBody.fromByteBuffer(ByteBuffer.wrap(content))) + .join(); + } + + private static int preconditionStatus(Throwable thrown) { + assertThat(thrown) .isInstanceOf(CompletionException.class) - .hasCauseInstanceOf(S3Exception.class) - .extracting(Throwable::getCause) - .satisfies(cause -> assertThat(((S3Exception) cause).statusCode()).isEqualTo(412)); + .hasCauseInstanceOf(S3Exception.class); + return ((S3Exception) thrown.getCause()).statusCode(); + } + + private static void assertPreconditionFailed(Throwable thrown) { + assertThat(preconditionStatus(thrown)).isEqualTo(412); } } diff --git a/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/QualificationImages.java b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/QualificationImages.java index f4b95cbb..efe1e497 100644 --- a/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/QualificationImages.java +++ b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/QualificationImages.java @@ -10,13 +10,13 @@ import org.testcontainers.utility.DockerImageName; * only supplies the pull, Testcontainers' own image resolution, so a missing image fails here as * {@code pinned image unavailable: } instead of inside a container start. */ -final class QualificationImages { +public final class QualificationImages { private QualificationImages() {} // Loaded per call, not in a static initializer: a refused override then reads as its own // message instead of an ExceptionInInitializerError. - static DockerImageName minio() { + public static DockerImageName minio() { MinioQualificationImage images = MinioQualificationImage.load(); return pulled(images, images.minio()); } diff --git a/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/s3/MinioS3ManagedObjectProviderContractTest.java b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/s3/MinioS3ManagedObjectProviderContractTest.java new file mode 100644 index 00000000..f4409a48 --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/s3/MinioS3ManagedObjectProviderContractTest.java @@ -0,0 +1,141 @@ +package dev.caskeleton.adapter.outbound.objectstorage.s3; + +import dev.caskeleton.adapter.outbound.objectstorage.contract.ObjectStorageProviderContract; +import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProvider; +import dev.caskeleton.adapter.outbound.objectstorage.qualification.QualificationImages; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.util.Base64; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.utility.MountableFile; +import software.amazon.awssdk.services.s3.S3AsyncClient; +import software.amazon.awssdk.services.s3.model.BucketVersioningStatus; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.PutBucketVersioningRequest; +import software.amazon.awssdk.services.s3.model.VersioningConfiguration; + +/** + * The S3 provider against the measured MinIO, under the same provider contract the local-dev + * provider inherits (review 05-16: the contract used to have one implementation under it, and the + * only real-vendor lane exercised raw SDK calls, not the adapter). + * + *

      The binding is compiled for the pgsty release the evidence names, and the client is the + * production factory's. MinIO serves TLS with a certificate made for this run, because a binding + * only accepts HTTPS endpoints: over plain HTTP the SDK signs the payload, which needs a second + * subscription the single-pass body bridge refuses, so an HTTP run would test a path production + * never takes. + */ +class MinioS3ManagedObjectProviderContractTest extends ObjectStorageProviderContract { + + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + private static GenericContainer minio; + private static S3ClientLifecycle lifecycle; + private static S3AsyncClient client; + private static ExecutorService contentWorker; + private static S3ManagedObjectProvider provider; + private static Runnable trustStoreBefore; + + @BeforeAll + // The container is assigned to a static field and stopped in the matching @AfterAll; the fluent + // withX chain reads to the compiler as a second, unclosed instance. + @SuppressWarnings("resource") + static void startMeasuredMinio() throws Exception { + String accessKey = "a" + UUID.randomUUID().toString().replace("-", ""); + String secretKey = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID(); + byte[] keyBytes = new byte[32]; + SECURE_RANDOM.nextBytes(keyBytes); + Path certificates = SelfSignedServerCertificate.writeTo(Files.createTempDirectory("minio-tls")); + trustStoreBefore = SelfSignedServerCertificate.trustForThisJvm(certificates); + minio = + new GenericContainer<>(QualificationImages.minio()) + .withCopyFileToContainer( + MountableFile.forHostPath(certificates.resolve("public.crt")), "/certs/public.crt") + .withCopyFileToContainer( + MountableFile.forHostPath(certificates.resolve("private.key")), + "/certs/private.key") + .withExposedPorts(9000) + .withEnv("MINIO_ROOT_USER", accessKey) + .withEnv("MINIO_ROOT_PASSWORD", secretKey) + .withEnv( + "MINIO_KMS_SECRET_KEY", + "contract-key:" + Base64.getEncoder().encodeToString(keyBytes)) + .withCommand("server", "/data", "--certs-dir", "/certs"); + minio.start(); + // The production client factory, so the provider runs on the client it ships with (checksum + // calculation WHEN_REQUIRED, no SDK multipart, bounded Netty pool). + lifecycle = + new S3AsyncClientFactory() + .create( + S3ClientPolicy.builder() + .region("ap-northeast-2") + .apiCallTimeout(Duration.ofSeconds(20)) + .apiCallAttemptTimeout(Duration.ofSeconds(10)) + .connectionTimeout(Duration.ofSeconds(2)) + .tlsNegotiationTimeout(Duration.ofSeconds(2)) + .connectionAcquireTimeout(Duration.ofSeconds(2)) + .readTimeout(Duration.ofSeconds(5)) + .writeTimeout(Duration.ofSeconds(5)) + .maximumConcurrency(8) + .maximumPendingAcquires(16) + .maximumAttempts(1) + .retryBaseDelay(Duration.ofMillis(10)) + .retryMaximumBackoff(Duration.ofMillis(20)) + .shutdownGrace(Duration.ofSeconds(2)) + .endpointOverride(URI.create("https://localhost:" + minio.getMappedPort(9000))) + .pathStyleAccess(true) + .staticCredentials(accessKey, secretKey) + .build()); + client = lifecycle.client(); + S3ProviderBinding binding = + S3ProviderBinding.compile( + "minio", + S3ProviderBindingTest.provider( + S3ProviderBindingTest.PGSTY_TYPE, + S3ProviderBindingTest.pgstySettings( + ObjectStorageProvider.Capability.IMMUTABLE_CREATE)), + Clock.systemUTC()); + client.createBucket(CreateBucketRequest.builder().bucket(binding.bucket()).build()).join(); + client + .putBucketVersioning( + PutBucketVersioningRequest.builder() + .bucket(binding.bucket()) + .versioningConfiguration( + VersioningConfiguration.builder() + .status(BucketVersioningStatus.ENABLED) + .build()) + .build()) + .join(); + contentWorker = Executors.newFixedThreadPool(2); + provider = new S3ManagedObjectProvider(client, binding, contentWorker); + } + + @AfterAll + static void stopMeasuredMinio() { + if (contentWorker != null) { + contentWorker.shutdownNow(); + } + if (lifecycle != null) { + lifecycle.close(); + } + if (minio != null) { + minio.stop(); + } + if (trustStoreBefore != null) { + trustStoreBefore.run(); + } + } + + @Override + protected ObjectStorageProvider provider() { + return provider; + } +} diff --git a/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/s3/SelfSignedServerCertificate.java b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/s3/SelfSignedServerCertificate.java new file mode 100644 index 00000000..35624b4b --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/integrationTest/java/dev/caskeleton/adapter/outbound/objectstorage/s3/SelfSignedServerCertificate.java @@ -0,0 +1,115 @@ +package dev.caskeleton.adapter.outbound.objectstorage.s3; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +/** + * A throwaway localhost server certificate for one lane run, made with the running JDK's keytool so + * no key material is committed. MinIO reads {@code public.crt} and {@code private.key} (PKCS#8 PEM) + * from its certs directory; the JVM trusts the same certificate through its default trust store + * properties, which the SDK's Netty client reads. + */ +final class SelfSignedServerCertificate { + + private static final String STORE = "server.p12"; + private static final String ALIAS = "minio"; + + private SelfSignedServerCertificate() {} + + static Path writeTo(Path directory) throws Exception { + String password = password(directory); + Path keytool = Path.of(System.getProperty("java.home"), "bin", "keytool"); + Process process = + new ProcessBuilder( + List.of( + keytool.toString(), + "-genkeypair", + "-alias", + ALIAS, + "-keyalg", + "EC", + "-groupname", + "secp256r1", + "-sigalg", + "SHA256withECDSA", + "-validity", + "2", + "-dname", + "CN=localhost", + "-ext", + "SAN=dns:localhost,ip:127.0.0.1", + "-storetype", + "PKCS12", + "-keystore", + directory.resolve(STORE).toString(), + "-storepass", + password, + "-keypass", + password)) + .redirectErrorStream(true) + .start(); + if (!process.waitFor(60, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException( + "keytool failed: " + + new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8)); + } + KeyStore store = KeyStore.getInstance("PKCS12"); + try (InputStream in = Files.newInputStream(directory.resolve(STORE))) { + store.load(in, password.toCharArray()); + } + Files.writeString( + directory.resolve("public.crt"), + pem("CERTIFICATE", store.getCertificate(ALIAS).getEncoded())); + Files.writeString( + directory.resolve("private.key"), + pem("PRIVATE KEY", store.getKey(ALIAS, password.toCharArray()).getEncoded())); + return directory; + } + + /** Points the JVM default trust store at the certificate; the returned action restores it. */ + static Runnable trustForThisJvm(Path directory) throws Exception { + String[] names = { + "javax.net.ssl.trustStore", "javax.net.ssl.trustStorePassword", "javax.net.ssl.trustStoreType" + }; + String[] before = new String[names.length]; + for (int index = 0; index < names.length; index++) { + before[index] = System.getProperty(names[index]); + } + System.setProperty(names[0], directory.resolve(STORE).toString()); + System.setProperty(names[1], password(directory)); + System.setProperty(names[2], "PKCS12"); + return () -> { + for (int index = 0; index < names.length; index++) { + if (before[index] == null) { + System.clearProperty(names[index]); + } else { + System.setProperty(names[index], before[index]); + } + } + }; + } + + // Derived from the directory so writeTo and trustForThisJvm agree without a shared field; the + // store holds a throwaway key for one run, so the value only has to be non-empty. + private static String password(Path directory) { + return UUID.nameUUIDFromBytes(directory.toString().getBytes(StandardCharsets.UTF_8)).toString(); + } + + private static String pem(String type, byte[] der) { + return "-----BEGIN " + + type + + "-----\n" + + Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII)).encodeToString(der) + + "\n-----END " + + type + + "-----\n"; + } +} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncClientFactory.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncClientFactory.java index c736a00a..d4923460 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncClientFactory.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncClientFactory.java @@ -35,6 +35,11 @@ public final class S3AsyncClientFactory { BackoffStrategy throttlingBackoff = BackoffStrategy.exponentialDelayHalfJitter( policy.retryBaseDelay(), policy.retryMaximumBackoff()); + // maxAttempts covers reads. A PUT cannot use it: S3AsyncRequestBodyBridge streams the + // producer once and refuses a second subscription, so an SDK retry of a mutation fails at + // once and is reported INDETERMINATE (review 05-23b). That is deliberate — replaying a + // producer could write different bytes — and the publication kernel settles the outcome with + // resolveCreate on its next attempt instead of the SDK retrying blind. StandardRetryStrategy retry = StandardRetryStrategy.builder() .maxAttempts(policy.maximumAttempts()) diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridge.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridge.java index 08c6e87d..dd301e6c 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridge.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridge.java @@ -83,6 +83,9 @@ public final class S3AsyncRequestBodyBridge implements AsyncRequestBody { private long demand; private boolean cancelled; private boolean terminated; + // Bytes handed to the subscriber; guarded by monitor. Once it reaches the exact length a + // downstream cancel is the SDK finishing, not the upload being abandoned. + private long delivered; private BridgeSubscription(Subscriber subscriber) { this.subscriber = subscriber; @@ -115,7 +118,8 @@ public final class S3AsyncRequestBodyBridge implements AsyncRequestBody { private void produce() { MessageDigest digest = Sha256.newMessageDigest(); long[] written = {0}; - CancellationView cancellation = () -> operation.cancellation().isCancelled() || isCancelled(); + CancellationView cancellation = + () -> operation.cancellation().isCancelled() || (isCancelled() && !deliveredEverything()); ObjectContentProductionContext context = ObjectContentProductionContext.open( operation.budget(), cancellation, operation.maximumChunkBytes()); @@ -144,6 +148,9 @@ public final class S3AsyncRequestBodyBridge implements AsyncRequestBody { } digest.update(copy); written[0] = next; + synchronized (monitor) { + delivered = next; + } }); try { requireActive(); @@ -161,11 +168,15 @@ public final class S3AsyncRequestBodyBridge implements AsyncRequestBody { "S3 producer content does not match its expected identity", null); } + boolean downstreamStillListening; synchronized (monitor) { terminated = true; + downstreamStillListening = !cancelled; } observedIdentity.complete(observed); - subscriber.onComplete(); + if (downstreamStillListening) { + subscriber.onComplete(); + } } catch (Exception exception) { ObjectStorageProviderException mapped = exception instanceof ObjectStorageProviderException providerException @@ -203,7 +214,7 @@ public final class S3AsyncRequestBodyBridge implements AsyncRequestBody { } private void requireActive() { - if (isCancelled()) { + if (isCancelled() && !deliveredEverything()) { throw providerFailure( ObjectStorageProviderException.Failure.CANCELLED, "S3 content production is cancelled", @@ -221,6 +232,19 @@ public final class S3AsyncRequestBodyBridge implements AsyncRequestBody { } } + /** + * Whether the subscriber already holds the exact length. The SDK cancels its subscription as + * soon as it has Content-Length bytes, without waiting for onComplete (and at once for an empty + * body), so a cancel from then on ends nothing: the producer is still run to the end and its + * digest checked, and the exact-length bound refuses any byte it tries to add. + */ + private boolean deliveredEverything() { + synchronized (monitor) { + return !operation.cancellation().isCancelled() + && delivered == operation.expectedContentIdentity().exactLength(); + } + } + private boolean isCancelled() { synchronized (monitor) { return cancelled || operation.cancellation().isCancelled(); diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridge.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridge.java index 046a7eca..7a86ecf0 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridge.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridge.java @@ -28,6 +28,16 @@ import software.amazon.awssdk.core.async.SdkPublisher; */ public final class S3AsyncResponseBodyBridge implements AsyncResponseTransformer { + /** + * The largest SDK buffer accepted, whatever chunk size the consumer asked for. Netty delivers + * HTTP/1.1 content in chunks of at most 8 KiB and HTTP/2 frames of at most 16 KiB by default, so + * real buffers are network-sized, not consumer-sized; requiring them to fit the consumer's chunk + * failed every real read with a small chunk (review 05-16, found by the MinIO provider contract). + * The consumer still receives at most what it asks for per read. Memory held is at most two such + * buffers; anything larger than this ceiling still fails closed. + */ + static final int TRANSPORT_BUFFER_CEILING_BYTES = 64 * 1024; + private static final Chunk END = new Chunk(new byte[0], true); private final ObjectStorageProvider.ReadOperation operation; @@ -192,7 +202,8 @@ public final class S3AsyncResponseBodyBridge implements AsyncResponseTransfor return; } int remaining = item.remaining(); - if (remaining < 1 || remaining > operation.maximumChunkBytes()) { + if (remaining < 1 + || remaining > Math.max(operation.maximumChunkBytes(), TRANSPORT_BUFFER_CEILING_BYTES)) { // fail() records the cause before it cancels: cancelling first lets the consumer wake on // the cancellation and complete the result with its own, less precise failure. fail( diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java index 3dfc7bad..3688afa5 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java @@ -9,11 +9,13 @@ import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProvi import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderDescriptor; import dev.caskeleton.application.outbound.SecretSourcePort; import java.time.Clock; +import java.util.Arrays; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Function; +import java.util.stream.Collectors; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.BucketVersioningStatus; import software.amazon.awssdk.services.s3.model.GetBucketVersioningRequest; @@ -65,9 +67,9 @@ public final class S3ObjectStorageProviderContribution @Override public Set providerTypes() { - return Set.of( - S3ProviderType.AWS_S3_GENERAL_PURPOSE.token(), - S3ProviderType.MINIO_COMMUNITY_2024_01_16.token()); + return Arrays.stream(S3ProviderType.values()) + .map(S3ProviderType::token) + .collect(Collectors.toUnmodifiableSet()); } @Override diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderBinding.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderBinding.java index 4ddcf5a4..2374f390 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderBinding.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderBinding.java @@ -182,25 +182,32 @@ public record S3ProviderBinding( if (!expectedIdentity.equals(evidence.providerAndDeploymentIdentity())) { throw invalid("capability evidence identity does not match the provider binding"); } - if (providerType == S3ProviderType.MINIO_COMMUNITY_2024_01_16 + if (providerType.selfHostedMinio() && evidence.status() == dev.caskeleton.adapter.outbound.objectstorage.readiness.CapabilityEvidenceStatus .SUPPORTED - && (config.capabilities().contains(ObjectStorageProvider.Capability.IMMUTABLE_CREATE) - || config - .capabilities() - .contains(ObjectStorageProvider.Capability.MULTI_NODE_LINEARIZABLE_CAS) - || config - .capabilities() - .contains(ObjectStorageProvider.Capability.RESPONSE_LOSS_RESOLUTION))) { + && claimsUnmeasuredMinioMutation(providerType, config)) { throw invalid( - "the exact MinIO release cannot claim native conditional managed mutation support"); + "the exact MinIO release cannot claim native conditional managed mutation support" + + " it was not measured for"); } profiles.put(name, new ObjectStorageOperationProfile(name, config.capabilities(), evidence)); } return Map.copyOf(profiles); } + private static boolean claimsUnmeasuredMinioMutation( + S3ProviderType providerType, S3ProviderCapabilityConfig config) { + return (!providerType.measuredCreateOnly() + && config.capabilities().contains(ObjectStorageProvider.Capability.IMMUTABLE_CREATE)) + || config + .capabilities() + .contains(ObjectStorageProvider.Capability.MULTI_NODE_LINEARIZABLE_CAS) + || config + .capabilities() + .contains(ObjectStorageProvider.Capability.RESPONSE_LOSS_RESOLUTION); + } + private static EnumMap supportAt( Map profiles, Instant instant) { EnumMap support = @@ -236,7 +243,7 @@ public record S3ProviderBinding( if (type == S3ProviderType.AWS_S3_GENERAL_PURPOSE && endpoint != null) { throw invalid("AWS endpoint override is not part of the qualified profile"); } - if (type == S3ProviderType.MINIO_COMMUNITY_2024_01_16 && endpoint == null) { + if (type.selfHostedMinio() && endpoint == null) { throw invalid("MinIO endpoint is required"); } if (endpoint == null) { diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderErrorMapper.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderErrorMapper.java index 54964c9b..c601cbef 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderErrorMapper.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderErrorMapper.java @@ -62,7 +62,11 @@ public final class S3ProviderErrorMapper { case 404 -> Failure.NOT_FOUND; case 409 -> Failure.CONFLICT; case 412 -> Failure.PRECONDITION_FAILED; - case 429, 500, 502, 503, 504 -> Failure.THROTTLED; + case 429 -> Failure.THROTTLED; + // A server error on a PUT or completion can arrive after the object was written, so it is + // not "confirmed not applied" (review 05-23b): the kernel resolves it. S3's own throttling + // reply carries SlowDown and is mapped above, before the status is looked at. + case 500, 502, 503, 504 -> mutation ? Failure.INDETERMINATE : Failure.THROTTLED; default -> mutation ? Failure.INDETERMINATE : Failure.UNKNOWN; }; } diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderType.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderType.java index 6ee78a77..99c877a4 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderType.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderType.java @@ -2,21 +2,50 @@ package dev.caskeleton.adapter.outbound.objectstorage.s3; import java.util.Arrays; -/** Closed exact S3-family provider allowlist. */ +/** + * Closed exact S3-family provider allowlist. + * + *

      Each MinIO entry names a server release, not an image source. The 2024-01-16 community release + * stays because servers running it still exist, even though Docker Hub no longer serves its image + * (review 05-09). The pgsty entry is the release the qualification lanes now run; its create-only + * behaviour was measured (a second {@code If-None-Match: *} PUT or multipart completion is refused + * with 412), so it is the only MinIO release that may claim {@code IMMUTABLE_CREATE}. + */ public enum S3ProviderType { - AWS_S3_GENERAL_PURPOSE("aws-s3-general-purpose"), - MINIO_COMMUNITY_2024_01_16("s3-compatible-minio-community-release-2024-01-16t16-07-38z"); + AWS_S3_GENERAL_PURPOSE("aws-s3-general-purpose", false, false), + MINIO_COMMUNITY_2024_01_16( + "s3-compatible-minio-community-release-2024-01-16t16-07-38z", true, false), + MINIO_PGSTY_2026_08_04("s3-compatible-minio-pgsty-release-2026-08-04t00-00-00z", true, true); private final String token; + private final boolean selfHostedMinio; + private final boolean measuredCreateOnly; - S3ProviderType(String token) { + S3ProviderType(String token, boolean selfHostedMinio, boolean measuredCreateOnly) { this.token = token; + this.selfHostedMinio = selfHostedMinio; + this.measuredCreateOnly = measuredCreateOnly; } public String token() { return token; } + /** A MinIO release: an endpoint is required and credentials come from named environment keys. */ + boolean selfHostedMinio() { + return selfHostedMinio; + } + + /** + * Whether the qualification lane measured create-only conditional writes on this MinIO release. + * Only then may a profile claim {@code IMMUTABLE_CREATE}. Multi-node linearizable CAS and + * response-loss resolution stay unclaimable for every MinIO release: the evidence is one local + * single-node container. + */ + boolean measuredCreateOnly() { + return measuredCreateOnly; + } + public static S3ProviderType parse(String token) { return Arrays.stream(values()) .filter(candidate -> candidate.token.equals(token)) diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderVersion.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderVersion.java index 6c754330..b30cbc75 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderVersion.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderVersion.java @@ -4,7 +4,9 @@ package dev.caskeleton.adapter.outbound.objectstorage.s3; public enum S3ProviderVersion { AWS_SDK_2_30_0(S3ProviderType.AWS_S3_GENERAL_PURPOSE, "aws-sdk-2.30.0"), MINIO_2024_01_16_SDK_2_30_0( - S3ProviderType.MINIO_COMMUNITY_2024_01_16, "release-2024-01-16t16-07-38z-sdk-2.30.0"); + S3ProviderType.MINIO_COMMUNITY_2024_01_16, "release-2024-01-16t16-07-38z-sdk-2.30.0"), + MINIO_PGSTY_2026_08_04_SDK_2_30_0( + S3ProviderType.MINIO_PGSTY_2026_08_04, "release-2026-08-04t00-00-00z-sdk-2.30.0"); private final S3ProviderType providerType; private final String token; diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/ComposeMinioImageMatchesEvidenceTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/ComposeMinioImageMatchesEvidenceTest.java new file mode 100644 index 00000000..91f91394 --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/ComposeMinioImageMatchesEvidenceTest.java @@ -0,0 +1,40 @@ +package dev.caskeleton.adapter.outbound.objectstorage.qualification; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The local compose MinIO is the image the lanes measured. Compose cannot read the evidence JSON, + * so this is the one check that keeps the two references from drifting apart again (review 05-09: + * four copies, two of them disagreeing). The build declares the compose file as this task's input. + */ +class ComposeMinioImageMatchesEvidenceTest { + + static final String COMPOSE_FILE_PROPERTY = "objectstorage.compose.file"; + private static final Pattern LOCAL_MINIO_DEFAULT = + Pattern.compile( + "x-local-minio-image:\\s*&local-minio-image\\s*\"\\$\\{LOCAL_MINIO_IMAGE:-([^}]+)}\""); + + @Test + @DisplayName("compose의 기본 MinIO 이미지는 evidence가 측정한 이미지와 같은 digest다") + void theComposeDefaultMinioImageIsTheMeasuredEvidenceImage() throws IOException { + // given + String compose = Files.readString(Path.of(System.getProperty(COMPOSE_FILE_PROPERTY))); + Matcher defaultImage = LOCAL_MINIO_DEFAULT.matcher(compose); + + // when + String measured = MinioQualificationImage.load(Optional.empty()).minio(); + + // then + assertThat(defaultImage.find()).as("x-local-minio-image default in the compose file").isTrue(); + assertThat(defaultImage.group(1)).isEqualTo(measured); + } +} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridgeTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridgeTest.java index d389c9af..b9db9a95 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridgeTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridgeTest.java @@ -15,7 +15,10 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; @@ -121,6 +124,78 @@ class S3AsyncRequestBodyBridgeTest { } } + /** + * The SDK stops its subscription once it holds Content-Length bytes, before any onComplete: a + * cancel after the exact length arrived is the upload finishing, not the caller giving up. The + * real MinIO lane found every S3 create failing on it (review 05-16). + */ + @ParameterizedTest + @ValueSource(ints = {0, 1, 193}) + @DisplayName("정확한 길이를 다 받은 뒤 구독이 취소되면 업로드는 완료로 기록된다") + void aCancelAfterTheExactLengthArrivedCompletesTheObservedIdentity(int size) throws Exception { + // given + byte[] content = new byte[size]; + for (int index = 0; index < size; index++) { + content[index] = (byte) index; + } + ObjectStorageProviderOperation operation = + ObjectStorageProviderContract.operation( + 503 + size, + content, + dev.caskeleton.application.objectstorage.content.CancellationView.never()); + var executor = Executors.newSingleThreadExecutor(); + try { + S3AsyncRequestBodyBridge bridge = + new S3AsyncRequestBodyBridge( + operation, ObjectStorageProviderContract.producer(content), executor); + + // when + bridge.subscribe(new CancelAtLengthSubscriber(size)); + + // then + assertThat(bridge.observedIdentity().get(5, TimeUnit.SECONDS)) + .isEqualTo(operation.expectedContentIdentity()); + } finally { + executor.shutdownNow(); + } + } + + /** What the SDK's content-length subscriber does: take exactly {@code length}, then cancel. */ + private static final class CancelAtLengthSubscriber implements Subscriber { + + private final long length; + private long received; + private Subscription subscription; + + private CancelAtLengthSubscriber(long length) { + this.length = length; + } + + @Override + public void onSubscribe(Subscription subscription) { + this.subscription = subscription; + if (length == 0) { + subscription.cancel(); + return; + } + subscription.request(Long.MAX_VALUE); + } + + @Override + public void onNext(ByteBuffer item) { + received += item.remaining(); + if (received >= length) { + subscription.cancel(); + } + } + + @Override + public void onError(Throwable throwable) {} + + @Override + public void onComplete() {} + } + private static final class CollectingSubscriber implements Subscriber { private final List bytes = new ArrayList<>(); diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridgeTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridgeTest.java index 9c9cc73a..80dc41b1 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridgeTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridgeTest.java @@ -19,6 +19,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.services.s3.model.GetObjectResponse; @@ -112,22 +113,68 @@ class S3AsyncResponseBodyBridgeTest { .hasCauseInstanceOf(RuntimeException.class); } + /** + * Netty hands the SDK network-sized buffers (HTTP/1.1 content chunks of up to 8 KiB), whatever + * chunk size the consumer asked for. The real MinIO lane failed every read whose chunk size was + * below that (review 05-16), so a buffer up to the transport ceiling is accepted and the consumer + * still reads it in pieces no larger than it asked for. + */ @Test + @DisplayName("소비자 chunk보다 큰 네트워크 버퍼도 상한 안이면 요청한 크기로 나눠 전달한다") + void aNetworkBufferLargerThanTheConsumerChunkIsDeliveredInConsumerSizedPieces() throws Exception { + // given + byte[] content = new byte[8192]; + for (int index = 0; index < content.length; index++) { + content[index] = (byte) (index * 13); + } + ByteArrayOutputStream delivered = new ByteArrayOutputStream(); + java.util.concurrent.atomic.AtomicInteger largestRead = + new java.util.concurrent.atomic.AtomicInteger(); + S3AsyncResponseBodyBridge bridge = + new S3AsyncResponseBodyBridge<>( + readUpTo(514, content), + (context, source) -> { + byte[] buffer = new byte[64]; + for (int count = source.read(buffer, 0, buffer.length); + count != -1; + count = source.read(buffer, 0, buffer.length)) { + largestRead.accumulateAndGet(count, Math::max); + delivered.write(buffer, 0, count); + } + }, + worker, + ignored -> {}); + var result = bridge.prepare(); + bridge.onResponse(GetObjectResponse.builder().contentLength((long) content.length).build()); + + // when + bridge.onStream(SdkPublisher.fromIterable(List.of(ByteBuffer.wrap(content)))); + + // then + assertThat(result.get(HANG_GUARD_MINUTES, TimeUnit.MINUTES).contentLength()) + .isEqualTo(content.length); + assertThat(delivered.toByteArray()).containsExactly(content); + assertThat(largestRead).hasValueLessThanOrEqualTo(64); + } + + @Test + @DisplayName("전송 상한보다 큰 SDK 버퍼는 닫힌 쪽으로 실패한다") void oversizedSdkChunkFailsClosed() throws Exception { // given + int oversize = S3AsyncResponseBodyBridge.TRANSPORT_BUFFER_CEILING_BYTES + 1; S3AsyncResponseBodyBridge oversized = new S3AsyncResponseBodyBridge<>( - read(513, new byte[65]), + readUpTo(513, new byte[oversize]), // The consumer reads: one that returns without reading races the publisher, and its // own "did not read the range" failure can then land before the chunk is ever seen. (context, source) -> source.read(new byte[64], 0, 64), worker, ignored -> {}); var result = oversized.prepare(); - oversized.onResponse(GetObjectResponse.builder().contentLength(65L).build()); + oversized.onResponse(GetObjectResponse.builder().contentLength((long) oversize).build()); // when - oversized.onStream(SdkPublisher.fromIterable(List.of(ByteBuffer.wrap(new byte[65])))); + oversized.onStream(SdkPublisher.fromIterable(List.of(ByteBuffer.wrap(new byte[oversize])))); // then Throwable thrown = catchThrowable(() -> result.get(HANG_GUARD_MINUTES, TimeUnit.MINUTES)); @@ -139,6 +186,22 @@ class S3AsyncResponseBodyBridgeTest { } /** A fresh read with its own budget, so no bridge inherits time another bridge already used. */ + /** A read of {@code content} with a 64-byte consumer chunk and room for the whole body. */ + private static ObjectStorageProvider.ReadOperation readUpTo(int seed, byte[] content) { + var key = ObjectStorageProviderContract.operation(seed, new byte[0], CancellationView.never()); + return new ObjectStorageProvider.ReadOperation( + key.canonicalDataKey(), + S3ObjectEvidenceMapper.versionForKey(key.canonicalDataKey()), + new dev.caskeleton.application.objectstorage.model.ObjectContentIdentity( + content.length, + dev.caskeleton.application.objectstorage.model.ObjectDigest.sha256(content)), + ObjectReadRange.of(0, content.length), + CallBudget.fromNow(NEVER_EXPIRES), + CancellationView.never(), + 64, + content.length); + } + private static ObjectStorageProvider.ReadOperation read(int seed, byte[] content) { var operation = ObjectStorageProviderContract.operation(seed, content, CancellationView.never()); diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderBindingTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderBindingTest.java index 0c529548..e3f4e2a9 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderBindingTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderBindingTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.objectstorage.s3; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageProviderSettings; import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProvider; @@ -16,7 +17,10 @@ import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.springframework.util.unit.DataSize; class S3ProviderBindingTest { @@ -279,6 +283,69 @@ class S3ProviderBindingTest { Map.of("managed-common", retirementClaim)); } + @Test + @DisplayName("측정한 pgsty MinIO release는 생성 전용(IMMUTABLE_CREATE) 지원을 주장할 수 있다") + void theMeasuredPgstyReleaseMayClaimImmutableCreate() { + // given + ObjectStorageProviderSettings settings = + provider(PGSTY_TYPE, pgstySettings(ObjectStorageProvider.Capability.IMMUTABLE_CREATE)); + + // when + S3ProviderBinding binding = S3ProviderBinding.compile("minio", settings, CLOCK); + + // then + assertThat( + List.of( + binding.providerType(), + binding.providerVersion(), + binding + .providerDescriptor() + .support() + .get(ObjectStorageProvider.Capability.IMMUTABLE_CREATE))) + .containsExactly( + S3ProviderType.MINIO_PGSTY_2026_08_04, + S3ProviderVersion.MINIO_PGSTY_2026_08_04_SDK_2_30_0, + ObjectStorageProvider.Support.SUPPORTED); + } + + @ParameterizedTest + @EnumSource( + value = ObjectStorageProvider.Capability.class, + names = {"MULTI_NODE_LINEARIZABLE_CAS", "RESPONSE_LOSS_RESOLUTION"}) + @DisplayName("단일 노드에서만 측정한 pgsty MinIO release는 다중 노드 CAS·응답 유실 해소를 주장할 수 없다") + void thePgstyReleaseCannotClaimWhatSingleNodeEvidenceDidNotMeasure( + ObjectStorageProvider.Capability unmeasured) { + // given + ObjectStorageProviderSettings settings = provider(PGSTY_TYPE, pgstySettings(unmeasured)); + + // when + Throwable thrown = catchThrowable(() -> S3ProviderBinding.compile("minio", settings, CLOCK)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot claim"); + } + + static final String PGSTY_TYPE = "s3-compatible-minio-pgsty-release-2026-08-04t00-00-00z"; + private static final String PGSTY_VERSION = "release-2026-08-04t00-00-00z-sdk-2.30.0"; + + static S3ProviderSettings pgstySettings(ObjectStorageProvider.Capability claimed) { + S3ProviderSettings source = withVersion(minioSettings(), PGSTY_VERSION); + S3ProviderCapabilityConfig existing = source.capabilityProfiles().get("managed-common"); + S3ProviderCapabilityConfig claim = + new S3ProviderCapabilityConfig( + CapabilityEvidenceStatus.SUPPORTED, + existing.source(), + existing.evidenceDigest(), + existing.observedAt(), + existing.validUntil(), + PGSTY_TYPE + ":" + PGSTY_VERSION + ":minio-cluster-test-01", + Set.of(claimed), + List.of("single-node container evidence")); + return mutate(source, null, null, null, null, null, null, null, null, Map.of("managed", claim)); + } + static ObjectStorageProviderSettings provider(String type, S3ProviderSettings settings) { return new ObjectStorageProviderSettings( type, diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderErrorMapperTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderErrorMapperTest.java index f63aa1c3..fd6ff9b9 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderErrorMapperTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderErrorMapperTest.java @@ -1,10 +1,15 @@ package dev.caskeleton.adapter.outbound.objectstorage.s3; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderException.Failure; import java.net.SocketTimeoutException; +import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.model.S3Exception; @@ -41,6 +46,42 @@ class S3ProviderErrorMapperTest { assertThat(mapping.safeMessage()).doesNotContain("secret", "endpoint"); } + /** + * A 5xx on a PUT or completion may come after the object was written (review 05-23b), so it is + * not "confirmed not applied"; the kernel must resolve it. Reads keep the retryable THROTTLED. + */ + @ParameterizedTest + @ValueSource(ints = {500, 502, 503, 504}) + @DisplayName("오류 코드 없는 5xx 쓰기 실패는 미반영 확정이 아니라 결과 불명이다") + void aServerErrorOnAMutationIsIndeterminateNotConfirmedUnapplied(int status) { + // given + S3Exception exception = s3Exception(status, "InternalError"); + + // when + List mappings = + List.of(mapper.map(exception, true), mapper.map(exception, false)); + + // then + assertThat(mappings) + .extracting( + S3ProviderErrorMapper.Mapping::failure, S3ProviderErrorMapper.Mapping::authoritative) + .containsExactly(tuple(Failure.INDETERMINATE, false), tuple(Failure.THROTTLED, true)); + } + + private static S3Exception s3Exception(int status, String code) { + return (S3Exception) + S3Exception.builder() + .statusCode(status) + .awsErrorDetails( + AwsErrorDetails.builder() + .errorCode(code) + .errorMessage("sensitive") + .serviceName("S3") + .build()) + .message("sensitive request") + .build(); + } + private void assertMapped(int status, String code, Failure expected) { S3Exception exception = (S3Exception) diff --git a/src/adapter/outbound/objectstorage/src/test/resources/object-storage/minio-provider-evidence.json b/src/adapter/outbound/objectstorage/src/test/resources/object-storage/minio-provider-evidence.json index f4e41f21..f3a5ff14 100644 --- a/src/adapter/outbound/objectstorage/src/test/resources/object-storage/minio-provider-evidence.json +++ b/src/adapter/outbound/objectstorage/src/test/resources/object-storage/minio-provider-evidence.json @@ -1,25 +1,35 @@ { "schema": 1, - "providerType": "s3-compatible-minio-community-release-2024-01-16t16-07-38z", - "providerVersion": "release-2024-01-16t16-07-38z-sdk-2.30.0", - "image": "minio/minio@sha256:4c4a4876193f030c81f57aabb22bcb9a73462010eb61fcab66908e03e5484af8", + "providerType": "s3-compatible-minio-pgsty-release-2026-08-04t00-00-00z", + "providerVersion": "release-2026-08-04t00-00-00z-sdk-2.30.0", + "image": "pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372", + "imageSource": "pgsty/minio (community fork of MinIO on Docker Hub, https://github.com/pgsty/minio); minio version RELEASE.2026-08-04T00-00-00Z, commit d88f46ccee345a9c2fabe2d221d9a9e56bc11aec", "toxiproxyImage": "ghcr.io/shopify/toxiproxy@sha256:9378ed52a28bc50edc1350f936f518f31fa95f0d15917d6eb40b8e376d1a214e", + "measuredAt": "2026-11-02", "profile": "managed-common", - "status": "UNSUPPORTED", - "excludedProfiles": [ + "status": "SUPPORTED", + "supportedProfiles": [ "managed-single-create-only", "conditional-control-create", - "managed-multipart-create-only", + "managed-multipart-create-only" + ], + "excludedProfiles": [ "direct-single-create-only", "direct-multipart-create-only" ], + "measurements": [ + "PutObject If-None-Match:* onto an existing key returned HTTP 412 and the first bytes stayed", + "PutObject If-Match with a stale ETag returned HTTP 412; with the current ETag it replaced the object", + "CompleteMultipartUpload If-None-Match:* onto an existing key returned HTTP 412 and the existing object stayed", + "DeleteObject If-Match with a stale ETag is still ignored and deletes; retirement uses version-id DELETE instead" + ], "limitations": [ - "PutObject If-None-Match was accepted and overwrote an existing object", - "stale PutObject If-Match returned HTTP 412 but create-if-absent control CAS is not safe", - "CompleteMultipartUpload accepted If-None-Match despite a pre-existing target and overwrote it", - "managed immutable create, conditional control creation, and multipart create-only are disabled", - "local single-node container evidence only", + "direct (presigned) create-only profiles were not measured: the lanes send the condition from the SDK, not through a signed URL", + "local single-node container evidence only; multi-node linearizable CAS and response-loss resolution are not claimed", "not AWS evidence", "not production TLS or deployment-topology evidence" + ], + "rejectedCandidates": [ + "cgr.dev/chainguard/minio@sha256:0a01100085e30fb08d2f39e39c9f5c9d83a95707f220b007d813b690cd41622d (RELEASE.2026-10-23T20-06-51Z): same conditional-write results, but its free tier offers only a moving latest tag (no named release to re-measure against, and no stated promise that an older digest stays pullable), it runs as uid 65532 (the compose data volume would need re-owning), and its client image cgr.dev/chainguard/minio-client has no shell for the compose bucket bootstrap script" ] } diff --git a/src/adapter/outbound/persistence-fileserver/CLAUDE.md b/src/adapter/outbound/persistence-fileserver/CLAUDE.md new file mode 100644 index 00000000..38c3600d --- /dev/null +++ b/src/adapter/outbound/persistence-fileserver/CLAUDE.md @@ -0,0 +1,47 @@ +# persistence-fileserver + +Relational persistence for the Fileserver capability: entities, Spring Data repositories and the +store adapters that implement `application-fileserver` ports. Root `AGENTS.md` and +`adapter/outbound/persistence-jpa/CLAUDE.md` still apply; this file adds what is local. + +## Packages + +- `entity/` — JPA rows only. Every entity extends `AssignedIdEntity`. +- `repository/` — Spring Data interfaces and the SQL text they run (`CleanupClaimSql`). +- package root — the store adapters (`Jpa*`), `FileEntityMapper`, and the `@Configuration` + classes that register them as beans. + +## Rules + +- **Transactions.** A store never opens one. Every write starts with + `CallerTransaction.require(" ")`, so a use case that forgot + `TransactionPort.inWrite` fails instead of committing statement by statement. +- **New rows.** Ids are assigned before the insert, so an entity must say whether it is new: + extend `AssignedIdEntity` (`Persistable`). Without it `save` merges — a SELECT before every + insert, and a second insert under an existing id overwrites the row instead of failing on the + primary key. A new `@Version` column may stay primitive `long`; newness comes from + `Persistable`, not from the version (review 04-17). +- **No policy here.** Retry budgets, lease lengths and other decisions belong to + `application-fileserver` and arrive as port arguments. A claim token or other fence travels in + the port type (`CleanupItem.claimToken`), never in a field of the adapter. +- **Claims.** A queue claim is one statement: CTE + `FOR UPDATE SKIP LOCKED` + `RETURNING` + (`CleanupClaimSql`). Settlements match the claim token and update zero rows for a stale worker. + +## Migrations + +- `src/main/resources/db/migration/jpa/fileserver/V*.sql`, applied as the capability's own Flyway + stream (`flyway_jpa_fileserver_history`). +- An applied file is never edited. Add a new version and its hash to the immutability list; + `persistence-jpa`'s `AppliedMigrationImmutabilityTest` pins these files where they live. + +## Tests + +- `src/test` — this leaf's own tests, no container (`AssignedIdEntityTest` runs Hibernate on H2). + Run: `./gradlew :adapter:outbound:persistence-fileserver:test --console=plain`. +- Port contracts live in `application-fileserver` testFixtures (`*PortContract`). The in-memory + fakes and the PostgreSQL tests both extend them. +- The real-PostgreSQL tests are still in `persistence-jpa`'s `postgresqlIntegrationTest` source + set, which owns the container and Flyway wiring: + `postgresqlFileserverMigrationIntegrationTest`, `postgresqlFileserverMetadataIntegrationTest`, + `postgresqlFileserverReclamationIntegrationTest` + (`./gradlew :adapter:outbound:persistence-jpa: --console=plain`). diff --git a/src/adapter/outbound/persistence-fileserver/build.gradle b/src/adapter/outbound/persistence-fileserver/build.gradle index 0075a7bc..4f3fc89f 100644 --- a/src/adapter/outbound/persistence-fileserver/build.gradle +++ b/src/adapter/outbound/persistence-fileserver/build.gradle @@ -25,6 +25,10 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework:spring-jdbc' implementation 'org.springframework:spring-context' + + // AssignedIdEntityTest runs the entities on an in-memory H2. persistence-jpa no longer carries + // the driver at runtime (review 09-09), so the test that uses it declares it. + testRuntimeOnly 'com.h2database:h2' } // Every public type here is reachable from any leaf that puts this jar on its classpath; the one diff --git a/src/adapter/outbound/persistence-fileserver/gradle.lockfile b/src/adapter/outbound/persistence-fileserver/gradle.lockfile index 0d208677..ed3eda7e 100644 --- a/src/adapter/outbound/persistence-fileserver/gradle.lockfile +++ b/src/adapter/outbound/persistence-fileserver/gradle.lockfile @@ -33,7 +33,7 @@ com.google.guava:guava:33.6.0-jre=checkstyle com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor -com.h2database:h2:2.4.240=runtimeClasspath,testRuntimeClasspath +com.h2database:h2:2.4.240=testRuntimeClasspath com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java index 5bb4124e..8912277d 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java @@ -11,9 +11,10 @@ import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; import dev.caskeleton.application.fileserver.cleanup.CleanupType; import java.time.Clock; +import java.time.Duration; import java.time.Instant; -import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.UUID; import org.springframework.data.domain.Limit; @@ -21,21 +22,21 @@ import org.springframework.data.domain.Limit; /** * Durable, at-most-one-worker cleanup queue over {@code fs_cleanup_item}. * - *

      Claiming is a conditional update rather than a read followed by a write, so two instances - * running the same batch cannot both execute the same physical delete. + *

      Claiming is one statement that locks the due rows it picks, skips rows another claim holds, + * and returns a per-row claim token, so two instances running the same batch never execute the same + * physical delete and never wait on each other's claim. * - *

      An item that keeps failing is eventually abandoned instead of retried forever. A poison entry - * that never succeeds would otherwise occupy a slot in every batch and starve the work behind it, - * and an abandoned row is still visible to an operator — it is parked, not discarded. + *

      This adapter stores and fences; it holds no policy. The lease length arrives with each claim + * and the retry budget is the application's ({@code DefaultCleanupService}), which calls {@link + * #markAbandoned} when it decides an item has failed for the last time. The claim token travels in + * the {@link CleanupItem} rather than in a map in this process: a worker that restarted or was + * superseded still settles nothing, because the token it presents no longer matches the row. * *

      Staging cleanups carry an upload id and published cleanups carry a content key. The row keeps * both columns nullable for that reason; which one is set is what tells the worker where to look. */ public class JpaCleanupQueue implements CleanupQueuePort { - /** After this many failed attempts an item stops being rescheduled. */ - public static final int MAXIMUM_ATTEMPTS = 8; - private static final String STATUS_PENDING = "PENDING"; private static final String STATUS_DONE = "DONE"; private static final String STATUS_FAILED = "FAILED"; @@ -44,6 +45,14 @@ public class JpaCleanupQueue implements CleanupQueuePort { private final FileserverCleanupRepository items; private final Clock clock; + /** + * The owner recorded on a claim, distinct per process incarnation. + * + *

      Diagnostic only — fencing is the per-row token. A configured name alone would make a + * restarted process indistinguishable from the one it replaced in an operator's query. + */ + private final String owner = "fileserver-cleanup:" + UUID.randomUUID(); + public JpaCleanupQueue(FileserverCleanupRepository items, Clock clock) { this.items = items; this.clock = clock; @@ -65,56 +74,19 @@ public class JpaCleanupQueue implements CleanupQueuePort { now)); } - /** How long a claim is valid before the reaper may take the item over. */ - private static final java.time.Duration LEASE = java.time.Duration.ofMinutes(10); - - /** - * Tokens for claims this process holds. - * - *

      Not persisted anywhere but the row. A settlement whose token is gone — because the process - * restarted, or because the reaper handed the item to someone else — updates zero rows, which is - * the correct answer rather than an error: this worker no longer owns the item. - */ - private final java.util.Map heldClaims = - new java.util.concurrent.ConcurrentHashMap<>(); - - /** - * The owner recorded on a claim, distinct per process incarnation. - * - *

      A configured name alone would make a restarted process indistinguishable from the one it - * replaced, which is the same defect the notification dispatcher had. - */ - private final String owner = "fileserver-cleanup:" + UUID.randomUUID(); - - private void settle( - UUID cleanupId, String status, Instant nextAttemptAt, String reasonCode, Instant now) { - UUID token = heldClaims.remove(cleanupId); - if (token == null) { - // Nothing to settle: this process does not hold the claim. Writing anyway is exactly the - // stale-worker overwrite the token exists to prevent. - return; - } - items.recordAttempt(cleanupId, token, status, nextAttemptAt, reasonCode, now); - } - @Override - public List claimDue(Instant now, int limit) { + public List claimDue(Instant now, int limit, Duration lease) { CallerTransaction.require("cleanup queue claimDue"); if (limit < 1) { throw new IllegalArgumentException("limit must be positive"); } - List claimed = new ArrayList<>(); - for (CleanupItemEntity due : items.findDue(now, Limit.of(limit))) { - UUID token = UUID.randomUUID(); - if (items.claim(due.getCleanupId(), owner, token, now.plus(LEASE), now) == 1) { - // The token stays in this process. A restart loses it, and that is the point: a worker - // that restarted no longer holds the claim, so its later completion must not apply. The - // reaper takes the item over once the lease expires. - heldClaims.put(due.getCleanupId(), token); - claimed.add(toItem(due)); - } + Objects.requireNonNull(lease, "lease"); + if (lease.isNegative() || lease.isZero()) { + throw new IllegalArgumentException("lease must be positive"); } - return List.copyOf(claimed); + return items.claimDue(now, limit, owner, now.plus(lease)).stream() + .map(JpaCleanupQueue::toItem) + .toList(); } @Override @@ -126,11 +98,9 @@ public class JpaCleanupQueue implements CleanupQueuePort { int reclaimed = 0; for (CleanupItemEntity abandoned : items.findExpiredClaims(now, Limit.of(limit))) { // Matched on the token that was read, so the reaper that loses the race changes nothing — - // and the worker that eventually wakes up finds its own token gone and settles nothing. + // and the worker that eventually wakes up presents a token the row no longer has. reclaimed += - items.reclaimExpiredClaim( - abandoned.getCleanupId(), abandoned.getClaimToken(), clock.instant()); - heldClaims.remove(abandoned.getCleanupId()); + items.reclaimExpiredClaim(abandoned.getCleanupId(), abandoned.getClaimToken(), now); } return reclaimed; } @@ -139,30 +109,49 @@ public class JpaCleanupQueue implements CleanupQueuePort { public void markDone(CleanupItem item) { CallerTransaction.require("cleanup queue markDone"); Instant now = clock.instant(); - settle(item.cleanupId(), STATUS_DONE, now, null, now); + settle(item, STATUS_DONE, now, null, now); } @Override public void markFailed(CleanupItem item, String reasonCode, Instant nextAttemptAt) { CallerTransaction.require("cleanup queue markFailed"); - Instant now = clock.instant(); - boolean exhausted = item.attempt() + 1 >= MAXIMUM_ATTEMPTS; - settle( - item.cleanupId(), - exhausted ? STATUS_ABANDONED : STATUS_FAILED, - nextAttemptAt, - reasonCode, - now); + settle(item, STATUS_FAILED, nextAttemptAt, reasonCode, clock.instant()); } - private static CleanupItem toItem(CleanupItemEntity entity) { + @Override + public void markAbandoned(CleanupItem item, String reasonCode) { + CallerTransaction.require("cleanup queue markAbandoned"); + Instant now = clock.instant(); + settle(item, STATUS_ABANDONED, now, reasonCode, now); + } + + /** + * Writes the outcome for the claim {@code item} came from, and only for it. + * + *

      Zero rows is the correct answer, not an error, when the claim was reclaimed in the meantime: + * this worker no longer owns the item, and writing anyway is exactly the stale-worker overwrite + * the token exists to prevent. + */ + private void settle( + CleanupItem item, String status, Instant nextAttemptAt, String reasonCode, Instant now) { + items.recordAttempt( + item.cleanupId(), item.claimToken(), status, nextAttemptAt, reasonCode, now); + } + + /** One row of {@code CleanupClaimSql.CLAIM_DUE}. */ + private static CleanupItem toItem(Object[] row) { + UUID cleanupId = (UUID) row[0]; + UUID claimToken = (UUID) row[1]; + int attempt = ((Number) row[2]).intValue(); + CleanupType type = CleanupType.valueOf((String) row[3]); return new CleanupItem( - entity.getCleanupId(), + cleanupId, new CleanupRequest( - CleanupType.valueOf(entity.getType()), - Optional.ofNullable(entity.getFileId()).map(FileId::of), - Optional.ofNullable(entity.getUploadId()).map(UploadId::of), - Optional.ofNullable(entity.getContentKey()).map(ContentKey::of)), - entity.getAttempt()); + type, + Optional.ofNullable((UUID) row[4]).map(FileId::of), + Optional.ofNullable((UUID) row[5]).map(UploadId::of), + Optional.ofNullable((String) row[6]).map(ContentKey::of)), + attempt, + claimToken); } } diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/AssignedIdEntity.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/AssignedIdEntity.java new file mode 100644 index 00000000..059a17f1 --- /dev/null +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/AssignedIdEntity.java @@ -0,0 +1,42 @@ +package dev.caskeleton.adapter.outbound.persistence.fileserver.entity; + +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.PostLoad; +import jakarta.persistence.PostPersist; +import jakarta.persistence.Transient; +import java.util.UUID; +import org.springframework.data.domain.Persistable; + +/** + * Base of every Fileserver row: the identifier is assigned before the row is written, so whether + * the row is new has to be said rather than inferred. + * + *

      Spring Data decides between {@code persist} and {@code merge} from the identifier, or from a + * wrapper {@code @Version} when there is one. Every id here is a UUID chosen by the caller, and the + * versions are primitive {@code long} — so every {@code save} of a new row was a merge: a SELECT + * before each insert, and a second insert under an id that already existed silently overwrote the + * first row instead of failing on the primary key (review 04-17). Half these entities have no + * version column at all, so a wrapper {@code Long version} would have fixed three of six; this + * fixes all of them without a migration. + * + *

      A row is new until it has been written or read. {@code save} on a loaded or merged row still + * updates it. Package-private: only the entities here extend it, and the leaf's public surface is a + * ceiling. + */ +@MappedSuperclass +abstract class AssignedIdEntity implements Persistable { + + /** True until the row is written or read; not a column. */ + @Transient private boolean newRow = true; + + @Override + public boolean isNew() { + return newRow; + } + + @PostLoad + @PostPersist + void markStored() { + newRow = false; + } +} diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/CleanupItemEntity.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/CleanupItemEntity.java index 9361e142..a5a4e5cc 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/CleanupItemEntity.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/CleanupItemEntity.java @@ -18,7 +18,7 @@ import org.hibernate.type.SqlTypes; */ @Entity @Table(name = "fs_cleanup_item") -public class CleanupItemEntity { +public class CleanupItemEntity extends AssignedIdEntity { @Id @JdbcTypeCode(SqlTypes.UUID) @@ -87,6 +87,11 @@ public class CleanupItemEntity { protected CleanupItemEntity() {} + @Override + public UUID getId() { + return cleanupId; + } + public CleanupItemEntity( UUID cleanupId, UUID fileId, diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/FileEntity.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/FileEntity.java index b9b4d1d7..cf933190 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/FileEntity.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/FileEntity.java @@ -20,7 +20,7 @@ import org.hibernate.type.SqlTypes; */ @Entity @Table(name = "fs_file") -public class FileEntity { +public class FileEntity extends AssignedIdEntity { @Id @JdbcTypeCode(SqlTypes.UUID) @@ -85,6 +85,11 @@ public class FileEntity { protected FileEntity() {} + @Override + public UUID getId() { + return fileId; + } + /** Builds the initial {@code CREATED} row; every later change is a conditional update. */ public FileEntity( UUID fileId, diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/QuotaReservationEntity.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/QuotaReservationEntity.java index 43165168..32319cef 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/QuotaReservationEntity.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/QuotaReservationEntity.java @@ -18,7 +18,7 @@ import org.hibernate.type.SqlTypes; */ @Entity @Table(name = "fs_quota_reservation") -public class QuotaReservationEntity { +public class QuotaReservationEntity extends AssignedIdEntity { @Id @JdbcTypeCode(SqlTypes.UUID) @@ -55,6 +55,11 @@ public class QuotaReservationEntity { protected QuotaReservationEntity() {} + @Override + public UUID getId() { + return reservationId; + } + public QuotaReservationEntity( UUID reservationId, String scopeType, diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/RecoveryItemEntity.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/RecoveryItemEntity.java index 4703b75a..020901fe 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/RecoveryItemEntity.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/RecoveryItemEntity.java @@ -19,7 +19,7 @@ import org.hibernate.type.SqlTypes; */ @Entity @Table(name = "fs_recovery_item") -public class RecoveryItemEntity { +public class RecoveryItemEntity extends AssignedIdEntity { @Id @JdbcTypeCode(SqlTypes.UUID) @@ -47,6 +47,11 @@ public class RecoveryItemEntity { protected RecoveryItemEntity() {} + @Override + public UUID getId() { + return recoveryId; + } + public RecoveryItemEntity( UUID recoveryId, UUID fileId, String reasonCode, String status, Instant createdAt) { this.recoveryId = recoveryId; diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/UploadSessionEntity.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/UploadSessionEntity.java index d93b200c..a681e73d 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/UploadSessionEntity.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/UploadSessionEntity.java @@ -24,7 +24,7 @@ import org.hibernate.type.SqlTypes; */ @Entity @Table(name = "fs_upload_session") -public class UploadSessionEntity { +public class UploadSessionEntity extends AssignedIdEntity { @Id @JdbcTypeCode(SqlTypes.UUID) @@ -78,6 +78,11 @@ public class UploadSessionEntity { protected UploadSessionEntity() {} + @Override + public UUID getId() { + return uploadId; + } + /** Builds a fresh upload resource at offset zero and without a lease. */ public UploadSessionEntity( UUID uploadId, diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/VerificationResultEntity.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/VerificationResultEntity.java index 5a037451..0326ef9f 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/VerificationResultEntity.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/VerificationResultEntity.java @@ -17,7 +17,7 @@ import org.hibernate.type.SqlTypes; */ @Entity @Table(name = "fs_verification_result") -public class VerificationResultEntity { +public class VerificationResultEntity extends AssignedIdEntity { @Id @JdbcTypeCode(SqlTypes.UUID) @@ -45,6 +45,11 @@ public class VerificationResultEntity { protected VerificationResultEntity() {} + @Override + public UUID getId() { + return verificationId; + } + public VerificationResultEntity( UUID verificationId, UUID fileId, diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSql.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSql.java new file mode 100644 index 00000000..40cddd7d --- /dev/null +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSql.java @@ -0,0 +1,56 @@ +package dev.caskeleton.adapter.outbound.persistence.fileserver.repository; + +/** + * The cleanup-queue claim, as one statement, in one place. + * + *

      The claim used to be a plain SELECT of due rows followed by one conditional UPDATE per row. + * The SELECT took no lock, so two workers read the same rows; the loser's UPDATE then waited on the + * winner's row lock until the winner committed, and only then found the row no longer due. A batch + * could stall behind another batch it was never going to share work with. Here the rows are locked + * as they are chosen, rows another claim holds are skipped rather than waited for, and the claim + * token each row now carries comes back in the same round trip — the pattern of {@code + * RecipientClaimSql} in the notification leaf. + * + *

      The token is generated per row by PostgreSQL ({@code gen_random_uuid()}, core since 13), so + * every claimed item is fenced on its own. + * + *

      Package-private: the repository is its one reader, and the leaf's public surface is a ceiling. + * {@link #positional(String)} rewrites the named parameters to JDBC placeholders for a test in this + * package that runs the identical text on a bare {@code Connection}. + */ +final class CleanupClaimSql { + + /** Claims due items and returns each one's identity, request, attempt count and claim token. */ + static final String CLAIM_DUE = + "WITH claimable AS (" + + " SELECT cleanup_id FROM fs_cleanup_item" + + " WHERE status IN ('PENDING', 'FAILED')" + + " AND next_attempt_at <= :now" + + " ORDER BY next_attempt_at, cleanup_id" + + " FOR UPDATE SKIP LOCKED" + + " LIMIT :batchSize" + + ") " + + "UPDATE fs_cleanup_item AS c " + + " SET status = 'IN_PROGRESS'," + + " claim_owner = :owner," + + " claim_token = gen_random_uuid()," + + " lease_until = :leaseUntil," + + " claim_fence = c.claim_fence + 1," + + " updated_at = :now" + + " FROM claimable" + + " WHERE c.cleanup_id = claimable.cleanup_id" + + " RETURNING c.cleanup_id, c.claim_token, c.attempt, c.type," + + " c.file_id, c.upload_id, c.content_key"; + + private CleanupClaimSql() {} + + /** + * Rewrites the named parameters to JDBC placeholders, left to right. + * + * @param namedSql the statement above + * @return the same statement with {@code ?} in place of every {@code :name} + */ + static String positional(String namedSql) { + return namedSql.replaceAll("(? { - @Query( - """ - select c from CleanupItemEntity c - where c.status in ('PENDING', 'FAILED') - and c.nextAttemptAt <= :now - order by c.nextAttemptAt asc - """) - List findDue(@Param("now") Instant now, Limit limit); - /** - * Takes ownership of one due item, recording who took it and until when. + * Claims due items and returns their claim tokens, in one statement ({@link + * CleanupClaimSql#CLAIM_DUE}). * - *

      The conditional status keeps two workers from running the same delete: whoever loses the - * race updates zero rows and skips the item rather than deleting behind the winner. - * - *

      The owner, token and lease are what make that ownership recoverable. Without them a worker - * that performed the physical delete and then died left the row IN_PROGRESS with nothing to + *

      The owner, token and lease are what make ownership recoverable. Without them a worker that + * performed the physical delete and then died left the row IN_PROGRESS with nothing to * distinguish it from an item a live worker is actively deleting — so nothing reclaimed it, and * the file's quota and lifecycle stayed unsettled indefinitely. + * + * @return one row per claimed item: cleanup_id, claim_token, attempt, type, file_id, upload_id, + * content_key */ @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query( - """ - update CleanupItemEntity c - set c.status = 'IN_PROGRESS', - c.claimOwner = :owner, - c.claimToken = :token, - c.leaseUntil = :leaseUntil, - c.claimFence = c.claimFence + 1, - c.updatedAt = :now - where c.cleanupId = :cleanupId - and c.status in ('PENDING', 'FAILED') - """) - int claim( - @Param("cleanupId") UUID cleanupId, + @Query(value = CleanupClaimSql.CLAIM_DUE, nativeQuery = true) + List claimDue( + @Param("now") Instant now, + @Param("batchSize") int batchSize, @Param("owner") String owner, - @Param("token") UUID token, - @Param("leaseUntil") Instant leaseUntil, - @Param("now") Instant now); + @Param("leaseUntil") Instant leaseUntil); /** * Records the outcome of an attempt, for the worker that still holds the claim. diff --git a/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/AssignedIdEntityTest.java b/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/AssignedIdEntityTest.java new file mode 100644 index 00000000..e1d59d4c --- /dev/null +++ b/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/entity/AssignedIdEntityTest.java @@ -0,0 +1,131 @@ +package dev.caskeleton.adapter.outbound.persistence.fileserver.entity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.JpaFileRepository; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import java.time.Instant; +import java.util.Map; +import java.util.UUID; +import org.hibernate.SessionFactory; +import org.hibernate.stat.Statistics; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.data.jpa.repository.support.JpaRepositoryFactory; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.SharedEntityManagerCreator; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * {@code save} of a new Fileserver row is an insert, not a merge (review 04-17). + * + *

      Runs the real Hibernate and Spring Data path against an in-memory H2 schema generated from the + * entities. What is under test is how Spring Data chooses between {@code persist} and {@code merge} + * and how many statements that costs, which does not depend on the vendor; the PostgreSQL schema + * itself is proved by the readiness lanes in persistence-jpa. + */ +class AssignedIdEntityTest { + + private static final Instant NOW = Instant.parse("2026-08-07T10:00:00Z"); + + private LocalContainerEntityManagerFactoryBean factoryBean; + private EntityManagerFactory entityManagerFactory; + private TransactionTemplate transactions; + private JpaFileRepository files; + private Statistics statistics; + + @BeforeEach + void startPersistenceUnit() { + DriverManagerDataSource dataSource = + new DriverManagerDataSource( + "jdbc:h2:mem:fileserver-" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1", "sa", ""); + factoryBean = new LocalContainerEntityManagerFactoryBean(); + factoryBean.setDataSource(dataSource); + factoryBean.setPackagesToScan(AssignedIdEntity.class.getPackageName()); + factoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + factoryBean.setJpaPropertyMap( + Map.of("hibernate.hbm2ddl.auto", "create-drop", "hibernate.generate_statistics", "true")); + factoryBean.afterPropertiesSet(); + entityManagerFactory = factoryBean.getObject(); + transactions = new TransactionTemplate(new JpaTransactionManager(entityManagerFactory)); + EntityManager shared = + SharedEntityManagerCreator.createSharedEntityManager(entityManagerFactory); + files = new JpaRepositoryFactory(shared).getRepository(JpaFileRepository.class); + statistics = entityManagerFactory.unwrap(SessionFactory.class).getStatistics(); + } + + @AfterEach + void closePersistenceUnit() { + factoryBean.destroy(); + } + + @Test + @DisplayName("미리 정한 id의 새 행을 저장하면 SELECT 없이 INSERT 한 문장만 나간다") + void savingANewRowWithAnAssignedIdIssuesOneInsertAndNoSelect() { + // given + FileEntity created = file(UUID.randomUUID(), "report.bin"); + statistics.clear(); + + // when + transactions.executeWithoutResult(ignored -> files.save(created)); + + // then + assertThat(statistics.getPrepareStatementCount()).isEqualTo(1); + assertThat(statistics.getEntityLoadCount()).isZero(); + } + + @Test + @DisplayName("이미 있는 id로 새 행을 저장하면 덮어쓰지 않고 기본 키 위반으로 실패한다") + void savingANewRowUnderAnExistingIdFailsInsteadOfOverwriting() { + // given + UUID fileId = UUID.randomUUID(); + transactions.executeWithoutResult(ignored -> files.save(file(fileId, "report.bin"))); + + // when + Throwable refused = + catchThrowable( + () -> + transactions.executeWithoutResult( + ignored -> files.save(file(fileId, "other.bin")))); + + // then + assertThat(refused).isNotNull(); + assertThat( + transactions.execute(ignored -> files.findById(fileId)).orElseThrow().getOriginalName()) + .isEqualTo("report.bin"); + } + + @Test + @DisplayName("읽어 온 행은 새 행이 아니므로 저장하면 갱신된다") + void aRowReadBackIsNotNew() { + // given + UUID fileId = UUID.randomUUID(); + transactions.executeWithoutResult(ignored -> files.save(file(fileId, "report.bin"))); + + // when + FileEntity found = transactions.execute(ignored -> files.findById(fileId)).orElseThrow(); + + // then + assertThat(found.isNew()).isFalse(); + } + + private static FileEntity file(UUID fileId, String originalName) { + return new FileEntity( + fileId, + "tenant-a", + "CREATED", + originalName, + "application/octet-stream", + 10L, + "user-1", + "tenant-a", + NOW); + } +} diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index 195b0df4..a6c476f2 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -218,12 +218,23 @@ should not exist. `SpringTransaction` pre-builds one `TransactionTemplate` per mode: -| Mode | Propagation | Isolation | Read-only | -|---|---|---|---| -| `inWrite` | `REQUIRED` | `READ_COMMITTED` | `false` | -| `inRootWrite` | `REQUIRED` | `READ_COMMITTED` | `false` | -| `inRead` | `REQUIRED` | `READ_COMMITTED` | `true` | -| `inNew` | `REQUIRES_NEW` | `READ_COMMITTED` | `false` | +| Mode | Propagation | Isolation | Read-only | Timeout | +|---|---|---|---|---| +| `inWrite` | `REQUIRED` | `READ_COMMITTED` (pool) | `false` | `app.persistence-jpa.transaction.write-timeout` (30 s) | +| `inRootWrite` | `REQUIRED` | `READ_COMMITTED` (pool) | `false` | same as `inWrite` | +| `inRead` | `REQUIRED` | `READ_COMMITTED` (pool) | `true` | `app.persistence-jpa.transaction.read-timeout` (30 s) | +| `inNew` | `REQUIRES_NEW` | `READ_COMMITTED` (pool) | `false` | 30 s, fixed | + +Isolation is pinned on the pool, not on the templates (review 09-05): the templates use +`ISOLATION_DEFAULT`, the module defaults set `spring.datasource.hikari.transaction-isolation: +TRANSACTION_READ_COMMITTED` (applied once per physical connection), and +`HikariPoolConstraintValidator` refuses to boot with any other level. Naming the level per template +made Spring call `getTransactionIsolation()` at every begin, which pgjdbc answers with a +`SHOW TRANSACTION ISOLATION LEVEL` round trip. + +Every mode is time-bounded (review 04-10). Spring hands the remaining time to each statement, so a +slow query or lock wait is cancelled by the server (`57014` → `DB_QUERY_CANCELED`), and a deadline +that passed before the next statement (`TransactionTimedOutException`) gets the same code. Pre-built templates are immutable after construction so concurrent callers cannot observe each other's reconfiguration. `inRootWrite` reuses the pre-built write template, @@ -273,11 +284,25 @@ framework-neutral `shared.error.PersistenceFailureException` carrying one of the | SQLState | code | vendor | |---|---|---| | `40P01` | `DB_DEADLOCK` | PostgreSQL (`.postgresql` package) | +| `55P03` | `DB_LOCK_TIMEOUT` | PostgreSQL | | `25P03` | `DB_IDLE_IN_TX_TIMEOUT` | PostgreSQL | | `57014` | `DB_QUERY_CANCELED` | PostgreSQL | +| `57P01`, `57P02` | `DB_UNAVAILABLE` (before commit; completion-unknown during it) | PostgreSQL | | `23513` | `DB_CHECK_VIOLATION` | H2 (`.h2` package) — H2 reports CHECK as 23513, not the standard 23514 the core table maps | | `HYT00` | `DB_QUERY_CANCELED` | H2 — H2 collapses statement and lock timeout into one state | +The PostgreSQL rows are not a second table (review 04-06). `PostgreSqlSqlStateErrorMapping` derives +them from `PostgreSqlFailureClassifier` (SQLState → `FailureCategory`) and +`FailureCategory.operationalError()` (category → code) — the same classification the library +`PostgreSqlExceptionTranslator` uses — leaving out the standard rows above, categories with no +specific code (`INTERNAL_ERROR`) and `COMPLETION_UNKNOWN` (phase-dependent). To add a PostgreSQL +state, add it to `PostgreSqlState` and the classifier; `SqlStateClassificationParityTest` fails if +the two paths disagree on any state. + +**No SQLState, classified by type:** a lost `@Version` race (`OptimisticLockingFailureException`, +JPA `OptimisticLockException`) → `DB_OPTIMISTIC_CONFLICT` (409, review 04-05); an expired Spring +transaction deadline (`TransactionTimedOutException`) → `DB_QUERY_CANCELED`. + **Commit phase (`translateCommitFailure`, ADR-JPA-003):** once the action has returned and `SpringTransaction` is committing a write transaction it began, a failure with `08*`, `40003`, a vendor-contributed termination state (`SqlStateErrorMapping.commitOutcomeUnknownStates()`: diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index f0fe0931..b8e3a295 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -46,7 +46,7 @@ outbox **relay**(스케줄러)는 이 모듈이 아니라 합성 루트의 `Outb `OutboxStorePort`와 messaging이 주는 `OutboxMessagePublishPort`가 모두 있을 때만 켜진다. durable operation HTTP 엔드포인트(`POST /operations`·`GET`·`DELETE /operations/{id}`)도 같은 -이유로 합성 루트의 `DurableOperationConfig`가 조립한다. 이 모듈이 주는 operation store와 outbox +이유로 `composition:durable-operation`의 `DurableOperationAutoConfiguration`이 조립한다. 이 모듈이 주는 operation store와 outbox append 포트(`APP_OUTBOX_ENABLED=true`)가 모두 있을 때만 켜진다. submit·cancel에는 `operation-submit` 역할(`operation:submit`, `operation:cancel`)이 필요하다. @@ -296,6 +296,14 @@ A가 FAILED로 바꾸면 다시 발행되고(중복 전달), A의 늦은 PUBLISH `WHERE event_id = ? AND status = 'IN_FLIGHT' AND lease_owner = ? AND lease_token = ?`. owner는 비우고 token은 그대로 둔다(token은 증가만 한다). 1 row면 `APPLIED`, 0 row면 `STALE`. `findById` + setter 경로와 `@Version`은 쓰지 않는다. +- **미룬 실패와 claim 해제(`V20`)**: `markDeferred(lease, next)`는 `markFailed`와 같은 전이에 + `deferred_attempt_count + 1`을 더한다(일시적 실패는 시도 예산 밖). `releaseLease(lease, at)`는 + 손대지 않은 claim을 `PENDING`, `next_attempt_at = at`, `attempt_count - 1`로 되돌린다(종료 중인 + relay가 쓴다). 둘 다 같은 lease 조건부 UPDATE다. +- **aggregate 순서 번호(`V21`)**: `JpaOutboxStore`는 `OutboxAggregateSequencePort`도 구현한다. + `outbox_aggregate_sequence` counter를 `UPDATE ... + 1`(row lock)로 올리고, 없으면 그 aggregate의 기존 + outbox 최대 `aggregate_sequence` + 1로 만든다. V21은 `outbox_event`의 순서 키 유일 인덱스도 만든다 — + 기존 중복 row가 있으면 migration이 실패하므로 먼저 정리해야 한다. - **STALE은 예외가 아니다**: row의 결과는 지금 lease를 가진 relay가 쓴다. use case는 결과를 `OutboxRelayResult.Outcome.STALE`로 남기고 `OutboxRelayFailureReportPort.reportStaleCompletion` 으로 알린 뒤 다음 이벤트로 넘어간다. FAILED/DEAD report는 보내지 않는다(아무것도 저장되지 diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index 2e4849f3..6820015f 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -75,11 +75,14 @@ dependencies { runtimeOnly 'org.postgresql:postgresql' runtimeOnly 'org.flywaydb:flyway-database-postgresql' - // Vendor (H2): the local-profile driver. Used only by the .h2 subpackage, which reaches it - // through JDBC/JPA rather than by importing org.h2 types — the same shape as the PostgreSQL - // driver above. Not `developmentOnly`: local is a deployable profile of this artifact, and the - // vendor selector, not the packaging, decides which driver a deployment loads. - runtimeOnly 'com.h2database:h2' + // Vendor (H2): the in-memory driver of the `bootRunH2` developer task and of this leaf's tests. + // The .h2 subpackage reaches it through JDBC/JPA, never by importing org.h2 types, so it compiles + // without it. It is not a runtime dependency (review 09-09): it used to ride into every + // service artifact that selected JPA (2.7 MB, one more engine to scan for CVEs) although no + // deployed profile runs on H2 — `local` defaults to the Compose PostgreSQL (JPA-INT-003) and + // PersistenceVendorProdSafetyValidator refuses H2 under prod. app-bootstrap's + // bootRunH2Classpath adds the driver for the one task that asks for H2 by name. + testRuntimeOnly 'com.h2database:h2' // JPA platform observability (design §37). Micrometer's observation API already arrives with // Spring; the meter registry does not, and MicrometerQueryObservation (library API, not composed) @@ -107,12 +110,17 @@ dependencies { // dependency graph — the thing Build Composition governs — is untouched. postgresqlIntegrationTestImplementation project(':adapter:outbound:persistence-fileserver') postgresqlIntegrationTestImplementation project(':application-fileserver') + // The fileserver port contracts (`*PortContract`) the in-memory fakes also pass (review 04-14). + postgresqlIntegrationTestImplementation testFixtures(project(':application-fileserver')) // The notification capability's persistence moved out the same way, and its real-PostgreSQL // qualifications stay here for the same reason: this lane owns the container, the Flyway wiring // and the readiness cards that name those tests (config/jpa/readiness-cards.yaml). Test scope // only. postgresqlIntegrationTestImplementation project(':adapter:outbound:persistence-notification') postgresqlIntegrationTestImplementation project(':application-notification') + // The application-owned store contracts the notification adapters are held to, the same ones + // the in-memory fakes pass (review 04-14). + postgresqlIntegrationTestImplementation testFixtures(project(':application-notification')) // The provider-event replay worker lives in the notification adapter and only fails against a // real JPA stack with no caller transaction, so its real-DB test runs here beside the // notification stores. Test scope only, like the Fileserver edge. Non-transitive: the worker @@ -161,7 +169,7 @@ dependencies { // Real-PostgreSQL lanes. A readiness lane runs one named class (the security lane also names the // runtime-role namespace-denial method), a platform lane selects a tag, and the pool lane has a // source set of its own. release.yml (jpa-release-gate) and config/jpa/*.{json,yaml} name these tasks. -def jpaEvidenceImage = providers.gradleProperty('jpaPostgreSqlEvidenceImage').orElse('postgres:16-alpine').get() +def jpaEvidenceImage = providers.gradleProperty('jpaPostgreSqlEvidenceImage').orElse(testContainerImages['postgres-16']).get() def jpaMatrixVersions = providers.gradleProperty('jpa.matrix.versions').orElse('16').get() def readinessLanes = [ postgresqlLifecycleIntegrationTest : ['PostgreSqlLifecycleIntegrationTest'], @@ -177,6 +185,7 @@ def readinessLanes = [ postgresqlOutboxAppendTransactionalIntegrationTest : ['PostgreSqlOutboxAppendTransactionalIntegrationTest'], postgresqlOutboxConcurrentRelayIntegrationTest : ['PostgreSqlOutboxConcurrentRelayIntegrationTest'], postgresqlOutboxRowLifecycleIntegrationTest : ['PostgreSqlOutboxRowLifecycleIntegrationTest'], + postgresqlOutboxAggregateSequenceIntegrationTest : ['PostgreSqlOutboxAggregateSequenceIntegrationTest'], postgresqlFileserverMigrationIntegrationTest : ['PostgreSqlFileserverMigrationIntegrationTest'], postgresqlFileserverMetadataIntegrationTest : ['PostgreSqlFileserverMetadataStoreIntegrationTest'], postgresqlFileserverReclamationIntegrationTest : ['PostgreSqlFileserverReclamationIntegrationTest'], @@ -214,7 +223,7 @@ strictTestLanes { } } rejectSkipped = true - jvmArgs '-Duser.timezone=UTC', '-Djpa.evidence.postgresql.image=' + jpaEvidenceImage + jvmArgs '-Djpa.evidence.postgresql.image=' + jpaEvidenceImage } } platformLanes.each { taskName, selection -> @@ -223,7 +232,6 @@ strictTestLanes { sourceSet = 'postgresqlIntegrationTest' tag = selection[0] description = selection[1] - jvmArgs '-Duser.timezone=UTC' systemProperty 'jpa.matrix.versions', jpaMatrixVersions } } @@ -231,7 +239,6 @@ strictTestLanes { performance() sourceSet = 'jpaPlatformPerformanceTest' description = 'Verifies Hikari pool and REQUIRES_NEW connection behaviour (design §38).' - jvmArgs '-Duser.timezone=UTC' } } diff --git a/src/adapter/outbound/persistence-jpa/gradle.lockfile b/src/adapter/outbound/persistence-jpa/gradle.lockfile index 35516576..973d61df 100644 --- a/src/adapter/outbound/persistence-jpa/gradle.lockfile +++ b/src/adapter/outbound/persistence-jpa/gradle.lockfile @@ -36,7 +36,7 @@ com.google.guava:guava:33.6.0-jre=checkstyle com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,jpaPlatformPerformanceTestAnnotationProcessor,postgresqlIntegrationTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,jpaPlatformPerformanceTestAnnotationProcessor,postgresqlIntegrationTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,jpaPlatformPerformanceTestAnnotationProcessor,postgresqlIntegrationTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor -com.h2database:h2:2.4.240=jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath +com.h2database:h2:2.4.240=jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath com.mysema.commons:mysema-commons-lang:0.2.4=compileClasspath,jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/FailureCategory.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/FailureCategory.java index 23a24ab2..5e7c55de 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/FailureCategory.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/FailureCategory.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.api.error; +import dev.caskeleton.shared.error.OperationalError; + /** * Provider-independent classification of a persistence failure (design §18.2). * @@ -37,10 +39,16 @@ public enum FailureCategory { /** An optimistic {@code @Version} check failed at flush or commit. */ OPTIMISTIC_CONFLICT, - /** A statement exceeded its configured statement timeout. */ + /** + * {@code 57014} — a statement was cancelled, which is how a statement timeout or the remaining + * time of a bounded transaction surfaces. + */ QUERY_TIMEOUT, - /** A transaction exceeded its configured transaction timeout. */ + /** + * {@code 25P03} — the server ended a session that sat idle inside an open transaction. Nothing + * was committed, which is why its code is retryable where {@link #QUERY_TIMEOUT}'s is not. + */ TRANSACTION_TIMEOUT, /** A connection could not be obtained or was lost outside the commit phase. */ @@ -56,5 +64,34 @@ public enum FailureCategory { ENTITY_NOT_FOUND, /** The SQLSTATE is not registered; the platform refuses to guess a disposition. */ - UNKNOWN + UNKNOWN; + + /** + * The operational code a failure in this category is reported as. This is the one category → code + * table: {@link JpaPersistenceException} reports it, and the PostgreSQL rows the default {@code + * TransactionPort} translator uses are derived from it, so the same SQLSTATE gives the same code + * on both paths (review 04-06). + * + *

      A category with no specific code keeps the answer the web catch-all gives an unclassified + * failure ({@code INTERNAL_ERROR}); classifying a schema mismatch or corrupt row as something the + * client could act on would be a guess. + */ + public OperationalError operationalError() { + return switch (this) { + case SERIALIZATION_FAILURE -> OperationalError.DB_SERIALIZATION_FAILURE; + case COMPLETION_UNKNOWN -> OperationalError.DB_COMPLETION_UNKNOWN; + case DEADLOCK -> OperationalError.DB_DEADLOCK; + case UNIQUE_CONSTRAINT -> OperationalError.DB_UNIQUE_VIOLATION; + case FOREIGN_KEY_CONSTRAINT -> OperationalError.DB_FK_VIOLATION; + case CHECK_CONSTRAINT -> OperationalError.DB_CHECK_VIOLATION; + case NOT_NULL_CONSTRAINT -> OperationalError.DB_NULL_VIOLATION; + case LOCK_NOT_AVAILABLE -> OperationalError.DB_LOCK_TIMEOUT; + case OPTIMISTIC_CONFLICT -> OperationalError.DB_OPTIMISTIC_CONFLICT; + case QUERY_TIMEOUT -> OperationalError.DB_QUERY_CANCELED; + case TRANSACTION_TIMEOUT -> OperationalError.DB_IDLE_IN_TX_TIMEOUT; + case CONNECTION_UNAVAILABLE -> OperationalError.DB_UNAVAILABLE; + case SCHEMA_MISMATCH, DATA_CORRUPTION, ENTITY_NOT_FOUND, UNKNOWN -> + OperationalError.INTERNAL_ERROR; + }; + } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/JpaPersistenceException.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/JpaPersistenceException.java index 1e391e5f..98d69b70 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/JpaPersistenceException.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/JpaPersistenceException.java @@ -49,29 +49,9 @@ public class JpaPersistenceException extends PersistenceFailureException { return operationalErrorOf(category); } - /** - * The operational code a failure category is reported as. - * - *

      A category with no specific code keeps the answer the web catch-all gave before this type - * was a carrier ({@code INTERNAL_ERROR}); classifying a schema mismatch or corrupt row as - * something the client could act on would be a guess. - */ + /** The operational code of {@code category}; {@link FailureCategory#operationalError()}. */ static OperationalError operationalErrorOf(FailureCategory category) { - return switch (category) { - case SERIALIZATION_FAILURE -> OperationalError.DB_SERIALIZATION_FAILURE; - case COMPLETION_UNKNOWN -> OperationalError.DB_COMPLETION_UNKNOWN; - case DEADLOCK -> OperationalError.DB_DEADLOCK; - case UNIQUE_CONSTRAINT -> OperationalError.DB_UNIQUE_VIOLATION; - case FOREIGN_KEY_CONSTRAINT -> OperationalError.DB_FK_VIOLATION; - case CHECK_CONSTRAINT -> OperationalError.DB_CHECK_VIOLATION; - case NOT_NULL_CONSTRAINT -> OperationalError.DB_NULL_VIOLATION; - case LOCK_NOT_AVAILABLE -> OperationalError.DB_LOCK_TIMEOUT; - case OPTIMISTIC_CONFLICT -> OperationalError.DB_OPTIMISTIC_CONFLICT; - case QUERY_TIMEOUT, TRANSACTION_TIMEOUT -> OperationalError.DB_QUERY_CANCELED; - case CONNECTION_UNAVAILABLE -> OperationalError.DB_UNAVAILABLE; - case SCHEMA_MISMATCH, DATA_CORRUPTION, ENTITY_NOT_FOUND, UNKNOWN -> - OperationalError.INTERNAL_ERROR; - }; + return category.operationalError(); } /** The bounded metadata carried by this failure. */ diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/JpaAdapterBeansConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/JpaAdapterBeansConfig.java index b7820b6a..18964a00 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/JpaAdapterBeansConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/JpaAdapterBeansConfig.java @@ -67,11 +67,21 @@ class JpaAdapterBeansConfig { return new PersistenceExceptionTranslator(mappings); } + /** + * The application's {@code TransactionPort}. The write and read bounds come from the module + * defaults ({@code app.persistence-jpa.transaction.*}, 30 s each; see {@link + * SpringTransaction.Timeouts}). + */ @Bean SpringTransaction springTransaction( PlatformTransactionManager transactionManager, - PersistenceExceptionTranslator exceptionTranslator) { - return new SpringTransaction(transactionManager, exceptionTranslator); + PersistenceExceptionTranslator exceptionTranslator, + @Value("${app.persistence-jpa.transaction.write-timeout:30s}") Duration writeTimeout, + @Value("${app.persistence-jpa.transaction.read-timeout:30s}") Duration readTimeout) { + return new SpringTransaction( + transactionManager, + exceptionTranslator, + new SpringTransaction.Timeouts(writeTimeout, readTimeout)); } @Bean diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/database/TenantDataSourceRegistry.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/database/TenantDataSourceRegistry.java index af7e4d95..90737a29 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/database/TenantDataSourceRegistry.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/database/TenantDataSourceRegistry.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.database; -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; +import dev.caskeleton.application.tenant.TenantId; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/rls/RlsTenantSessionBinder.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/rls/RlsTenantSessionBinder.java index ceade3e8..dd2b484e 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/rls/RlsTenantSessionBinder.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/rls/RlsTenantSessionBinder.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.rls; -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; +import dev.caskeleton.application.tenant.TenantId; import jakarta.persistence.EntityManager; import java.util.Objects; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaMultiTenantConnectionProvider.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaMultiTenantConnectionProvider.java index 967c46fd..e114181b 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaMultiTenantConnectionProvider.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaMultiTenantConnectionProvider.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.schema; -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; +import dev.caskeleton.application.tenant.TenantId; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantMigrationOrchestrator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantMigrationOrchestrator.java index 098ed950..58978c1f 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantMigrationOrchestrator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantMigrationOrchestrator.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.schema; -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; +import dev.caskeleton.application.tenant.TenantId; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantRegistry.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantRegistry.java index 8c8534b4..14176e65 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantRegistry.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantRegistry.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.schema; -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; +import dev.caskeleton.application.tenant.TenantId; import java.util.Map; import java.util.Objects; import java.util.Optional; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/TenantMigrationStatus.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/TenantMigrationStatus.java index 8748996d..2cde87d4 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/TenantMigrationStatus.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/TenantMigrationStatus.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.schema; -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; +import dev.caskeleton.application.tenant.TenantId; import java.util.Objects; import java.util.Optional; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/tenant/TenantContext.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/tenant/TenantContext.java index 93349d59..3e789175 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/tenant/TenantContext.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/tenant/TenantContext.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.tenant; +import dev.caskeleton.application.tenant.TenantId; import java.util.Objects; import java.util.Optional; import java.util.function.Supplier; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/tenant/TenantId.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/tenant/TenantId.java deleted file mode 100644 index 190812dc..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/tenant/TenantId.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.tenant; - -import java.util.regex.Pattern; - -/** - * A tenant identity (experimental plan Task 2). - * - *

      The format is bounded because a tenant id ends up in a schema name, a {@code set_config} - * value, and a routing key. A tenant id like {@code ../public} is what turns schema-per-tenant into - * a path-traversal problem, so the shape is validated at the type rather than at each use. - * - *

      The value never becomes a metric tag: tenant cardinality is unbounded by definition, and a - * tenant id in telemetry is customer data in a system that is rarely treated as one. - */ -public record TenantId(String value) { - - private static final Pattern FORMAT = Pattern.compile("[a-z0-9][a-z0-9_-]{1,62}"); - - public TenantId { - if (value == null || !FORMAT.matcher(value).matches()) { - throw new IllegalArgumentException("invalid tenant id"); - } - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java index 8cad7f27..6e1cc5db 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java @@ -7,6 +7,7 @@ import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCo import dev.caskeleton.shared.error.ApiErrorCode; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; +import jakarta.persistence.OptimisticLockException; import java.io.IOException; import java.sql.SQLException; import java.sql.SQLNonTransientConnectionException; @@ -21,6 +22,8 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import org.springframework.dao.DataAccessException; +import org.springframework.dao.OptimisticLockingFailureException; +import org.springframework.transaction.TransactionTimedOutException; /** * Classifies a Spring {@link DataAccessException} into a framework-neutral {@link OperationalError} @@ -36,7 +39,8 @@ import org.springframework.dao.DataAccessException; public class PersistenceExceptionTranslator { /** SQLState class prefix for connection failures → {@code DB_UNAVAILABLE}. */ - private static final String CONNECTION_CLASS_PREFIX = "08"; + private static final String CONNECTION_CLASS_PREFIX = + StandardSqlStateErrorMapping.CONNECTION_EXCEPTION_CLASS; private final Map byExactSqlState; private final Set vendorCommitOutcomeUnknownStates; @@ -91,12 +95,23 @@ public class PersistenceExceptionTranslator { /** * Classify a transaction or persistence wrapper by walking its cause chain for the first * SQLState. + * + *

      Two failures carry no SQLState and are classified by type instead. A lost {@code @Version} + * race ({@link OptimisticLockingFailureException}, or the JPA {@link OptimisticLockException} an + * unproxied entity manager throws) is {@code DB_OPTIMISTIC_CONFLICT}: the client re-reads and + * decides, it is not a server fault (review 04-05). A Spring transaction deadline that expired + * before the next statement ({@link TransactionTimedOutException}) is {@code DB_QUERY_CANCELED}, + * the same code the server gives when the deadline cancels a running statement ({@code 57014}). */ public Optional translate(Throwable ex) { Objects.requireNonNull(ex, "ex"); String sqlState = extractSqlState(ex); if (sqlState == null) { - return Optional.empty(); + return classifyByType(ex) + .map( + code -> + new PersistenceFailureException( + code, "persistence failure classified from " + code.name(), ex)); } ApiErrorCode code = classify(sqlState); if (code == null) { @@ -109,6 +124,22 @@ public class PersistenceExceptionTranslator { code, "persistence failure classified from SQLState=" + sqlState, ex)); } + /** The code of a failure that has no SQLState, by its type anywhere in the cause chain. */ + private static Optional classifyByType(Throwable ex) { + for (Throwable t = ex; t != null; t = t.getCause()) { + if (t instanceof OptimisticLockingFailureException || t instanceof OptimisticLockException) { + return Optional.of(OperationalError.DB_OPTIMISTIC_CONFLICT); + } + if (t instanceof TransactionTimedOutException) { + return Optional.of(OperationalError.DB_QUERY_CANCELED); + } + if (t.getCause() == t) { + break; + } + } + return Optional.empty(); + } + /** * Classify a failure raised while committing a write transaction this call began. * diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/StandardSqlStateErrorMapping.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/StandardSqlStateErrorMapping.java index 5cf7653e..0aeb4991 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/StandardSqlStateErrorMapping.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/StandardSqlStateErrorMapping.java @@ -14,6 +14,13 @@ import java.util.Map; */ public class StandardSqlStateErrorMapping implements SqlStateErrorMapping { + /** + * SQLSTATE class {@code 08} "connection exception": every code in it is a connection failure. + * Spelled here once; {@link PersistenceExceptionTranslator} and {@code PostgreSqlState} both read + * it. + */ + public static final String CONNECTION_EXCEPTION_CLASS = "08"; + /** {@code 40001} serialization_failure. */ public static final String SERIALIZATION_FAILURE = "40001"; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java index bc7a779c..b3903ba6 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java @@ -9,6 +9,7 @@ import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.EventId; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; import dev.caskeleton.application.outbox.ClaimedOutboxEvent; +import dev.caskeleton.application.outbox.OutboxAggregateSequencePort; import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxCompletion; import dev.caskeleton.application.outbox.OutboxEventStatus; @@ -41,7 +42,8 @@ import org.slf4j.LoggerFactory; * columns repeat the contract id, aggregate id and correlation id for the claim gate and the * metrics queries. */ -public class JpaOutboxStore implements OutboxAppendPort, OutboxStorePort { +public class JpaOutboxStore + implements OutboxAppendPort, OutboxStorePort, OutboxAggregateSequencePort { private static final Logger log = LoggerFactory.getLogger(JpaOutboxStore.class); @@ -68,6 +70,7 @@ public class JpaOutboxStore implements OutboxAppendPort, OutboxStorePort { entity.setOccurredAt(event.occurredAt()); entity.setStatus(OutboxEventStatus.PENDING.name()); entity.setAttemptCount(0); + entity.setDeferredAttemptCount(0); // PENDING: nextAttemptAt = occurredAt so the relay can claim immediately. entity.setNextAttemptAt(event.occurredAt()); entity.setCorrelationId(event.correlationId()); @@ -92,6 +95,33 @@ public class JpaOutboxStore implements OutboxAppendPort, OutboxStorePort { repository.save(entity); } + /** + * An aggregate's next order number from its counter row ({@code outbox_aggregate_sequence}, V21), + * in the caller's transaction. + * + *

      The increment is an {@code UPDATE}, which holds the counter row's lock until the caller + * commits: a second writer of the same aggregate waits, then increments the committed value, so + * the numbers follow commit order. An aggregate's first number is inserted instead, seeded after + * the highest {@code aggregate_sequence} its outbox rows already carry — rows numbered before the + * counter existed (the sample used epoch microseconds) must still come first. Two writers + * creating the same counter at once collide on its primary key and one transaction fails: a + * rollback the caller retries, never two events with one number. The counter outlives the + * reaper's deletes, so a number is never handed out twice. + */ + @Override + public long nextSequence(AggregateIdentity aggregate) { + // Outside a caller transaction the counter commits apart from the event it numbers. + requireTransaction("nextSequence"); + Objects.requireNonNull(aggregate, "aggregate must not be null"); + String tenant = aggregate.tenantScope(); + String type = aggregate.aggregateType(); + String id = aggregate.aggregateId(); + if (repository.incrementAggregateSequence(tenant, type, id) == 0) { + repository.createAggregateSequence(tenant, type, id); + } + return repository.aggregateSequence(tenant, type, id); + } + /** * The claim repository returns the rows locked ({@code FOR UPDATE SKIP LOCKED}) until this * transaction commits, so incrementing the token here cannot race another relay's claim. @@ -148,6 +178,22 @@ public class JpaOutboxStore implements OutboxAppendPort, OutboxStorePort { repository.failLease(lease.eventId(), lease.owner(), lease.token(), nextAttemptAt)); } + /** Marks the leased row FAILED as a deferred claim; see {@link #markPublished}. */ + @Override + public OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt) { + requireTransaction("markDeferred"); + return completion( + repository.deferLease(lease.eventId(), lease.owner(), lease.token(), nextAttemptAt)); + } + + /** Returns the leased row to PENDING without spending an attempt; see {@link #markPublished}. */ + @Override + public OutboxCompletion releaseLease(OutboxLease lease, Instant claimableAt) { + requireTransaction("releaseLease"); + return completion( + repository.releaseLease(lease.eventId(), lease.owner(), lease.token(), claimableAt)); + } + /** Marks the leased row DEAD; see {@link #markPublished}. */ @Override public OutboxCompletion markDead(OutboxLease lease) { @@ -227,7 +273,10 @@ public class JpaOutboxStore implements OutboxAppendPort, OutboxStorePort { entity.getContractCatalogRevision(), entity.getDestinationBindingRevision()); return new ClaimedOutboxEvent( - event, OutboxEventStatus.valueOf(entity.getStatus()), entity.getAttemptCount()); + event, + OutboxEventStatus.valueOf(entity.getStatus()), + entity.getAttemptCount(), + entity.getDeferredAttemptCount()); } catch (IllegalArgumentException exception) { throw new IllegalStateException( "invalid canonical outbox metadata for eventId=" + entity.getEventId(), exception); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java index c7572f94..87b0c782 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java @@ -75,6 +75,86 @@ public interface OutboxEventJpaRepository extends Repository { @Column(name = "attempt_count", nullable = false) private int attemptCount; + /** + * Claims that ended deferred — the broker did not answer or refused for now — and so do not count + * against the attempt budget (V20). + */ + @Column(name = "deferred_attempt_count", nullable = false) + private int deferredAttemptCount; + /** Dual-purpose per status (PENDING / IN_FLIGHT / FAILED) — see README "outbox". */ @Column(name = "next_attempt_at", nullable = false) private Instant nextAttemptAt; @@ -189,6 +196,14 @@ public class OutboxEventEntity implements Persistable { this.attemptCount = attemptCount; } + public int getDeferredAttemptCount() { + return deferredAttemptCount; + } + + public void setDeferredAttemptCount(int deferredAttemptCount) { + this.deferredAttemptCount = deferredAttemptCount; + } + public Instant getNextAttemptAt() { return nextAttemptAt; } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMapping.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMapping.java index f4b0835d..457ff569 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMapping.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMapping.java @@ -1,42 +1,92 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql; +import dev.caskeleton.adapter.outbound.persistence.api.error.FailureCategory; import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping; +import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; +import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlFailureClassifier; import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlState; import dev.caskeleton.shared.error.OperationalError; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; /** - * PostgreSQL-specific {@link SqlStateErrorMapping} contributing vendor-only SQLState codes. See the - * module README for the code/category/retryable table. + * PostgreSQL-specific {@link SqlStateErrorMapping} contributing vendor-only SQLState codes. * - *

      The codes come from {@link PostgreSqlState}, the one PostgreSQL SQLSTATE table; this class - * only says which of them become which operational error. + *

      Nothing here is a second table. The rows are derived from the one PostgreSQL classification — + * {@link PostgreSqlFailureClassifier} (SQLSTATE → {@link FailureCategory}) followed by {@link + * FailureCategory#operationalError()} (category → code) — which is also what the library {@code + * PostgreSqlExceptionTranslator} uses. Before review 04-06 this class spelled its own rows and the + * two had drifted: {@code 25P03} was retryable here and final there, {@code 57P01} was a 503 there + * and an unclassified 500 here. Adding a state to {@link PostgreSqlState} and the classifier now + * changes both paths at once; {@code SqlStateClassificationParityTest} proves they agree. + * + *

      Three kinds of state are left out of the exact rows: + * + *

        + *
      • the SQL-standard states {@link StandardSqlStateErrorMapping} already contributes (a second + * contribution of the same state fails the boot); + *
      • states whose category has no specific code — the transport catch-all answers those with + * {@code INTERNAL_ERROR} already; + *
      • {@link FailureCategory#COMPLETION_UNKNOWN}: whether the outcome is unknown depends on the + * transaction phase, so it is a {@link #commitOutcomeUnknownStates() commit-phase} state. + *
      */ public class PostgreSqlSqlStateErrorMapping implements SqlStateErrorMapping { - private static final Map MAPPINGS = - Map.of( - PostgreSqlState.DEADLOCK_DETECTED.code(), OperationalError.DB_DEADLOCK, - PostgreSqlState.LOCK_NOT_AVAILABLE.code(), OperationalError.DB_LOCK_TIMEOUT, - PostgreSqlState.IDLE_IN_TRANSACTION_TIMEOUT.code(), - OperationalError.DB_IDLE_IN_TX_TIMEOUT, - PostgreSqlState.QUERY_CANCELED.code(), OperationalError.DB_QUERY_CANCELED); + private static final PostgreSqlFailureClassifier CLASSIFIER = new PostgreSqlFailureClassifier(); - /** - * A backend terminated mid-commit reports {@code 57P01}/{@code 57P02}, not a connection-class - * state, and the commit record may already be in the WAL when it does. - */ - private static final Set COMMIT_OUTCOME_UNKNOWN = - Set.of(PostgreSqlState.ADMIN_SHUTDOWN.code(), PostgreSqlState.CRASH_SHUTDOWN.code()); + private static final Map MAPPINGS = deriveExactMappings(); + + private static final Set COMMIT_OUTCOME_UNKNOWN = deriveCommitOutcomeUnknownStates(); @Override public Map exactMappings() { return MAPPINGS; } + /** + * A backend terminated mid-commit reports {@code 57P01}/{@code 57P02}, not a connection-class + * state, and the commit record may already be in the WAL when it does. Derived: every vendor + * state the classifier calls a lost connection or an unknown completion that the translator's own + * rule ({@code 08*}, {@code 40003}) does not already cover. + */ @Override public Set commitOutcomeUnknownStates() { return COMMIT_OUTCOME_UNKNOWN; } + + private static Map deriveExactMappings() { + Set standard = new StandardSqlStateErrorMapping().exactMappings().keySet(); + Map rows = new LinkedHashMap<>(); + for (PostgreSqlState state : PostgreSqlState.values()) { + FailureCategory category = CLASSIFIER.classify(state); + OperationalError code = category.operationalError(); + if (standard.contains(state.code()) + || category == FailureCategory.COMPLETION_UNKNOWN + || code == OperationalError.INTERNAL_ERROR) { + continue; + } + rows.put(state.code(), code); + } + return Map.copyOf(rows); + } + + private static Set deriveCommitOutcomeUnknownStates() { + Set states = new LinkedHashSet<>(); + for (PostgreSqlState state : PostgreSqlState.values()) { + FailureCategory category = CLASSIFIER.classify(state); + boolean phaseDependent = + category == FailureCategory.CONNECTION_UNAVAILABLE + || category == FailureCategory.COMPLETION_UNKNOWN; + boolean translatorOwned = + PostgreSqlState.isConnectionClass(state.code()) + || StandardSqlStateErrorMapping.STATEMENT_COMPLETION_UNKNOWN.equals(state.code()); + if (phaseDependent && !translatorOwned) { + states.add(state.code()); + } + } + return Set.copyOf(states); + } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlState.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlState.java index 5ad4ca16..ff4fc21b 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlState.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlState.java @@ -73,7 +73,8 @@ public enum PostgreSqlState { .collect(Collectors.toUnmodifiableMap(PostgreSqlState::code, state -> state)); /** SQLSTATE class 08 is "connection exception"; every code in it is a connection failure. */ - public static final String CONNECTION_CLASS = "08"; + public static final String CONNECTION_CLASS = + StandardSqlStateErrorMapping.CONNECTION_EXCEPTION_CLASS; private final String code; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidator.java index 309b73a4..9d9a850a 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidator.java @@ -22,6 +22,14 @@ class HikariPoolConstraintValidator implements StartupRule { static final String LEAK_DETECTION_KEY = "spring.datasource.hikari.leak-detection-threshold"; static final String MAX_POOL_SIZE_KEY = "spring.datasource.hikari.maximum-pool-size"; static final String MIN_IDLE_KEY = "spring.datasource.hikari.minimum-idle"; + static final String TRANSACTION_ISOLATION_KEY = "spring.datasource.hikari.transaction-isolation"; + + /** + * The only pool isolation the application runs at. {@code SpringTransaction} leaves isolation to + * the pool so no transaction asks the server for it (review 09-05); this rule is what keeps that + * from becoming "whatever the server default is". + */ + static final String READ_COMMITTED = "TRANSACTION_READ_COMMITTED"; // Operator-facing env keys, so a boot failure names the APP_* variable the operator set. // Knobs without a registered env key emit ENV_KEY_PENDING instead of a fabricated name. @@ -59,6 +67,17 @@ class HikariPoolConstraintValidator implements StartupRule { "APP_DATASOURCE_POOL_MIN_IDLE (" + MIN_IDLE_KEY + ") must be >= 0, was " + minIdle); } + String isolation = environment.getProperty(TRANSACTION_ISOLATION_KEY); + if (isolation != null && !READ_COMMITTED.equals(isolation.trim())) { + violations.reject( + TRANSACTION_ISOLATION_KEY + + " must be " + + READ_COMMITTED + + " (SpringTransaction runs every mode at READ COMMITTED and takes the level from the" + + " pool), was " + + isolation); + } + Long connectionTimeout = parseMillis( CONNECTION_TIMEOUT_KEY, environment.getProperty(CONNECTION_TIMEOUT_KEY), violations); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java index 597d415f..64816cff 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java @@ -6,13 +6,19 @@ import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy; import dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier; import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets; import java.sql.SQLException; +import java.util.Arrays; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; import javax.sql.DataSource; import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.flyway.autoconfigure.FlywayMigrationInitializer; import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -40,6 +46,9 @@ import org.springframework.core.env.Environment; matchIfMissing = true) class JpaStartupAutoConfiguration { + /** The resolved-datasource check's bean name, which every Flyway initializer depends on. */ + static final String RESOLVED_DATA_SOURCE_CHECK = "jpaResolvedDataSourceCheck"; + /** The module switch: on while the module is present unless a deployment turns it off. */ static final String ENABLED_PROPERTY = "app.persistence-jpa.enabled"; @@ -60,7 +69,7 @@ class JpaStartupAutoConfiguration { environment.getProperty("app.runtime.migration-on-startup", Boolean.class, true)); } - /** Env-validation (exit 78): datasource connection env present before migration runs. */ + /** Env-validation (exit 78): datasource connection env present before any bean opens it. */ @Bean static RequiredEnvironmentValidator requiredEnvironmentValidator() { return new RequiredEnvironmentValidator(); @@ -101,8 +110,14 @@ class JpaStartupAutoConfiguration { /** * Validates the datasource the application actually resolved. PostgreSQL validation opens a * connection during startup; the H2 development vendor skips the product check. + * + *

      It must judge the database before Flyway changes it: a migration applied to a database this + * check then refuses (an unsupported version, an unreachable primary that a retry later reached) + * cannot be taken back. Both beans need only the datasource, so nothing ordered them and the + * container created whichever it met first. {@link #resolvedDataSourceCheckBeforeMigration()} + * makes every Flyway initializer depend on this bean by name. */ - @Bean + @Bean(RESOLVED_DATA_SOURCE_CHECK) InitializingBean jpaResolvedDataSourceCheck( JpaDataSourceProfileValidator validator, DataSource dataSource, Environment environment) { String vendor = @@ -110,6 +125,29 @@ class JpaStartupAutoConfiguration { return () -> validator.validateResolved(dataSource, "postgresql".equalsIgnoreCase(vendor)); } + /** + * Makes each Flyway initializer wait for {@link #jpaResolvedDataSourceCheck}. A bean-factory + * post-processor, because the initializer is Boot's bean: the dependency has to be added to its + * definition, not declared on it. Static, so declaring it creates nothing else early. + * + * @return the post-processor + */ + @Bean + static BeanFactoryPostProcessor resolvedDataSourceCheckBeforeMigration() { + return beanFactory -> { + for (String initializer : + beanFactory.getBeanNamesForType(FlywayMigrationInitializer.class, true, false)) { + BeanDefinition definition = beanFactory.getBeanDefinition(initializer); + Set dependsOn = new LinkedHashSet<>(); + if (definition.getDependsOn() != null) { + dependsOn.addAll(Arrays.asList(definition.getDependsOn())); + } + dependsOn.add(RESOLVED_DATA_SOURCE_CHECK); + definition.setDependsOn(dependsOn.toArray(String[]::new)); + } + }; + } + /** * The relational credential, owed under {@code prod} exactly while this module is on. * @@ -117,9 +155,12 @@ class JpaStartupAutoConfiguration { * itself (P22-new-1) — knowledge of a capability in the leaf that is supposed to hold none. The * module now names its own secret, the way the Redis roles do, and a composition without it owes * no database password because nothing contributes one. + * + *

      Static: the secret guard is a startup rule and reads the contributions before any ordinary + * singleton exists, which must not create this configuration class. */ @Bean - RequiredProductionSecrets jpaProductionSecrets() { + static RequiredProductionSecrets jpaProductionSecrets() { return environment -> List.of("APP_DATASOURCE_PASSWORD"); } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java index 9f639b60..c86691cd 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java @@ -10,6 +10,7 @@ import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.shared.error.PersistenceFailureException; import java.time.Duration; import java.util.Locale; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; @@ -20,9 +21,18 @@ import org.springframework.transaction.support.TransactionTemplate; /** * Spring-backed {@link TransactionPort}: one pre-built {@link TransactionTemplate} per mode, all - * pinned to {@link Isolation#READ_COMMITTED}. See README "transaction" for why the templates are + * running at {@link Isolation#READ_COMMITTED}. See README "transaction" for why the templates are * pre-built (mutable-template race) and CLAUDE.md for the mode table. * + *

      The isolation is pinned on the pool, not on each template (review 09-05). A template that + * names a level makes Spring ask the connection for its current one at every begin, and pgjdbc + * answers that with a server round trip ({@code SHOW TRANSACTION ISOLATION LEVEL}) — one in six + * round trips of a single-row read, for a level PostgreSQL already uses. The module defaults set + * {@code spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED}, which Hikari + * applies once per physical connection, and {@code HikariPoolConstraintValidator} refuses to boot + * with any other level, so "never the vendor default" still holds without the per-transaction + * query. + * *

      A failure is classified by the phase it happened in. Before and during the action it goes * through {@link PersistenceExceptionTranslator#translate(Throwable)}; once the action has returned * and this call is committing a write transaction it began, it goes through {@link @@ -46,6 +56,14 @@ public class SpringTransaction implements TransactionPort { public SpringTransaction( PlatformTransactionManager transactionManager, PersistenceExceptionTranslator exceptionTranslator) { + this(transactionManager, exceptionTranslator, Timeouts.DEFAULT); + } + + public SpringTransaction( + PlatformTransactionManager transactionManager, + PersistenceExceptionTranslator exceptionTranslator, + Timeouts timeouts) { + Objects.requireNonNull(timeouts, "timeouts"); this.writeTemplate = template( transactionManager, @@ -67,6 +85,10 @@ public class SpringTransaction implements TransactionPort { // inNew is for outbox, audit and compensation writes, which usually run while the caller's own // transaction holds a second connection. An unbounded one could pin both for good. this.requiresNewTemplate.template().setTimeout(REQUIRES_NEW_TIMEOUT_SECONDS); + // The caller's own transactions are bounded too (review 04-10): an unbounded one holds its + // pooled connection for as long as its slowest statement or lock wait takes. + this.writeTemplate.template().setTimeout(timeouts.writeSeconds()); + this.readTemplate.template().setTimeout(timeouts.readSeconds()); this.exceptionTranslator = exceptionTranslator; } @@ -93,6 +115,61 @@ public class SpringTransaction implements TransactionPort { return execute(requiresNewTemplate, action); } + /** + * How long one {@link SpringTransaction} write or read transaction may run (review 04-10). + * + *

      Without a bound, a slow query, a row-lock wait or an external call inside the transaction + * holds a pooled connection until it ends on its own; the pool (10 connections by default) runs + * dry and every other request fails at {@code connection-timeout}. With one, Spring hands the + * remaining time to every statement (Hibernate and {@code JdbcTemplate} both set the JDBC query + * timeout), so the server cancels the statement ({@code 57014}, {@code DB_QUERY_CANCELED}) and + * the connection comes back. + * + *

      The default is 30 seconds for both: the budget {@code inNew} already has, and the Hikari + * {@code leak-detection-threshold} at which the pool already reports a held connection as a leak. + * A transaction longer than that was already treated as a fault; now it is also stopped. A + * service that needs a longer unit of work sets {@code app.persistence-jpa.transaction.*} — and + * should ask why it does. + * + * @param write the bound on {@code inWrite} and {@code inRootWrite} + * @param read the bound on {@code inRead} + */ + public record Timeouts(Duration write, Duration read) { + + /** 30 seconds each; see the class comment for why. */ + public static final Timeouts DEFAULT = + new Timeouts(Duration.ofSeconds(30), Duration.ofSeconds(30)); + + public Timeouts { + requireWholePositiveSeconds(write, "write"); + requireWholePositiveSeconds(read, "read"); + } + + int writeSeconds() { + return (int) write.toSeconds(); + } + + int readSeconds() { + return (int) read.toSeconds(); + } + + // Spring's transaction timeout is whole seconds; "1500ms" would silently become 1 s. + private static void requireWholePositiveSeconds(Duration value, String name) { + Objects.requireNonNull(value, name); + if (value.isNegative() + || value.isZero() + || value.toNanosPart() != 0 + || value.toSeconds() > Integer.MAX_VALUE) { + throw new IllegalArgumentException( + "app.persistence-jpa.transaction." + + name + + "-timeout must be a whole number of seconds" + + " greater than zero, was " + + value); + } + } + } + /** One mode's template and the bounded name a failed commit in it is reported under. */ private record ModeTemplate( TransactionTemplate template, PersistenceOperationName commitOperation) {} @@ -106,7 +183,9 @@ public class SpringTransaction implements TransactionPort { TransactionTemplate template = new TransactionTemplate(transactionManager); template.setName("application-" + modeName); template.setPropagationBehavior(propagation); - template.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + // READ_COMMITTED comes from the pool (see the class comment); naming it here costs a round + // trip. + template.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT); template.setReadOnly(readOnly); return new ModeTemplate( template, diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml b/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml index 9d1553e8..a694c225 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml @@ -79,6 +79,11 @@ spring: # New env key APP_DATASOURCE_INIT_FAIL_TIMEOUT delegated to # feature-env-driven-runtime-configuration. initialization-fail-timeout: 1 + # Review 09-05: the one place the application's isolation is set. SpringTransaction leaves + # isolation to the pool, because naming it per transaction makes pgjdbc ask the server + # (SHOW TRANSACTION ISOLATION LEVEL) at every begin. Hikari sets this once per physical + # connection. PINNED: HikariPoolConstraintValidator refuses to boot with any other value. + transaction-isolation: TRANSACTION_READ_COMMITTED # --------------------------------------------------------------------------- # D8 (feature-database-connection-pool-contract) — SLOW QUERY DETECTION # POLICY ONLY — no library dependency added here. Implementation is DEFERRED @@ -140,13 +145,19 @@ spring: hibernate: # true | false (paired with show-sql) format_sql: ${APP_DATASOURCE_FORMAT_SQL:false} - # Advanced JPA batch/fetch/measurement knobs. Defaults preserve Hibernate's off state. - # HibernateJpaBatchExecutor requires batch_size > 0 and generate_statistics=true so it can prove - # batching happened instead of trusting a configuration value. + # Advanced JPA batch/fetch/measurement knobs. + # JDBC batching is ON by default (review 09-07): with it off, flushing N new rows is N round + # trips on one held connection, and a 1,000-item write held a pooled connection for + # thousands of them. 50 rows per batch with insert/update ordering is Hibernate's own + # recommended range; every entity here uses assigned UUIDs, so IDENTITY does not silently + # disable it. A constraint failure inside a batch still carries its SQLState and + # constraint name (PostgreSqlServerErrorFields walks getNextException). Set 0/false to + # turn it off. HibernateJpaBatchExecutor additionally needs generate_statistics=true so it + # can prove batching happened instead of trusting a configuration value. jdbc: - batch_size: ${APP_JPA_HIBERNATE_BATCH_SIZE:0} - order_inserts: ${APP_JPA_HIBERNATE_ORDER_INSERTS:false} - order_updates: ${APP_JPA_HIBERNATE_ORDER_UPDATES:false} + batch_size: ${APP_JPA_HIBERNATE_BATCH_SIZE:50} + order_inserts: ${APP_JPA_HIBERNATE_ORDER_INSERTS:true} + order_updates: ${APP_JPA_HIBERNATE_ORDER_UPDATES:true} default_batch_fetch_size: ${APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE:0} generate_statistics: ${APP_JPA_HIBERNATE_GENERATE_STATISTICS:false} @@ -156,6 +167,14 @@ app: # module's beans and Boot's JDBC/Hibernate/Spring Data JPA/Flyway auto-configurations # (JpaActivationEnvironmentPostProcessor), so no datasource is bound or connected. enabled: ${APP_PERSISTENCE_JPA_ENABLED:true} + # Upper bound on one TransactionPort write (inWrite/inRootWrite) and read (inRead) transaction + # (review 04-10). Whole seconds only — Spring's transaction timeout is an int of seconds. The + # remaining time is handed to every statement, so a slow query or lock wait is cancelled + # (57014 → DB_QUERY_CANCELED) and the connection returns to the pool. 30s = the inNew budget + # and the Hikari leak-detection-threshold above. Plain values, not APP_* env keys. + transaction: + write-timeout: 30s + read-timeout: 30s persistence: # postgresql | h2 — the vendor composition (claim SQL, SQLState mapping, Flyway location). vendor: ${APP_PERSISTENCE_VENDOR:postgresql} diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V20__outbox_event_deferred_attempt_count.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V20__outbox_event_deferred_attempt_count.sql new file mode 100644 index 00000000..1df02290 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V20__outbox_event_deferred_attempt_count.sql @@ -0,0 +1,17 @@ +-- Deferred claims, counted apart from the attempt budget. +-- +-- attempt_count counts every claim, and the relay dead-letters a row whose publish threw once that +-- count reaches the budget (OutboxBackoffPolicy.MAX_ATTEMPTS). A claim that ended with "the broker +-- did not answer" or "refused for now" (shutdown, saturation, credentials being rotated) is not +-- the message's fault and does not spend the budget, but it was still counted, so a row that waited +-- out an outage was dead-lettered by the first failure the adapter could not classify after it. +-- +-- The relay records those claims here (markDeferred) and checks attempt_count - +-- deferred_attempt_count against the budget. attempt_count keeps counting every claim: the retry +-- delay grows with it, which keeps a long outage polled at most five minutes apart. +-- +-- The default fills existing rows without a rewrite: every earlier claim counts against the +-- budget, which is what the relay assumed until now. +ALTER TABLE outbox_event + ADD COLUMN deferred_attempt_count INTEGER NOT NULL DEFAULT 0 + CONSTRAINT ck_outbox_event_deferred_attempt_count CHECK (deferred_attempt_count >= 0); diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V21__outbox_aggregate_sequence.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V21__outbox_aggregate_sequence.sql new file mode 100644 index 00000000..f22aa20f --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V21__outbox_aggregate_sequence.sql @@ -0,0 +1,27 @@ +-- An aggregate's event order, counted by the database instead of read off a clock. +-- +-- The claim gate releases an aggregate's events by (aggregate_sequence, event_index). The sample +-- filled aggregate_sequence with the occurrence time in microseconds, which is not the commit order +-- when two instances' clocks differ or NTP steps back, and two events in one microsecond had the +-- same number and no order at all (review 06-07). +-- +-- outbox_aggregate_sequence holds one counter per aggregate. Incrementing it locks the row until +-- the writer commits, so the numbers follow commit order; it outlives the reaper's deletes, so a +-- number is never reused. JpaOutboxAggregateSequences seeds a new counter from the aggregate's +-- highest existing aggregate_sequence, so rows numbered by the old clock scheme still come first. +CREATE TABLE IF NOT EXISTS outbox_aggregate_sequence ( + tenant_scope VARCHAR(96) NOT NULL, + aggregate_type VARCHAR(64) NOT NULL, + aggregate_id VARCHAR(256) NOT NULL, + last_sequence BIGINT NOT NULL, + CONSTRAINT pk_outbox_aggregate_sequence PRIMARY KEY (tenant_scope, aggregate_type, aggregate_id), + CONSTRAINT ck_outbox_aggregate_sequence_positive CHECK (last_sequence >= 1) +); + +-- One number, one event: a second event appended under an order its aggregate already used is +-- refused at append time, in the writer's transaction, rather than released by the gate in no +-- defined order. Rows without canonical order columns (pre-canonical, all NULL) are not compared. +-- This fails if duplicates already exist; resolve them (they are exactly the rows the gate could +-- not order) before migrating. +CREATE UNIQUE INDEX IF NOT EXISTS ux_outbox_event_aggregate_order + ON outbox_event (tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java index b51e63d9..183e2df2 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java @@ -47,7 +47,8 @@ final class NotificationFixtures { migration("jpa/notification-platform", "V8__notification_admin_claim.sql"), migration("jpa/notification-platform", "V9__notification_evidence_certainty.sql"), migration("jpa/notification-platform", "V10__variables_payload_envelope_guard.sql"), - migration("jpa/notification-platform", "V11__notification_reconciliation_claim_lease.sql")); + migration("jpa/notification-platform", "V11__notification_reconciliation_claim_lease.sql"), + migration("jpa/notification-platform", "V12__notification_suppression_target_unique.sql")); } /** diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaStack.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaStack.java new file mode 100644 index 00000000..9c9f1a29 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaStack.java @@ -0,0 +1,108 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import java.util.Map; +import java.util.function.Supplier; +import org.flywaydb.core.Flyway; +import org.springframework.data.jpa.repository.support.JpaRepositoryFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.SharedEntityManagerCreator; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * The notification stores' real JPA stack on a migrated PostgreSQL, without a Spring context. + * + *

      The two streams are applied through Flyway the way production applies them, the entity manager + * is the shared, transaction-bound one and transactions come from a {@link JpaTransactionManager} — + * the stores' writes refuse to run outside a caller transaction ({@code CallerTransaction}), and a + * transaction opened on a private {@code EntityManager} is not one Spring can see. + */ +public final class NotificationJpaStack implements AutoCloseable { + + private final JpaPlatformContractSupport database; + private final EntityManagerFactory factory; + private final TransactionTemplate transactions; + private final JpaRepositoryFactory repositories; + + private NotificationJpaStack(JpaPlatformContractSupport database) { + this.database = database; + migrate(database); + LocalContainerEntityManagerFactoryBean factoryBean = + new LocalContainerEntityManagerFactoryBean(); + factoryBean.setDataSource(database.dataSource()); + factoryBean.setPackagesToScan( + "dev.caskeleton.adapter.outbound.persistence.notification.platform"); + factoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + factoryBean.setJpaPropertyMap( + Map.of( + "hibernate.hbm2ddl.auto", "validate", + "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect")); + factoryBean.afterPropertiesSet(); + this.factory = factoryBean.getObject(); + EntityManager shared = SharedEntityManagerCreator.createSharedEntityManager(factory); + this.transactions = new TransactionTemplate(new JpaTransactionManager(factory)); + this.repositories = new JpaRepositoryFactory(shared); + } + + /** Starts a server, applies both streams and builds the persistence unit. */ + public static NotificationJpaStack start() { + return new NotificationJpaStack(JpaPlatformContractSupport.start()); + } + + /** A real Spring Data repository on the shared entity manager. */ + public R repository(Class type) { + return repositories.getRepository(type); + } + + /** Runs {@code work} in one committed transaction, as the application's transaction port does. */ + public T inTransaction(Supplier work) { + return transactions.execute(status -> work.get()); + } + + /** Plain JDBC on the same server, for setup and for reading what the database holds. */ + public JdbcTemplate jdbc() { + return new JdbcTemplate(database.dataSource()); + } + + @Override + public void close() { + try { + factory.close(); + } finally { + database.close(); + } + } + + private static void migrate(JpaPlatformContractSupport database) { + Flyway core = + Flyway.configure() + .dataSource(database.dataSource()) + .locations("classpath:db/migration/jpa/core") + .table("flyway_jpa_core_history") + .baselineVersion("0") + .baselineDescription("core baseline") + .load(); + core.baseline(); + core.migrate(); + new JdbcTemplate(database.dataSource()) + .update( + "update capability_schema_registry set lifecycle_state = 'ACTIVE' " + + "where capability_id = ?", + "jpa-flyway-migration"); + Flyway notification = + Flyway.configure() + .dataSource(database.dataSource()) + .locations("classpath:db/migration/jpa/notification-platform") + .table("flyway_jpa_notification_history") + .baselineVersion("0") + .baselineDescription("notification baseline") + .load(); + notification.baseline(); + notification.migrate(); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlPreferenceStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlPreferenceStoreContractTest.java new file mode 100644 index 00000000..9c050dbf --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlPreferenceStoreContractTest.java @@ -0,0 +1,57 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaPolicyStores; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.PreferenceJpaRepository; +import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort; +import dev.caskeleton.application.notification.platform.policy.testkit.PreferenceStoreContract; +import java.time.Clock; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaPolicyStores.Preferences} held to the preference contract against a real PostgreSQL. + * + *

      The table has a unique key on tenant and recipient, so the old find-then-insert did not + * duplicate rows: it turned the second of two first saves into a unique violation, a 409 for a + * write that is supposed to be idempotent (review 04-08). + */ +@Tag("jpa-contract") +class PostgreSqlPreferenceStoreContractTest extends PreferenceStoreContract { + + private static NotificationJpaStack stack; + private static JpaPolicyStores.Preferences store; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + store = + new JpaPolicyStores.Preferences( + stack.repository(PreferenceJpaRepository.class), UUID::randomUUID, Clock.systemUTC()); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.jdbc().update("DELETE FROM notification_preference"); + } + + @Override + protected PreferenceStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlSuppressionStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlSuppressionStoreContractTest.java new file mode 100644 index 00000000..a78e1a17 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlSuppressionStoreContractTest.java @@ -0,0 +1,57 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaSuppressionStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.SuppressionJpaRepository; +import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; +import dev.caskeleton.application.notification.platform.policy.testkit.SuppressionStoreContract; +import java.time.Clock; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaSuppressionStore} held to the suppression contract against a real PostgreSQL. + * + *

      The race case is the reason this runs here rather than on the fake alone: the store used to + * find the entry and insert it when absent, and two bounce webhooks for one address both found + * nothing (review 04-08). + */ +@Tag("jpa-contract") +class PostgreSqlSuppressionStoreContractTest extends SuppressionStoreContract { + + private static NotificationJpaStack stack; + private static JpaSuppressionStore store; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + store = + new JpaSuppressionStore( + stack.repository(SuppressionJpaRepository.class), UUID::randomUUID, Clock.systemUTC()); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.jdbc().update("DELETE FROM notification_suppression"); + } + + @Override + protected SuppressionStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/SuppressionTargetUniqueMigrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/SuppressionTargetUniqueMigrationTest.java new file mode 100644 index 00000000..374a3fde --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/SuppressionTargetUniqueMigrationTest.java @@ -0,0 +1,108 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * V12 deletes duplicate suppression rows before it adds the unique key, and which row survives is a + * rule written in the migration. This holds the migration to that rule on a database that already + * has the duplicates the old find-then-insert produced (review 04-08). + */ +@Tag("jpa-contract") +class SuppressionTargetUniqueMigrationTest { + + private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z"); + private static final String TARGET = "c".repeat(64); + + @Test + @DisplayName("중복 수신 거부 중 만료 없는 행 하나만 남기고 고유 제약을 건다") + void theMigrationKeepsThePermanentRowAndAddsTheKey() { + try (JpaPlatformContractSupport database = JpaPlatformContractSupport.start()) { + // given + JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); + migrateCore(database, jdbc); + Flyway notification = notificationStream(database, "11"); + notification.migrate(); + UUID expiring = insert(jdbc, NOW.minusSeconds(60), NOW.plusSeconds(3600), NOW); + UUID permanent = insert(jdbc, NOW, null, NOW.plusSeconds(1)); + UUID laterPermanent = insert(jdbc, NOW.plusSeconds(30), null, NOW.plusSeconds(2)); + UUID otherTenant = insert(jdbc, "tenant-b", NOW, null, NOW); + + // when + notificationStream(database, "12").migrate(); + + // then + List surviving = + jdbc.queryForList( + "SELECT id FROM notification_suppression ORDER BY tenant_id", UUID.class); + assertThat(surviving) + .as("the permanent row in force longest survives; another tenant's row is untouched") + .containsExactly(permanent, otherTenant) + .doesNotContain(expiring, laterPermanent); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM pg_constraint WHERE conname =" + + " 'uk_notification_suppression_target'", + Integer.class)) + .isEqualTo(1); + } + } + + private static UUID insert( + JdbcTemplate jdbc, Instant effectiveAt, Instant expiresAt, Instant at) { + return insert(jdbc, "tenant-a", effectiveAt, expiresAt, at); + } + + private static UUID insert( + JdbcTemplate jdbc, String tenant, Instant effectiveAt, Instant expiresAt, Instant createdAt) { + UUID id = UUID.randomUUID(); + jdbc.update( + "INSERT INTO notification_suppression (id, tenant_id, scope, reason," + + " normalized_target_hmac, effective_at, expires_at, source, created_at)" + + " VALUES (?, ?, 'CONTACT_POINT', 'HARD_BOUNCE', ?, ?, ?, 'PROVIDER', ?)", + id, + tenant, + TARGET, + Timestamp.from(effectiveAt), + expiresAt == null ? null : Timestamp.from(expiresAt), + Timestamp.from(createdAt)); + return id; + } + + private static void migrateCore(JpaPlatformContractSupport database, JdbcTemplate jdbc) { + Flyway core = + Flyway.configure() + .dataSource(database.dataSource()) + .locations("classpath:db/migration/jpa/core") + .table("flyway_jpa_core_history") + .baselineVersion("0") + .baselineDescription("core baseline") + .load(); + core.baseline(); + core.migrate(); + jdbc.update( + "update capability_schema_registry set lifecycle_state = 'ACTIVE' where capability_id = ?", + "jpa-flyway-migration"); + } + + private static Flyway notificationStream(JpaPlatformContractSupport database, String target) { + return Flyway.configure() + .dataSource(database.dataSource()) + .locations("classpath:db/migration/jpa/notification-platform") + .table("flyway_jpa_notification_history") + .baselineVersion("0") + .baselineOnMigrate(true) + .target(target) + .load(); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientExpiryVersionContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientExpiryVersionContractTest.java new file mode 100644 index 00000000..11cbd8f0 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientExpiryVersionContractTest.java @@ -0,0 +1,103 @@ +package dev.caskeleton.adapter.outbound.persistence.notification.platform; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.persistence.notification.NotificationJpaStack; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.UUID; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * The expiry pass against a delivery somebody read before it ran (review 04-07). + * + *

      {@link RecipientClaimSql#EXPIRE_OVERDUE} did not advance {@code version}, so a stale delivery + * flushed afterwards turned EXPIRED back into a dispatchable state without any conflict. + */ +@Tag("jpa-contract") +class RecipientExpiryVersionContractTest { + + private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z"); + + private static NotificationJpaStack stack; + private static RecipientDeliveryJpaRepository deliveries; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + deliveries = stack.repository(RecipientDeliveryJpaRepository.class); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @Test + @DisplayName("만료 처리 전에 읽은 배송을 저장하면 낙관적 락 충돌이 난다") + void aStaleDeliveryFlushedAfterTheExpiryPassConflicts() { + // given + UUID id = insertOverdueDelivery(); + RecipientDeliveryEntity stale = + stack.inTransaction(() -> deliveries.findById(id).orElseThrow()); + stack.inTransaction(() -> deliveries.expireOverdue(NOW, 10)); + + // when + Throwable conflict = + catchThrowable( + () -> + stack.inTransaction( + () -> { + stale.transition("RETRY_WAITING", NOW.plusSeconds(30), NOW); + return deliveries.saveAndFlush(stale); + })); + + // then + assertThat(conflict).as("the stale write must be refused, not applied").isNotNull(); + assertThat( + stack + .jdbc() + .queryForObject( + "SELECT delivery_state FROM notification_recipient_delivery WHERE id = ?", + String.class, + id)) + .isEqualTo("EXPIRED"); + } + + private static UUID insertOverdueDelivery() { + UUID requestId = UUID.randomUUID(); + UUID id = UUID.randomUUID(); + stack + .jdbc() + .update( + "INSERT INTO notification_request (id, tenant_id, idempotency_key," + + " request_fingerprint, category, template_id, template_version, strategy_type," + + " variables_payload, request_status, metadata_json, created_at, updated_at)" + + " VALUES (?, 'tenant-a', ?, ?, 'transactional', 'welcome', 1, 'IMMEDIATE', '{}'," + + " 'ACCEPTED', '{}'::jsonb, now(), now())", + requestId, + "key-" + requestId, + "0".repeat(64)); + stack + .jdbc() + .update( + "INSERT INTO notification_recipient_delivery (id, notification_id, tenant_id," + + " recipient_ref, routing_plan_json, delivery_state, submission_outcome," + + " delivery_outcome, evidence_level, attempt_count, next_dispatch_at, expires_at," + + " created_at, updated_at) VALUES (?, ?, 'tenant-a', 'user-1', '{}'::jsonb," + + " 'READY_TO_DISPATCH', 'NOT_SUBMITTED', 'UNKNOWN', 'NONE', 0, ?, ?, now()," + + " now())", + id, + requestId, + Timestamp.from(NOW.minusSeconds(3600)), + Timestamp.from(NOW.minusSeconds(1))); + return id; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxBulkReadVersionContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxBulkReadVersionContractTest.java new file mode 100644 index 00000000..8caecf72 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxBulkReadVersionContractTest.java @@ -0,0 +1,99 @@ +package dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.persistence.notification.NotificationJpaStack; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.UUID; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * The bulk mark-all-read against an inbox item somebody read before it ran (review 04-07). + * + *

      The statement did not advance {@code version}, so the stale item's flush matched the row and + * wrote its pre-bulk state back over READ, and optimistic locking reported nothing. + */ +@Tag("jpa-contract") +class InboxBulkReadVersionContractTest { + + private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z"); + + private static NotificationJpaStack stack; + private static InboxItemJpaRepository items; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + items = stack.repository(InboxItemJpaRepository.class); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @Test + @DisplayName("전체 읽음 처리 전에 읽은 항목을 저장하면 낙관적 락 충돌이 난다") + void aStaleItemFlushedAfterTheBulkReadConflicts() { + // given + UUID id = insertUnreadItem(); + InboxItemEntity stale = + stack.inTransaction( + () -> items.findByTenantIdAndOwnerRefAndId("tenant-a", "user-1", id).orElseThrow()); + stack.inTransaction(() -> items.markAllRead("tenant-a", "user-1", null, null, 100, NOW)); + + // when + Throwable conflict = + catchThrowable( + () -> + stack.inTransaction( + () -> { + stale.markSeen(NOW.plusSeconds(1)); + return items.saveAndFlush(stale); + })); + + // then + assertThat(conflict).as("the stale write must be refused, not applied").isNotNull(); + assertThat(isOptimisticLockFailure(conflict)) + .as("refused as an optimistic-lock conflict: %s", conflict) + .isTrue(); + assertThat( + stack + .jdbc() + .queryForObject( + "SELECT state FROM notification_inbox_item WHERE id = ?", String.class, id)) + .isEqualTo("READ"); + } + + private static UUID insertUnreadItem() { + UUID id = UUID.randomUUID(); + stack + .jdbc() + .update( + "INSERT INTO notification_inbox_item (id, tenant_id, owner_ref, category," + + " content_json, state, created_at) VALUES (?, 'tenant-a', 'user-1'," + + " 'payment.receipt', '{}'::jsonb, 'DELIVERED', ?)", + id, + Timestamp.from(NOW.minusSeconds(60))); + return id; + } + + static boolean isOptimisticLockFailure(Throwable failure) { + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current instanceof jakarta.persistence.OptimisticLockException + || current instanceof org.hibernate.StaleStateException + || current instanceof org.springframework.dao.OptimisticLockingFailureException) { + return true; + } + } + return false; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/JpaLifecycleAssociationContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/JpaLifecycleAssociationContractTest.java index a7f75204..ef26cc43 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/JpaLifecycleAssociationContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/JpaLifecycleAssociationContractTest.java @@ -148,6 +148,7 @@ class JpaLifecycleAssociationContractTest { } @Test + @DisplayName("부모 컬렉션에 자식을 넣으면 자식의 외래 키가 기록된다") void addingToTheParentCollectionWritesTheChildForeignKey() { // given Long parentId = diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/RlsIsolationFailureTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/RlsIsolationFailureTest.java index 7937b920..eabd42b0 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/RlsIsolationFailureTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/RlsIsolationFailureTest.java @@ -7,8 +7,8 @@ import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import dev.caskeleton.adapter.outbound.persistence.experimental.rls.RlsPolicyVerifier; import dev.caskeleton.adapter.outbound.persistence.experimental.rls.RlsTenantSessionBinder; -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.application.tenant.TenantId; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/SchemaTenantMigrationContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/SchemaTenantMigrationContractTest.java index 33ef5210..e4874d37 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/SchemaTenantMigrationContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/SchemaTenantMigrationContractTest.java @@ -9,8 +9,8 @@ import dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaMul import dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaTenantMigrationOrchestrator; import dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaTenantRegistry; import dev.caskeleton.adapter.outbound.persistence.experimental.schema.TenantMigrationStatus; -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.application.tenant.TenantId; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/TenantColumnIsolationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/TenantColumnIsolationTest.java index f0082848..324a6d87 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/TenantColumnIsolationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/TenantColumnIsolationTest.java @@ -5,8 +5,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantAwareRepositoryGuard; import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantContext; -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.application.tenant.TenantId; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/TenantPoolCapacityContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/TenantPoolCapacityContractTest.java index 1539efb3..b2ef5043 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/TenantPoolCapacityContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/TenantPoolCapacityContractTest.java @@ -7,8 +7,8 @@ import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import dev.caskeleton.adapter.outbound.persistence.experimental.database.TenantDataSourceRegistry; import dev.caskeleton.adapter.outbound.persistence.experimental.database.TenantPoolBudget; -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.application.tenant.TenantId; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java index e203211e..e092996f 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java @@ -5,13 +5,17 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.outbound.persistence.lock.LockRegistryDistributedLock; import dev.caskeleton.application.lock.DistributedLock; +import dev.caskeleton.application.lock.DistributedLockPort; import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; +import dev.caskeleton.application.lock.testkit.DistributedLockContract; import java.time.Duration; import java.util.ConcurrentModificationException; import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.integration.jdbc.lock.DefaultLockRepository; import org.springframework.integration.jdbc.lock.JdbcLockRegistry; @@ -146,4 +150,34 @@ class PostgreSqlDistributedLockIntegrationTest { repository.start(); return repository; } + + /** + * The port contract every {@link dev.caskeleton.application.lock.DistributedLockPort} passes — + * the in-memory fake runs the same one — over two adapters on one PostgreSQL lock table. + */ + @Nested + class SharedPortContract extends DistributedLockContract { + + private final Duration ttl = Duration.ofSeconds(30); + private final DefaultLockRepository repositoryA = repository(dataSource); + private final DefaultLockRepository repositoryB = repository(dataSource); + private final LockRegistryDistributedLock adapterA = adapter(repositoryA, ttl); + private final LockRegistryDistributedLock adapterB = adapter(repositoryB, ttl); + + @AfterEach + void stopRepositories() { + repositoryA.stop(); + repositoryB.stop(); + } + + @Override + protected DistributedLockPort firstInstance() { + return adapterA; + } + + @Override + protected DistributedLockPort secondInstance() { + return adapterB; + } + } } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java index a6becd4a..2d883e2b 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java @@ -14,6 +14,7 @@ import dev.caskeleton.application.fileserver.api.StorageNamespace; import dev.caskeleton.application.fileserver.api.UploadId; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; import dev.caskeleton.application.fileserver.api.metadata.FileOwner; import dev.caskeleton.application.fileserver.api.metadata.FileRecord; import dev.caskeleton.application.fileserver.api.metadata.FileRecordDraft; @@ -25,6 +26,7 @@ import dev.caskeleton.application.fileserver.api.metadata.UploadSession; import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft; import dev.caskeleton.application.fileserver.api.metadata.WriterLease; import dev.caskeleton.application.fileserver.api.transfer.UploadMode; +import dev.caskeleton.application.fileserver.testkit.FileMetadataPortContract; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -50,8 +52,11 @@ import org.springframework.transaction.support.TransactionTemplate; * *

      Every scenario races two writers on purpose: exactly one must win and the loser must surface * an optimistic conflict rather than silently overwrite. + * + *

      It also runs {@link FileMetadataPortContract}, the contract the in-memory fake that use-case + * tests run on is held to. */ -class PostgreSqlFileserverMetadataStoreIntegrationTest { +class PostgreSqlFileserverMetadataStoreIntegrationTest extends FileMetadataPortContract { private static final String DIGEST = "a".repeat(64); private static final String ETAG = "\"" + DIGEST + "\""; @@ -94,6 +99,16 @@ class PostgreSqlFileserverMetadataStoreIntegrationTest { } } + @Override + protected FileMetadataPort metadata() { + return files; + } + + @Override + protected T transactionally(Supplier action) { + return transactions.execute(ignored -> action.get()); + } + @BeforeEach void clearRows() { jdbc.update("delete from fs_cleanup_item"); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java index 8cbcffd7..eb67ee3a 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java @@ -25,9 +25,11 @@ import dev.caskeleton.application.fileserver.api.metadata.UploadSession; import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft; import dev.caskeleton.application.fileserver.api.transfer.UploadMode; import dev.caskeleton.application.fileserver.cleanup.CleanupItem; +import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; import dev.caskeleton.application.fileserver.cleanup.CleanupType; import dev.caskeleton.application.fileserver.recovery.ReconciliationStatus; +import dev.caskeleton.application.fileserver.testkit.CleanupQueuePortContract; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -35,6 +37,11 @@ import java.util.List; import java.util.Optional; import java.util.OptionalLong; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.AfterAll; @@ -53,7 +60,9 @@ import org.springframework.transaction.support.TransactionTemplate; * nothing about them: the partial unique index, the {@code IN ('PENDING','FAILED')} claim guard, * and the {@code committedBytes >= :amount} floor only exist in the database. */ -class PostgreSqlFileserverReclamationIntegrationTest { +class PostgreSqlFileserverReclamationIntegrationTest extends CleanupQueuePortContract { + + private static final Duration LEASE = Duration.ofMinutes(10); private static PostgreSqlReadinessSupport postgres; private static FileserverJpaTestContext context; @@ -105,8 +114,27 @@ class PostgreSqlFileserverReclamationIntegrationTest { } } + /** Every item a test enqueues is due by this instant; captured once so a test's times agree. */ + private Instant enqueueBy; + + @Override + protected CleanupQueuePort queue() { + return cleanupQueue; + } + + @Override + protected Instant enqueueInstant() { + return enqueueBy; + } + + @Override + protected T transactionally(Supplier action) { + return inTransaction(action); + } + @BeforeEach void truncate() { + enqueueBy = Instant.now().plusSeconds(5); jdbc.execute( "TRUNCATE fs_recovery_item, fs_cleanup_item, fs_quota_reservation," + " fs_verification_result, fs_upload_session, fs_file CASCADE"); @@ -123,7 +151,8 @@ class PostgreSqlFileserverReclamationIntegrationTest { return null; }); - List claimed = inTransaction(() -> cleanupQueue.claimDue(Instant.now(), 10)); + List claimed = + inTransaction(() -> cleanupQueue.claimDue(Instant.now(), 10, LEASE)); assertThat(claimed) .singleElement() @@ -135,94 +164,60 @@ class PostgreSqlFileserverReclamationIntegrationTest { }); } + /** + * The claim locks the rows it picks and skips rows another claim holds. It used to read due rows + * without a lock and update them one by one, so the second worker's update waited on the first + * worker's row lock until that transaction ended, and then found the row no longer due (review + * 04-13). + */ @Test - void aClaimedItemIsNotHandedToASecondWorker() { - FileRecord record = insertRecord(); + void aSecondWorkerClaimsPastARowAnotherWorkerIsStillClaimingInsteadOfWaiting() throws Exception { + // given inTransaction( () -> { cleanupQueue.enqueue( CleanupRequest.forContent( - CleanupType.DELETED_READY_CONTENT, record.fileId(), contentKey())); - return null; - }); - - List first = inTransaction(() -> cleanupQueue.claimDue(Instant.now(), 10)); - List second = inTransaction(() -> cleanupQueue.claimDue(Instant.now(), 10)); - - assertThat(first).hasSize(1); - assertThat(second).isEmpty(); - } - - @Test - void aFailedItemBecomesDueAgainOnlyAfterItsBackoff() { - FileRecord record = insertRecord(); - inTransaction( - () -> { + CleanupType.DELETED_READY_CONTENT, FileId.of(UUID.randomUUID()), contentKey())); cleanupQueue.enqueue( CleanupRequest.forContent( - CleanupType.DELETED_READY_CONTENT, record.fileId(), contentKey())); - return null; - }); - CleanupItem item = inTransaction(() -> cleanupQueue.claimDue(Instant.now(), 10)).get(0); - Instant retryAt = Instant.now().plus(Duration.ofMinutes(5)); - inTransaction( - () -> { - cleanupQueue.markFailed(item, "STORAGE_UNAVAILABLE", retryAt); + CleanupType.DELETED_READY_CONTENT, FileId.of(UUID.randomUUID()), contentKey())); return null; }); + Instant now = enqueueBy; + CountDownLatch firstClaimed = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + Future> first = + workers.submit( + () -> + inTransaction( + () -> { + List claimed = cleanupQueue.claimDue(now, 1, LEASE); + firstClaimed.countDown(); + awaitQuietly(releaseFirst); + return claimed; + })); + firstClaimed.await(); - assertThat(inTransaction(() -> cleanupQueue.claimDue(Instant.now(), 10))).isEmpty(); - assertThat(inTransaction(() -> cleanupQueue.claimDue(retryAt.plusSeconds(1), 10))).hasSize(1); - } - - @Test - void anItemThatKeepsFailingIsAbandonedRatherThanRetriedForever() { - FileRecord record = insertRecord(); - inTransaction( - () -> { - cleanupQueue.enqueue( - CleanupRequest.forContent( - CleanupType.DELETED_READY_CONTENT, record.fileId(), contentKey())); - return null; - }); - - Instant due = Instant.now(); - for (int attempt = 0; attempt < JpaCleanupQueue.MAXIMUM_ATTEMPTS; attempt++) { - List claimed = inTransaction(() -> cleanupQueue.claimDue(due, 10)); - if (claimed.isEmpty()) { - break; + // when + Future> second = + workers.submit(() -> inTransaction(() -> cleanupQueue.claimDue(now, 2, LEASE))); + List secondClaim; + try { + secondClaim = second.get(5, TimeUnit.SECONDS); + } finally { + releaseFirst.countDown(); } - inTransaction( - () -> { - cleanupQueue.markFailed(claimed.get(0), "STILL_FAILING", due); - return null; - }); + + // then + List firstClaim = first.get(5, TimeUnit.SECONDS); + assertThat(firstClaim).hasSize(1); + assertThat(secondClaim).hasSize(1); + assertThat(secondClaim.get(0).cleanupId()).isNotEqualTo(firstClaim.get(0).cleanupId()); + } finally { + workers.shutdownNow(); } - - assertThat(inTransaction(() -> cleanupQueue.claimDue(due.plusSeconds(1), 10))).isEmpty(); - assertThat(statusCounts("fs_cleanup_item", "ABANDONED")).isEqualTo(1); - } - - @Test - void aDoneItemIsNeverClaimedAgain() { - FileRecord record = insertRecord(); - inTransaction( - () -> { - cleanupQueue.enqueue( - CleanupRequest.forContent( - CleanupType.DELETED_READY_CONTENT, record.fileId(), contentKey())); - return null; - }); - CleanupItem item = inTransaction(() -> cleanupQueue.claimDue(Instant.now(), 10)).get(0); - - inTransaction( - () -> { - cleanupQueue.markDone(item); - return null; - }); - - assertThat(inTransaction(() -> cleanupQueue.claimDue(Instant.now().plusSeconds(600), 10))) - .isEmpty(); } @Test @@ -445,6 +440,14 @@ class PostgreSqlFileserverReclamationIntegrationTest { Instant.now().plus(Duration.ofHours(1))))); } + private static void awaitQuietly(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + } + private static ContentKey contentKey() { String flat = UUID.randomUUID().toString().replace("-", ""); return ContentKey.of(flat.substring(0, 2) + '/' + flat.substring(2, 4) + '/' + flat); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java index e26623d3..58809891 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java @@ -50,7 +50,7 @@ class PostgreSqlMigrationIntegrationTest { assertThat(appliedVersions(postgres, "flyway_schema_history")) .containsExactly( "1", "3", "4", "5", "6", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", - "19"); + "19", "20", "21"); assertThat( singleValue( postgres, diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java index 6cf1d029..309f1908 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java @@ -100,12 +100,14 @@ final class PostgreSqlOptionalStreamLifecycle { // where it would look like a decryption bug instead of an un-migrated table. // V11 gives a reconciliation job claim a lease and a fence, so two instances cannot both // hold one job. + // V12 makes a suppression unique per target and reason, so the store can upsert with ON + // CONFLICT instead of a find-then-insert two webhooks could both win. // // This list is the stream's contract, not a note about its length: the lifecycle below // disables, re-enables and interrupts the stream and asserts the applied set is unchanged // each time. So a migration added to the stream belongs here, and the version that landed // without being added is why the lane failed the first time anybody ran it. - List.of("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"), + List.of("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"), List.of()); } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAggregateSequenceIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAggregateSequenceIntegrationTest.java new file mode 100644 index 00000000..e40cca12 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAggregateSequenceIntegrationTest.java @@ -0,0 +1,111 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore; +import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.outbox.OutboxAggregateSequencePort; +import dev.caskeleton.application.outbox.testkit.OutboxAggregateSequenceContract; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +import java.time.Instant; +import java.util.UUID; +import javax.sql.DataSource; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +/** + * The aggregate order counter and the order uniqueness rule against real PostgreSQL (V21, review + * 06-07): the shared {@link OutboxAggregateSequenceContract}, the seed from rows numbered before + * the counter existed, and a second append under a used order refused at append time. + */ +class PostgreSqlOutboxAggregateSequenceIntegrationTest extends OutboxAggregateSequenceContract { + + private static final Instant OCCURRED = Instant.parse("2026-11-01T00:00:00Z"); + + private static PostgreSqlReadinessSupport postgres; + private static AnnotationConfigApplicationContext context; + private static OutboxAggregateSequencePort sequences; + + @BeforeAll + static void setup() { + postgres = PostgreSqlReadinessSupport.start(); + DataSource dataSource = postgres.dataSource(); + OutboxIntegrationSupport.migrate(dataSource); + context = OutboxIntegrationSupport.buildContext(dataSource, e -> {}, Clock.systemUTC()); + sequences = context.getBean(JpaOutboxStore.class); + } + + @AfterAll + static void cleanup() { + if (context != null) { + context.close(); + } + if (postgres != null) { + postgres.close(); + } + } + + @Override + protected OutboxAggregateSequencePort sequences() { + return sequences; + } + + @Override + protected TransactionPort transactions() { + return context.getBean(SpringTransaction.class); + } + + @Test + @DisplayName("카운터가 없던 aggregate의 첫 번호는 이미 있는 outbox 행의 가장 큰 번호 다음이다") + void aNewCounterStartsAfterTheHighestOrderTheAggregatesRowsAlreadyCarry() { + // given: a row numbered by the old wall-clock scheme + String aggregateId = "clock-numbered-" + UUID.randomUUID(); + long clockNumber = 1_761_955_200_000_000L; + append(aggregateId, clockNumber); + + // when + long next = + transactions() + .inWrite( + () -> + sequences.nextSequence( + new AggregateIdentity("default", "testkit", aggregateId))); + + // then + assertThat(next).isEqualTo(clockNumber + 1); + } + + @Test + @DisplayName("같은 aggregate에 같은 순서 번호로 두 번 append하면 두 번째는 실패한다") + void aSecondEventUnderAnOrderItsAggregateAlreadyUsedIsRefused() { + // given + String aggregateId = "duplicate-order-" + UUID.randomUUID(); + append(aggregateId, 7); + + // when + Throwable thrown = catchThrowable(() -> append(aggregateId, 7)); + + // then + assertThat(thrown).isNotNull(); + } + + private static void append(String aggregateId, long sequence) { + JpaOutboxStore store = context.getBean(JpaOutboxStore.class); + context + .getBean(SpringTransaction.class) + .inWrite( + () -> { + store.append( + OutboxEvents.event( + UUID.randomUUID().toString(), aggregateId, sequence, OCCURRED)); + return null; + }); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java index 532e9aee..f3ffc6fc 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java @@ -17,7 +17,8 @@ import org.testcontainers.utility.MountableFile; final class PostgreSqlReadinessSupport implements AutoCloseable { private static final String IMAGE = - System.getProperty("jpa.evidence.postgresql.image", "postgres:16-alpine"); + System.getProperty( + "jpa.evidence.postgresql.image", System.getProperty("ca.test.image.postgres-16")); private final PostgreSQLContainer container; private final HikariDataSource dataSource; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java index 5d066da2..2ee91d75 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java @@ -3,6 +3,8 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator; import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; @@ -10,6 +12,14 @@ import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlState import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; +import jakarta.persistence.Entity; +import jakarta.persistence.EntityManager; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Version; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; @@ -21,13 +31,19 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import javax.sql.DataSource; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.SharedEntityManagerCreator; /** * {@code SpringTransaction} against real PostgreSQL. @@ -202,6 +218,160 @@ class PostgreSqlTransactionIntegrationTest { } } + // ---- review 04-05: a lost @Version race reaches the caller as a conflict, not a 500 ---- + + @Test + @Tag("jpa-failure") + @Timeout(30) + @DisplayName("커밋 전에 다른 트랜잭션이 같은 행을 바꾸면 DB_OPTIMISTIC_CONFLICT로 알리고 상대의 변경을 지킨다") + void aVersionRaceLostAtCommitIsAnOptimisticConflict() { + // given + JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); + Configuration configuration = new Configuration(); + configuration.getProperties().put("hibernate.connection.datasource", postgres.dataSource()); + configuration.setProperty("hibernate.hbm2ddl.auto", "create"); + configuration.addAnnotatedClass(VersionedRow.class); + try (SessionFactory sessionFactory = configuration.buildSessionFactory()) { + sessionFactory.inTransaction(session -> session.persist(new VersionedRow(1L, "initial"))); + EntityManager entityManager = + SharedEntityManagerCreator.createSharedEntityManager(sessionFactory); + SpringTransaction port = + new SpringTransaction(new JpaTransactionManager(sessionFactory), translator()); + + // when + Throwable thrown = + catchThrowable( + () -> + port.inWrite( + () -> { + VersionedRow row = entityManager.find(VersionedRow.class, 1L); + // another request commits first, on its own connection + jdbc.update( + "update readiness_versioned set label = 'theirs'," + + " version = version + 1 where id = 1"); + row.label = "mine"; + return null; + })); + + // then + assertThat(thrown).isInstanceOf(PersistenceFailureException.class); + assertThat(((PersistenceFailureException) thrown).errorCode()) + .isEqualTo(OperationalError.DB_OPTIMISTIC_CONFLICT); + assertThat( + jdbc.queryForObject( + "select label from readiness_versioned where id = 1", String.class)) + .isEqualTo("theirs"); + } + } + + // ---- review 04-10: a write transaction cannot hold its connection past its bound ---- + + @Test + @Tag("jpa-failure") + @Timeout(20) + @DisplayName("제한 시간을 넘는 쓰기 트랜잭션은 그 시간 안에 DB_QUERY_CANCELED로 끝나고 연결을 돌려준다") + void aWriteTransactionLongerThanItsBoundIsCancelledInTime() { + // given + JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); + SpringTransaction port = + new SpringTransaction( + new DataSourceTransactionManager(postgres.dataSource()), + translator(), + new SpringTransaction.Timeouts(Duration.ofSeconds(1), Duration.ofSeconds(1))); + long startedAt = System.nanoTime(); + + // when + Throwable thrown = + catchThrowable( + () -> port.inWrite(() -> jdbc.queryForObject("select pg_sleep(10)", Object.class))); + + // then + Duration elapsed = Duration.ofNanos(System.nanoTime() - startedAt); + assertThat(thrown).isInstanceOf(PersistenceFailureException.class); + assertThat(((PersistenceFailureException) thrown).errorCode()) + .isEqualTo(OperationalError.DB_QUERY_CANCELED); + assertThat(elapsed).isLessThan(Duration.ofSeconds(5)); + } + + // ---- review 09-05: READ COMMITTED comes from the pool, with no per-transaction round trip ---- + + @Test + @DisplayName("풀이 고정한 READ COMMITTED로 트랜잭션이 돌고, 시작할 때 서버에 격리 수준을 묻지 않는다") + void transactionsRunAtThePoolsReadCommittedWithoutAskingTheServer() throws Exception { + // given — a server default that is NOT read committed, so only the pool can make it so + HikariConfig config = new HikariConfig(); + config.setJdbcUrl(postgres.dataSource().getJdbcUrl()); + config.setUsername(postgres.dataSource().getUsername()); + config.setPassword(postgres.dataSource().getPassword()); + config.setMaximumPoolSize(2); + config.addDataSourceProperty("options", "-c default_transaction_isolation=repeatable\\ read"); + config.setTransactionIsolation("TRANSACTION_READ_COMMITTED"); + try (HikariDataSource pool = new HikariDataSource(config)) { + AtomicInteger isolationQueries = new AtomicInteger(); + DataSource counting = countingIsolationQueries(pool, isolationQueries); + JdbcTemplate jdbc = new JdbcTemplate(counting); + SpringTransaction port = + new SpringTransaction(new DataSourceTransactionManager(counting), translator()); + + // when + String isolation = + port.inWrite(() -> jdbc.queryForObject("show transaction_isolation", String.class)); + + // then + assertThat(isolation).isEqualTo("read committed"); + assertThat(isolationQueries).hasValue(0); + } + } + + /** A data source whose connections count {@code getTransactionIsolation()} calls. */ + private static DataSource countingIsolationQueries(DataSource target, AtomicInteger calls) { + return (DataSource) + Proxy.newProxyInstance( + DataSource.class.getClassLoader(), + new Class[] {DataSource.class}, + (proxy, method, args) -> { + Object result = invoke(method, target, args); + if (result instanceof Connection connection) { + return Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (connectionProxy, connectionMethod, connectionArgs) -> { + if (connectionMethod.getName().equals("getTransactionIsolation")) { + calls.incrementAndGet(); + } + return invoke(connectionMethod, connection, connectionArgs); + }); + } + return result; + }); + } + + private static Object invoke(Method method, Object target, Object[] args) throws Throwable { + try { + return method.invoke(target, args); + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + } + + /** The {@code @Version} entity of the optimistic-conflict scenario. */ + @Entity + @Table(name = "readiness_versioned") + static class VersionedRow { + @Id Long id; + + @Version Long version; + + String label; + + protected VersionedRow() {} + + VersionedRow(Long id, String label) { + this.id = id; + this.label = label; + } + } + private static SpringTransaction transactionPort() { return new SpringTransaction( new DataSourceTransactionManager(postgres.dataSource()), translator()); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/api/error/JpaPersistenceExceptionCodeTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/api/error/JpaPersistenceExceptionCodeTest.java index bf7080ef..c76a8540 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/api/error/JpaPersistenceExceptionCodeTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/api/error/JpaPersistenceExceptionCodeTest.java @@ -34,7 +34,7 @@ class JpaPersistenceExceptionCodeTest { Arguments.of(FailureCategory.LOCK_NOT_AVAILABLE, OperationalError.DB_LOCK_TIMEOUT), Arguments.of(FailureCategory.OPTIMISTIC_CONFLICT, OperationalError.DB_OPTIMISTIC_CONFLICT), Arguments.of(FailureCategory.QUERY_TIMEOUT, OperationalError.DB_QUERY_CANCELED), - Arguments.of(FailureCategory.TRANSACTION_TIMEOUT, OperationalError.DB_QUERY_CANCELED), + Arguments.of(FailureCategory.TRANSACTION_TIMEOUT, OperationalError.DB_IDLE_IN_TX_TIMEOUT), Arguments.of(FailureCategory.CONNECTION_UNAVAILABLE, OperationalError.DB_UNAVAILABLE), Arguments.of(FailureCategory.SCHEMA_MISMATCH, OperationalError.INTERNAL_ERROR), Arguments.of(FailureCategory.DATA_CORRUPTION, OperationalError.INTERNAL_ERROR), diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFailClosedTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFailClosedTest.java index 5daf7f8f..a560adf4 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFailClosedTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFailClosedTest.java @@ -12,7 +12,7 @@ import dev.caskeleton.adapter.outbound.persistence.experimental.replica.ReplicaT import dev.caskeleton.adapter.outbound.persistence.experimental.replica.TransactionContext; import dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaTenantRegistry; import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantContext; -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; +import dev.caskeleton.application.tenant.TenantId; import java.time.Duration; import java.time.Instant; import java.util.Map; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslatorTest.java index a0a9b9b2..ba62cf1e 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslatorTest.java @@ -342,4 +342,37 @@ class PersistenceExceptionTranslatorTest { private record SecondMapping(Map exactMappings) implements SqlStateErrorMapping {} + + // ---- failures with no SQLState that still have a definite code ---- + + @Test + @DisplayName("SQLState 없는 JPA 낙관적 락 예외는 DB_OPTIMISTIC_CONFLICT로 분류한다") + void aJpaOptimisticLockExceptionIsAnOptimisticConflict() { + // given + RuntimeException failure = + new jakarta.persistence.OptimisticLockException("Row was updated by another transaction"); + + // when + Optional result = translator.translate(failure); + + // then + assertThat(result).isPresent(); + assertThat(result.orElseThrow().errorCode()).isEqualTo(OperationalError.DB_OPTIMISTIC_CONFLICT); + } + + @Test + @DisplayName("트랜잭션 제한 시간이 다음 문장 전에 지나면 DB_QUERY_CANCELED로 분류한다") + void anExpiredTransactionDeadlineIsAQueryCancellation() { + // given + RuntimeException failure = + new org.springframework.transaction.TransactionTimedOutException( + "Transaction timed out: deadline was Sat Nov 01 00:00:00 UTC 2026"); + + // when + Optional result = translator.translate(failure); + + // then + assertThat(result).isPresent(); + assertThat(result.orElseThrow().errorCode()).isEqualTo(OperationalError.DB_QUERY_CANCELED); + } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/ModuleDefaultJdbcBatchingTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/ModuleDefaultJdbcBatchingTest.java new file mode 100644 index 00000000..0add5b95 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/ModuleDefaultJdbcBatchingTest.java @@ -0,0 +1,44 @@ +package dev.caskeleton.adapter.outbound.persistence.hibernate.batch; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.ClassPathResource; + +/** + * Review 09-07: with Hibernate's batching off, a write of N rows is N round trips on one held + * connection. The module default turns batching on; an operator can still turn it off. + */ +class ModuleDefaultJdbcBatchingTest { + + @Test + @DisplayName("모듈 기본값은 JDBC batch와 insert·update 정렬을 켠다") + void theModuleDefaultsTurnJdbcBatchingOn() throws IOException { + // given + // the file alone: no operator environment variable may answer for it + StandardEnvironment environment = new StandardEnvironment(); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); + new YamlPropertySourceLoader() + .load( + "persistence-jpa", new ClassPathResource("config/module-defaults/persistence-jpa.yml")) + .forEach(source -> environment.getPropertySources().addLast(source)); + String prefix = "spring.jpa.properties.hibernate."; + + // when + Integer batchSize = environment.getProperty(prefix + "jdbc.batch_size", Integer.class); + + // then + assertThat(batchSize).isEqualTo(50); + assertThat(environment.getProperty(prefix + "order_inserts", Boolean.class)).isTrue(); + assertThat(environment.getProperty(prefix + "order_updates", Boolean.class)).isTrue(); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMappingTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMappingTest.java index 844d0df1..74e6caf7 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMappingTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlSqlStateErrorMappingTest.java @@ -37,9 +37,16 @@ class PostgreSqlSqlStateErrorMappingTest { } @Test - void pgMappingContributesExactlyFourCodes() { + @DisplayName("PostgreSQL 표가 기여하는 행은 분류기에서 파생된 여섯 상태다") + void pgMappingContributesTheSixCodesDerivedFromTheClassifier() { + // when Map codes = pgMapping.exactMappings(); - assertThat(codes).containsOnlyKeys("40P01", "55P03", "25P03", "57014"); + + // then + assertThat(codes) + .containsOnlyKeys("40P01", "55P03", "25P03", "57014", "57P01", "57P02") + .containsEntry("57P01", OperationalError.DB_UNAVAILABLE) + .containsEntry("57P02", OperationalError.DB_UNAVAILABLE); } @Test diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/SqlStateClassificationParityTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/SqlStateClassificationParityTest.java new file mode 100644 index 00000000..5a863411 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/SqlStateClassificationParityTest.java @@ -0,0 +1,68 @@ +package dev.caskeleton.adapter.outbound.persistence.postgresql; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; +import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator; +import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; +import dev.caskeleton.adapter.outbound.persistence.postgresql.constraint.PostgreSqlConstraintCatalog; +import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlExceptionTranslator; +import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlState; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.OperationalError; +import java.sql.SQLException; +import java.time.Duration; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataIntegrityViolationException; + +/** + * Review 04-06: a PostgreSQL deployment classifies a SQLSTATE on two paths — the default {@code + * TransactionPort} translator and the library {@link PostgreSqlExceptionTranslator}. Both must give + * the client the same code, or the same outage is retryable on one path and final on the other. + */ +class SqlStateClassificationParityTest { + + private static final PersistenceOperationName OPERATION = + new PersistenceOperationName("parity.check"); + + private final PersistenceExceptionTranslator transactionPortPath = + new PersistenceExceptionTranslator( + List.of(new StandardSqlStateErrorMapping(), new PostgreSqlSqlStateErrorMapping())); + + private final PostgreSqlExceptionTranslator libraryPath = + PostgreSqlExceptionTranslator.with(PostgreSqlConstraintCatalog.empty()); + + static Stream sqlStates() { + return Stream.concat( + Stream.of(PostgreSqlState.values()).map(PostgreSqlState::code), + // a connection-class state no enum member names, and one nothing classifies + Stream.of("08006", "XX000")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("sqlStates") + @DisplayName("같은 SQLState는 트랜잭션 포트 경로와 라이브러리 경로에서 같은 코드로 분류된다") + void bothPathsReportTheSameCodeForASqlState(String sqlState) { + // given + DataAccessException failure = + new DataIntegrityViolationException("wrapper", new SQLException("driver", sqlState)); + ApiErrorCode library = + libraryPath.translate(failure, OPERATION, 1, Duration.ZERO, null).errorCode(); + + // when + ApiErrorCode transactionPort = + transactionPortPath + .translate(failure) + .map(carrier -> carrier.errorCode()) + // unclassified: the inbound catch-all answers the raw failure with INTERNAL_ERROR + .orElse(OperationalError.INTERNAL_ERROR); + + // then + assertThat(transactionPort).isEqualTo(library); + } +} 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 b919ffba..906cc346 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 @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -22,6 +23,39 @@ class HikariPoolConstraintValidatorTest { new ApplicationContextRunner() .withUserConfiguration(StartupRuleAutoConfiguration.class, ValidatorConfig.class); + // --- review 09-05: the pool owns READ COMMITTED, so no other level may boot --- + + @Test + @DisplayName("풀 격리 수준이 READ COMMITTED가 아니면 기동을 거부한다") + void aPoolIsolationOtherThanReadCommittedFailsStartup() { + // when + runner + .withPropertyValues( + "spring.datasource.hikari.transaction-isolation=TRANSACTION_SERIALIZABLE") + .run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasStackTraceContaining("transaction-isolation") + .hasStackTraceContaining("TRANSACTION_READ_COMMITTED"); + }); + } + + @Test + @DisplayName("풀 격리 수준이 READ COMMITTED면 기동한다") + void aReadCommittedPoolStartsCleanly() { + // when + runner + .withPropertyValues( + "spring.datasource.hikari.transaction-isolation=TRANSACTION_READ_COMMITTED") + .run( + context -> { + // then + assertThat(context).hasNotFailed(); + }); + } + // --- D2 / HIKARI-CFG-C1: connection-timeout >= 250 --- @Test diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfigurationTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfigurationTest.java index 5bff38b7..bb89c3c5 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfigurationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfigurationTest.java @@ -11,12 +11,14 @@ import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfigurat import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.DatabaseMetaData; +import java.sql.SQLException; import java.util.concurrent.atomic.AtomicInteger; import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.flyway.autoconfigure.FlywayMigrationInitializer; import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -180,6 +182,45 @@ class JpaStartupAutoConfigurationTest { }); } + @Test + @DisplayName("연결된 데이터베이스 검사가 실패하면 Flyway 마이그레이션을 시작하기 전에 기동이 멈춘다") + void anUnsupportedDatabaseStopsTheBootBeforeAnyMigrationRuns() { + // given + AtomicInteger migrations = new AtomicInteger(); + DataSource unreachable = + new AbstractDataSource() { + @Override + public Connection getConnection() throws SQLException { + throw new SQLException("database unreachable"); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return getConnection(); + } + }; + + // when + runner + .withBean( + "flywayInitializer", + FlywayMigrationInitializer.class, + () -> + new FlywayMigrationInitializer( + Flyway.configure().dataSource(unreachable).load(), + flyway -> migrations.incrementAndGet())) + .withBean(DataSource.class, () -> unreachable) + .withPropertyValues("spring.jpa.open-in-view=false") + .run( + context -> { + // then + assertThat(context.getStartupFailure()) + .hasStackTraceContaining( + "could not open a connection to validate the datasource"); + assertThat(migrations).hasValue(0); + }); + } + @Test void safetySettingsDefaultToEnabled() { runner diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaVersionedBulkUpdateRuleTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaVersionedBulkUpdateRuleTest.java new file mode 100644 index 00000000..c843d302 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaVersionedBulkUpdateRuleTest.java @@ -0,0 +1,91 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.JpaVersionedBulkUpdateRule; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** The versioned bulk-update rule, with both branches executed on statements written for it. */ +class JpaVersionedBulkUpdateRuleTest { + + private static final Map> VERSIONED = + Map.of( + "inboxitementity", Set.of("version"), + "notification_inbox_item", Set.of("version"), + "fileentity", Set.of("version"), + "durable_operation", Set.of("rowversion", "row_version")); + + @Test + @DisplayName("version을 올리지 않는 native bulk UPDATE는 위반이다") + void aNativeBulkUpdateThatLeavesTheVersionIsAViolation() { + // when + Optional violation = + JpaVersionedBulkUpdateRule.versionBumpViolation( + "UPDATE notification_inbox_item SET read_at = :at, state = 'READ' WHERE id IN (" + + " SELECT id FROM notification_inbox_item WHERE owner_ref = :owner)", + VERSIONED); + + // then + assertThat(violation) + .hasValue("updates versioned 'notification_inbox_item' without version = itself + 1"); + } + + @Test + @DisplayName("별칭을 붙여 version을 올리는 JPQL bulk UPDATE는 통과한다") + void aJpqlBulkUpdateThatAdvancesTheAliasedVersionIsAccepted() { + // when + Optional violation = + JpaVersionedBulkUpdateRule.versionBumpViolation( + "update FileEntity f set f.state = :state, f.version = f.version + 1 where f.id = :id", + VERSIONED); + + // then + assertThat(violation).isEmpty(); + } + + @Test + @DisplayName("CTE 뒤의 UPDATE도 검사하고 FOR UPDATE 잠금 절은 대상으로 보지 않는다") + void theUpdateAfterACteIsCheckedAndARowLockIsNot() { + // when + Optional violation = + JpaVersionedBulkUpdateRule.versionBumpViolation( + "WITH c AS (SELECT id FROM notification_inbox_item FOR UPDATE SKIP LOCKED LIMIT 5)" + + " UPDATE notification_inbox_item AS i SET state = 'READ' FROM c WHERE i.id =" + + " c.id", + VERSIONED); + + // then + assertThat(violation).isPresent(); + } + + @Test + @DisplayName("@Version이 없는 테이블의 bulk UPDATE는 규칙 대상이 아니다") + void aBulkUpdateOfAnUnversionedTableIsNotTheRulesBusiness() { + // when + Optional violation = + JpaVersionedBulkUpdateRule.versionBumpViolation( + "UPDATE notification_provider_event SET projection_error_code = :code WHERE id = :id", + VERSIONED); + + // then + assertThat(violation).isEmpty(); + } + + @Test + @DisplayName("version 컬럼 이름이 다르면 그 이름으로 올렸는지 본다") + void aVersionColumnWithAnotherNameIsCheckedUnderThatName() { + // when + Optional violation = + JpaVersionedBulkUpdateRule.versionBumpViolation( + "UPDATE durable_operation SET state = 'FAILED', row_version = row_version + 1" + + " WHERE id = :id", + VERSIONED); + + // then + assertThat(violation).isEmpty(); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java index 631f1932..89a771c0 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java @@ -100,6 +100,7 @@ class JpaArchitectureRulesTest { } @Test + @DisplayName("mappedBy 쪽 @OneToMany는 원칙과 대안을 담은 메시지로 거부된다") void anInverseOneToManyIsRefusedWithThePrincipleAndTheAlternatives() { // given var classes = @@ -122,6 +123,7 @@ class JpaArchitectureRulesTest { } @Test + @DisplayName("mappedBy 쪽 @OneToOne은 거부된다") void anInverseOneToOneIsRefused() { // given var classes = @@ -141,6 +143,7 @@ class JpaArchitectureRulesTest { } @Test + @DisplayName("mappedBy 쪽 @ManyToMany는 거부된다") void anInverseManyToManyIsRefused() { // given var classes = @@ -160,6 +163,7 @@ class JpaArchitectureRulesTest { } @Test + @DisplayName("양방향 쌍에서는 mappedBy 쪽만 위반으로 보고된다") void onlyTheMappedBySideOfABidirectionalPairIsReported() { // given var classes = @@ -178,6 +182,7 @@ class JpaArchitectureRulesTest { } @Test + @DisplayName("단방향 연관관계는 통과한다") void unidirectionalAssociationsPass() { var classes = new ClassFileImporter() diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/PostgreSqlVersionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/PostgreSqlVersionTest.java index 482bf843..9262e61c 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/PostgreSqlVersionTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/PostgreSqlVersionTest.java @@ -48,10 +48,15 @@ class PostgreSqlVersionTest { } @Test - @DisplayName("each version pins an image tag carrying its major version") - void eachVersionPinsAnImage() { + @DisplayName("버전마다 자기 major 번호를 담은 이미지 목록 키로 이미지를 받는다") + void eachVersionResolvesTheCatalogImageNamedAfterItsMajorVersion() { + // The image itself is a digest in config/testing/container-images.properties (review + // 2026-11-01 08-04), so the major version is carried by the catalog key the version reads. for (PostgreSqlVersion version : PostgreSqlVersion.stable()) { - assertThat(version.image()).contains(String.valueOf(version.majorVersion())); + assertThat(version.imageKey()).isEqualTo("postgres-" + version.majorVersion()); + assertThat(version.image()) + .isEqualTo(System.getProperty("ca.test.image.postgres-" + version.majorVersion())) + .startsWith("postgres"); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionTest.java index 929044dc..528be5e7 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionTest.java @@ -6,10 +6,13 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; +import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator; +import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; import dev.caskeleton.application.transaction.NestedRootTransactionRejectedException; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; import java.sql.SQLException; +import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @@ -18,6 +21,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -35,7 +39,7 @@ class SpringTransactionTest { } @Test - void inWriteUsesRequiredPropagationReadCommittedIsolationAndNotReadOnly() { + void inWriteUsesRequiredPropagationPoolIsolationAndNotReadOnly() { RecordingTransactionManager tm = new RecordingTransactionManager(); SpringTransaction port = new SpringTransaction(tm); @@ -46,15 +50,14 @@ class SpringTransactionTest { TransactionDefinition definition = tm.definitions.get(0); assertThat(definition.getPropagationBehavior()) .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_DEFAULT); assertThat(definition.isReadOnly()).isFalse(); assertThat(tm.commits).isOne(); assertThat(tm.rollbacks).isZero(); } @Test - void inReadUsesRequiredPropagationReadCommittedIsolationAndReadOnly() { + void inReadUsesRequiredPropagationPoolIsolationAndReadOnly() { RecordingTransactionManager tm = new RecordingTransactionManager(); SpringTransaction port = new SpringTransaction(tm); @@ -64,13 +67,12 @@ class SpringTransactionTest { TransactionDefinition definition = tm.definitions.get(0); assertThat(definition.getPropagationBehavior()) .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_DEFAULT); assertThat(definition.isReadOnly()).isTrue(); } @Test - void inRootWriteUsesRequiredPropagationReadCommittedIsolationAndNotReadOnly() { + void inRootWriteUsesRequiredPropagationPoolIsolationAndNotReadOnly() { RecordingTransactionManager tm = new RecordingTransactionManager(); SpringTransaction port = new SpringTransaction(tm); @@ -81,8 +83,7 @@ class SpringTransactionTest { TransactionDefinition definition = tm.definitions.get(0); assertThat(definition.getPropagationBehavior()) .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_DEFAULT); assertThat(definition.isReadOnly()).isFalse(); assertThat(tm.commits).isOne(); assertThat(tm.rollbacks).isZero(); @@ -152,7 +153,7 @@ class SpringTransactionTest { } @Test - void inNewUsesRequiresNewPropagationReadCommittedIsolationAndNotReadOnly() { + void inNewUsesRequiresNewPropagationPoolIsolationAndNotReadOnly() { RecordingTransactionManager tm = new RecordingTransactionManager(); SpringTransaction port = new SpringTransaction(tm); @@ -161,13 +162,10 @@ class SpringTransactionTest { TransactionDefinition definition = tm.definitions.get(0); assertThat(definition.getPropagationBehavior()) .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_DEFAULT); assertThat(definition.isReadOnly()).isFalse(); } - // ---- feature-transaction-concurrency-contract D3: vendor default isolation is forbidden ---- - /** Compensation and recovery writes must not hold a connection indefinitely. */ @Test void inNewBoundsItsTransactionToThirtySeconds() { @@ -182,25 +180,82 @@ class SpringTransactionTest { assertThat(tm.definitions.get(0).getTimeout()).isEqualTo(30); } + // ---- review 04-10: the caller's own write and read transactions are bounded too ---- + @Test - void everyModePinsAnExplicitIsolationNeverTheVendorDefault() { + @DisplayName("쓰기·읽기 트랜잭션은 기본으로 30초 제한을 받는다") + void writeAndReadTransactionsAreBoundedByDefault() { + // given RecordingTransactionManager tm = new RecordingTransactionManager(); SpringTransaction port = new SpringTransaction(tm); + // when + port.inWrite(() -> null); + port.inRootWrite(() -> null); + port.inRead(() -> null); + + // then + assertThat(tm.definitions) + .extracting(TransactionDefinition::getTimeout) + .containsExactly(30, 30, 30); + } + + @Test + @DisplayName("설정한 쓰기·읽기 제한 시간이 각 모드의 트랜잭션에 걸린다") + void configuredTimeoutsBoundTheirModes() { + // given + RecordingTransactionManager tm = new RecordingTransactionManager(); + SpringTransaction port = + new SpringTransaction( + tm, + new PersistenceExceptionTranslator(List.of(new StandardSqlStateErrorMapping())), + new SpringTransaction.Timeouts(Duration.ofSeconds(7), Duration.ofSeconds(3))); + + // when port.inWrite(() -> null); port.inRead(() -> null); port.inNew(() -> null); - assertThat(tm.definitions).hasSize(3); + // then assertThat(tm.definitions) - .as( - "delegating to the vendor default is forbidden — engine defaults differ " - + "(PostgreSQL READ COMMITTED vs MySQL InnoDB REPEATABLE READ)") - .allSatisfy( - definition -> - assertThat(definition.getIsolationLevel()) - .isNotEqualTo(TransactionDefinition.ISOLATION_DEFAULT) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED)); + .extracting(TransactionDefinition::getTimeout) + .containsExactly(7, 3, 30); + } + + @Test + @DisplayName("초 단위로 떨어지지 않는 제한 시간은 조립 때 거부한다") + void aTimeoutThatIsNotWholeSecondsIsRejected() { + // when + Throwable thrown = + catchThrowable( + () -> new SpringTransaction.Timeouts(Duration.ofMillis(1500), Duration.ofSeconds(5))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("write-timeout"); + } + + /** + * Review 09-05: READ COMMITTED is pinned on the pool ({@code HikariPoolConstraintValidator} + * refuses any other level), so naming it per transaction only buys a server round trip. + */ + @Test + @DisplayName("어느 모드도 트랜잭션마다 격리 수준을 지정하지 않는다 — 격리 수준은 풀이 고정한다") + void noModeNamesAnIsolationLevelSoNoBeginAsksTheServerForIt() { + // given + RecordingTransactionManager tm = new RecordingTransactionManager(); + SpringTransaction port = new SpringTransaction(tm); + + // when + port.inWrite(() -> null); + port.inRead(() -> null); + port.inNew(() -> null); + + // then + assertThat(tm.definitions) + .extracting(TransactionDefinition::getIsolationLevel) + .containsOnly(TransactionDefinition.ISOLATION_DEFAULT); } @Test @@ -331,6 +386,50 @@ class SpringTransactionTest { .isEqualTo(OperationalError.DB_UNIQUE_VIOLATION); } + // ---- review 04-05: a lost @Version race is a conflict the client resolves, not a server error + // ---- + + @Test + @DisplayName("커밋 시점 @Version 충돌은 500이 아니라 DB_OPTIMISTIC_CONFLICT로 알린다") + void versionConflictAtCommitIsReportedAsOptimisticConflict() { + // given + RecordingTransactionManager tm = new RecordingTransactionManager(); + tm.commitFailure = new ObjectOptimisticLockingFailureException("WorkLog", "a-work-log-id"); + SpringTransaction port = new SpringTransaction(tm); + + // when + Throwable thrown = catchThrowable(() -> port.inWrite(() -> "written")); + + // then + assertThat(thrown).isInstanceOf(PersistenceFailureException.class); + assertThat(((PersistenceFailureException) thrown).errorCode()) + .isEqualTo(OperationalError.DB_OPTIMISTIC_CONFLICT); + assertThat(thrown).hasCauseInstanceOf(ObjectOptimisticLockingFailureException.class); + } + + @Test + @DisplayName("본문 안 flush에서 난 @Version 충돌도 DB_OPTIMISTIC_CONFLICT로 알린다") + void versionConflictInsideTheActionIsReportedAsOptimisticConflict() { + // given + RecordingTransactionManager tm = new RecordingTransactionManager(); + SpringTransaction port = new SpringTransaction(tm); + + // when + Throwable thrown = + catchThrowable( + () -> + port.inWrite( + () -> { + throw new ObjectOptimisticLockingFailureException("WorkLog", "a-work-log-id"); + })); + + // then + assertThat(thrown).isInstanceOf(PersistenceFailureException.class); + assertThat(((PersistenceFailureException) thrown).errorCode()) + .isEqualTo(OperationalError.DB_OPTIMISTIC_CONFLICT); + assertThat(tm.rollbacks).isOne(); + } + private static IllegalStateException catchAndReturn(Runnable action) { try { action.run(); diff --git a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 index 31f20b17..e44b6dd0 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 +++ b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 @@ -12,6 +12,7 @@ 95be788589f01e32c9179acc80817e227e81805f8d518e8a9ac36e1c31b51da7 jpa/idempotency/V2__request_hash_varchar.sql 4379872989af0c97b937ff48527c788a2ba0216218d4df9435eba8c6e053ad8d jpa/notification-platform/V10__variables_payload_envelope_guard.sql fb1eee652330995e2f761dd0c0cb9ca137b1c50dd99253aa9958c3ec130cf74b jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql +a4c3b56e74bdeaa32be2e716e377aa920bc327b4517bf3d6c6c753cdbcf5c745 jpa/notification-platform/V12__notification_suppression_target_unique.sql 1ac7cc1c2509868eb0ce202e1917bb36846f98f17ad4922abe3fac0ef128199b jpa/notification-platform/V1__notification_platform_core.sql 0add67aa23580e51712f84fabe9b09e08401ef708cfa1b3292b120fdb5c12fa2 jpa/notification-platform/V2__notification_platform_contact_template_policy.sql f5b98598a59cc4376f5d233b410f8a5ae9f3cd94156291ebdf2d0da5a66f34ef jpa/notification-platform/V3__notification_platform_inbox_admin.sql @@ -31,6 +32,8 @@ c5f9c638c6d5b7768e803a23b3f16e9e0a5e09918c0838ed9c81cb6d9524ec9c jpa/notificati b8f571e6cada72a8f2776f4462509ce4b535c964c75b1c3cfb34b9dc07446d59 postgresql/V17__outbox_event_lease_fencing.sql 44cacbde7d1381ca5290fb8ec28005e8127ff6b453ff84277ec8d1b3293d76c8 postgresql/V18__outbox_event_unpublished_aggregate_order.sql a0306e5b0fbcaf43984d256362dc4244aec57a0ce5031e4f5263be3762fe1caf postgresql/V19__outbox_event_canonical_only.sql +c997fa20e10b68e0ca1b30cd7275018deaadc99bb0370b7b806332e9826e5217 postgresql/V20__outbox_event_deferred_attempt_count.sql +f830cda5a8cb72378c5af5d98810db61dc0dc36e416758c5da0de2ac34a68e27 postgresql/V21__outbox_aggregate_sequence.sql 8ab106731d4d04d3719da0692069947736dc490ca46aa5a3ea9bdf65a5d956dc postgresql/V1__idempotency_record.sql 6b62a01a4eeb792b81015b4810ecc6f3f021e0a17dea50c871493f7694d4f0b9 postgresql/V3__outbox_event.sql c57ab8a35a10079190ad8a563be58fae4147c9406c5bb752debb6998324ccdf6 postgresql/V4__int_lock.sql diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaVersionedBulkUpdateRule.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaVersionedBulkUpdateRule.java new file mode 100644 index 00000000..c235c135 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaVersionedBulkUpdateRule.java @@ -0,0 +1,182 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods; + +import com.tngtech.archunit.base.DescribedPredicate; +import com.tngtech.archunit.core.domain.JavaClass; +import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.domain.JavaMethod; +import com.tngtech.archunit.lang.ArchCondition; +import com.tngtech.archunit.lang.ArchRule; +import com.tngtech.archunit.lang.ConditionEvents; +import com.tngtech.archunit.lang.SimpleConditionEvent; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import jakarta.persistence.Version; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * A bulk update of a {@code @Version} entity advances the version in the statement. + * + *

      A JPQL or native {@code update} goes straight to the database, so Hibernate never increments + * the version column for it. A managed entity loaded before the statement then still holds the old + * version, and its later flush matches the row and succeeds — overwriting the bulk change with + * pre-update values while optimistic locking reports no conflict (review 04-07: the inbox + * mark-all-read and the delivery expiry pass did exactly this). The same shape as {@link + * JpaAuditMechanismRule#bulkUpdatesOfAuditedEntitiesStampAudit}: the versioned names are computed + * from the graph being checked and passed in. + */ +public final class JpaVersionedBulkUpdateRule { + + private static final String MODIFYING = "org.springframework.data.jpa.repository.Modifying"; + private static final String QUERY = "org.springframework.data.jpa.repository.Query"; + + /** Every {@code update } in a statement, including the one after a CTE. */ + private static final Pattern UPDATE_TARGET = Pattern.compile("\\bupdate\\s+([a-z_][a-z0-9_.]*)"); + + private JpaVersionedBulkUpdateRule() {} + + /** + * The JPQL entity names and table names of every {@code @Version} entity in {@code classes}, + * lower-cased, each mapped to the names its version is written under (the field and the column). + */ + public static Map> versionedTargets(JavaClasses classes) { + Map> targets = new LinkedHashMap<>(); + classes.stream() + .filter(type -> type.isAnnotatedWith(Entity.class)) + .forEach( + entity -> { + Set versionNames = versionNames(entity); + if (versionNames.isEmpty()) { + return; + } + Set names = new LinkedHashSet<>(); + names.add(entity.getSimpleName()); + entity.tryGetAnnotationOfType(Entity.class).map(Entity::name).ifPresent(names::add); + entity.tryGetAnnotationOfType(Table.class).map(Table::name).ifPresent(names::add); + names.stream() + .filter(name -> !name.isBlank()) + .map(name -> name.toLowerCase(Locale.ROOT)) + .forEach(name -> targets.put(name, versionNames)); + }); + return targets; + } + + /** + * The rule. + * + * @param versionedTargets {@link #versionedTargets} of the graph being checked + */ + public static ArchRule bulkUpdatesOfVersionedEntitiesAdvanceVersion( + Map> versionedTargets) { + Map> versioned = Map.copyOf(versionedTargets); + return methods() + .that( + new DescribedPredicate("are annotated with Spring Data @Modifying") { + @Override + public boolean test(JavaMethod method) { + return method.getAnnotations().stream() + .anyMatch(annotation -> MODIFYING.equals(annotation.getRawType().getName())); + } + }) + .should(new AdvancesVersion(versioned)) + .as("a bulk update of a @Version entity advances the version in the statement") + .because( + "Hibernate does not increment the version for a bulk statement, so an entity read" + + " before it flushes over the change without an optimistic-lock conflict") + .allowEmptyShould(true); + } + + /** + * The violation in one statement, when there is one. Exposed so both branches can be executed + * directly rather than only through whatever the production graph happens to contain. + * + * @param query the JPQL or native statement + * @param versionedTargets lower-cased entity and table names mapped to their version names + * @return the reason this statement violates the rule, or empty + */ + public static Optional versionBumpViolation( + String query, Map> versionedTargets) { + String normalized = query.toLowerCase(Locale.ROOT).replaceAll("\\s+", " "); + Matcher update = UPDATE_TARGET.matcher(normalized); + while (update.find()) { + String target = update.group(1); + Set versionNames = versionedTargets.get(target); + if (versionNames == null) { + continue; + } + int where = normalized.indexOf(" where ", update.end()); + String assignments = + where < 0 + ? normalized.substring(update.end()) + : normalized.substring(update.end(), where); + if (versionNames.stream().noneMatch(name -> bump(name).matcher(assignments).find())) { + return Optional.of( + "updates versioned '" + + target + + "' without " + + String.join(" or ", versionNames.stream().sorted().toList()) + + " = itself + 1"); + } + } + return Optional.empty(); + } + + /** {@code name = name + 1}, with or without an alias on either side. */ + private static Pattern bump(String name) { + String quoted = Pattern.quote(name); + return Pattern.compile( + "(? versionNames(JavaClass entity) { + Set names = new LinkedHashSet<>(); + entity.getAllFields().stream() + .filter(field -> field.isAnnotatedWith(Version.class)) + .forEach( + field -> { + names.add(field.getName().toLowerCase(Locale.ROOT)); + field + .tryGetAnnotationOfType(Column.class) + .map(Column::name) + .filter(name -> !name.isBlank()) + .ifPresent(name -> names.add(name.toLowerCase(Locale.ROOT))); + }); + return Set.copyOf(names); + } + + private static final class AdvancesVersion extends ArchCondition { + + private final Map> versionedTargets; + + AdvancesVersion(Map> versionedTargets) { + super("advance the version when the target entity is versioned"); + this.versionedTargets = versionedTargets; + } + + @Override + public void check(JavaMethod method, ConditionEvents events) { + method.getAnnotations().stream() + .filter(annotation -> QUERY.equals(annotation.getRawType().getName())) + .map(annotation -> annotation.get("value").orElse("")) + .map(Object::toString) + .forEach( + statement -> + versionBumpViolation(statement, versionedTargets) + .ifPresent( + reason -> + events.add( + SimpleConditionEvent.violated( + method, method.getFullName() + " " + reason)))); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/PostgreSqlVersion.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/PostgreSqlVersion.java index d0c44af9..164c5319 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/PostgreSqlVersion.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/PostgreSqlVersion.java @@ -14,20 +14,22 @@ import java.util.Optional; public enum PostgreSqlVersion { /** PostgreSQL 16 — the oldest Stable version. */ - PG_16(16, "postgres:16-alpine"), + PG_16(16, "postgres-16"), /** PostgreSQL 17. */ - PG_17(17, "postgres:17-alpine"), + PG_17(17, "postgres-17"), /** PostgreSQL 18 — the newest Stable version. */ - PG_18(18, "postgres:18-alpine"); + PG_18(18, "postgres-18"); private final int majorVersion; - private final String image; - PostgreSqlVersion(int majorVersion, String image) { + /** The key of this version's image in config/testing/container-images.properties. */ + private final String imageKey; + + PostgreSqlVersion(int majorVersion, String imageKey) { this.majorVersion = majorVersion; - this.image = image; + this.imageKey = imageKey; } /** The Stable matrix, oldest first. */ @@ -73,8 +75,24 @@ public enum PostgreSqlVersion { return majorVersion; } - /** The container image this version runs from. */ + /** The key of this version's image in config/testing/container-images.properties. */ + public String imageKey() { + return imageKey; + } + + /** + * The container image this version runs from, as the build hands it to every Test JVM from + * config/testing/container-images.properties. + */ public String image() { + String image = System.getProperty("ca.test.image." + imageKey); + if (image == null || image.isBlank()) { + throw new IllegalStateException( + "system property ca.test.image." + + imageKey + + " is not set; run the test through Gradle, which reads" + + " config/testing/container-images.properties"); + } return image; } } diff --git a/src/adapter/outbound/persistence-mongo/CLAUDE.md b/src/adapter/outbound/persistence-mongo/CLAUDE.md index 9416a9de..3534ef10 100644 --- a/src/adapter/outbound/persistence-mongo/CLAUDE.md +++ b/src/adapter/outbound/persistence-mongo/CLAUDE.md @@ -30,7 +30,13 @@ design package's assumed module layout onto this leaf lives in deployment supplies `MongoCredentialResolver`. The typed profile is not documentation-only: `MongoProfileClientSettingsAutoConfiguration` applies `MongoClientSettingsFactory` to Boot's actual `MongoClientSettings.Builder` at lowest precedence, so its TLS, Stable API, timeout and pool - policy overrides generic defaults. + policy overrides generic defaults. Without a typed profile (URI-only), + `MongoUriOnlyClientDefaults` applies finite socket/connect/server-selection timeouts and a pool + bound **before** Boot applies the connection string, so URI parameters still win; there is no + setting key of its own. +- Consumers: a service's own adapter leaf takes this leaf as `implementation`. The procedure is + `docs/mongodb/consumer-leaf-guide.md`; the worked example (document, mapper, repository, port + implementation) is the test-source package `…mongo.example`, run by `mongoStableContractTest`. - `MongoDefaultsEnvironmentPostProcessor`, registered through `META-INF/spring.factories`, loads `config/mongo.yml` at lowest precedence and, on an explicit `enabled=false`, appends Boot 4's Mongo auto-configurations (read from Boot's own registration files) to diff --git a/src/adapter/outbound/persistence-mongo/README.md b/src/adapter/outbound/persistence-mongo/README.md index f3184a6d..b2e8303a 100644 --- a/src/adapter/outbound/persistence-mongo/README.md +++ b/src/adapter/outbound/persistence-mongo/README.md @@ -49,6 +49,13 @@ app.persistence-mongo.platform.active-profile=standard-uri spring.mongodb.uri=${SPRING_MONGODB_URI} ``` +typed profile 없이 URI만 준 배포에도 driver 기본값(socket 읽기 무제한, server selection 30초, pool 100) +대신 유한 기본값이 적용된다: socket 읽기 30s, connect 5s, server selection 5s, pool 최대 40, pool 대기 +2s(`MongoUriOnlyClientDefaults`, 값과 이유는 그 클래스 주석). 이 값은 Boot가 connection string을 적용하기 +전에 들어가므로, URI에 `socketTimeoutMS`·`connectTimeoutMS`·`serverSelectionTimeoutMS`·`maxPoolSize`· +`waitQueueTimeoutMS`를 적으면 그 값이 이긴다. 별도 설정 키는 없다. typed profile이 있으면 profile 값이 +모두 덮어쓴다. + typed profile을 사용하는 배포는 `SPRING_MONGODB_URI` 대신 선택된 `app.persistence-mongo.platform.profiles..uri-secret`을 설정한다. `SecretSourcePort` bean이 있으면 그것으로 resolve하는 `MongoCredentialResolver`가 자동으로 등록되고, @@ -142,9 +149,14 @@ Mongo auto-configuration 이름을 Boot 자신의 등록 파일에서 읽어 배 bean으로 등록되지 않고 설정 키도 없다. 서비스의 Mongo 어댑터 leaf가 이 leaf를 `implementation`으로 받아 생성자로 만든다(AGENTS.md capability 규칙의 라이브러리형 예외). 테스트 열은 그 진입점을 검증하는 이 leaf의 테스트다. +소비 leaf를 만드는 절차(레지스트리 edge, Gradle 줄, collection profile 등록, 예외 변환, 정책을 우회하는 +경로)는 [`docs/mongodb/consumer-leaf-guide.md`](../../../../docs/mongodb/consumer-leaf-guide.md)에 있다. +document·mapper·repository·port 구현 한 벌의 동작 예시는 테스트 소스의 +`dev.caskeleton.adapter.outbound.mongo.example` 패키지에 있고 `mongoStableContractTest`에서 돈다. + | 패키지 | 진입점 | 테스트 | |---|---|---| -| `transaction` | `MongoTransactionRetryCoordinator`, `MongoTransactionScope`, `SpringMongoTransactionSessionFactory` | `MongoTransactionRetryCoordinatorTest`, `CleanupFailureIsReportedTest`, `MongoTransactionScopeTest`, `MongoSessionAcquisitionTest` | +| `transaction` | `MongoTransactionRetryCoordinator`, `MongoTransactionScope`, `SpringMongoTransactionSessionFactory` | `MongoTransactionRetryCoordinatorTest`, `MongoTransactionBodyTranslatedFailureTest`, `CleanupFailureIsReportedTest`, `MongoTransactionScopeTest`, `MongoSessionAcquisitionTest`, `mongoReplicaSetTest` lane(`MongoTransactionWriteConflictLaneTest`) | | `transaction.session` | `SpringMongoCausalSessionExecutor` | `MongoCausalSessionExecutorTest` | | `imperative.revision` | `VersionedMongoUpdater` | `VersionedMongoUpdaterTest` | | `query` | `PolicyAwareMongoQueryBuilder`, `MongoQueryPolicy` | `PolicyAwareMongoQueryBuilderTest`, `LiteralSearchIsExpressibleTest` | diff --git a/src/adapter/outbound/persistence-mongo/build.gradle b/src/adapter/outbound/persistence-mongo/build.gradle index 24aa7e4b..f5d0cef9 100644 --- a/src/adapter/outbound/persistence-mongo/build.gradle +++ b/src/adapter/outbound/persistence-mongo/build.gradle @@ -158,11 +158,11 @@ strictTestLanes { description = 'Single-node replica set contract lane: mapping, atomic write, transaction ' + '(design §29).' systemProperty 'mongodb.primary.image', - providers.gradleProperty('mongoPrimaryImage').orElse('mongo:8.0.16').get() + providers.gradleProperty('mongoPrimaryImage').orElse(testContainerImages['mongo-8']).get() systemProperty 'mongodb.compatibility.image', - providers.gradleProperty('mongoCompatibilityImage').orElse('mongo:7.0.28').get() + providers.gradleProperty('mongoCompatibilityImage').orElse(testContainerImages['mongo-7']).get() systemProperty 'mongodb.toxiproxy.image', - providers.gradleProperty('mongoToxiproxyImage').orElse('ghcr.io/shopify/toxiproxy:2.12.0').get() + providers.gradleProperty('mongoToxiproxyImage').orElse(testContainerImages['toxiproxy']).get() } lane('mongoFailoverTest') { integration() @@ -171,11 +171,11 @@ strictTestLanes { description = 'Three-node replica set failover lane: primary kill, partition, unknown ' + 'commit, resume (design §29).' systemProperty 'mongodb.primary.image', - providers.gradleProperty('mongoPrimaryImage').orElse('mongo:8.0.16').get() + providers.gradleProperty('mongoPrimaryImage').orElse(testContainerImages['mongo-8']).get() systemProperty 'mongodb.compatibility.image', - providers.gradleProperty('mongoCompatibilityImage').orElse('mongo:7.0.28').get() + providers.gradleProperty('mongoCompatibilityImage').orElse(testContainerImages['mongo-7']).get() systemProperty 'mongodb.toxiproxy.image', - providers.gradleProperty('mongoToxiproxyImage').orElse('ghcr.io/shopify/toxiproxy:2.12.0').get() + providers.gradleProperty('mongoToxiproxyImage').orElse(testContainerImages['toxiproxy']).get() } lane('mongoMigrationTest') { integration() @@ -184,11 +184,11 @@ strictTestLanes { description = 'Migration lane: empty / N-1 / oldest-supported snapshots, lock, checkpoint ' + 'restart (design §12).' systemProperty 'mongodb.primary.image', - providers.gradleProperty('mongoPrimaryImage').orElse('mongo:8.0.16').get() + providers.gradleProperty('mongoPrimaryImage').orElse(testContainerImages['mongo-8']).get() systemProperty 'mongodb.compatibility.image', - providers.gradleProperty('mongoCompatibilityImage').orElse('mongo:7.0.28').get() + providers.gradleProperty('mongoCompatibilityImage').orElse(testContainerImages['mongo-7']).get() systemProperty 'mongodb.toxiproxy.image', - providers.gradleProperty('mongoToxiproxyImage').orElse('ghcr.io/shopify/toxiproxy:2.12.0').get() + providers.gradleProperty('mongoToxiproxyImage').orElse(testContainerImages['toxiproxy']).get() } lane('mongoCompatibilityTest') { integration() @@ -196,11 +196,11 @@ strictTestLanes { tag = 'mongodb-compatibility' description = 'MongoDB 7.0 compatibility and 8.0 primary certification matrix (design §30).' systemProperty 'mongodb.primary.image', - providers.gradleProperty('mongoPrimaryImage').orElse('mongo:8.0.16').get() + providers.gradleProperty('mongoPrimaryImage').orElse(testContainerImages['mongo-8']).get() systemProperty 'mongodb.compatibility.image', - providers.gradleProperty('mongoCompatibilityImage').orElse('mongo:7.0.28').get() + providers.gradleProperty('mongoCompatibilityImage').orElse(testContainerImages['mongo-7']).get() systemProperty 'mongodb.toxiproxy.image', - providers.gradleProperty('mongoToxiproxyImage').orElse('ghcr.io/shopify/toxiproxy:2.12.0').get() + providers.gradleProperty('mongoToxiproxyImage').orElse(testContainerImages['toxiproxy']).get() } lane('mongoSecurityIntegrationTest') { integration() @@ -209,11 +209,11 @@ strictTestLanes { description = 'RBAC, TLS, injection and redaction release gate against a real server ' + '(design §26).' systemProperty 'mongodb.primary.image', - providers.gradleProperty('mongoPrimaryImage').orElse('mongo:8.0.16').get() + providers.gradleProperty('mongoPrimaryImage').orElse(testContainerImages['mongo-8']).get() systemProperty 'mongodb.compatibility.image', - providers.gradleProperty('mongoCompatibilityImage').orElse('mongo:7.0.28').get() + providers.gradleProperty('mongoCompatibilityImage').orElse(testContainerImages['mongo-7']).get() systemProperty 'mongodb.toxiproxy.image', - providers.gradleProperty('mongoToxiproxyImage').orElse('ghcr.io/shopify/toxiproxy:2.12.0').get() + providers.gradleProperty('mongoToxiproxyImage').orElse(testContainerImages['toxiproxy']).get() } lane('mongoStableContractTest') { @@ -231,11 +231,11 @@ strictTestLanes { description = 'Certifies contention, aggregation spill, pagination and pool resource ' + 'bounds (design §29).' systemProperty 'mongodb.primary.image', - providers.gradleProperty('mongoPrimaryImage').orElse('mongo:8.0.16').get() + providers.gradleProperty('mongoPrimaryImage').orElse(testContainerImages['mongo-8']).get() systemProperty 'mongodb.compatibility.image', - providers.gradleProperty('mongoCompatibilityImage').orElse('mongo:7.0.28').get() + providers.gradleProperty('mongoCompatibilityImage').orElse(testContainerImages['mongo-7']).get() systemProperty 'mongodb.toxiproxy.image', - providers.gradleProperty('mongoToxiproxyImage').orElse('ghcr.io/shopify/toxiproxy:2.12.0').get() + providers.gradleProperty('mongoToxiproxyImage').orElse(testContainerImages['toxiproxy']).get() // Assertions on by default: a performance gate without bounds is only a report. systemProperty 'performance.assertions.enabled', providers.gradleProperty('performance.assertions.enabled').orElse('true').get() @@ -288,3 +288,10 @@ apiSurface { 'root yet.', ] } + +// MongoModuleBoundaryTest lists the package directories under src/main/java; a directory is not a +// class, so the listing is declared, or a cached lane misses a new top-level package (review +// 2026-11-01 08-02). +tasks.withType(Test).configureEach { + inputs.dir('src/main/java').withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('mainSourceTree') +} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java index d7c94a9d..8b718792 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java @@ -58,6 +58,20 @@ class MongoProfileClientSettingsAutoConfiguration { return MongoCredentialResolver.fromSecretSource(secretSource::resolve); } + /** + * Finite timeouts and a pool bound for the URI-only path (review 04-12). + * + *

      Ordered first, so Boot's standard customizer — which applies the connection string at order + * 0 — overrides any value the URI states, and the typed-profile customizer, ordered last, + * overrides all of them when a profile exists. See {@link MongoUriOnlyClientDefaults}. + */ + @Bean("mongoUriOnlyClientDefaultsCustomizer") + @ConditionalOnMissingBean(name = "mongoUriOnlyClientDefaultsCustomizer") + MongoClientSettingsBuilderCustomizer mongoUriOnlyClientDefaultsCustomizer( + MongoPlatformSettings settings) { + return new UriOnlyDefaultsCustomizer(settings); + } + @Bean("mongoProfileClientSettingsCustomizer") @ConditionalOnMissingBean(name = "mongoProfileClientSettingsCustomizer") MongoClientSettingsBuilderCustomizer mongoProfileClientSettingsCustomizer( @@ -65,6 +79,27 @@ class MongoProfileClientSettingsAutoConfiguration { return new OrderedProfileCustomizer(settings, credentialResolvers); } + private static final class UriOnlyDefaultsCustomizer + implements MongoClientSettingsBuilderCustomizer, Ordered { + private final MongoPlatformSettings settings; + + private UriOnlyDefaultsCustomizer(MongoPlatformSettings settings) { + this.settings = Objects.requireNonNull(settings, "settings"); + } + + @Override + public void customize(MongoClientSettings.Builder builder) { + if (settings.profiles().isEmpty()) { + MongoUriOnlyClientDefaults.applyTo(builder); + } + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + } + private static final class OrderedProfileCustomizer implements MongoClientSettingsBuilderCustomizer, Ordered { private final MongoPlatformSettings settings; diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoUriOnlyClientDefaults.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoUriOnlyClientDefaults.java new file mode 100644 index 00000000..2541c6cf --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoUriOnlyClientDefaults.java @@ -0,0 +1,64 @@ +package dev.caskeleton.adapter.outbound.mongo.client; + +import com.mongodb.MongoClientSettings; +import java.time.Duration; +import java.util.concurrent.TimeUnit; + +/** + * Finite driver bounds for a deployment that gives only {@code spring.mongodb.uri}. + * + *

      Without a typed profile the profile customizer steps aside, and the driver's own defaults used + * to apply: a socket read that waits forever, 30 seconds of server selection and a pool of 100 per + * instance (review 04-12). A request thread then hangs as long as the server does, and a fleet of + * instances can open more connections than the server is sized for. + * + *

      These values are applied before Boot's standard customizer applies the connection + * string, so anything the URI states — {@code socketTimeoutMS}, {@code connectTimeoutMS}, {@code + * serverSelectionTimeoutMS}, {@code maxPoolSize}, {@code waitQueueTimeoutMS} — still wins. That is + * the override, and why no setting key of its own exists: the URI already has one per value. A + * typed profile replaces all of them (its customizer runs last), so this only shapes the URI-only + * path. + * + *

      The values, and why: + * + *

        + *
      • socket read 30 s — long enough for an ordinary query or aggregation on a healthy server, + * finite so a dead peer frees the thread. A workload with longer reads states it in the URI. + *
      • connect 5 s and server selection 5 s — a primary that cannot be reached in 5 seconds is an + * outage, and failing fast lets the caller's own timeout and retry policy act; the driver's + * 30 seconds outlasts most HTTP request timeouts. + *
      • pool 40, wait 2 s — the same bound the README's production profile example uses; a request + * that cannot get a connection in 2 seconds is better refused than queued. + *
      + */ +final class MongoUriOnlyClientDefaults { + + static final Duration SOCKET_READ_TIMEOUT = Duration.ofSeconds(30); + + static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(5); + + static final Duration SERVER_SELECTION_TIMEOUT = Duration.ofSeconds(5); + + static final int POOL_MAX_SIZE = 40; + + static final Duration POOL_MAX_WAIT_TIME = Duration.ofSeconds(2); + + private MongoUriOnlyClientDefaults() {} + + static void applyTo(MongoClientSettings.Builder builder) { + builder + .applyToSocketSettings( + socket -> + socket + .readTimeout(SOCKET_READ_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS) + .connectTimeout(CONNECT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) + .applyToClusterSettings( + cluster -> + cluster.serverSelectionTimeout( + SERVER_SELECTION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) + .applyToConnectionPoolSettings( + pool -> + pool.maxSize(POOL_MAX_SIZE) + .maxWaitTime(POOL_MAX_WAIT_TIME.toMillis(), TimeUnit.MILLISECONDS)); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringMongoTransactionSessionFactory.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringMongoTransactionSessionFactory.java index 92bda406..ad8ac5d0 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringMongoTransactionSessionFactory.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringMongoTransactionSessionFactory.java @@ -138,8 +138,17 @@ public final class SpringMongoTransactionSessionFactory implements MongoTransact MongoTransactionScope.Registration registration = MongoTransactionScope.bind(sessionBound); try { return body.apply(sessionBound); - } catch (MongoException driverFailure) { - throw translate(driverFailure, MongoFailurePhase.TRANSACTION_BODY); + } catch (RuntimeException bodyFailure) { + // The body works through a MongoTemplate, and MongoTemplate translates driver failures into + // Spring's DataAccessException before they leave it. Catching only MongoException let a + // translated WriteConflict past the classifier, so the TransientTransactionError label + // under it never reached the coordinator's body-replay branch (review 04-11). The driver + // failure is looked for down the cause chain; a failure with none is the caller's own and + // leaves unchanged. + if (MongoFailureExtractor.driverFailureIn(bodyFailure).isEmpty()) { + throw bodyFailure; + } + throw translate(bodyFailure, MongoFailurePhase.TRANSACTION_BODY); } finally { registration.close(); } diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/retry/MongoTransactionRetryCoordinator.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/retry/MongoTransactionRetryCoordinator.java index 028037fa..41090b69 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/retry/MongoTransactionRetryCoordinator.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/retry/MongoTransactionRetryCoordinator.java @@ -147,7 +147,13 @@ public final class MongoTransactionRetryCoordinator implements MongoTransactionE for (int commitAttempt = 1; budget.allowsAttempt(commitAttempt, elapsedSince(startedAt)); commitAttempt++) { - sleep(budget.delayBefore(commitAttempt, random)); + if (!sleepBeforeCommit(budget.delayBefore(commitAttempt, random))) { + // Interrupted while waiting to retry a commit whose outcome is already unknown. Reporting + // that as a plain IllegalStateException dropped the one fact the caller needs: the + // transaction may have committed, so it must be reconciled, not replayed. + decisionRecorder.accept(MongoRetryDecision.reconcile("commit retry interrupted")); + throw commitUnknown(lastUnknown); + } try { session.commit(); return value; @@ -175,6 +181,24 @@ public final class MongoTransactionRetryCoordinator implements MongoTransactionE return Duration.ofNanos(System.nanoTime() - startedAtNanos); } + /** + * Waits before a commit attempt. Returns false, with the interrupt status kept, when the wait was + * interrupted — the caller decides what an interrupted commit retry means, because only it knows + * that the commit outcome is already unknown. + */ + private static boolean sleepBeforeCommit(Duration delay) { + if (delay.isZero() || delay.isNegative()) { + return true; + } + try { + Thread.sleep(delay.toMillis()); + return true; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return false; + } + } + private static void sleep(Duration delay) { if (delay.isZero() || delay.isNegative()) { return; diff --git a/src/adapter/outbound/persistence-mongo/src/main/resources/config/mongo.yml b/src/adapter/outbound/persistence-mongo/src/main/resources/config/mongo.yml index e3a8272e..47dfe836 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/resources/config/mongo.yml +++ b/src/adapter/outbound/persistence-mongo/src/main/resources/config/mongo.yml @@ -8,9 +8,13 @@ app: # true | false — 모듈이 있으면 켜진다. false 로 끄면 Spring Boot 의 Mongo 자동 설정도 함께 빠진다. enabled: ${APP_PERSISTENCE_MONGO_ENABLED:true} platform: - # 켠 상태에서 비어 있으면 안 된다. profile 은 정확히 하나: client 하나와 pool 하나만 만들고, - # 고르지 않은 profile 의 secret 은 해석하지 않는다. 기동 검사와 readiness 도 이 profile 만 - # 관측한 topology 와 비교한다. + # platform.profiles 를 선언했을 때만 필수다(MongoPlatformSettings.validate). 그때 profile 은 + # 정확히 하나: client 하나와 pool 하나만 만들고, 고르지 않은 profile 의 secret 은 해석하지 + # 않는다. 기동 검사와 readiness 도 이 profile 만 관측한 topology 와 비교한다. + # profile 없이 URI 만 준 배포는 비워 두고, 대신 유한 기본값(socket 읽기 30s, connect 5s, + # server selection 5s, pool 40, pool 대기 2s — MongoUriOnlyClientDefaults)이 적용된다. + # 바꾸려면 URI 에 socketTimeoutMS / connectTimeoutMS / serverSelectionTimeoutMS / + # maxPoolSize / waitQueueTimeoutMS 를 적는다. URI 값이 기본값보다 우선한다. active-profile: ${APP_PERSISTENCE_MONGO_ACTIVE_PROFILE:} # 연결 source 도 명시해야 한다. 표준 배포는 SPRING_MONGODB_URI(Boot 4 -> spring.mongodb.uri)를 # 준다. typed-profile 배포는 대신 diff --git a/src/adapter/outbound/persistence-mongo/src/mongoIntegrationTest/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionWriteConflictLaneTest.java b/src/adapter/outbound/persistence-mongo/src/mongoIntegrationTest/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionWriteConflictLaneTest.java new file mode 100644 index 00000000..f28a6b8f --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/mongoIntegrationTest/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionWriteConflictLaneTest.java @@ -0,0 +1,126 @@ +package dev.caskeleton.adapter.outbound.mongo.transaction; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.mongodb.client.ClientSession; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.Updates; +import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyRegistry; +import dev.caskeleton.adapter.outbound.mongo.testkit.rs.MongoReplicaSetFixture; +import dev.caskeleton.adapter.outbound.mongo.testkit.rs.MongoSingleReplicaSetContainer; +import dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoTransactionRetryCoordinator; +import java.util.concurrent.atomic.AtomicInteger; +import org.bson.Document; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; + +/** + * A real WriteConflict, raised by a real server, reaches the transaction body through {@code + * MongoTemplate} — that is, translated into Spring's exception hierarchy — and is still replayed. + * + *

      The unit test proves the classification on a hand-built exception. This one proves the shape + * the server and Spring Data actually produce: the label sits on a driver exception that Spring has + * wrapped, and that is the shape the coordinator previously never saw (review 04-11). + */ +@Tag("mongodb-replicaset") +class MongoTransactionWriteConflictLaneTest { + + private static MongoSingleReplicaSetContainer mongo; + + private static MongoClient client; + + private static MongoTemplate template; + + private static MongoCollection accounts; + + @BeforeAll + static void start() { + mongo = MongoSingleReplicaSetContainer.mongoEight(); + mongo.start(); + client = MongoClients.create(mongo.connectionString()); + String database = + MongoReplicaSetFixture.forTest(mongo, MongoTransactionWriteConflictLaneTest.class) + .databaseName(); + template = new MongoTemplate(new SimpleMongoClientDatabaseFactory(client, database)); + accounts = client.getDatabase(database).getCollection("accounts"); + // Collections cannot be created implicitly inside a transaction on every supported version. + accounts.insertOne(new Document("_id", "acct-1").append("balance", 0)); + } + + @AfterAll + static void stop() { + if (client != null) { + client.close(); + } + if (mongo != null) { + mongo.close(); + } + } + + @Test + @DisplayName("다른 트랜잭션과 쓰기가 충돌하면 본문을 새 세션에서 한 번 더 실행하고 커밋한다") + void aWriteConflictInTheBodyReplaysTheBodyAndCommits() { + // given + MongoTransactionRetryCoordinator coordinator = + MongoTransactionRetryCoordinator.standard( + new SpringMongoTransactionSessionFactory(template, MongoConsistencyRegistry.standard()), + "account.credit"); + AtomicInteger bodyCalls = new AtomicInteger(); + + // when + String result = + coordinator.execute( + MongoTransactionProfile.majority(), + operations -> { + if (bodyCalls.incrementAndGet() == 1) { + creditWhileAnotherTransactionHoldsTheDocument(operations); + } else { + credit(operations); + } + return "credited"; + }); + + // then + assertThat(result).isEqualTo("credited"); + assertThat(bodyCalls).as("the conflicting attempt and the replay").hasValue(2); + assertThat(accounts.find(Filters.eq("_id", "acct-1")).first().getInteger("balance")) + .as("the interfering credit and the replayed credit, and no other") + .isEqualTo(110); + } + + /** + * Opens a second transaction that writes the same document and keeps it open while the body + * writes, which is what makes the server answer WriteConflict with TransientTransactionError. The + * interfering transaction commits whatever the body's outcome, so the replay sees its write. + */ + private static void creditWhileAnotherTransactionHoldsTheDocument( + org.springframework.data.mongodb.core.MongoOperations operations) { + try (ClientSession interfering = client.startSession()) { + interfering.startTransaction(); + accounts.updateOne(interfering, Filters.eq("_id", "acct-1"), Updates.inc("balance", 100)); + try { + credit(operations); + } finally { + interfering.commitTransaction(); + } + } + } + + private static void credit(org.springframework.data.mongodb.core.MongoOperations operations) { + operations.updateFirst( + Query.query(Criteria.where("_id").is("acct-1")), + new Update().inc("balance", 10), + "accounts"); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/MongoProxiedReplicaSetNode.java b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/MongoProxiedReplicaSetNode.java index b6d323c6..ec17619f 100644 --- a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/MongoProxiedReplicaSetNode.java +++ b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/MongoProxiedReplicaSetNode.java @@ -48,7 +48,9 @@ public final class MongoProxiedReplicaSetNode implements AutoCloseable { /** A proxied node on the MongoDB 8.0 primary lane. */ public static MongoProxiedReplicaSetNode startMongoEight() { MongoProxiedReplicaSetNode node = - new MongoProxiedReplicaSetNode(System.getProperty("mongodb.primary.image", "mongo:8.0.16")); + new MongoProxiedReplicaSetNode( + System.getProperty( + "mongodb.primary.image", System.getProperty("ca.test.image.mongo-8"))); node.start(); return node; } diff --git a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/MongoThreeNodeReplicaSet.java b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/MongoThreeNodeReplicaSet.java index 77b587ce..0cb01d11 100644 --- a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/MongoThreeNodeReplicaSet.java +++ b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/MongoThreeNodeReplicaSet.java @@ -64,7 +64,9 @@ public final class MongoThreeNodeReplicaSet implements AutoCloseable, MongoPrima /** A three-node set on the MongoDB 8.0 primary lane. */ public static MongoThreeNodeReplicaSet startMongoEight() { MongoThreeNodeReplicaSet replicaSet = - new MongoThreeNodeReplicaSet(System.getProperty("mongodb.primary.image", "mongo:8.0.16")); + new MongoThreeNodeReplicaSet( + System.getProperty( + "mongodb.primary.image", System.getProperty("ca.test.image.mongo-8"))); replicaSet.start(); return replicaSet; } diff --git a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/ToxiproxyMongoNetworkFaultController.java b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/ToxiproxyMongoNetworkFaultController.java index 5fa768ac..cc3927ce 100644 --- a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/ToxiproxyMongoNetworkFaultController.java +++ b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/failover/ToxiproxyMongoNetworkFaultController.java @@ -28,7 +28,8 @@ import org.testcontainers.utility.DockerImageName; public final class ToxiproxyMongoNetworkFaultController implements MongoNetworkFaultController, AutoCloseable { - private static final String DEFAULT_TOXIPROXY_IMAGE = "ghcr.io/shopify/toxiproxy:2.12.0"; + private static final String DEFAULT_TOXIPROXY_IMAGE = + System.getProperty("ca.test.image.toxiproxy"); private static final int MONGO_PORT = 27017; diff --git a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoAuthenticatedReplicaSetContainer.java b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoAuthenticatedReplicaSetContainer.java index ea2e9f9b..bb8085e8 100644 --- a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoAuthenticatedReplicaSetContainer.java +++ b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoAuthenticatedReplicaSetContainer.java @@ -71,7 +71,9 @@ public final class MongoAuthenticatedReplicaSetContainer implements AutoCloseabl /** An authenticated single-node set on the MongoDB 8.0 primary lane. */ public static MongoAuthenticatedReplicaSetContainer mongoEight() { return new MongoAuthenticatedReplicaSetContainer( - System.getProperty(MongoSingleReplicaSetContainer.PRIMARY_IMAGE_PROPERTY, "mongo:8.0.16")); + System.getProperty( + MongoSingleReplicaSetContainer.PRIMARY_IMAGE_PROPERTY, + System.getProperty("ca.test.image.mongo-8"))); } /** Starts the node, initiates the set, and creates the bootstrap superuser. */ diff --git a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoSingleReplicaSetContainer.java b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoSingleReplicaSetContainer.java index 6d3e3230..f8c7474c 100644 --- a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoSingleReplicaSetContainer.java +++ b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoSingleReplicaSetContainer.java @@ -38,13 +38,14 @@ public final class MongoSingleReplicaSetContainer implements AutoCloseable { /** The MongoDB 8.0 primary certification lane. */ public static MongoSingleReplicaSetContainer mongoEight() { return new MongoSingleReplicaSetContainer( - System.getProperty(PRIMARY_IMAGE_PROPERTY, "mongo:8.0.16")); + System.getProperty(PRIMARY_IMAGE_PROPERTY, System.getProperty("ca.test.image.mongo-8"))); } /** The MongoDB 7.0 compatibility lane. */ public static MongoSingleReplicaSetContainer mongoSeven() { return new MongoSingleReplicaSetContainer( - System.getProperty(COMPATIBILITY_IMAGE_PROPERTY, "mongo:7.0.28")); + System.getProperty( + COMPATIBILITY_IMAGE_PROPERTY, System.getProperty("ca.test.image.mongo-7"))); } /** An explicitly pinned image. */ diff --git a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoTlsReplicaSetContainer.java b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoTlsReplicaSetContainer.java index ccbbee2f..37e99983 100644 --- a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoTlsReplicaSetContainer.java +++ b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/rs/MongoTlsReplicaSetContainer.java @@ -89,7 +89,8 @@ public final class MongoTlsReplicaSetContainer implements AutoCloseable { private static String image() { return System.getProperty( - MongoSingleReplicaSetContainer.PRIMARY_IMAGE_PROPERTY, "mongo:8.0.16"); + MongoSingleReplicaSetContainer.PRIMARY_IMAGE_PROPERTY, + System.getProperty("ca.test.image.mongo-8")); } /** diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java index f13360a1..d7c83a7d 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java @@ -27,6 +27,12 @@ class MongoProfileClientSettingsAutoConfigurationTest { private static final String ACTIVE = "primary"; private static final String URI = "mongodb://mongo:27017/app?replicaSet=rs0"; + /** + * Looked up by name: the configuration also registers the URI-only defaults customizer, so the + * type alone no longer names one bean. + */ + private static final String PROFILE_CUSTOMIZER = "mongoProfileClientSettingsCustomizer"; + @Test void typedProfileCustomizerReachesTheBootDriverBuilder() { MongoProfileProperties profile = MongoProfileProperties.production("secret://mongodb/primary"); @@ -40,10 +46,12 @@ class MongoProfileClientSettingsAutoConfigurationTest { .withPropertyValues("app.persistence-mongo.enabled=true") .run( context -> { - assertThat(context).hasSingleBean(MongoClientSettingsBuilderCustomizer.class); + assertThat(context).hasBean(PROFILE_CUSTOMIZER); MongoClientSettings.Builder builder = MongoClientSettings.builder(); - context.getBean(MongoClientSettingsBuilderCustomizer.class).customize(builder); + context + .getBean(PROFILE_CUSTOMIZER, MongoClientSettingsBuilderCustomizer.class) + .customize(builder); MongoClientSettings settings = builder.build(); assertThat(settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) @@ -77,7 +85,8 @@ class MongoProfileClientSettingsAutoConfigurationTest { assertThatThrownBy( () -> context - .getBean(MongoClientSettingsBuilderCustomizer.class) + .getBean( + PROFILE_CUSTOMIZER, MongoClientSettingsBuilderCustomizer.class) .customize(MongoClientSettings.builder())) .hasMessageContaining("primry") .hasMessageContaining("not configured")); @@ -127,7 +136,9 @@ class MongoProfileClientSettingsAutoConfigurationTest { .run( context -> { MongoClientSettings.Builder builder = MongoClientSettings.builder(); - context.getBean(MongoClientSettingsBuilderCustomizer.class).customize(builder); + context + .getBean(PROFILE_CUSTOMIZER, MongoClientSettingsBuilderCustomizer.class) + .customize(builder); assertThat(builder.build().getServerApi()).isNull(); }); } @@ -147,7 +158,8 @@ class MongoProfileClientSettingsAutoConfigurationTest { assertThatThrownBy( () -> context - .getBean(MongoClientSettingsBuilderCustomizer.class) + .getBean( + PROFILE_CUSTOMIZER, MongoClientSettingsBuilderCustomizer.class) .customize(MongoClientSettings.builder())) .hasMessageContaining("MongoCredentialResolver")); } @@ -174,7 +186,9 @@ class MongoProfileClientSettingsAutoConfigurationTest { .run( context -> { // when - context.getBean(MongoClientSettingsBuilderCustomizer.class).customize(builder); + context + .getBean(PROFILE_CUSTOMIZER, MongoClientSettingsBuilderCustomizer.class) + .customize(builder); // then assertThat(builder.build().getClusterSettings().getHosts()) diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoUriOnlyClientDefaultsTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoUriOnlyClientDefaultsTest.java new file mode 100644 index 00000000..628f6e19 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoUriOnlyClientDefaultsTest.java @@ -0,0 +1,97 @@ +package dev.caskeleton.adapter.outbound.mongo.client; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; +import dev.caskeleton.adapter.outbound.mongo.autoconfigure.MongoPlatformSettings; +import java.util.concurrent.TimeUnit; +import org.bson.UuidRepresentation; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.mongodb.autoconfigure.MongoClientSettingsBuilderCustomizer; +import org.springframework.boot.mongodb.autoconfigure.StandardMongoClientSettingsBuilderCustomizer; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.ApplicationContext; + +/** + * A deployment that gives only {@code spring.mongodb.uri} has no typed profile, and the profile + * customizer steps aside. What remained were the driver's own defaults: no socket read timeout at + * all, 30 seconds of server selection and a pool of 100 (review 04-12). These tests assemble the + * customizers the way Boot's client factory does — every bean, in order, with Boot's standard + * connection-string customizer among them — and read what the driver would be built with. + */ +class MongoUriOnlyClientDefaultsTest { + + private static final String URI = "mongodb://mongo:27017/app?replicaSet=rs0"; + + @Test + @DisplayName("URI만 준 기동에서도 socket 읽기와 server selection timeout이 유한하고 pool에 상한이 있다") + void aUriOnlyDeploymentGetsFiniteTimeoutsAndABoundedPool() { + runner(URI) + .run( + context -> { + // when + MongoClientSettings settings = settingsBuiltBy(context); + + // then + assertThat(settings.getSocketSettings().getReadTimeout(TimeUnit.MILLISECONDS)) + .as("0 means a read waits forever") + .isEqualTo(MongoUriOnlyClientDefaults.SOCKET_READ_TIMEOUT.toMillis()); + assertThat(settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) + .isEqualTo(MongoUriOnlyClientDefaults.CONNECT_TIMEOUT.toMillis()); + assertThat( + settings + .getClusterSettings() + .getServerSelectionTimeout(TimeUnit.MILLISECONDS)) + .isEqualTo(MongoUriOnlyClientDefaults.SERVER_SELECTION_TIMEOUT.toMillis()); + assertThat(settings.getConnectionPoolSettings().getMaxSize()) + .isEqualTo(MongoUriOnlyClientDefaults.POOL_MAX_SIZE); + assertThat(settings.getConnectionPoolSettings().getMaxWaitTime(TimeUnit.MILLISECONDS)) + .isEqualTo(MongoUriOnlyClientDefaults.POOL_MAX_WAIT_TIME.toMillis()); + }); + } + + @Test + @DisplayName("URI에 적은 timeout과 pool 값은 기본값보다 우선한다") + void valuesWrittenInTheUriOutrankTheDefaults() { + runner(URI + "&socketTimeoutMS=1234&serverSelectionTimeoutMS=2345&maxPoolSize=7") + .run( + context -> { + // when + MongoClientSettings settings = settingsBuiltBy(context); + + // then + assertThat(settings.getSocketSettings().getReadTimeout(TimeUnit.MILLISECONDS)) + .isEqualTo(1234); + assertThat( + settings + .getClusterSettings() + .getServerSelectionTimeout(TimeUnit.MILLISECONDS)) + .isEqualTo(2345); + assertThat(settings.getConnectionPoolSettings().getMaxSize()).isEqualTo(7); + }); + } + + private static ApplicationContextRunner runner(String uri) { + return new ApplicationContextRunner() + .withUserConfiguration(MongoProfileClientSettingsAutoConfiguration.class) + .withBean(MongoPlatformSettings.class, MongoPlatformSettings::empty) + .withBean( + StandardMongoClientSettingsBuilderCustomizer.class, + () -> + new StandardMongoClientSettingsBuilderCustomizer( + () -> new ConnectionString(uri), UuidRepresentation.STANDARD)) + .withPropertyValues("app.persistence-mongo.enabled=true"); + } + + /** What Boot's client factory does: every customizer, in order, on one builder. */ + private static MongoClientSettings settingsBuiltBy(ApplicationContext context) { + MongoClientSettings.Builder builder = MongoClientSettings.builder(); + context + .getBeanProvider(MongoClientSettingsBuilderCustomizer.class) + .orderedStream() + .forEach(customizer -> customizer.customize(builder)); + return builder.build(); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/MongoNoteStore.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/MongoNoteStore.java new file mode 100644 index 00000000..d189d922 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/MongoNoteStore.java @@ -0,0 +1,40 @@ +package dev.caskeleton.adapter.outbound.mongo.example; + +import dev.caskeleton.adapter.outbound.mongo.api.error.MongoDuplicateKeyException; +import java.util.Objects; +import java.util.Optional; + +/** + * The port implementation: domain in, domain out, and the one place a platform failure becomes a + * domain failure. + * + *

      Only the failure the port promises is translated. Everything else — a timeout, an ambiguous + * write, a server-selection failure — leaves as the platform's {@code MongoPersistenceException}, + * which carries the outcome ({@code outcome()}, {@code ambiguous()}) the caller needs to decide on + * a retry. Wrapping those in a generic domain exception would erase that. + */ +public final class MongoNoteStore implements NoteStore { + + private final NoteDocumentRepository repository; + + private final NoteDocumentMapper mapper; + + public MongoNoteStore(NoteDocumentRepository repository, NoteDocumentMapper mapper) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.mapper = Objects.requireNonNull(mapper, "mapper"); + } + + @Override + public void add(Note note) { + try { + repository.insert(mapper.toDocument(note)); + } catch (MongoDuplicateKeyException taken) { + throw new NoteAlreadyExistsException(note.id(), taken); + } + } + + @Override + public Optional find(String id) { + return repository.findById(id).map(mapper::toDomain); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/MongoNoteStoreExampleTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/MongoNoteStoreExampleTest.java new file mode 100644 index 00000000..f420f8cc --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/MongoNoteStoreExampleTest.java @@ -0,0 +1,133 @@ +package dev.caskeleton.adapter.outbound.mongo.example; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.mongodb.MongoWriteException; +import com.mongodb.ServerAddress; +import com.mongodb.WriteError; +import dev.caskeleton.adapter.outbound.mongo.api.error.MongoDuplicateKeyException; +import dev.caskeleton.adapter.outbound.mongo.api.observation.MongoOperationObserver; +import dev.caskeleton.adapter.outbound.mongo.failure.DefaultMongoFailureClassifier; +import dev.caskeleton.adapter.outbound.mongo.failure.DefaultMongoFailureTranslator; +import dev.caskeleton.adapter.outbound.mongo.imperative.DefaultMongoImperativeExecutor; +import dev.caskeleton.adapter.outbound.mongo.imperative.MongoCollectionProfileRegistry; +import dev.caskeleton.adapter.outbound.mongo.imperative.MongoConsistencyBinder; +import java.util.Optional; +import org.bson.BsonDocument; +import org.bson.Document; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.convert.MappingMongoConverter; +import org.springframework.data.mongodb.core.convert.NoOpDbRefResolver; +import org.springframework.data.mongodb.core.mapping.MongoMappingContext; +import org.springframework.data.mongodb.core.query.Query; + +/** + * Runs the consumer example against the real executor and failure translator. Only the template + * underneath is a stand-in, so what is exercised is everything a service's adapter leaf would + * write: the mapper, the executor call with its registered operation and collection profile, and + * the one translation the port promises. + */ +@Tag("mongodb-contract") +class MongoNoteStoreExampleTest { + + private MongoTemplate template; + + private NoteStore store; + + @BeforeEach + void wireTheExampleTheWayAServiceWould() { + template = mock(MongoTemplate.class); + MongoConsistencyBinder consistency = mock(MongoConsistencyBinder.class); + when(consistency.templateFor(any())).thenReturn(template); + DefaultMongoImperativeExecutor executor = + new DefaultMongoImperativeExecutor( + consistency, + // The service registers its collection profile; the auto-configured registry is empty. + MongoCollectionProfileRegistry.builder() + .register(NoteDocument.COLLECTION, NoteDocument.COLLECTION) + .build(), + new DefaultMongoFailureTranslator(new DefaultMongoFailureClassifier()), + MongoOperationObserver.none()); + store = new MongoNoteStore(new NoteDocumentRepository(executor), new NoteDocumentMapper()); + } + + @Test + @DisplayName("저장하면 domain 객체가 document로 바뀌어 등록한 collection에 들어간다") + void addingANoteInsertsItsDocumentIntoTheRegisteredCollection() { + // given + Note note = new Note("n-1", "first"); + + // when + store.add(note); + + // then + verify(template).insert(new NoteDocument("n-1", "first"), NoteDocument.COLLECTION); + } + + @Test + @DisplayName("이미 있는 id로 저장하면 port가 약속한 도메인 예외로 바뀐다") + void aTakenIdBecomesTheDomainFailureThePortPromises() { + // given + when(template.insert(any(NoteDocument.class), eq(NoteDocument.COLLECTION))) + .thenThrow(new DuplicateKeyException("E11000", duplicateKey())); + + // when + Throwable thrown = catchThrowable(() -> store.add(new Note("n-1", "first"))); + + // then + assertThat(thrown) + .isInstanceOf(NoteStore.NoteAlreadyExistsException.class) + .hasCauseInstanceOf(MongoDuplicateKeyException.class); + } + + @Test + @DisplayName("조회한 document는 mapper를 거쳐 domain 객체로 돌아온다") + void aFoundDocumentComesBackAsTheDomainType() { + // given + when(template.findOne(any(Query.class), eq(NoteDocument.class), eq(NoteDocument.COLLECTION))) + .thenReturn(new NoteDocument("n-1", "first")); + + // when + Optional found = store.find("n-1"); + + // then + assertThat(found).contains(new Note("n-1", "first")); + } + + @Test + @DisplayName("document는 @Field로 정한 이름으로 저장된다") + void theDocumentIsStoredUnderItsDeclaredFieldNames() { + // given + MongoMappingContext mapping = new MongoMappingContext(); + mapping.afterPropertiesSet(); + MappingMongoConverter converter = + new MappingMongoConverter(NoOpDbRefResolver.INSTANCE, mapping); + converter.afterPropertiesSet(); + Document stored = new Document(); + + // when + converter.write(new NoteDocument("n-1", "first"), stored); + + // then + assertThat(stored).containsEntry("_id", "n-1").containsEntry("t", "first"); + assertThat(stored).doesNotContainKey("title"); + } + + private static MongoWriteException duplicateKey() { + return new MongoWriteException( + new WriteError(11000, "E11000 duplicate key error", new BsonDocument()), + new ServerAddress(), + java.util.Set.of()); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/Note.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/Note.java new file mode 100644 index 00000000..52efed65 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/Note.java @@ -0,0 +1,17 @@ +package dev.caskeleton.adapter.outbound.mongo.example; + +import java.util.Objects; + +/** + * Stand-in for a {@code domain-core} type: no Spring, no driver, no BSON annotation. + * + * @param id the note's identity, chosen by the domain + * @param title what the note is called + */ +public record Note(String id, String title) { + + public Note { + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(title, "title"); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocument.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocument.java new file mode 100644 index 00000000..39ef5a9d --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocument.java @@ -0,0 +1,23 @@ +package dev.caskeleton.adapter.outbound.mongo.example; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; + +/** + * The stored shape, owned by the adapter leaf. It is the only type that carries Spring Data + * annotations; the domain type above never does. + * + *

      The stored field name is short and fixed with {@code @Field}, so renaming the Java component + * is not a data migration. The {@code @Document} collection is the physical name; the platform + * reaches it through a collection profile, registered in {@code MongoCollectionProfileRegistry}. + * + * @param id the {@code _id} + * @param title stored as {@code t} + */ +@Document(NoteDocument.COLLECTION) +public record NoteDocument(@Id String id, @Field("t") String title) { + + /** The physical collection, and the collection profile name the example registers it under. */ + public static final String COLLECTION = "notes"; +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocumentMapper.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocumentMapper.java new file mode 100644 index 00000000..fc6272b1 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocumentMapper.java @@ -0,0 +1,16 @@ +package dev.caskeleton.adapter.outbound.mongo.example; + +/** + * Translates between the domain type and the stored shape — and does nothing else. A mapper that + * validates, defaults or decides is holding a business rule in the wrong layer (AGENTS.md). + */ +public final class NoteDocumentMapper { + + public NoteDocument toDocument(Note note) { + return new NoteDocument(note.id(), note.title()); + } + + public Note toDomain(NoteDocument document) { + return new Note(document.id(), document.title()); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocumentRepository.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocumentRepository.java new file mode 100644 index 00000000..fec48f68 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteDocumentRepository.java @@ -0,0 +1,74 @@ +package dev.caskeleton.adapter.outbound.mongo.example; + +import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationContext; +import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationType; +import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyProfile; +import dev.caskeleton.adapter.outbound.mongo.imperative.DefaultMongoImperativeExecutor; +import java.time.Duration; +import java.util.Objects; +import java.util.Optional; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; + +/** + * The adapter-local repository, written against the platform's executor rather than a Spring Data + * {@code MongoRepository}. + * + *

      Every call goes through {@link DefaultMongoImperativeExecutor}: a registered operation name, a + * registered collection profile, a consistency profile, a deadline, observation and exactly one + * failure translation. A {@code MongoRepository} is allowed in an adapter leaf ({@code + * MongoRepositoryArchitectureRules.allowedRepositorySuperTypes}), but it reaches the collection + * with none of that: its failures arrive as Spring's {@code DuplicateKeyException} and the like + * rather than the platform's {@code MongoDuplicateKeyException}, and its derived queries never see + * {@code MongoQueryPolicy}. The consumer guide states what a service takes on if it chooses one + * anyway. + */ +public final class NoteDocumentRepository { + + /** One deadline for the example. A real adapter names one per operation. */ + private static final Duration TIMEOUT = Duration.ofSeconds(2); + + private static final MongoOperationContext INSERT = + MongoOperationContext.of( + "note.add", + "primary", + NoteDocument.COLLECTION, + MongoConsistencyProfile.PRIMARY_MAJORITY, + TIMEOUT); + + private static final MongoOperationContext FIND = + MongoOperationContext.of( + "note.find", + "primary", + NoteDocument.COLLECTION, + MongoConsistencyProfile.PRIMARY_MAJORITY, + TIMEOUT); + + private final DefaultMongoImperativeExecutor executor; + + public NoteDocumentRepository(DefaultMongoImperativeExecutor executor) { + this.executor = Objects.requireNonNull(executor, "executor"); + } + + /** + * Inserts, never upserts: an id that is taken must fail rather than overwrite. + * + * @throws dev.caskeleton.adapter.outbound.mongo.api.error.MongoDuplicateKeyException when the id + * is taken — already translated by the executor + */ + public void insert(NoteDocument document) { + executor.execute(INSERT, MongoOperationType.INSERT, access -> access.scoped().insert(document)); + } + + public Optional findById(String id) { + return executor + .execute( + FIND, + MongoOperationType.FIND, + access -> + access + .scoped() + .findOne(Query.query(Criteria.where("_id").is(id)), NoteDocument.class)) + .value(); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteStore.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteStore.java new file mode 100644 index 00000000..072c1aaf --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/NoteStore.java @@ -0,0 +1,31 @@ +package dev.caskeleton.adapter.outbound.mongo.example; + +import java.util.Optional; + +/** + * Stand-in for an {@code application-core} outbound port. It speaks domain types and a domain + * failure, never {@code MongoDuplicateKeyException} — the port must not know which database is + * behind it. + */ +public interface NoteStore { + + /** + * Stores a new note. + * + * @throws NoteAlreadyExistsException when a note with the same id is already stored + */ + void add(Note note); + + /** The note with this id, if one is stored. */ + Optional find(String id); + + /** The domain's own failure for an id that is already taken. */ + final class NoteAlreadyExistsException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public NoteAlreadyExistsException(String id, Throwable cause) { + super("note already exists: " + id, cause); + } + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/package-info.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/package-info.java new file mode 100644 index 00000000..84548a91 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/example/package-info.java @@ -0,0 +1,27 @@ +/** + * A worked example of how a derived service's own adapter leaf consumes this library (review + * 04-15). + * + *

      It lives in this leaf's test source set on purpose. Production code here must not ship a + * placeholder document or repository (CLAUDE.md "Forbidden"), and the test-fixtures variant is put + * on every consumer's test classpath, where an example type would be picked up as if it were API. + * As tests, the example compiles against the real library and runs in {@code + * mongoStableContractTest}, so it cannot drift from the API it demonstrates. + * + *

      The cast, and where each type lives in a real service: + * + *

        + *
      • {@link dev.caskeleton.adapter.outbound.mongo.example.Note} and {@link + * dev.caskeleton.adapter.outbound.mongo.example.NoteStore} — stand-ins for a {@code + * domain-core} type and an {@code application-core} outbound port. Framework-free. + *
      • {@link dev.caskeleton.adapter.outbound.mongo.example.NoteDocument}, {@link + * dev.caskeleton.adapter.outbound.mongo.example.NoteDocumentMapper}, {@link + * dev.caskeleton.adapter.outbound.mongo.example.NoteDocumentRepository} and {@link + * dev.caskeleton.adapter.outbound.mongo.example.MongoNoteStore} — the service's own outbound + * adapter leaf, which takes this leaf as {@code implementation}. + *
      + * + *

      The registration procedure — the registry edge, the Gradle line, exception translation and + * what bypasses the query policy — is {@code docs/mongodb/consumer-leaf-guide.md}. + */ +package dev.caskeleton.adapter.outbound.mongo.example; diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionBodyTranslatedFailureTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionBodyTranslatedFailureTest.java new file mode 100644 index 00000000..00d0c023 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionBodyTranslatedFailureTest.java @@ -0,0 +1,97 @@ +package dev.caskeleton.adapter.outbound.mongo.transaction; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.mongodb.MongoException; +import com.mongodb.client.ClientSession; +import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyRegistry; +import dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoTransactionRetryCoordinator; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.mongodb.MongoDatabaseFactory; +import org.springframework.data.mongodb.UncategorizedMongoDbException; +import org.springframework.data.mongodb.core.MongoTemplate; + +/** + * What the transaction body sees is a session-bound {@code MongoTemplate}, and {@code + * MongoTemplate} translates driver failures into Spring's {@code DataAccessException} hierarchy + * before they leave it. A WriteConflict therefore reaches {@code runBody} as a Spring exception + * whose cause carries the {@code TransientTransactionError} label. Catching only {@code + * MongoException} let it past the classifier, and the coordinator's body-replay branch never ran + * (review 04-11). + */ +@Tag("mongodb-contract") +class MongoTransactionBodyTranslatedFailureTest { + + @Test + @DisplayName("본문이 Spring이 번역한 TransientTransactionError를 던지면 새 세션에서 본문을 한 번 더 실행한다") + void aSpringTranslatedTransientErrorReplaysTheBody() { + // given + MongoTransactionRetryCoordinator coordinator = + MongoTransactionRetryCoordinator.standard(sessionFactory(), "order.reserve"); + AtomicInteger bodyCalls = new AtomicInteger(); + + // when + String result = + coordinator.execute( + MongoTransactionProfile.majority(), + operations -> { + if (bodyCalls.incrementAndGet() == 1) { + throw new UncategorizedMongoDbException("Write conflict", writeConflict()); + } + return "ok"; + }); + + // then + assertThat(result).isEqualTo("ok"); + assertThat(bodyCalls).hasValue(2); + } + + @Test + @DisplayName("본문이 Mongo 원인이 없는 Spring 예외를 던지면 재시도하지 않고 그 예외를 그대로 내보낸다") + void aNonMongoFailureFromTheBodyIsNotReplayed() { + // given + MongoTransactionRetryCoordinator coordinator = + MongoTransactionRetryCoordinator.standard(sessionFactory(), "order.reserve"); + AtomicInteger bodyCalls = new AtomicInteger(); + DataIntegrityViolationException domainFailure = + new DataIntegrityViolationException("not a driver failure"); + + // when + Throwable thrown = + catchThrowable( + () -> + coordinator.execute( + MongoTransactionProfile.majority(), + operations -> { + bodyCalls.incrementAndGet(); + throw domainFailure; + })); + + // then + assertThat(thrown).isSameAs(domainFailure); + assertThat(bodyCalls).hasValue(1); + } + + private static MongoException writeConflict() { + MongoException conflict = new MongoException(112, "WriteConflict"); + conflict.addLabel(MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL); + return conflict; + } + + private static SpringMongoTransactionSessionFactory sessionFactory() { + MongoDatabaseFactory databases = mock(MongoDatabaseFactory.class); + when(databases.getSession(any())).thenAnswer(invocation -> mock(ClientSession.class)); + MongoTemplate template = mock(MongoTemplate.class); + when(template.getMongoDatabaseFactory()).thenReturn(databases); + when(template.withSession(any(ClientSession.class))).thenReturn(mock(MongoTemplate.class)); + return new SpringMongoTransactionSessionFactory(template, MongoConsistencyRegistry.standard()); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/retry/MongoTransactionRetryCoordinatorTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/retry/MongoTransactionRetryCoordinatorTest.java index 2fde8127..62c17905 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/retry/MongoTransactionRetryCoordinatorTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/retry/MongoTransactionRetryCoordinatorTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.mongo.transaction.retry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationName; import dev.caskeleton.adapter.outbound.mongo.api.error.MongoFailureContext; @@ -16,6 +17,7 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.random.RandomGenerator; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.data.mongodb.core.MongoOperations; @@ -75,6 +77,42 @@ class MongoTransactionRetryCoordinatorTest { .hasMessageContaining("reconcile"); } + @Test + @DisplayName("commit 재시도 대기 중 인터럽트되면 결과를 모르는 commit으로 알리고 인터럽트 표시를 남긴다") + void anInterruptDuringCommitRetryBackoffStaysACommitUnknown() { + // given + RecordingSessionFactory sessions = RecordingSessionFactory.commitAlwaysUnknown(); + MongoTransactionRetryCoordinator coordinator = + new MongoTransactionRetryCoordinator( + sessions, + MongoRetryBudget.standard(), + MongoCommitReconciler.standard(), + RandomGenerator.getDefault(), + decision -> {}, + OPERATION); + + // when + Throwable thrown = + catchThrowable( + () -> + coordinator.execute( + MongoTransactionProfile.majority(), + operations -> { + // The first commit has no backoff; the second one sleeps, and an interrupted + // thread fails that sleep at once. + Thread.currentThread().interrupt(); + return "ok"; + })); + + // then + boolean interruptKept = Thread.interrupted(); + assertThat(thrown) + .isInstanceOf(MongoTransactionCommitUnknownException.class) + .hasMessageContaining("reconcile"); + assertThat(interruptKept).isTrue(); + assertThat(sessions.commitCalls()).isEqualTo(1); + } + @Test void everyRetryDecisionIsRecordedWithItsScope() { List decisions = new ArrayList<>(); diff --git a/src/adapter/outbound/persistence-notification/CLAUDE.md b/src/adapter/outbound/persistence-notification/CLAUDE.md new file mode 100644 index 00000000..630842ef --- /dev/null +++ b/src/adapter/outbound/persistence-notification/CLAUDE.md @@ -0,0 +1,40 @@ +# adapter:outbound:persistence-notification — notification relational persistence + +## Registered identity + +- Module ID: `adapter-outbound-persistence-notification`; Gradle path and allowed edges are in + `src/config/architecture/modules.json`. +- Focused test: `./gradlew :adapter:outbound:persistence-notification:test --console=plain`. +- Package root: `dev.caskeleton.adapter.outbound.persistence.notification`. Entities, Spring Data + repositories, stores and SQL constants are in `platform` (inbox in `platform.inbox`). + +## Where the tests are + +| What | Where | Run | +|---|---|---| +| Unit and wiring tests | this leaf, `src/test` | `:adapter:outbound:persistence-notification:test` | +| Real PostgreSQL tests of these stores | `persistence-jpa`, `src/postgresqlIntegrationTest/.../persistence/notification` (that lane owns the container and Flyway wiring) | `:adapter:outbound:persistence-jpa:postgresqlIntegrationTest --tests ''` | +| Port contracts the stores must pass | `application-notification` testFixtures, `*.testkit.*StoreContract` | the in-memory fake and the PostgreSQL test both extend the contract | +| Migration pins | `persistence-jpa/src/test/resources/db/applied-migrations.sha256` | `AppliedMigrationImmutabilityTest` in `:adapter:outbound:persistence-jpa:test` | + +A store whose port has a contract in `application-notification` testFixtures is tested by a +PostgreSQL subclass of that contract, not by a separate hand-written PostgreSQL test. + +## Rules + +- **Every write joins the caller's transaction.** A store write starts with + `CallerTransaction.require("")`; the use case owns the transaction (owner decision 33). +- **Migrations** live in `src/main/resources/db/migration/jpa/notification-platform` and run as + their own Flyway stream (`NotificationSchemaStream`, history table + `flyway_jpa_notification_history`). An applied file is never edited: add the next `V__`, pin + its SHA-256 in `applied-migrations.sha256`, and add it to `NotificationFixtures.migrations()`. + A migration that deletes rows states in a SQL comment which row survives and why. +- **Insert-or-update is decided by the database.** Never find-then-insert: insert with + `ON CONFLICT () DO NOTHING`, and when it inserted nothing, update the existing row + through the managed entity (`JpaSuppressionStore.upsert`, `JpaPolicyStores.Preferences.save`, + `DeduplicationClaims.insertOrFind`). The conflict target needs a unique constraint in a migration. +- **A bulk or native `UPDATE` of a `@Version` table advances the version** (`version = version + 1`) + and is `@Modifying(clearAutomatically = true, flushAutomatically = true)` when the caller may + re-read the row. `JpaVersionedBulkUpdateRule` (persistence-jpa testFixtures) enforces the + version part in `:app-bootstrap:architectureTest`. +- Repositories extend `Repository`, not `CrudRepository`, and expose only tenant-scoped finders. diff --git a/src/adapter/outbound/persistence-notification/gradle.lockfile b/src/adapter/outbound/persistence-notification/gradle.lockfile index a3f72d20..f05fb514 100644 --- a/src/adapter/outbound/persistence-notification/gradle.lockfile +++ b/src/adapter/outbound/persistence-notification/gradle.lockfile @@ -33,7 +33,6 @@ com.google.guava:guava:33.6.0-jre=checkstyle com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor -com.h2database:h2:2.4.240=runtimeClasspath,testRuntimeClasspath com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java index 9c24d0b3..f5bba6de 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java @@ -13,6 +13,7 @@ import dev.caskeleton.application.notification.platform.policy.PreferenceRecord; import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort; import dev.caskeleton.application.notification.platform.policy.RecipientIdentity; import java.time.Clock; +import java.time.Instant; import java.util.Arrays; import java.util.List; import java.util.Objects; @@ -46,41 +47,72 @@ public final class JpaPolicyStores { .map(Preferences::toRecord); } + /** + * Inserts the first preference, or overwrites the stored one. + * + *

      Insert first and let {@code uk_notification_preference} decide, then update the stored row + * through the managed entity when the insert lost — the same reason the suppression store gives + * for not using {@code ON CONFLICT DO UPDATE}. + */ @Override public PreferenceRecord save(PreferenceRecord record) { CallerTransaction.require("preference save"); Objects.requireNonNull(record, "record"); String preferred = encode(record.preferredOrder()); String muted = encode(List.copyOf(record.mutedChannels())); - return preferences - .findByTenantIdAndRecipientRef(record.tenantId().value(), record.recipientRef()) - .map( - entity -> { - entity.update(preferred, muted, clock.instant()); - return toRecord(preferences.saveAndFlush(entity)); - }) - .orElseGet( - () -> - toRecord( - preferences.saveAndFlush( - new PreferenceEntity( - ids.nextId(), - record.tenantId().value(), - record.recipientRef(), - preferred, - muted, - clock.instant())))); + Instant now = clock.instant(); + int inserted = + preferences.insertIfAbsent( + ids.nextId(), + record.tenantId().value(), + record.recipientRef(), + preferred, + muted, + now); + if (inserted == 1) { + return new PreferenceRecord( + record.tenantId(), + record.recipientRef(), + record.preferredOrder(), + record.mutedChannels(), + now); + } + PreferenceEntity existing = + preferences + .findByTenantIdAndRecipientRef(record.tenantId().value(), record.recipientRef()) + .orElseThrow( + () -> + new IllegalStateException( + "preference save lost to a row that disappeared before it could be" + + " updated")); + existing.update(preferred, muted, now); + return toRecord(preferences.saveAndFlush(existing)); } + /** + * A JSON array of channel names, because both columns are {@code jsonb}. + * + *

      It was a comma-joined string, which PostgreSQL refuses as JSON — so every first preference + * save failed on a real database, and only the empty default {@code []} could ever be read. The + * PostgreSQL contract test is what surfaced it; no test had run this store against PostgreSQL. + */ private static String encode(List channels) { - return channels.stream().map(Enum::name).collect(Collectors.joining(",")); + return channels.stream() + .map(channel -> "\"" + channel.name() + "\"") + .collect(Collectors.joining(",", "[", "]")); } + /** Reads the JSON array {@link #encode} writes; channel names need no escaping. */ private static List decodeList(String value) { if (value == null || value.isBlank()) { return List.of(); } - return Arrays.stream(value.split(",", -1)) + String body = value.strip(); + if (body.startsWith("[") && body.endsWith("]")) { + body = body.substring(1, body.length() - 1); + } + return Arrays.stream(body.split(",", -1)) + .map(name -> name.strip().replace("\"", "")) .filter(name -> !name.isBlank()) .map(Channel::valueOf) .toList(); diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java index c70a3113..f16ff271 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java @@ -14,6 +14,7 @@ import java.time.Instant; import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.UUID; /** * Suppression persistence. @@ -44,23 +45,61 @@ public final class JpaSuppressionStore implements SuppressionStorePort { .toList(); } + /** + * Inserts the entry, or refreshes the one already stored for its target and reason. + * + *

      Insert first and let {@code uk_notification_suppression_target} decide, then refresh the + * stored row when the insert lost. Not {@code ON CONFLICT DO UPDATE}: the refresh goes through + * the managed entity, so an entry this transaction already loaded is the one that changes, rather + * than a stale copy the first-level cache would keep handing back after a native update. + */ @Override public SuppressionEntry upsert(SuppressionEntry entry) { CallerTransaction.require("suppression upsert"); Objects.requireNonNull(entry, "entry"); - return suppressions - .findByTenantIdAndNormalizedTargetHmacAndReason( - entry.tenantId().value(), entry.normalizedTargetHmac(), entry.reason().name()) - .map( - existing -> { - existing.refresh( - entry.reason().name(), - entry.effectiveAt(), - entry.expiresAt().orElse(null), - entry.source().name()); - return toEntry(suppressions.saveAndFlush(existing)); - }) - .orElseGet(() -> toEntry(suppressions.saveAndFlush(toEntity(entry)))); + UUID id = ids.nextId(); + int inserted = + suppressions.insertIfAbsent( + id, + entry.tenantId().value(), + entry.scope().name(), + entry.reason().name(), + entry.normalizedTargetHmac(), + entry.notificationCategory().orElse(null), + entry.effectiveAt(), + entry.expiresAt().orElse(null), + entry.source().name(), + clock.instant()); + if (inserted == 1) { + return new SuppressionEntry( + new SuppressionId(id), + entry.tenantId(), + entry.scope(), + entry.reason(), + entry.normalizedTargetHmac(), + entry.notificationCategory(), + entry.effectiveAt(), + entry.expiresAt(), + entry.source()); + } + SuppressionEntity existing = + suppressions + .findByTenantIdAndNormalizedTargetHmacAndReason( + entry.tenantId().value(), entry.normalizedTargetHmac(), entry.reason().name()) + // The conflicting row was removed between the two statements. Reporting it beats + // retrying in a loop: the caller's transaction is intact and the next report re-adds + // it. + .orElseThrow( + () -> + new IllegalStateException( + "suppression upsert lost to an entry that was removed before it could be" + + " refreshed")); + existing.refresh( + entry.reason().name(), + entry.effectiveAt(), + entry.expiresAt().orElse(null), + entry.source().name()); + return toEntry(suppressions.saveAndFlush(existing)); } @Override @@ -78,20 +117,6 @@ public final class JpaSuppressionStore implements SuppressionStorePort { }); } - private SuppressionEntity toEntity(SuppressionEntry entry) { - return new SuppressionEntity( - ids.nextId(), - entry.tenantId().value(), - entry.scope().name(), - entry.reason().name(), - entry.normalizedTargetHmac(), - entry.notificationCategory().orElse(null), - entry.effectiveAt(), - entry.expiresAt().orElse(null), - entry.source().name(), - clock.instant()); - } - private static SuppressionEntry toEntry(SuppressionEntity entity) { return new SuppressionEntry( new SuppressionId(entity.id()), diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java index b04c9d7b..f8922ec0 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java @@ -1,8 +1,12 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import java.time.Instant; import java.util.Optional; import java.util.UUID; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.Repository; +import org.springframework.data.repository.query.Param; /* * Top-level, not nested inside a holder class. Spring Data does not discover nested repository @@ -21,4 +25,32 @@ public interface PreferenceJpaRepository extends Repository findByTenantIdAndRecipientRef(String tenantId, String recipientRef); + + /** + * Inserts the first preference for a recipient, or reports that one already exists. + * + *

      {@code ON CONFLICT DO NOTHING} on {@code uk_notification_preference}, the shape {@link + * DeduplicationClaimJpaRepository#claimWindow} uses. The find-then-insert it replaces turned the + * second of two concurrent first saves into a unique violation — a 409 for a write that is meant + * to be idempotent — and left that caller's transaction aborted. + * + * @return 1 when this call inserted the preference, 0 when one already existed + */ + @Modifying(flushAutomatically = true) + @Query( + value = + "INSERT INTO notification_preference (" + + " id, tenant_id, recipient_ref, preferred_order, muted_channels, updated_at" + + ") VALUES (" + + " :id, :tenantId, :recipientRef, CAST(:preferredOrder AS jsonb)," + + " CAST(:mutedChannels AS jsonb), :updatedAt" + + ") ON CONFLICT (tenant_id, recipient_ref) DO NOTHING", + nativeQuery = true) + int insertIfAbsent( + @Param("id") UUID id, + @Param("tenantId") String tenantId, + @Param("recipientRef") String recipientRef, + @Param("preferredOrder") String preferredOrder, + @Param("mutedChannels") String mutedChannels, + @Param("updatedAt") Instant updatedAt); } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java index 7304cf6f..2b7b757d 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java @@ -54,6 +54,8 @@ public final class RecipientClaimSql { "UPDATE notification_recipient_delivery SET" + " delivery_state = 'EXPIRED'," + " next_dispatch_at = NULL," + // The @Version column, advanced for the reason CLAIM_BATCH gives (review 04-07). + + " version = version + 1," + " updated_at = :now" + " WHERE id IN (" + " SELECT id FROM notification_recipient_delivery" diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java index 614d20e6..a3beab48 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java @@ -55,7 +55,9 @@ public interface RecipientDeliveryJpaRepository extends Repository findByTenantIdAndNormalizedTargetHmacAndReason( String tenantId, String normalizedTargetHmac, String reason); + + /** + * Inserts the entry, or reports that one already exists for its target and reason. + * + *

      {@code ON CONFLICT DO NOTHING} on {@code uk_notification_suppression_target} (V12), the + * shape {@link DeduplicationClaimJpaRepository#claimWindow} uses. A find-then-insert let two + * webhooks for one address both find nothing and both insert; here the database decides, a loser + * waits for the winner's commit, and its transaction stays usable for the refresh that follows. + * + * @return 1 when this call inserted the entry, 0 when one already existed + */ + @Modifying(flushAutomatically = true) + @Query( + value = + "INSERT INTO notification_suppression (" + + " id, tenant_id, scope, reason, normalized_target_hmac, notification_category," + + " effective_at, expires_at, source, created_at" + + ") VALUES (" + + " :id, :tenantId, :scope, :reason, :normalizedTargetHmac, :notificationCategory," + + " :effectiveAt, :expiresAt, :source, :createdAt" + + ") ON CONFLICT (tenant_id, normalized_target_hmac, reason) DO NOTHING", + nativeQuery = true) + int insertIfAbsent( + @Param("id") UUID id, + @Param("tenantId") String tenantId, + @Param("scope") String scope, + @Param("reason") String reason, + @Param("normalizedTargetHmac") String normalizedTargetHmac, + @Param("notificationCategory") String notificationCategory, + @Param("effectiveAt") Instant effectiveAt, + @Param("expiresAt") Instant expiresAt, + @Param("source") String source, + @Param("createdAt") Instant createdAt); } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java index 8200e9f3..7585154d 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java @@ -79,11 +79,16 @@ public interface InboxItemJpaRepository extends Repository 1; + +ALTER TABLE notification_suppression + ADD CONSTRAINT uk_notification_suppression_target + UNIQUE (tenant_id, normalized_target_hmac, reason); + +COMMENT ON CONSTRAINT uk_notification_suppression_target ON notification_suppression IS + 'One entry per target and reason. JpaSuppressionStore.upsert inserts ON CONFLICT on this key ' + 'and refreshes the existing row when it loses.'; diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributor.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributor.java index aee4fb09..beb8beca 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributor.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributor.java @@ -106,7 +106,12 @@ public final class RedisHealthContributor { } return new RedisHealth(true, detail("reachable", String.valueOf(reply))); } catch (RedisLaneUnavailableException refused) { - // A refusal is raised before any command exists: either shutdown began, or the lane is full. + // A refusal is raised before any command exists: shutdown began, the lane is full, or the + // connection could not be opened. Only the full lane is load on a server that answers. + if (refused.connectionFailed()) { + return new RedisHealth( + false, detail("unreachable", refused.getCause().getClass().getSimpleName())); + } return owner.state() != RedisRuntimeOwner.State.OPEN ? shuttingDown() : new RedisHealth(true, detail("saturated", "lane at its connection limit")); diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLaneUnavailableException.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLaneUnavailableException.java index d3951860..38bed245 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLaneUnavailableException.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLaneUnavailableException.java @@ -4,7 +4,7 @@ import java.util.Objects; /** * No connection could be lent: the lane stayed full for the acquire timeout, the wait was - * interrupted, or the runtime is shutting down. + * interrupted, the runtime is shutting down, or the connection could not be opened. * *

      Always raised before any command exists, so nothing reached Redis. A caller may treat it as * "unavailable" rather than as a write that might have landed — the distinction every semantic @@ -27,6 +27,31 @@ public final class RedisLaneUnavailableException extends RuntimeException { this.lane = Objects.requireNonNull(lane, "lane must be non-null"); } + /** + * Creates the failure for a connection that could not be opened. + * + * @param lane the lane that could not lend a connection + * @param reason a fixed, payload-free reason + * @param cause the driver's failure to connect + */ + public RedisLaneUnavailableException(String lane, String reason, Throwable cause) { + super(Objects.requireNonNull(reason, "reason must be non-null"), cause); + this.lane = Objects.requireNonNull(lane, "lane must be non-null"); + } + + /** + * Whether the refusal is a connection that could not be opened, rather than a full lane or a + * closing runtime. + * + *

      Both are "nothing was sent". They differ for health: a full lane is load on a working + * server, a connection that could not be opened is a server (or credential) that is not there. + * + * @return true when opening the connection failed + */ + public boolean connectionFailed() { + return getCause() != null; + } + /** * Returns the lane that refused. * diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java index 7998d5c7..45014405 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java @@ -143,8 +143,31 @@ public final class RedisRuntimeOwner implements AutoCloseable { * @throws IllegalArgumentException when no limit was configured for the lane */ public RedisLease borrow(RedisLane kind, Optional routingKey) { + return borrow(kind, routingKey, acquireTimeout); + } + + /** + * Borrows a connection, waiting for a full lane no longer than the caller has left. + * + *

      The owner's acquire timeout is a ceiling, not a promise: a caller with a deadline — a rate + * limit evaluated on a request path — must not spend seconds queueing for a connection whose + * answer arrives after it gave up. The wait is the shorter of the two. + * + * @param kind the lane + * @param routingKey a key whose slot decides the node, on topologies that have more than one + * @param maximumWait the longest this caller will wait for a returned connection + * @return the lease, which must be closed + * @throws RedisLaneUnavailableException when no connection could be lent within the wait, the + * owner is closing, or the connection could not be opened + */ + public RedisLease borrow(RedisLane kind, Optional routingKey, Duration maximumWait) { Objects.requireNonNull(kind, "connection kind must be non-null"); Objects.requireNonNull(routingKey, "routing key must be non-null"); + Objects.requireNonNull(maximumWait, "maximum wait must be non-null"); + Duration wait = + maximumWait.isNegative() + ? Duration.ZERO + : (maximumWait.compareTo(acquireTimeout) < 0 ? maximumWait : acquireTimeout); if (!permits.containsKey(kind)) { throw new IllegalArgumentException( "connection lane " @@ -162,7 +185,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { Semaphore lane = permits.get(kind); boolean admitted; try { - admitted = lane.tryAcquire(acquireTimeout.toNanos(), TimeUnit.NANOSECONDS); + admitted = lane.tryAcquire(wait.toNanos(), TimeUnit.NANOSECONDS); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw reject(kind, "interrupted while waiting for a connection on lane " + kind.name()); @@ -175,7 +198,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { + " reached its limit of " + limits.get(kind) + " and no connection was returned within " - + acquireTimeout); + + wait); } synchronized (monitor) { if (state.get() != State.OPEN) { @@ -198,7 +221,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { connection = null; } if (connection == null) { - connection = client.openLane(kind, routingKey); + connection = openLane(kind, routingKey); } return new Lease(kind, connection, routingKey.isEmpty()); } catch (RuntimeException failure) { @@ -210,6 +233,29 @@ public final class RedisRuntimeOwner implements AutoCloseable { } } + /** + * Opens a connection, reporting any failure as the lane being unavailable. + * + *

      Opening a connection sends no command, so its failure — refused, unresolvable host, + * handshake or authentication failure, connect timeout — is a definite "nothing was sent". Left + * as the driver's exception it reached the semantic adapters as an unknown outcome: an + * idempotency claim went to reconciliation and a rate limit reported a mutation it could not rule + * out, for an outage in which no command left this process. + */ + private RedisRuntimeClient.RedisLaneConnection openLane( + RedisLane kind, Optional routingKey) { + try { + return client.openLane(kind, routingKey); + } catch (RedisLaneUnavailableException refused) { + throw refused; + } catch (RuntimeException failure) { + throw new RedisLaneUnavailableException( + kind.name(), + "a connection for lane " + kind.name() + " could not be opened; nothing was sent", + failure); + } + } + private void release( RedisLane kind, RedisRuntimeClient.RedisLaneConnection connection, boolean reusable) { boolean drained; diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributorTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributorTest.java index 5c656746..48a58e01 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributorTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributorTest.java @@ -66,6 +66,41 @@ class RedisHealthContributorTest { .containsExactly(false, "unreachable"); } + @Test + @DisplayName("연결을 열지 못한 lane은 포화가 아니라 unreachable로 보고한다") + void aLaneWhoseConnectionCannotBeOpenedIsUnreachable() { + // given + RedisRuntimeOwner owner = + narrowOwner( + new RedisRuntimeClient() { + @Override + public dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode + mode() { + return dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode + .STANDALONE; + } + + @Override + public RedisLaneConnection openLane(RedisLane lane, Optional routingKey) { + throw new IllegalStateException("WRONGPASS invalid username-password pair"); + } + + @Override + public void close() {} + }); + RedisHealthContributor contributor = new RedisHealthContributor(owner, Duration.ofSeconds(1)); + + // when + RedisHealthContributor.RedisHealth health = contributor.probe(); + + // then + // A refused lease and a refused connection both arrive as "lane unavailable"; only the first is + // load. Reporting a dead server or a wrong password as "saturated" kept the pod ready. + assertThat(health) + .extracting(RedisHealthContributor.RedisHealth::reachable, h -> h.detail().get("state")) + .containsExactly(false, "unreachable"); + } + private static RedisRuntimeClient client(SemanticRedisCommands commands) { return StubRedisRuntimeClient.serving(commands); } diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwnerTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwnerTest.java index 78569797..f2863ecc 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwnerTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwnerTest.java @@ -114,6 +114,52 @@ class RedisRuntimeOwnerTest { } } + @Test + @DisplayName("연결을 열지 못한 borrow는 명령을 보내기 전 실패이므로 lane unavailable로 거부하고 permit을 돌려준다") + void aConnectionThatCouldNotBeOpenedIsRefusedAsLaneUnavailable() { + // given + client.failOpen = true; + try (RedisRuntimeOwner owner = owner(1, Duration.ofSeconds(1))) { + + // when + Throwable refused = catchThrowable(() -> owner.borrow(RedisConnectionKind.REGULAR)); + + // then + assertThat(refused) + .as("nothing was sent, so the caller must be able to report 'not sent', not 'unknown'") + .isInstanceOf(RedisLaneUnavailableException.class) + .hasRootCauseMessage("connection refused"); + assertThat(owner.outstanding(RedisConnectionKind.REGULAR)).isZero(); + } + } + + @Test + @DisplayName("borrow는 호출자가 남긴 시간이 acquire timeout보다 짧으면 그 시간만 기다리고 거부한다") + void aBorrowWaitsNoLongerThanTheCallersRemainingBudget() { + // given + try (RedisRuntimeOwner owner = + new RedisRuntimeOwner(client, limits(1), Duration.ofSeconds(5), Duration.ofSeconds(1))) { + RedisLease held = owner.borrow(ContributedLane.EXCLUSIVE); + long started = System.nanoTime(); + + // when + Throwable refused = + catchThrowable( + () -> + owner.borrow( + ContributedLane.EXCLUSIVE, + java.util.Optional.empty(), + Duration.ofMillis(20))); + + // then + assertThat(refused).isInstanceOf(RedisLaneUnavailableException.class); + assertThat(Duration.ofNanos(System.nanoTime() - started)) + .as("the 5s acquire timeout must not outlive a caller that has 20ms left") + .isLessThan(Duration.ofSeconds(2)); + held.close(); + } + } + @Test @DisplayName("closing stops admission before it drains") void closingStopsAdmissionFirst() throws Exception { @@ -237,6 +283,7 @@ class RedisRuntimeOwnerTest { private int opened; private int closed; private boolean shutdown; + private boolean failOpen; void killPooled() { live.forEach(connection -> connection.alive = false); @@ -249,6 +296,9 @@ class RedisRuntimeOwnerTest { @Override public RedisLaneConnection openLane(RedisLane kind, java.util.Optional routingKey) { + if (failOpen) { + throw new IllegalStateException("connection refused"); + } opened++; FakeConnection connection = new FakeConnection(this); live.add(connection); diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java index e3d5bdcf..13d8fbb3 100644 --- a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java +++ b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java @@ -524,12 +524,13 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand return CompletableFuture.failedFuture( new io.lettuce.core.RedisNoScriptException("NOSCRIPT No matching script")); } - if (source.contains("redis.sha1hex(current)")) { - return done(replaceIfObserved(text(key), arguments)); - } + // The revision program also compares digests, so it is recognised first. if (source.contains("strictlyNewer")) { return done(replaceIfRevisionNewer(text(key), arguments)); } + if (source.contains("redis.sha1hex(current)")) { + return done(replaceIfObserved(text(key), arguments)); + } if (source.contains("redis.call('TIME')") && source.contains("return {1}")) { return done(1L); } @@ -541,18 +542,12 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand private long replaceIfObserved(String rendered, List arguments) { Entry current = live(rendered); - if (current == null) { - return 0L; - } String expected = text(arguments.get(0)); - String actual; - try { - byte[] digest = java.security.MessageDigest.getInstance("SHA-1").digest(current.value); - actual = java.util.HexFormat.of().formatHex(digest); - } catch (java.security.NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-1 must be available", impossible); - } - if (!actual.equals(expected)) { + if (current == null) { + if (!"absent".equals(expected)) { + return 0L; + } + } else if (!sha1Hex(current.value).equals(expected)) { return 0L; } long ttlMillis = Long.parseLong(text(arguments.get(2))); @@ -563,10 +558,29 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand /** * The cache's revision-ordered replacement: applies when nothing is stored, when the stored entry * is from an older region generation, or when the caller's decimal revision is strictly greater - * than the stored one at the same generation and schema version. + * than the stored one at the same generation and schema version. With a write condition the + * stored state must still be the observed one, and an observed vacant state applies outright. + * + *

      The revision comparison mirrors the cache port's {@code CacheSourceRevisionOrder}, which + * this leaf cannot reach (it has no project dependencies); {@code CacheRegionContract}, run by + * cache-redis over this fixture and over a real server, is what keeps the copies equal. */ private long replaceIfRevisionNewer(String rendered, List arguments) { Entry current = live(rendered); + String expected = text(arguments.get(5)); + if (!expected.isEmpty()) { + if (current == null) { + if (!"absent".equals(expected)) { + return 0L; + } + } else if (!sha1Hex(current.value).equals(expected)) { + return 0L; + } else if ("1".equals(text(arguments.get(6)))) { + long ttlMillis = Long.parseLong(text(arguments.get(2))); + entries.put(rendered, new Entry(arguments.get(1), now() + ttlMillis)); + return 1L; + } + } if (current != null) { // digest(64) | version | revision | generation | ... String stored = current.text(); @@ -603,6 +617,15 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand return 1L; } + private static String sha1Hex(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-1").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-1 must be available", impossible); + } + } + /** Returns the live fields of a hash. */ private Map hash(String rendered) { return hashes.computeIfAbsent(rendered, unusedKey -> new LinkedHashMap<>()); diff --git a/src/adapter/outbound/support/build.gradle b/src/adapter/outbound/support/build.gradle index a6eae57b..ede1171f 100644 --- a/src/adapter/outbound/support/build.gradle +++ b/src/adapter/outbound/support/build.gradle @@ -25,6 +25,7 @@ dependencies { compileOnly libs.logstash.logback.encoder compileOnly 'ch.qos.logback:logback-core' + testImplementation testFixtures(project(':application-core')) testImplementation libs.logstash.logback.encoder testImplementation 'ch.qos.logback:logback-classic' testRuntimeOnly 'org.yaml:snakeyaml' diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java index 0ab521c2..29980a6c 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java @@ -33,6 +33,16 @@ import java.util.Map; * whose schema file was edited without its hash fails startup instead of stamping every event with * a hash of a schema that no longer exists. * + *

      A contribution must also name this encoder's serializer, {@link #SERIALIZER_ID}. The id only + * feeds the catalog revision today, and two spellings for one serializer meant two revisions for + * the same encoding; an unknown id now fails startup instead. + * + *

      Refusals of a draft come in two kinds. {@link IllegalStateException} means the server was + * assembled wrong — the contract is not registered, the draft names another destination, or its + * payload is not the contract's record — and no change to the request can fix it, so the transports + * report 500 and log it. {@link IllegalArgumentException} means this event cannot be encoded as + * given: a size bound, a non-canonical value. + * *

      What this encoder does not do is validate the payload against its JSON Schema. The record type * is the contract the application compiles against, and the schema file is its published * description; a service that wants the two cross-checked on every event supplies its own encoder @@ -52,6 +62,9 @@ public final class JsonIntegrationEventEncoder implements IntegrationEventEncode /** The media type of every envelope this encoder writes. */ public static final String CONTENT_TYPE = "application/json"; + /** The serializer id every contract this encoder accepts declares. */ + public static final String SERIALIZER_ID = "json-envelope-v1"; + private static final int ENVELOPE_VERSION = 1; private static final byte[] SCHEMA_SET_DOMAIN = utf8("ca-skeleton.messaging.schema-set.v1"); private static final byte[] CATALOG_DOMAIN = utf8("ca-skeleton.messaging.contract-catalog.v1"); @@ -98,11 +111,11 @@ public final class JsonIntegrationEventEncoder implements IntegrationEventEncode String key = key(draft.contractId().value(), draft.payloadVersion()); Entry entry = entries.get(key); if (entry == null) { - throw new IllegalArgumentException("no integration event contract is registered for " + key); + throw new IllegalStateException("no integration event contract is registered for " + key); } ContractDescriptor descriptor = entry.contribution().descriptor(); if (!draft.destinationId().equals(descriptor.logicalDestination())) { - throw new IllegalArgumentException( + throw new IllegalStateException( "draft destination " + draft.destinationId().value() + " is not the destination contract " @@ -111,7 +124,7 @@ public final class JsonIntegrationEventEncoder implements IntegrationEventEncode } IntegrationPayload payload = draft.featurePayload(); if (payload.getClass() != entry.contribution().exactPayloadRecordType()) { - throw new IllegalArgumentException( + throw new IllegalStateException( "draft payload must be exactly " + entry.contribution().exactPayloadRecordType()); } @@ -181,6 +194,14 @@ public final class JsonIntegrationEventEncoder implements IntegrationEventEncode || contribution.payloadSchemaHash() == null) { throw new IllegalArgumentException(key + " needs a descriptor and a payload schema identity"); } + if (!SERIALIZER_ID.equals(contribution.descriptor().serializerId())) { + throw new IllegalArgumentException( + key + + " declares serializer " + + contribution.descriptor().serializerId() + + " but this encoder is " + + SERIALIZER_ID); + } Sha256 onClasspath = resourceHash(type.getClassLoader(), contribution.payloadSchemaResource().value()); if (!onClasspath.equals(contribution.payloadSchemaHash())) { diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessor.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessor.java index 302842c0..ce12415b 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessor.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessor.java @@ -2,13 +2,20 @@ package dev.caskeleton.adapter.outbound.support.startup; import java.io.IOException; import java.io.UncheckedIOException; +import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; import org.springframework.boot.EnvironmentPostProcessor; import org.springframework.boot.SpringApplication; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.EnumerablePropertySource; +import org.springframework.core.env.PropertySource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; @@ -25,6 +32,9 @@ import org.springframework.core.io.support.PathMatchingResourcePatternResolver; * hyphenated property trees an environment variable cannot reach directly. Runs straight after * config data ({@link StartupOrder#MODULE_DEFAULTS}) so the readiness contributions and startup * validators that read a module's switch see the value the module ships. + * + *

      Two module files with the same name, or two files shipping the same key, stop startup: the + * value one of them would silently lose to the other is a conflict between modules, not a default. */ public final class ModuleDefaultsEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { @@ -39,15 +49,48 @@ public final class ModuleDefaultsEnvironmentPostProcessor Resource[] defaults = new PathMatchingResourcePatternResolver(application.getClassLoader()) .getResources(LOCATION); - // Sorted so two modules that ever disagreed would disagree the same way on every host. + // Sorted so the order is the same on every host. Order no longer decides anything: two files + // with one name, or two files shipping one key, stop startup below (review 05-23d), because + // which module's value won would otherwise depend on that sort. Arrays.sort(defaults, Comparator.comparing(Resource::getFilename)); YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + Map fileByName = new HashMap<>(); + Map fileByKey = new TreeMap<>(); + List> loaded = new ArrayList<>(); for (Resource resource : defaults) { - loader - .load( - "module-defaults (config/module-defaults/" + resource.getFilename() + ")", resource) - .forEach(environment.getPropertySources()::addLast); + String file = resource.getFilename(); + String sameName = fileByName.putIfAbsent(file, resource.getDescription()); + if (sameName != null) { + throw StartupFailures.envValidation( + "two capability modules ship config/module-defaults/" + + file + + " (" + + sameName + + " and " + + resource.getDescription() + + "); rename one, a module's defaults file is named after the module"); + } + for (PropertySource source : + loader.load("module-defaults (config/module-defaults/" + file + ")", resource)) { + if (source instanceof EnumerablePropertySource enumerable) { + for (String key : enumerable.getPropertyNames()) { + String other = fileByKey.putIfAbsent(key, file); + if (other != null && !other.equals(file)) { + throw StartupFailures.envValidation( + "config/module-defaults/" + + other + + " and config/module-defaults/" + + file + + " both ship " + + key + + "; one module owns a key, the other must not repeat it"); + } + } + } + loaded.add(source); + } } + loaded.forEach(environment.getPropertySources()::addLast); } catch (IOException failure) { throw new UncheckedIOException("failed to read " + LOCATION, failure); } diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupOrder.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupOrder.java index 2babe663..08ca1646 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupOrder.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupOrder.java @@ -50,8 +50,11 @@ public final class StartupOrder { public static final int RUNTIME_ENVIRONMENT_PROFILE = Ordered.LOWEST_PRECEDENCE - 1; /** - * Tracing sample-rate defaulting. Runs after every rule that can refuse the boot outright — there - * is no value in defaulting a sample rate for a process that is about to exit. + * Tracing key translation ({@code TracingEnvironmentPostProcessor}): {@code app.tracing.*} into + * the Boot keys its tracing auto-configuration reads — the resolved sample rate and the OTLP + * export endpoint. Named for both since 07-01, when it stopped being only sample-rate defaulting. + * Runs after every rule that can refuse the boot outright: there is no value in translating + * tracing keys for a process that is about to exit. */ - public static final int TRACING_SAMPLING = Ordered.LOWEST_PRECEDENCE; + public static final int TRACING_PROPERTIES = Ordered.LOWEST_PRECEDENCE; } diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java index ce6087ea..b19930be 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java @@ -9,14 +9,18 @@ import org.springframework.core.env.Environment; *

      A rule only finds violations; it never throws and never decides when it runs. The {@link * StartupRuleRunner} runs every rule a module contributed — each is a bean — once, before any other * singleton is created, and raises the violations of a rule as the typed startup failure of its - * {@link #phase()}. Declare a rule with a {@code static} {@code @Bean} method and no parameters, so - * running it early pulls nothing else forward. Before this, sixteen validators across the - * composition root and the JPA module each implemented {@code SmartInitializingSingleton}, opened - * their own validation context and chose their own way to throw; the rule a module adds is now a - * list of messages and nothing else. + * {@link #phase()}. Declare a rule with a {@code static} {@code @Bean} method that takes nothing + * but what is listed below, so running it early pulls nothing else forward. Before this, sixteen + * validators across the composition root and the JPA module each implemented {@code + * SmartInitializingSingleton}, opened their own validation context and chose their own way to + * throw; the rule a module adds is now a list of messages and nothing else. * - *

      A check that needs a bean other than the environment — a secret source, the datasource, the - * bean factory — is not a rule and stays a bean of its own. + *

      A rule may take two things besides the environment, both without creating anything early: the + * bean factory, to ask about bean definitions (a name, a type) and never to get a bean; + * and an {@code ObjectProvider} of beans that are themselves declared {@code static} with no + * dependencies, read only when the rule runs (the secret guard reads each module's {@code + * RequiredProductionSecrets} this way). A check that needs a live connection — the datasource + * version check — is not a rule; it stays a bean and is ordered before what it protects. */ public interface StartupRule { diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderContractTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderContractTest.java new file mode 100644 index 00000000..5b6de448 --- /dev/null +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderContractTest.java @@ -0,0 +1,15 @@ +package dev.caskeleton.adapter.outbound.support.messaging; + +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; +import dev.caskeleton.application.messaging.event.testkit.IntegrationEventEncoderContract; +import java.util.Collection; + +class JsonIntegrationEventEncoderContractTest extends IntegrationEventEncoderContract { + + @Override + protected IntegrationEventEncoderPort encoderKnowing( + Collection> contracts) { + return new JsonIntegrationEventEncoder(contracts); + } +} diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java index 6ccbe394..7c193bb6 100644 --- a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java @@ -158,7 +158,7 @@ class JsonIntegrationEventEncoderTest { // then assertThat(thrown) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(IllegalStateException.class) .hasMessage("no integration event contract is registered for testkit.encoder-sample:v1"); } @@ -169,10 +169,41 @@ class JsonIntegrationEventEncoderTest { // then assertThat(thrown) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(IllegalStateException.class) .hasMessageContaining("draft destination other-events is not the destination"); } + @Test + void aContractNamingAnotherSerializerFailsConstruction() { + // given + ContractDescriptor otherSerializer = + new ContractDescriptor( + "adapter-outbound-support", + DESTINATION, + "json-schema-envelope-v1", + true, + 4096, + 8192, + ContractDescriptor.SensitivityClassification.INTERNAL, + Duration.ofDays(1)); + TestContribution contribution = + new TestContribution<>( + SamplePayload.class, + List.of("name", "count", "tags", "note"), + schemaHash(), + otherSerializer); + + // when + Throwable thrown = catchThrowable(() -> new JsonIntegrationEventEncoder(List.of(contribution))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "testkit.encoder-sample:v1 declares serializer json-schema-envelope-v1 but this" + + " encoder is json-envelope-v1"); + } + @Test void aPayloadLargerThanTheDeclaredBoundIsRefused() { // given diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessorTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessorTest.java index 543ef4c5..988aabcf 100644 --- a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessorTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessorTest.java @@ -1,12 +1,22 @@ package dev.caskeleton.adapter.outbound.support.startup; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Map; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.SpringApplication; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.DefaultResourceLoader; /** A module's shipped file is found by location, and a deployment's value always beats it. */ class ModuleDefaultsEnvironmentPostProcessorTest { @@ -34,6 +44,56 @@ class ModuleDefaultsEnvironmentPostProcessorTest { .startsWith("module-defaults"); } + @Test + @DisplayName("두 모듈 파일이 같은 키를 실으면 어느 쪽이 이기는지 정하지 않고 기동을 멈춘다") + void twoModuleFilesShippingTheSameKeyStopStartupNamingBothFiles(@TempDir Path root) + throws IOException { + // given + Path first = moduleFile(root.resolve("first"), "alpha.yml", "shared:\n key: one\n"); + Path second = moduleFile(root.resolve("second"), "beta.yml", "shared:\n key: two\n"); + + // when + Throwable thrown = catchThrowable(() -> processedFrom(first, second)); + + // then + assertThat(thrown) + .isInstanceOf(StartupFailureException.class) + .hasMessageContainingAll("shared.key", "alpha.yml", "beta.yml"); + } + + @Test + @DisplayName("두 모듈이 같은 이름의 파일을 실으면 기동을 멈춘다") + void twoModulesShippingTheSameFileNameStopStartup(@TempDir Path root) throws IOException { + // given + Path first = moduleFile(root.resolve("first"), "same.yml", "first:\n key: one\n"); + Path second = moduleFile(root.resolve("second"), "same.yml", "second:\n key: two\n"); + + // when + Throwable thrown = catchThrowable(() -> processedFrom(first, second)); + + // then + assertThat(thrown).isInstanceOf(StartupFailureException.class).hasMessageContaining("same.yml"); + } + + private static Path moduleFile(Path classpathRoot, String name, String yaml) throws IOException { + Path directory = Files.createDirectories(classpathRoot.resolve("config/module-defaults")); + Files.writeString(directory.resolve(name), yaml); + return classpathRoot; + } + + private static StandardEnvironment processedFrom(Path... classpathRoots) + throws MalformedURLException { + URL[] urls = new URL[classpathRoots.length]; + for (int index = 0; index < classpathRoots.length; index++) { + urls[index] = classpathRoots[index].toUri().toURL(); + } + SpringApplication application = new SpringApplication(); + application.setResourceLoader(new DefaultResourceLoader(new URLClassLoader(urls, null))); + StandardEnvironment environment = new StandardEnvironment(); + new ModuleDefaultsEnvironmentPostProcessor().postProcessEnvironment(environment, application); + return environment; + } + private static StandardEnvironment processed(Map deployment) { StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("deployment", deployment)); diff --git a/src/app-bootstrap/CLAUDE.md b/src/app-bootstrap/CLAUDE.md index 99057767..98ba21c7 100644 --- a/src/app-bootstrap/CLAUDE.md +++ b/src/app-bootstrap/CLAUDE.md @@ -62,17 +62,20 @@ configurations, Redis as one 376-line class. switch registry, no cross-capability dependency validator, no activation endpoint. Component scan covers `dev.caskeleton.bootstrap` only; web (`WebAdapterAutoConfiguration`, `WebSecurityAutoConfiguration`, `WebMethodSecurityAutoConfiguration`) 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: `operation` (the durable - operation use cases and their `/operations` endpoints, on only when the operation store and the - outbox append port exist), `common`. The outbox relay and the idempotency executor are - `composition:outbox-relay` and `composition:idempotency`, selected by one `runtimeOnly` line each - (the sample takes the idempotency one too). The runtime wiring both composition roots need — + composition every application needs: `common` (the clock). The outbox relay, the idempotency + executor and the durable operations (use cases and `/operations` endpoints, 07-08) are + `composition:outbox-relay`, `composition:idempotency` and `composition:durable-operation`, selected + by one `runtimeOnly` line each and building nothing until their ports exist (the sample takes the + idempotency one too). A capability's role→permission mapping ships in its own + `config/module-defaults` file, not in `config/security.yml`. The runtime wiring both composition roots need — tracing, the metrics contract filters, domain-context propagation, user-principal pseudonymization (`PrivacySettings`) and the actuator chain — is `composition:service-runtime`, which the sample takes by the same line instead of carrying copies. - **`Settings` lives beside its capability**, not in `settings/`. The `settings/` package - holds only settings that belong to no capability — `BootstrapSettings`, `LoggingSettings`, - `RuntimeSafetySettings`. + holds only settings that belong to no capability — `BootstrapSettings`, `RuntimeSafetySettings` — + bound strictly with `StrictSettingsBinder`, never scanned. Logging has no settings record: + `logback-spring.xml` reads `app.logging.*` itself and `LoggingConfigurationRule` refuses values + Logback cannot use. - **`runtime/` holds guards about the application itself** — secrets, numeric bounds, error-detail exposure, multi-instance coordination, the runtime-profile check (`RuntimeEnvironmentProfileValidator`). A guard about a capability's settings (the JPA OSIV/DDL/pool/TLS/vendor guards, the Mongo diff --git a/src/app-bootstrap/README.md b/src/app-bootstrap/README.md index 62be2607..8962338a 100644 --- a/src/app-bootstrap/README.md +++ b/src/app-bootstrap/README.md @@ -131,11 +131,12 @@ README의 "startup" 절에 있다. `prod_default: null`로 분류된 모든 키는 prod 에서 비어 있지 않게 주입돼야 한다 — 빈 시크릿으로 부팅하는 것은 금지다. dev/local 프로파일은 두 검사를 건너뛴다(`__LOCAL_DEV_*`가 의도된 로컬 폴백이므로). -- **`SmartInitializingSingleton` 타이밍을 의도적으로 받아들였다.** 이 콜백은 모든 싱글톤 생성 *후* - context refresh 완료 *전*에 한 번 실행된다. 따라서 eager `DataSource`가 이 가드보다 먼저 - `__LOCAL_DEV_` 자격증명으로 연결을 시도할 가능성은 있다. 그러나 prod 에서 `__LOCAL_DEV_` 값에 - 도달하는 것 자체가 예외적 오적재이고, 트래픽을 받기 전에 context 가 중단되므로 이 타이밍으로 - 충분하다고 판단했다. 더 이른 차단이 필요해지면 `EnvironmentPostProcessor`로 승격한다. +- **다른 싱글톤을 만들기 전에 판정한다(`StartupRule`, 07-02).** 예전에는 `SmartInitializingSingleton` + 이라 모든 싱글톤 생성 *후*에 돌았다. 그래서 비밀값이 빠진 prod 배포도 DataSource가 연결을 열고 + Flyway가 마이그레이션한 *뒤*에야 거부됐다. 지금은 support의 `StartupRuleRunner`가 bean factory + post-processor 단계에서 부른다. 이를 위해 `SecretSourcePort` bean을 받지 않고 같은 선택 규칙 + (`SecretSourceFactory.fromEnvironment`)으로 백엔드를 직접 만든다. 모듈 기여(`RequiredProductionSecrets`)는 + 규칙이 돌 때 읽으므로, 기여하는 bean은 `static` `@Bean`으로 선언한다(설정 클래스를 일찍 만들지 않게). - **필수 시크릿 검사는 Spring 환경이 아니라 `SecretSource` 백엔드를 통해 한다.** 존재 검사를 백엔드(`secretSource.resolve(key)`) 경유로 하기 때문에, env → Vault/AWS 백엔드 교체 시에도 검사가 자동으로 따라간다. 검사를 Spring `Environment`에 고정했다면 백엔드를 바꿀 때 검증 로직이 함께 @@ -158,10 +159,12 @@ README의 "startup" 절에 있다. persistence-jpa의 datasource·Flyway·OSIV·TLS·vendor·Hikari 검사)는 `StartupRule`이다: 위반 목록만 돌려주고, `adapter:outbound:support`의 `StartupRuleRunner` 하나가 다른 싱글톤을 만들기 전에(bean factory post-processor 단계) 규칙마다 그 phase의 종료 코드로 실패시킨다. 그래서 prod 금지 값은 DataSource가 -연결을 열거나 Flyway가 마이그레이션하기 전에 거부된다. 규칙은 그만큼 일찍 만들어지므로 매개변수 없는 -`static` `@Bean` 메서드로 선언한다. 다른 bean이 필요한 검사(`SecretSourceValidator`의 `SecretSourcePort`, -`StartupSafetyValidator`의 bean factory, persistence-jpa의 datasource 검사)는 계속 bean이고, 부팅 전에 -돌아야 하는 profile 규칙(`RuntimeEnvironmentProfileValidator`)은 `EnvironmentPostProcessor`로 남는다. +연결을 열거나 Flyway가 마이그레이션하기 전에 거부된다. 규칙은 그만큼 일찍 만들어지므로 `static` `@Bean` 메서드로 선언한다. 같은 단계에서 도는 것은 이제 셋이 더 있다. +`SecretSourceValidator`(모듈이 기여한 비밀값 이름을 규칙이 돌 때 읽는다), `StartupSafetyValidator`(bean +*정의*만 보고 bean은 만들지 않는다), `LoggingConfigurationRule`(Logback이 쓸 수 없는 `app.logging.*` 값). +DB 연결이 꼭 필요한 persistence-jpa의 datasource 버전 검사는 bean으로 남되, 모든 Flyway initializer가 +그 검사에 `dependsOn` 하도록 묶어 마이그레이션보다 먼저 돈다. 부팅 전에 돌아야 하는 profile 규칙 +(`RuntimeEnvironmentProfileValidator`)은 `EnvironmentPostProcessor`로 남는다. 관계형 설정 가드(`HikariPoolConstraintValidator`, `OpenInViewSafetyValidator`, `JpaDangerousConfigurationGuard`, `PostgreSqlTransportSecurityValidator`, @@ -182,11 +185,11 @@ post-processor 단계) 규칙마다 그 phase의 종료 코드로 실패시킨 금지"). ### StartupSafetyValidator -- **`SmartInitializingSingleton` 타이밍을 고른 이유가 핵심이다.** 검사는 모든 싱글톤 생성 후 context - refresh 완료 전에 한 번 돈다. `EnvironmentPostProcessor`는 bean 정의가 생기기 전에 실행돼 bean - *존재 여부*(multi-instance 검사에 필요)를 검사할 수 없고, `ApplicationReadyEvent` 리스너는 트래픽 - 직전에야 발동해 잘못된 부팅을 거부하기엔 너무 늦다. 그래서 이 중간 타이밍을 택했고, 위반 시 - throw 하여 context 가 시작을 거부한다. +- **bean 정의가 다 모인 뒤, 싱글톤을 만들기 전에 판정한다(`StartupRule`, 07-02).** `EnvironmentPostProcessor`는 + bean 정의가 생기기 전이라 bean *존재 여부*를 볼 수 없다. 예전의 `SmartInitializingSingleton`은 모든 + 싱글톤 생성 후라, lock 없는 multi-instance 배포가 저장소에 연결하고 마이그레이션한 뒤에야 거부됐다. + bean factory post-processor 단계는 둘 사이다: 이름·타입 검사(`containsBean`, `isTypeMatch`)는 정의만으로 + 답하므로 아무 bean도 만들지 않는다. - **prod 에러 상세 노출은 `ErrorDetailExposureSafetyValidator`가 막는다(이 클래스가 아니다).** prod에서 `spring.web.error.include-stacktrace`·`include-message`·`include-binding-errors`가 `never`가 아니거나 `include-exception=true`면 PROFILE_MISMATCH(exit 71)로 부팅을 중단한다. env override로 들어온 값도 @@ -362,26 +365,29 @@ relay 조립(`OutboxRelayAutoConfiguration`, 스케줄러·metrics·leader token ## settings — @ConfigurationProperties 검증 정책 -이 모듈의 설정 record 들은 대체로 두 가지 검증 전략 중 하나를 고른다: **fail-fast**(잘못되면 기동 +이 모듈의 설정 record(`BootstrapSettings`, `RuntimeSafetySettings`, `AsyncExecutorSettings`, +`SecretSourceSettings`)는 모듈들과 같이 `StrictSettingsBinder`로 묶는다: prefix 아래 모르는 키는 기본값으로 +조용히 넘어가지 않고 기동을 실패시킨다(07-10). 그래서 `@ConfigurationPropertiesScan`은 쓰지 않는다. +설정 record 들은 대체로 두 가지 검증 전략 중 하나를 고른다: **fail-fast**(잘못되면 기동 중단)와 **warn-and-default**(경고만 남기고 안전한 기본값으로 진행). 어느 쪽을 쓰는지가 각 record 의 핵심 결정이다. ### BootstrapSettings - **`appName`은 비어 있으면 시작을 실패시킨다(fail-fast).** `app.bootstrap.*` 바인딩이며, 앱 이름은 운영자가 직접 제공해야 하고 합리적인 기본값이 존재하지 않으므로, 비어 있거나 blank 면 - `@NotBlank`로 막는다(Spring Boot 가 `BindValidationException`을 띄우고 컨텍스트 기동을 거부). + compact constructor가 ENV_VALIDATION으로 막는다. 다른 settings 의 "warn-and-default"와 달리 여기서 fail-fast 를 택한 이유는, 잘못된 앱 이름으로 조용히 기동되는 것보다 즉시 멈추는 편이 안전하기 때문이다. -### LoggingSettings -- **모든 항목이 "warn-and-default" 정책이다.** `app.logging.*` 바인딩(원천은 .env). 잘못된 - 값은 경고 로그를 남기고 안전한 기본값으로 진행할 뿐 시작을 실패시키지 않는다. -- **fail-fast 대신 warn-and-default 를 택한 이유.** Logback 은 이 record 가 바인딩되기 전에 자기 - 초기화 단계에서 `` 바인딩으로 이미 같은 값들을 자체 기본값과 함께 소비했다. 따라서 - 이 record 의 역할은 로깅을 다시 강제하는 것이 아니라, 입력이 잘못됐을 때 운영자에게 명확한 경고를 - 표면화하는 것이다. -- **size 문자열(`maxSize`, `totalSizeCap`)은 검증하지 않는다.** 이 값들의 파싱 계약은 logback 이 - 소유하므로 logback 에게 맡긴다. +### 로깅 설정 (`app.logging.*`) +- **읽는 곳은 `logback-spring.xml` 하나다.** ``로 Spring + Environment를 읽으므로 env(`APP_LOG_*`, `config/observability.yml`이 매핑), profile 파일, 명령행 인자가 모두 + 같은 길로 들어간다. 예전에는 env 이름을 직접 읽어 `app.logging.*`를 yml로 바꿔도 반영되지 않았고, + `LoggingSettings`가 같은 키를 따로 바인딩해 Logback이 쓰지 않는 대체값을 경고했다(07-06). 그 record는 지웠다. +- **Logback이 쓸 수 없는 값은 기동을 멈춘다.** `LoggingConfigurationRule`(`StartupRule`)이 파일 경로 공백, + 보관 일수·큐 크기 하한, 시간대, 샘플링 비율 범위를 env 키 이름으로 보고한다. size 문자열은 Logback이 파싱한다. +- **한계:** Logback은 `src/.env`가 환경에 들어오기 전에 초기화된다(dotenv run listener가 Boot의 이벤트 + 발행보다 늦다). `.env`에만 있는 로깅 값은 반영되지 않으므로 export하거나 프로세스에 넘긴다. 예전 방식도 같았다. ### RuntimeSafetySettings - **시작 시 `StartupSafetyValidator`가 강제하는 운영 안전 설정이다.** 현재 구현된 runtime @@ -427,6 +433,15 @@ app-bootstrap 은 합성 루트라 "왜 이 의존성이, 왜 이 scope 로" 결 로그 인코더는 런타임에만 있으면 되지만, `StartupFailures`가 `StructuredArguments`를 **compile time**에 호출해 `startup.phase`/`error.code`/`error.category` JSON 필드를 방출하므로 compile classpath 에 있어야 한다. +- **기본 jar에 Jackson 2와 3이 함께 실린다 — 의도한 것이다(09-11).** 애플리케이션 JSON은 Boot 4의 + Jackson 3이다. Jackson 2(`jackson-databind`·`jackson-core`·`jackson-dataformat-yaml`· + `jackson-datatype-jsr310` 2.21.x)는 두 의존성이 요구한다: `logstash-logback-encoder` 8.0(JSON 로그)과 + web 어댑터의 springdoc → `swagger-core-jakarta`(OpenAPI 문서). 둘 다 Jackson 3 판이 없어 뺄 수 없다 + (`./gradlew :app-bootstrap:dependencyInsight --configuration productionRuntimeClasspath --dependency + com.fasterxml.jackson.core:jackson-databind`로 확인). 그래서 보안 패치는 두 계열을 따로 본다. +- **OTLP exporter는 JDK HttpClient sender를 쓴다(09-11).** 기본 sender(`opentelemetry-exporter-sender-okhttp`)는 + okhttp·okio·kotlin-stdlib(약 3 MB)를 모든 이미지에 실었다. `composition:service-runtime`이 그 sender를 + 빼고 `opentelemetry-exporter-sender-jdk`를 싣는다. export 동작은 `TracingExportSystemTest`가 확인한다. ### 테스트 의존성 (transitive 로 안 새서 명시 선언) - **`testImplementation project(':adapter-persistence-postgresql')`** — vendor 클래스 diff --git a/src/app-bootstrap/build.gradle b/src/app-bootstrap/build.gradle index 2a0a7309..8b312763 100644 --- a/src/app-bootstrap/build.gradle +++ b/src/app-bootstrap/build.gradle @@ -66,7 +66,6 @@ strictTestLanes { description = 'Runs the whole-repository ArchUnit and architecture contract source set.' sourceSet = 'architectureTest' maxHeapSize = '2g' - jvmArgs '-Duser.timezone=UTC' shouldRunAfter 'test' } lane('systemTest') { @@ -74,7 +73,6 @@ strictTestLanes { description = 'Runs full-application startup and shipped-profile characterization tests.' sourceSet = 'systemTest' maxHeapSize = '1g' - jvmArgs '-Duser.timezone=UTC' shouldRunAfter 'test' } lane('conditionalTransportBuildContractTest') { @@ -82,7 +80,6 @@ strictTestLanes { sourceSet = 'conditionalTransportBuildContractTest' requires 'dev.caskeleton.bootstrap.transport.ConditionalTransportBuildContractTest' rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' shouldRunAfter 'test' } } @@ -170,10 +167,11 @@ dependencies { // runtimeOnly project(':composition:fileserver-platform') // 파일 서버 // runtimeOnly project(':composition:notification-platform') // 알림 (persistence-jpa·persistence-notification을 함께 가져온다) - // 기본 조립에 있는 application composition. 둘 다 포트만 보고, 필요한 것(outbox store, 멱등성 + // 기본 조립에 있는 application composition. 셋 다 포트만 보고, 필요한 것(outbox store, 멱등성 // provider)이 없으면 아무것도 만들지 않는다. sample-portfolio도 같은 멱등성 모듈을 쓴다. runtimeOnly project(':composition:outbox-relay') // outbox relay (store·발행 포트가 있을 때만) runtimeOnly project(':composition:idempotency') // 요청 멱등성 executor (provider≠disabled) + runtimeOnly project(':composition:durable-operation') // /operations (operation store·outbox가 있을 때만) // 모든 서비스가 받는 runtime 배선: tracing, metrics 계약 filter, domain context, user principal // 가명화, actuator 보안 chain. sample-portfolio도 같은 줄을 쓴다. runtimeOnly project(':composition:service-runtime') @@ -202,6 +200,8 @@ 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'))) + // A feature's composition test registers the domain ports' fakes (scripts/new-feature.sh). + testImplementation(testFixtures(project(':domain-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 @@ -313,24 +313,97 @@ dependencies { conditionalTransportBuildContractTestRuntimeOnly 'org.junit.platform:junit-platform-launcher' } -// The contract tests here read the repository itself — docs/registries and docs/runbooks, the -// module registry and the rest of src/config, build scripts, Dockerfiles, Compose files, workflows, -// src/.env.example, the root guidance documents. Every one of those is an input, or Gradle calls -// the lane up to date after exactly the edit the test exists to catch. +// Tests that read the repository itself — registries, runbooks, guidance documents, build scripts, +// workflows, Compose files, other leaves' sources — run in two tagged lanes, and only those lanes +// receive the repository root (`ca.repository.root`) and declare what they read as inputs. The plain +// `test` lane gets neither: a repository-reading test left untagged fails there for want of a root +// instead of turning `test` into a task that every document edit invalidates (review 2026-11-01 +// 08-03; the inputs are what keeps O-4a's "the lane reruns when a file it reads changes"). +// +// documentContractTest tag document-contract main stage docs/**, the guidance documents, +// and the files the same classes +// cross-check them with +// repositoryContractTest tag repository-contract pull request build, configuration, workflow and +// Compose files and leaf sources; +// no document, so a docs/** edit +// leaves it up to date +// +// The pull-request lane exists because some of those contracts are release and security +// properties — the signing job's OIDC scope, the Docker staging contract, the request-logging body +// capture ban — that must stop a merge, not be found after one. def repositoryRootForContractTests = rootProject.projectDir.parentFile +def repositoryContractExcludes = ['**/build/**', '**/.gradle/**', '**/node_modules/**'] def repositoryContractInputs = files( fileTree(repositoryRootForContractTests) { - include 'docs/**', '.github/**', 'infra/**', 'scripts/**', '*.md', '*.yml', '*.example' + include '.github/**', 'infra/**', 'scripts/**', '*.yml', '*.example', '.tool-versions' + exclude '**/*.md' + exclude repositoryContractExcludes }, fileTree(rootProject.projectDir) { - include 'config/**', '**/*.gradle', 'gradle/*.toml', 'Dockerfile*', '.env*', '**/*.md' - exclude '**/build/**', '**/.gradle/**' + include 'config/**', '**/*.gradle', 'gradle/*.toml', 'Dockerfile*', '.env*', '**/src/main/**' + // SampleRuntimeDefaultsContractTest compares the sample's runtime defaults with these. + include 'sample-portfolio/src/main/resources/application.yml' + exclude '**/*.md' + exclude repositoryContractExcludes }) -tasks.withType(Test).configureEach { - systemProperty 'ca.repository.root', repositoryRootForContractTests.absolutePath - inputs.files(repositoryContractInputs) - .withPathSensitivity(PathSensitivity.RELATIVE) - .withPropertyName('repositoryContractInputs') +def documentContractInputs = files( + repositoryContractInputs, + fileTree(repositoryRootForContractTests) { + include 'docs/**', '*.md', '.github/**/*.md' + }, + fileTree(rootProject.projectDir) { + include '**/*.md' + exclude repositoryContractExcludes + }) +strictTestLanes { + lane('documentContractTest') { + tag = 'document-contract' + description = 'Holds the composition to the repository documents and registries it promises.' + rejectSkipped = true + mainStage() + systemProperty 'ca.repository.root', repositoryRootForContractTests.absolutePath + customize { Test task -> + task.inputs.files(documentContractInputs) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName('documentContractInputs') + } + } + lane('repositoryContractTest') { + tag = 'repository-contract' + description = 'Holds the composition to the build, configuration and workflow files it does not own.' + systemProperty 'ca.repository.root', repositoryRootForContractTests.absolutePath + customize { Test task -> + task.inputs.files(repositoryContractInputs) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName('repositoryContractInputs') + } + } +} +tasks.named('test', Test) { + useJUnitPlatform { excludeTags 'repository-contract' } +} +tasks.named('check') { + dependsOn 'repositoryContractTest' +} + +// The other suites find the repository themselves and read what Gradle cannot otherwise see: the +// architecture suite scans every leaf's production sources and its own rule sources as text, the +// opt-in classpath contract reads this build script, and the Compose characterization reads the +// Compose files. +tasks.named('architectureTest', Test) { + inputs.files(fileTree(rootProject.projectDir) { + include '**/src/main/java/**/*.java', 'app-bootstrap/src/architectureTest/java/**' + exclude repositoryContractExcludes + }).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('scannedSources') +} +tasks.named('conditionalTransportBuildContractTest', Test) { + inputs.file('build.gradle').withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('buildScript') +} +tasks.named('integrationTest', Test) { + inputs.files(fileTree(repositoryRootForContractTests) { + include '*.yml', 'infra/**' + exclude repositoryContractExcludes + }).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('composeFiles') } // Fast developer test lane. Whole-repository ArchUnit graphs and full composition-root boot @@ -340,9 +413,6 @@ tasks.named('test', Test) { // Two forks are the measured sweet spot after moving whole-repository ArchUnit and full boot // composition tests out of the fast lane. More forks duplicate Spring contexts for little gain. maxParallelForks = 2 - // Pin UTC for the TEST JVM so timestamp tests are host-locale-independent (production UTC is - // owned elsewhere). - jvmArgs '-Duser.timezone=UTC' } @@ -449,6 +519,9 @@ tasks.register('stageQualificationDockerJar', Sync) { def h2RunClasspath = compositionRuntimeClasspath('bootRunH2Classpath') dependencies { bootRunH2Classpath project(':adapter:outbound:persistence-jpa') + // The driver is not a runtime dependency of persistence-jpa (review 09-09), so the task that + // chose H2 brings it. + bootRunH2Classpath 'com.h2database:h2' } tasks.register('bootRunH2', org.springframework.boot.gradle.tasks.run.BootRun) { group = 'application' diff --git a/src/app-bootstrap/gradle.lockfile b/src/app-bootstrap/gradle.lockfile index 6a5c4975..d1f49c14 100644 --- a/src/app-bootstrap/gradle.lockfile +++ b/src/app-bootstrap/gradle.lockfile @@ -20,7 +20,7 @@ com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,architectureTes com.github.docker-java:docker-java-api:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath com.github.docker-java:docker-java-transport-zerodep:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath com.github.docker-java:docker-java-transport:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath -com.github.f4b6a3:uuid-creator:6.1.1=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +com.github.f4b6a3:uuid-creator:6.1.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor com.github.luben:zstd-jni:1.5.6-10=architectureTestRuntimeClasspath,qualificationRuntimeClasspath com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs @@ -54,7 +54,7 @@ com.google.protobuf:protobuf-java:3.25.5=architectureTestRuntimeClasspath,condit com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor com.graphql-java:graphql-java:25.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath com.graphql-java:java-dataloader:6.0.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath -com.h2database:h2:2.4.240=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +com.h2database:h2:2.4.240=bootRunH2Classpath com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath com.networknt:json-schema-validator:3.0.2=architectureTestRuntimeClasspath,qualificationRuntimeClasspath @@ -63,10 +63,6 @@ com.nimbusds:lang-tag:1.7=architectureTestRuntimeClasspath,qualificationRuntimeC com.nimbusds:nimbus-jose-jwt:10.4=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath com.nimbusds:oauth2-oidc-sdk:11.26.1=architectureTestRuntimeClasspath,qualificationRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.squareup.okhttp3:okhttp-jvm:5.2.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.squareup.okhttp3:okhttp:5.2.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.squareup.okio:okio-jvm:3.16.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.squareup.okio:okio:3.16.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath com.sun.istack:istack-commons-runtime:4.1.2=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath com.tngtech.archunit:archunit-junit5-api:1.3.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath com.tngtech.archunit:archunit-junit5-engine-api:1.3.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath @@ -134,7 +130,7 @@ io.opentelemetry:opentelemetry-context:1.55.0=architectureTestCompileClasspath,a io.opentelemetry:opentelemetry-exporter-common:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-exporter-otlp-common:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-exporter-sender-okhttp:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-sender-jdk:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-sdk-common:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath @@ -230,8 +226,6 @@ org.hibernate.validator:hibernate-validator:9.0.1.Final=architectureTestCompileC org.javassist:javassist:3.28.0-GA=checkstyle org.javassist:javassist:3.29.0-GA=architectureTestRuntimeClasspath,qualificationRuntimeClasspath org.jboss.logging:jboss-logging:3.6.3.Final=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib:2.2.21=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.jetbrains:annotations:13.0=bootRunH2Classpath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath org.jetbrains:annotations:17.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,architectureTestAnnotationProcessor,architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,checkstyle,compileClasspath,conditionalTransportBuildContractTestAnnotationProcessor,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestAnnotationProcessor,systemTestCompileClasspath,systemTestRuntimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java index 0aa777dd..7017eacc 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java @@ -21,6 +21,7 @@ import com.tngtech.archunit.lang.ConditionEvents; import com.tngtech.archunit.lang.SimpleConditionEvent; import dev.caskeleton.application.capability.UseCaseCapability; import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.security.SystemInvoked; import dev.caskeleton.application.usecase.CommandUseCase; import dev.caskeleton.application.usecase.QueryUseCase; import java.util.HashSet; @@ -424,6 +425,23 @@ class ApplicationBoundaryArchitectureTest { + "static-analysis blind spot (D4 limit).") .allowEmptyShould(true); + /** + * A use case only the system calls states that with {@link SystemInvoked} and declares no + * permission. Both together would be the decorative gate this marker replaces: a check that + * either never runs or refuses every scheduler tick. + */ + @ArchTest + static final ArchRule SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION = + classes() + .that() + .areAnnotatedWith(SystemInvoked.class) + .should() + .notBeAnnotatedWith(RequiresPermission.class) + .as( + "a @SystemInvoked use case declares no @RequiresPermission: the system caller has no " + + "Authentication, so the gate would be decoration") + .allowEmptyShould(true); + @ArchTest static final ArchRule APPLICATION_AND_DOMAIN_DO_NOT_DEPEND_ON_SPRING_SECURITY = noClasses() @@ -537,6 +555,9 @@ class ApplicationBoundaryArchitectureTest { if (!writeRepository) { return; } + if (item.isAnnotatedWith(SystemInvoked.class.getName())) { + return; + } if (!item.isAnnotatedWith(RequiresPermission.class.getName())) { events.add( SimpleConditionEvent.violated( 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 c673352e..fe3d5cc8 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 @@ -161,6 +161,7 @@ class ArchRuleDiscoveryContractTest { "REQUEST_DTOS_DO_NOT_SILENCE_UNKNOWN_FIELDS", "SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES", "STARTUP_FAILURES_ARE_RAISED_THROUGH_THE_TYPED_FACTORY", + "SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION", "THROWABLES_ARE_NAMED_EXCEPTION", "USE_CASE_CAPABILITY_MATCHES_TRANSACTION_PORT_BOUNDARY", "USE_CASE_PORTS_CARRY_ONE_OPERATION", diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/DomainFeatureOnboardingContractTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/DomainFeatureOnboardingContractTest.java index 6ef69a32..2f3f0138 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/DomainFeatureOnboardingContractTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/DomainFeatureOnboardingContractTest.java @@ -4,12 +4,42 @@ import static org.assertj.core.api.Assertions.assertThat; import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ClassFileImporter; +import com.tngtech.archunit.lang.ArchRule; +import com.tngtech.archunit.lang.EvaluationResult; +import dev.caskeleton.bootstrap.authz.RequiresPermissionProxyabilityTest; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -/** Contract dry-run for adding a real domain feature against the production boundaries. */ +/** + * Contract dry-run for adding a real domain feature against the production boundaries. + * + *

      The fixture under {@code dev.caskeleton.onboarding} is test code, so every production suite + * leaves it out ({@link ProductionClassImportOption}). Left there, it drifted into a shape the + * production rules reject — a {@code final} use case carrying {@code @RequiresPermission}, which + * fails startup the moment it becomes a bean. {@link + * #onboardingSliceBreaksNoProductionArchitectureRule()} closes that gap: it holds the fixture to + * every rule the production suites declare, not to a hand-picked subset. + */ class DomainFeatureOnboardingContractTest { + /** + * Every class whose {@code static final ArchRule} constants guard production code. A new suite is + * added here; a new rule in a listed suite is picked up without editing this test. + */ + private static final List> PRODUCTION_RULE_SUITES = + List.of( + DomainPurityArchitectureTest.class, + ApplicationBoundaryArchitectureTest.class, + AdapterBoundaryArchitectureTest.class, + TypeBoundaryArchitectureTest.class, + ForbiddenApiArchitectureTest.class, + NamingConventionTest.class, + RequiresPermissionProxyabilityTest.class); + private static final String ROOT = "dev.caskeleton.onboarding"; private static final JavaClasses ONBOARDING_CLASSES = @@ -68,7 +98,7 @@ class DomainFeatureOnboardingContractTest { ROOT + ".domain.feature.FeatureAggregateId", ROOT + ".domain.feature.FeatureAggregateIdFactory", ROOT + ".application.command.CreateFeatureAggregateCommand", - ROOT + ".application.port.FeatureAggregateWritePort", + ROOT + ".domain.feature.FeatureAggregateRepository", ROOT + ".application.usecase.CreateFeatureAggregateUseCase", ROOT + ".adapter.outbound.persistence.entity.FeatureAggregateEntity", ROOT + ".adapter.outbound.persistence.mapper.FeatureAggregateEntityMapper", @@ -107,6 +137,38 @@ class DomainFeatureOnboardingContractTest { .isNotNull(); } + @Test + @DisplayName("온보딩 fixture는 production 아키텍처 규칙을 하나도 어기지 않는다") + void onboardingSliceBreaksNoProductionArchitectureRule() throws IllegalAccessException { + // given + List rules = productionRules(); + + // when + List violations = new ArrayList<>(); + for (ArchRule rule : rules) { + EvaluationResult result = rule.allowEmptyShould(true).evaluate(ONBOARDING_CLASSES); + if (result.hasViolation()) { + violations.add(rule.getDescription() + System.lineSeparator() + result.getFailureReport()); + } + } + + // then + assertThat(violations).isEmpty(); + } + + private static List productionRules() throws IllegalAccessException { + List rules = new ArrayList<>(); + for (Class suite : PRODUCTION_RULE_SUITES) { + for (Field field : suite.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) && ArchRule.class.equals(field.getType())) { + field.setAccessible(true); + rules.add((ArchRule) field.get(null)); + } + } + } + return rules; + } + private static List classNames() { return ONBOARDING_CLASSES.stream().map(javaClass -> javaClass.getName()).sorted().toList(); } 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 a3456d33..d03825b7 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 @@ -55,13 +55,9 @@ class ForbiddenApiArchitectureTest { "dev.caskeleton.shared.response", "dev.caskeleton.shared.request", "dev.caskeleton.shared.error", - "dev.caskeleton.shared.operation", - "dev.caskeleton.shared.headers", "dev.caskeleton.shared.logging", "dev.caskeleton.shared.tracing", "dev.caskeleton.shared.metrics", - "dev.caskeleton.shared.registry", - "dev.caskeleton.shared.annotation", // Not this module at all — see the defect note on the rule above. The Mongo leaf has // a // tenancy.shared package of its own and only began tripping this rule when that leaf diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java index fc1097dc..db694f5a 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java @@ -96,6 +96,7 @@ class JpaProductionArchitectureTest { } @Test + @DisplayName("운영 엔티티의 연관관계는 모두 한쪽에서만 매핑된다") void everyProductionAssociationIsMappedFromOneSideOnly() { JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(productionClasses); } @@ -124,6 +125,19 @@ class JpaProductionArchitectureTest { .check(productionClasses); } + @Test + @DisplayName("@Version 엔티티를 바꾸는 bulk UPDATE는 version을 올린다") + void bulkUpdatesOfVersionedEntitiesAdvanceTheVersion() { + // Hibernate does not touch the version for a bulk statement, so an entity read before it + // flushes over the change with no optimistic-lock conflict (review 04-07). The versioned set is + // computed from the same graph, like the audited set above. + dev.caskeleton.adapter.outbound.persistence.testkit.arch.JpaVersionedBulkUpdateRule + .bulkUpdatesOfVersionedEntitiesAdvanceVersion( + dev.caskeleton.adapter.outbound.persistence.testkit.arch.JpaVersionedBulkUpdateRule + .versionedTargets(productionClasses)) + .check(productionClasses); + } + @Test @DisplayName("no tenant-scoped repository inherits the tenant-blind CRUD surface") void noTenantScopedRepositoryInheritsBroadCrud() { diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java index 171d1e87..920353db 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java @@ -8,14 +8,14 @@ import com.tngtech.archunit.lang.ArchRule; import org.springframework.boot.context.properties.ConfigurationProperties; /** - * Naming convention enforcement — the machine-checkable ({@code [객관]}) subset of {@code - * .agents/plugins/ca-superpowers/rules/code-conventions.md}. + * Naming convention enforcement — the machine-checkable subset of the naming table in {@code + * src/application-core/CLAUDE.md} ("Naming convention"), which is the rule book. * - *

      The naming/idiom SSOT is {@code code-conventions.md}. This test enforces only the rules that - * ArchUnit can decide reliably (N6, I5). {@code [판단]} naming rules (N2/N7/N8/...) and rules with - * intentional project exceptions (N3/N4 — e.g. the {@code IdFactory} domain port, the {@code - * SpringTransaction} canonical impl) stay in {@code ca-quality-reviewer} (doc+review), per the - * code-conventions enforcement matrix. + *

      This test enforces only the rules that ArchUnit can decide reliably (N6 configuration binding, + * I5 throwables). The rest of that table — repository vs store port, id factories, use case suffix + * exceptions — is a review rule, and the review checks it against that table. (The previous rule + * book, {@code .agents/plugins/ca-superpowers/rules/code-conventions.md}, is not in the + * repository.) */ @AnalyzeClasses(packages = "dev.caskeleton", importOptions = ProductionClassImportOption.class) class NamingConventionTest { diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/authz/RequiresPermissionProxyabilityTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/authz/RequiresPermissionProxyabilityTest.java index 160c93f2..cbed5f6b 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/authz/RequiresPermissionProxyabilityTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/authz/RequiresPermissionProxyabilityTest.java @@ -4,6 +4,7 @@ import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods; import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.domain.JavaModifier; import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.lang.ArchRule; import dev.caskeleton.application.security.RequiresPermission; @@ -33,7 +34,49 @@ import org.junit.jupiter.api.Test; * silently does not run is indistinguishable from one that passes. * */ -class RequiresPermissionProxyabilityTest { +public class RequiresPermissionProxyabilityTest { + + /** + * The three rules are constants so that the onboarding fixture (test classes the production + * import option leaves out) is held to the same rules — {@code + * DomainFeatureOnboardingContractTest} evaluates them against the fixture. + */ + public static final ArchRule NO_ANNOTATED_CLASS_IS_FINAL = + classes() + .that() + .areAnnotatedWith(RequiresPermission.class) + .should() + .notHaveModifier(JavaModifier.FINAL) + .because( + "CGLIB cannot subclass a final class, so registering one as a bean fails startup " + + "with 'Cannot subclass final class' — and until it is registered the " + + "annotation enforces nothing"); + + public static final ArchRule NO_ANNOTATED_METHOD_IS_FINAL = + methods() + .that() + .areAnnotatedWith(RequiresPermission.class) + .should() + .notHaveModifier(JavaModifier.FINAL) + .because( + "a CGLIB proxy inherits a final method rather than overriding it, so the " + + "authorization check is skipped with no error anywhere — the annotation reads " + + "as enforcement and is decoration") + .allowEmptyShould(true); + + public static final ArchRule NO_METHOD_OF_AN_ANNOTATED_CLASS_IS_FINAL = + methods() + .that() + .areDeclaredInClassesThat() + .areAnnotatedWith(RequiresPermission.class) + .and() + .arePublic() + .should() + .notHaveModifier(JavaModifier.FINAL) + .because( + "the advisor's pointcut matches the class annotation, so every public method of " + + "such a class is an enforcement point and a final one is a hole in it") + .allowEmptyShould(true); private static JavaClasses productionClasses; @@ -48,53 +91,18 @@ class RequiresPermissionProxyabilityTest { @Test @DisplayName("no class carrying @RequiresPermission is final") void noAnnotatedClassIsFinal() { - ArchRule rule = - classes() - .that() - .areAnnotatedWith(RequiresPermission.class) - .should() - .notHaveModifier(com.tngtech.archunit.core.domain.JavaModifier.FINAL) - .because( - "CGLIB cannot subclass a final class, so registering one as a bean fails startup " - + "with 'Cannot subclass final class' — and until it is registered the " - + "annotation enforces nothing"); - - rule.check(productionClasses); + NO_ANNOTATED_CLASS_IS_FINAL.check(productionClasses); } @Test @DisplayName("no method carrying @RequiresPermission is final") void noAnnotatedMethodIsFinal() { - ArchRule rule = - methods() - .that() - .areAnnotatedWith(RequiresPermission.class) - .should() - .notHaveModifier(com.tngtech.archunit.core.domain.JavaModifier.FINAL) - .because( - "a CGLIB proxy inherits a final method rather than overriding it, so the " - + "authorization check is skipped with no error anywhere — the annotation reads " - + "as enforcement and is decoration"); - - rule.allowEmptyShould(true).check(productionClasses); + NO_ANNOTATED_METHOD_IS_FINAL.check(productionClasses); } @Test @DisplayName("a method of an annotated class is not final either") void noMethodOfAnAnnotatedClassIsFinal() { - ArchRule rule = - methods() - .that() - .areDeclaredInClassesThat() - .areAnnotatedWith(RequiresPermission.class) - .and() - .arePublic() - .should() - .notHaveModifier(com.tngtech.archunit.core.domain.JavaModifier.FINAL) - .because( - "the advisor's pointcut matches the class annotation, so every public method of " - + "such a class is an enforcement point and a final one is a hole in it"); - - rule.allowEmptyShould(true).check(productionClasses); + NO_METHOD_OF_AN_ANNOTATED_CLASS_IS_FINAL.check(productionClasses); } } diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/PostgreSqlTestContainer.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/PostgreSqlTestContainer.java index b09a7981..fcbcb1ec 100644 --- a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/PostgreSqlTestContainer.java +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/PostgreSqlTestContainer.java @@ -7,7 +7,7 @@ import org.testcontainers.postgresql.PostgreSQLContainer; */ public final class PostgreSqlTestContainer { - public static final String IMAGE = "postgres:16-alpine"; + public static final String IMAGE = System.getProperty("ca.test.image.postgres-16"); private static final String REUSE_ENV = "TESTCONTAINERS_REUSE_ENABLE"; private PostgreSqlTestContainer() {} 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 e9b8aa7a..8a60862c 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 @@ -5,10 +5,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; -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.error.GlobalExceptionHandler; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapper; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; @@ -44,7 +40,6 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.context.annotation.Bean; @@ -500,15 +495,12 @@ class FileserverCompositionIntegrationTest { // declarations over overlapping packages produced a duplicate uploadLeaseRepository definition — // and, more to the point, a test that declared its own scan would keep passing if the shipped one // were ever registered nowhere, which is exactly the failure this arrangement exists to catch. - @EnableConfigurationProperties(RolePermissionPolicy.class) @Import({ FileserverPlatformAutoConfiguration.class, DomainContextConfig.class, - // The permission gate the running application puts in front of every fileserver write, and - // the handler that answers its refusal. Without them a @RequiresPermission is only a marker. - MethodSecurityConfig.class, - AuthorizationAdapter.class, - RolePermissionRegistry.class, + // The handler that answers a refused permission. The permission gate itself is the web leaf's + // WebMethodSecurityAutoConfiguration, which arrives by auto-configuration as in the running + // application; importing it here as well registered it twice. GlobalExceptionHandler.class }) static class FileserverRuntime { 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 54c39409..962d5b73 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 @@ -7,10 +7,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import com.jayway.jsonpath.JsonPath; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; -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.envelope.EnvelopeBodyAdvice; import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer; import dev.caskeleton.composition.runtime.context.DomainContextConfig; @@ -22,7 +18,6 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.context.annotation.Import; @@ -221,20 +216,17 @@ class DurableOperationCompositionIntegrationTest { /** The shipped composition over a datasource, plus the web authorization pieces it relies on. */ @SpringBootConfiguration - // 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. + // The web security root would add the JWT/session security chain, which needs an issuer. The + // permission check is WebMethodSecurityAutoConfiguration, kept by auto-configuration as in the + // running application. @EnableAutoConfiguration( 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. DomainContextConfig.class, - MethodSecurityConfig.class, - AuthorizationAdapter.class, - RolePermissionRegistry.class, EnvelopeBodyAdvice.class }) static class OperationRuntime {} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java index 8884d716..ec6d8a55 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java @@ -2,7 +2,6 @@ package dev.caskeleton.bootstrap; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.ConfigurationPropertiesScan; /** * Composition root. @@ -11,19 +10,11 @@ import org.springframework.boot.context.properties.ConfigurationPropertiesScan; * beans and settings through its {@code AutoConfiguration.imports}, so adding a capability is one * build line and removing it is deleting that line — nothing here names a module. * - *

      {@code @ConfigurationPropertiesScan} names the bootstrap packages whose settings are always - * bound. {@code bootstrap.autoconfigure} is left out on purpose: each auto-configuration there - * binds its own settings with {@code @EnableConfigurationProperties}, so a root whose condition is - * off binds nothing. + *

      No {@code @ConfigurationPropertiesScan}: a scanned settings class binds leniently and ignores + * a misspelt key, so the root's own settings are bound strictly by the configuration that uses them + * ({@code StrictSettingsBinder}, 07-10), the way every module binds its own. */ @SpringBootApplication -@ConfigurationPropertiesScan( - basePackages = { - "dev.caskeleton.bootstrap.async", - "dev.caskeleton.bootstrap.runtime", - "dev.caskeleton.bootstrap.security", - "dev.caskeleton.bootstrap.settings" - }) public class CaSkeletonApplication { public static void main(String[] args) { diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfig.java index ec45a6b3..cfe6ec07 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfig.java @@ -3,10 +3,10 @@ package dev.caskeleton.bootstrap.async; import dev.caskeleton.shared.concurrency.DomainContextPropagator; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.beans.factory.ObjectProvider; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; +import org.springframework.core.env.Environment; import org.springframework.core.task.TaskDecorator; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @@ -18,14 +18,24 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; */ @Configuration @EnableAsync -@EnableConfigurationProperties(AsyncExecutorSettings.class) public class AsyncExecutorConfig { /** Spring's default {@code @Async} executor bean name (Boot's auto-config backs off). */ public static final String EXECUTOR_BEAN_NAME = "applicationTaskExecutor"; - /** Shutdown await: container app-shutdown budget (20s) minus a 1s cleanup margin. */ - static final int AWAIT_TERMINATION_SECONDS = 19; + /** + * How long close waits for queued async work. It is spent after the web server's graceful drain + * ({@code spring.lifecycle.timeout-per-shutdown-phase}, 30s) has finished, because Spring stops + * lifecycle beans before it destroys this executor — so the two add up. The container grace in + * the root {@code docker-compose.yml} is sized to that sum; {@code + * DeveloperExperienceContractTest} fails when it is not (07-07). + */ + public static final int AWAIT_TERMINATION_SECONDS = 19; + + @Bean + AsyncExecutorSettings asyncExecutorSettings(Environment environment) { + return AsyncExecutorSettings.bind(environment); + } @Bean TaskDecorator asyncContextTaskDecorator(DomainContextPropagator domainContextPropagator) { diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettings.java index 83d46fe3..931efbdc 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettings.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettings.java @@ -1,22 +1,23 @@ package dev.caskeleton.bootstrap.async; +import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder; import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.validation.annotation.Validated; +import org.springframework.core.env.Environment; /** * Async executor pool sizing knobs, bound from {@code app.async.executor.*}. Rejects {@code - * Integer.MAX_VALUE} as a queue capacity so the queue stays bounded. See README for the design - * rationale. + * Integer.MAX_VALUE} as a queue capacity so the queue stays bounded. Bound strictly (07-10): a + * misspelt key such as {@code app.async.executor.core-sise} fails startup instead of leaving the + * default silently in force. See README for the design rationale. * * @param coreSize always-alive worker count (≥ 1) * @param maxSize hard ceiling on workers (≥ 1 and ≥ {@code coreSize}) * @param queueCapacity bounded backlog depth (1 ≤ capacity < {@code Integer.MAX_VALUE}) */ -@Validated -@ConfigurationProperties(prefix = "app.async.executor") public record AsyncExecutorSettings(Integer coreSize, Integer maxSize, Integer queueCapacity) { + static final String PREFIX = "app.async.executor"; + private static final int DEFAULT_CORE_SIZE = 10; private static final int DEFAULT_MAX_SIZE = 50; private static final int DEFAULT_QUEUE_CAPACITY = 200; @@ -61,4 +62,14 @@ public record AsyncExecutorSettings(Integer coreSize, Integer maxSize, Integer q + ") (positive_int_ge_core)"); } } + + /** + * Binds the prefix strictly. + * + * @param environment the environment to bind from + * @return the validated settings + */ + public static AsyncExecutorSettings bind(Environment environment) { + return StrictSettingsBinder.bind(environment, PREFIX, AsyncExecutorSettings.class); + } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/logging/LoggingConfigurationRule.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/logging/LoggingConfigurationRule.java new file mode 100644 index 00000000..bf864a30 --- /dev/null +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/logging/LoggingConfigurationRule.java @@ -0,0 +1,116 @@ +package dev.caskeleton.bootstrap.logging; + +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupRule; +import java.time.DateTimeException; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.List; +import org.springframework.core.env.Environment; + +/** + * Refuses {@code app.logging.*} values Logback cannot use. + * + *

      Logback reads these keys itself ({@code logback-spring.xml}), before any bean exists, so they + * have exactly one reader. What used to stand beside it was {@code LoggingSettings}: a record that + * bound the same keys, replaced a bad value with a fallback and logged that it had — while Logback, + * which it never configured, went on using the bad value (07-06). The fallback it announced was not + * even Logback's ({@code logs/app.json} against {@code logs/ca-skeleton.json}). A warning about a + * correction nobody applies is worse than none, so a value Logback would reject now stops startup + * instead, with the variable that set it named. + */ +public class LoggingConfigurationRule implements StartupRule { + + @Override + public StartupPhase phase() { + return StartupPhase.ENV_VALIDATION; + } + + @Override + public String summary() { + return "logging configuration (app.logging.*) has values Logback cannot use"; + } + + @Override + public List violations(Environment environment) { + List violations = new ArrayList<>(); + if (flag(environment, "app.logging.file.enabled", violations)) { + String path = environment.getProperty("app.logging.file.path"); + if (path == null || path.isBlank()) { + violations.add( + "APP_LOG_FILE_PATH (app.logging.file.path) is blank while file logging is on"); + } + atLeast( + environment, "app.logging.file.max-history", "APP_LOG_FILE_MAX_HISTORY", 1, violations); + } + if (flag(environment, "app.logging.async.enabled", violations)) { + atLeast( + environment, "app.logging.async.queue-size", "APP_LOG_ASYNC_QUEUE_SIZE", 1, violations); + atLeast( + environment, + "app.logging.async.discarding-threshold", + "APP_LOG_ASYNC_DISCARDING_THRESHOLD", + 0, + violations); + } + String timezone = environment.getProperty("app.logging.json.timezone"); + if (timezone != null && !"default".equalsIgnoreCase(timezone.trim())) { + try { + ZoneId.of(timezone.trim()); + } catch (DateTimeException invalid) { + violations.add( + "APP_LOG_JSON_TIMEZONE (app.logging.json.timezone) is not an IANA zone: " + timezone); + } + } + atLeast( + environment, + "app.logging.json.logger-name-length", + "APP_LOG_JSON_LOGGER_NAME_LENGTH", + 0, + violations); + String rate = environment.getProperty("app.logging.sampling-rate"); + if (rate != null) { + try { + double value = Double.parseDouble(rate.trim()); + if (!(value >= 0.0 && value <= 1.0)) { + violations.add( + "APP_LOG_SAMPLING_RATE (app.logging.sampling-rate) must be in [0.0, 1.0], was " + + rate); + } + } catch (NumberFormatException invalid) { + violations.add( + "APP_LOG_SAMPLING_RATE (app.logging.sampling-rate) is not a number: " + rate); + } + } + return violations; + } + + private static boolean flag(Environment environment, String key, List violations) { + String value = environment.getProperty(key); + if (value == null) { + return false; + } + String trimmed = value.trim(); + if (!"true".equalsIgnoreCase(trimmed) && !"false".equalsIgnoreCase(trimmed)) { + violations.add(key + " must be true or false, was " + value); + return false; + } + return Boolean.parseBoolean(trimmed); + } + + private static void atLeast( + Environment environment, String key, String variable, int minimum, List violations) { + String value = environment.getProperty(key); + if (value == null) { + return; + } + try { + int parsed = Integer.parseInt(value.trim()); + if (parsed < minimum) { + violations.add(variable + " (" + key + ") must be >= " + minimum + ", was " + parsed); + } + } catch (NumberFormatException invalid) { + violations.add(variable + " (" + key + ") is not an integer: " + value); + } + } +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java index b379649d..bb78f9e3 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java @@ -3,6 +3,7 @@ package dev.caskeleton.bootstrap.runtime; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; +import dev.caskeleton.bootstrap.CaSkeletonApplication; import dev.caskeleton.shared.runtime.RuntimeEnvironment; import java.util.List; import org.springframework.boot.EnvironmentPostProcessor; @@ -82,8 +83,7 @@ public class RuntimeEnvironmentProfileValidator implements EnvironmentPostProces */ private static boolean isDeployableArtifact(SpringApplication application) { Class mainClass = application.getMainApplicationClass(); - return mainClass != null - && "dev.caskeleton.bootstrap.CaSkeletonApplication".equals(mainClass.getName()); + return mainClass != null && CaSkeletonApplication.class.getName().equals(mainClass.getName()); } @Override diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java index 380a76c9..a0b630c5 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java @@ -1,22 +1,22 @@ package dev.caskeleton.bootstrap.runtime; -import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings; +import dev.caskeleton.bootstrap.logging.LoggingConfigurationRule; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * Wires the runtime-safety startup fail-fast validators into the running application. See README - * for the design rationale. The relational guards (OSIV, DDL, pool, TLS, vendor) belong to the - * persistence-jpa module and arrive with it. + * Wires the runtime-safety startup rules into the running application. See README for the design + * rationale. The relational guards (OSIV, DDL, pool, TLS, vendor) belong to the persistence-jpa + * module and arrive with it. Every bean here is {@code static}: support's runner evaluates the + * rules before any other singleton exists, which must not create this class. */ -@Configuration +@Configuration(proxyBeanMethods = false) public class RuntimeSafetyConfig { @Bean - StartupSafetyValidator startupSafetyValidator( - RuntimeSafetySettings settings, ListableBeanFactory beanFactory) { - return new StartupSafetyValidator(settings, beanFactory); + static StartupSafetyValidator startupSafetyValidator(ListableBeanFactory beanFactory) { + return new StartupSafetyValidator(beanFactory); } @Bean @@ -24,6 +24,11 @@ public class RuntimeSafetyConfig { return new RuntimeNumericBoundsValidator(); } + @Bean + static LoggingConfigurationRule loggingConfigurationRule() { + return new LoggingConfigurationRule(); + } + @Bean static ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator() { return new ErrorDetailExposureSafetyValidator(); diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java index 1849aec9..8778fcc6 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java @@ -3,31 +3,35 @@ package dev.caskeleton.bootstrap.runtime; import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets; import dev.caskeleton.application.outbound.SecretSourcePort; import org.springframework.beans.factory.ObjectProvider; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.Environment; /** * Wires the secret/config-source backend and its startup fail-fast guard. See README for the design * rationale. */ -@Configuration -@EnableConfigurationProperties(SecretSourceSettings.class) +@Configuration(proxyBeanMethods = false) public class SecretSourceConfig { @Bean - SecretSourcePort secretSource( - SecretSourceSettings properties, ConfigurableEnvironment environment) { - return SecretSourceFactory.create(properties.strategy(), environment); + SecretSourcePort secretSource(Environment environment) { + return SecretSourceFactory.fromEnvironment(environment); } + /** + * The guard, as a startup rule: it runs before any ordinary singleton exists, so a prod + * deployment missing a secret stops before a datasource opens a connection or a migration runs + * (07-02). Static, so creating it creates neither this class nor the backend bean above; the + * contributions are read when the rule runs, and each contributor declares its bean {@code + * static} too. + * + * @param contributed the secrets each selected module needs + * @return the rule + */ @Bean - SecretSourceValidator secretSourceValidator( - ConfigurableEnvironment environment, - SecretSourcePort secretSource, + static SecretSourceValidator secretSourceValidator( ObjectProvider contributed) { - return new SecretSourceValidator( - environment, secretSource, contributed.orderedStream().toList()); + return new SecretSourceValidator(() -> contributed.orderedStream().toList()); } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceFactory.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceFactory.java index 4846be1d..38bd68b8 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceFactory.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceFactory.java @@ -17,4 +17,15 @@ public final class SecretSourceFactory { case ENVIRONMENT -> new EnvironmentSecretSource(environment); }; } + + /** + * Builds the backend {@code app.secret-source.strategy} selects. The one place the selection is + * read, for the {@code SecretSourcePort} bean and for the startup guard alike. + * + * @param environment the resolved environment + * @return the backend + */ + public static SecretSourcePort fromEnvironment(Environment environment) { + return create(SecretSourceSettings.bind(environment).strategy(), environment); + } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceSettings.java index 6630bd0f..ad7eb218 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceSettings.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceSettings.java @@ -1,19 +1,31 @@ package dev.caskeleton.bootstrap.runtime; -import org.springframework.boot.context.properties.ConfigurationProperties; +import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder; +import org.springframework.core.env.Environment; /** - * Secret backend selection, bound from {@code app.secret-source.strategy}. See README for the - * design rationale. + * Secret backend selection, bound strictly from {@code app.secret-source.strategy} (07-10). See + * README for the design rationale. * * @param strategy the secret backend; {@code null} → {@code ENVIRONMENT} */ -@ConfigurationProperties(prefix = "app.secret-source") public record SecretSourceSettings(SecretSourceStrategy strategy) { + static final String PREFIX = "app.secret-source"; + public SecretSourceSettings { if (strategy == null) { strategy = SecretSourceStrategy.ENVIRONMENT; } } + + /** + * Binds the prefix strictly. + * + * @param environment the environment to bind from + * @return the settings + */ + public static SecretSourceSettings bind(Environment environment) { + return StrictSettingsBinder.bind(environment, PREFIX, SecretSourceSettings.class); + } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java index b7d3c374..a8b01557 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java @@ -3,21 +3,31 @@ package dev.caskeleton.bootstrap.runtime; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets; import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; -import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; +import dev.caskeleton.adapter.outbound.support.startup.StartupRule; import dev.caskeleton.application.outbound.SecretSourcePort; +import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; +import java.util.Objects; import java.util.Set; -import org.springframework.beans.factory.SmartInitializingSingleton; +import java.util.function.Supplier; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.EnumerablePropertySource; +import org.springframework.core.env.Environment; import org.springframework.core.env.PropertySource; /** - * Fail-fast startup guard for the secret/config-source contract (prod-profile only; a violation - * throws so the application refuses to start). See README for the design rationale. + * Fail-fast startup rule for the secret/config-source contract (prod-profile only). See README for + * the design rationale. + * + *

      A startup rule, not a {@code SmartInitializingSingleton} as it once was (07-02). That callback + * runs after every singleton exists — after a datasource has opened a connection with whatever + * password it had and after Flyway has migrated — so a prod deployment missing its secrets was + * refused only once it had already reached the database. As a rule it runs before any ordinary + * singleton is created. It builds the secret backend from the environment itself rather than taking + * the {@code SecretSourcePort} bean, so running early pulls no other bean forward. */ -public class SecretSourceValidator implements SmartInitializingSingleton { +public class SecretSourceValidator implements StartupRule { /** Prefix marking a dev/local fake credential; forbidden to reach the prod profile. */ static final String LOCAL_DEV_SENTINEL_PREFIX = "__LOCAL_DEV_"; @@ -34,38 +44,51 @@ public class SecretSourceValidator implements SmartInitializingSingleton { public static final List REQUIRED_PROD_SECRETS = List.of("APP_PRIVACY_PSEUDONYMIZATION_SALT"); - private final ConfigurableEnvironment environment; - private final SecretSourcePort secretSource; - private final List contributed; + private final Supplier> contributed; - public SecretSourceValidator( - ConfigurableEnvironment environment, - SecretSourcePort secretSource, - List contributed) { - this.environment = environment; - this.secretSource = secretSource; - this.contributed = List.copyOf(contributed); + /** + * Creates the rule. + * + * @param contributed the secrets each selected module needs, read when the rule runs + */ + public SecretSourceValidator(Supplier> contributed) { + this.contributed = Objects.requireNonNull(contributed, "contributed"); } @Override - public void afterSingletonsInstantiated() { - if (!RuntimeProfileSnapshot.from(environment).isProduction()) { - return; - } - - StartupValidationContext validation = - StartupValidationContext.forPhase(StartupPhase.ENV_VALIDATION); - collectLocalDevSentinelViolations(validation); - collectMissingSecretViolations(validation); - validation.failIfViolated( - "prod secret/config-source contract is invalid", - "inject real non-blank secrets from the secret manager / mounted environment; " - + "local/dev sentinel credentials are forbidden in prod."); + public StartupPhase phase() { + return StartupPhase.ENV_VALIDATION; } - private void collectLocalDevSentinelViolations(StartupValidationContext validation) { + @Override + public String summary() { + return "prod secret/config-source contract is invalid"; + } + + @Override + public String remedy() { + return "inject real non-blank secrets from the secret manager / mounted environment; " + + "local/dev sentinel credentials are forbidden in prod."; + } + + @Override + public List violations(Environment environment) { + if (!RuntimeProfileSnapshot.from(environment).isProduction()) { + return List.of(); + } + List violations = new ArrayList<>(); + collectLocalDevSentinelViolations(environment, violations); + collectMissingSecretViolations(environment, violations); + return violations; + } + + private static void collectLocalDevSentinelViolations( + Environment environment, List violations) { + if (!(environment instanceof ConfigurableEnvironment configurable)) { + return; + } Set offenders = new LinkedHashSet<>(); - for (PropertySource source : environment.getPropertySources()) { + for (PropertySource source : configurable.getPropertySources()) { if (source instanceof EnumerablePropertySource enumerable) { for (String name : enumerable.getPropertyNames()) { Object value = enumerable.getProperty(name); @@ -76,19 +99,20 @@ public class SecretSourceValidator implements SmartInitializingSingleton { } } for (String offender : offenders) { - validation.reject( + violations.add( "'" + LOCAL_DEV_SENTINEL_PREFIX + "' sentinel credential is configured for " + offender); } } - private void collectMissingSecretViolations(StartupValidationContext validation) { + private void collectMissingSecretViolations(Environment environment, List violations) { + SecretSourcePort secretSource = SecretSourceFactory.fromEnvironment(environment); Set required = new LinkedHashSet<>(REQUIRED_PROD_SECRETS); // Each module names the secrets its selected capabilities need. This guard does not know which // capabilities a module has or how they are selected — it only checks the names resolve. - contributed.forEach(module -> required.addAll(module.requiredSecrets(environment))); + contributed.get().forEach(module -> required.addAll(module.requiredSecrets(environment))); for (String key : required) { if (secretSource.resolve(key).isEmpty()) { - validation.reject(key + " is missing/blank"); + violations.add(key + " is missing/blank"); } } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java index 207caf80..79fe8729 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java @@ -1,34 +1,48 @@ package dev.caskeleton.bootstrap.runtime; import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; -import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; +import dev.caskeleton.adapter.outbound.support.startup.StartupRule; import dev.caskeleton.application.lock.DistributedLockPort; import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings; +import java.util.List; +import java.util.Objects; import org.springframework.beans.factory.ListableBeanFactory; -import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.core.env.Environment; /** - * Fail-fast startup guard for env-combination invariants. Implemented as a {@link - * SmartInitializingSingleton} so the check runs once after every singleton is instantiated but - * before the context finishes refreshing; a violation throws so the context refuses to start. See - * README for the design rationale. + * Fail-fast startup rule for env-combination invariants. See README for the design rationale. + * + *

      A startup rule rather than the {@code SmartInitializingSingleton} it was (07-02): that ran + * after every singleton existed, so a multi-instance deployment with no cross-instance lock had + * already connected to its stores and migrated before it was refused. The question it asks — is a + * bean of that name and type declared? — is answered by the bean definitions, which are complete + * before any singleton is created, so asking it then creates nothing. */ -public class StartupSafetyValidator implements SmartInitializingSingleton { +public class StartupSafetyValidator implements StartupRule { /** Shipped cross-instance lock provider selected by multi-instance mode. */ static final String DISTRIBUTED_LOCK_PROVIDER_BEAN = "distributedLockProvider"; - private final RuntimeSafetySettings settings; private final ListableBeanFactory beanFactory; - public StartupSafetyValidator(RuntimeSafetySettings settings, ListableBeanFactory beanFactory) { - this.settings = settings; - this.beanFactory = beanFactory; + /** + * Creates the rule. + * + * @param beanFactory the bean definitions the rule inspects; it creates no bean + */ + public StartupSafetyValidator(ListableBeanFactory beanFactory) { + this.beanFactory = Objects.requireNonNull(beanFactory, "beanFactory"); } @Override - public void afterSingletonsInstantiated() { - validateMultiInstance(); + public StartupPhase phase() { + // ADAPTER_ENABLEMENT (exit 72): a required adapter is missing. + return StartupPhase.ADAPTER_ENABLEMENT; + } + + @Override + public String summary() { + return "APP_MULTI_INSTANCE_ENABLED=true requires the cross-instance DistributedLockPort"; } /** @@ -39,24 +53,21 @@ public class StartupSafetyValidator implements SmartInitializingSingleton { * optional efficiency, rate limiting is validated by its transport/provider contract, and outbox * coordination exists only when outbox itself is enabled. */ - private void validateMultiInstance() { - if (!settings.multiInstanceEnabled()) { - return; + @Override + public List violations(Environment environment) { + if (!RuntimeSafetySettings.bind(environment).multiInstanceEnabled()) { + return List.of(); } - StartupValidationContext invalid = - StartupValidationContext.forPhase(StartupPhase.ADAPTER_ENABLEMENT); if (!beanFactory.containsBean(DISTRIBUTED_LOCK_PROVIDER_BEAN)) { - invalid.reject(DISTRIBUTED_LOCK_PROVIDER_BEAN + " (missing)"); - } else if (!beanFactory.isTypeMatch( - DISTRIBUTED_LOCK_PROVIDER_BEAN, DistributedLockPort.class)) { - invalid.reject( + return List.of(DISTRIBUTED_LOCK_PROVIDER_BEAN + " (missing)"); + } + if (!beanFactory.isTypeMatch(DISTRIBUTED_LOCK_PROVIDER_BEAN, DistributedLockPort.class)) { + return List.of( DISTRIBUTED_LOCK_PROVIDER_BEAN + " (must implement " + DistributedLockPort.class.getName() + ")"); } - // ADAPTER_ENABLEMENT (exit 72) follows from the context's phase. - invalid.failIfViolated( - "APP_MULTI_INSTANCE_ENABLED=true requires the cross-instance DistributedLockPort"); + return List.of(); } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/BootstrapSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/BootstrapSettings.java index 13dc4498..ee6b9eac 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/BootstrapSettings.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/BootstrapSettings.java @@ -1,16 +1,35 @@ package dev.caskeleton.bootstrap.settings; -import jakarta.validation.constraints.NotBlank; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.validation.annotation.Validated; +import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; +import org.springframework.core.env.Environment; /** - * Bootstrap-scope settings bound from {@code app.bootstrap.*}. {@code appName} is fail-fast - * (@NotBlank): no sensible default, so a blank value must stop startup rather than warn-and-default - * like the other settings. See README for the design rationale. + * Bootstrap-scope settings bound from {@code app.bootstrap.*}. {@code appName} is fail-fast: no + * sensible default, so a blank value must stop startup rather than warn-and-default. Bound strictly + * (07-10), so a misspelt key under {@code app.bootstrap} fails startup too. See README for the + * design rationale. + * + * @param appName the application name, required */ -@Validated -@ConfigurationProperties(prefix = "app.bootstrap") -public record BootstrapSettings( - @NotBlank(message = "APP_NAME (app.bootstrap.app-name) is required and must not be blank") - String appName) {} +public record BootstrapSettings(String appName) { + + static final String PREFIX = "app.bootstrap"; + + public BootstrapSettings { + if (appName == null || appName.isBlank() || appName.contains("${")) { + throw StartupFailures.envValidation( + "APP_NAME (app.bootstrap.app-name) is required and must not be blank"); + } + } + + /** + * Binds the prefix strictly. + * + * @param environment the environment to bind from + * @return the settings + */ + public static BootstrapSettings bind(Environment environment) { + return StrictSettingsBinder.bind(environment, PREFIX, BootstrapSettings.class); + } +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/BootstrapSettingsConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/BootstrapSettingsConfig.java new file mode 100644 index 00000000..40f39755 --- /dev/null +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/BootstrapSettingsConfig.java @@ -0,0 +1,18 @@ +package dev.caskeleton.bootstrap.settings; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +/** + * Binds the composition root's own identity settings strictly. A bean rather than a scanned + * {@code @ConfigurationProperties} class, because a scanned class ignores unknown keys (07-10). + */ +@Configuration(proxyBeanMethods = false) +public class BootstrapSettingsConfig { + + @Bean + BootstrapSettings bootstrapSettings(Environment environment) { + return BootstrapSettings.bind(environment); + } +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/LoggingSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/LoggingSettings.java deleted file mode 100644 index a023ffcc..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/LoggingSettings.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.bootstrap.settings; - -import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings; -import java.time.ZoneId; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * Logging settings bound from {@code app.logging.*}. Every knob is "warn-and-default": a bad value - * logs a warning and proceeds with a safe fallback rather than failing startup. See README for the - * design rationale. - */ -@ConfigurationProperties(prefix = "app.logging") -public record LoggingSettings(File file, Async async, Json json) { - - public record File( - boolean enabled, String path, String maxSize, int maxHistory, String totalSizeCap) { - - public File { - if (enabled) { - if (path == null || path.isBlank()) { - RuntimeWarnings.settingFallback( - "APP_LOG_FILE_PATH", path, "logs/app.json", "it is blank while file logging is on"); - path = "logs/app.json"; - } - if (maxHistory <= 0) { - RuntimeWarnings.settingFallback( - "APP_LOG_FILE_MAX_HISTORY", maxHistory, 14, "it must be >= 1"); - maxHistory = 14; - } - // Size strings (maxSize, totalSizeCap) are parsed by logback; let it own that contract. - } - } - } - - public record Async(boolean enabled, int queueSize, int discardingThreshold) { - - public Async { - if (enabled) { - if (queueSize <= 0) { - RuntimeWarnings.settingFallback( - "APP_LOG_ASYNC_QUEUE_SIZE", queueSize, 512, "it must be >= 1"); - queueSize = 512; - } - if (discardingThreshold < 0) { - RuntimeWarnings.settingFallback( - "APP_LOG_ASYNC_DISCARDING_THRESHOLD", discardingThreshold, 20, "it must be >= 0"); - discardingThreshold = 20; - } - } - } - } - - public record Json( - String timezone, String timestampPattern, boolean includeCallerData, int loggerNameLength) { - private static final String DEFAULT_TIMEZONE = "UTC"; - private static final String DEFAULT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - - public Json { - if (timezone == null || timezone.isBlank()) { - RuntimeWarnings.settingFallback( - "APP_LOG_JSON_TIMEZONE", timezone, DEFAULT_TIMEZONE, "it is blank"); - timezone = DEFAULT_TIMEZONE; - } else if (!"default".equalsIgnoreCase(timezone)) { - try { - ZoneId.of(timezone); - } catch (Exception e) { - RuntimeWarnings.settingFallback( - "APP_LOG_JSON_TIMEZONE", timezone, DEFAULT_TIMEZONE, "it is not a valid IANA zone"); - timezone = DEFAULT_TIMEZONE; - } - } - if (timestampPattern == null || timestampPattern.isBlank()) { - RuntimeWarnings.settingFallback( - "APP_LOG_JSON_TIMESTAMP_PATTERN", timestampPattern, DEFAULT_PATTERN, "it is blank"); - timestampPattern = DEFAULT_PATTERN; - } - if (loggerNameLength < 0) { - RuntimeWarnings.settingFallback( - "APP_LOG_JSON_LOGGER_NAME_LENGTH", loggerNameLength, 0, "it must be >= 0"); - loggerNameLength = 0; - } - } - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/RuntimeSafetySettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/RuntimeSafetySettings.java index 04bd9744..97da2688 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/RuntimeSafetySettings.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/RuntimeSafetySettings.java @@ -1,13 +1,36 @@ package dev.caskeleton.bootstrap.settings; -import org.springframework.boot.context.properties.ConfigurationProperties; +import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder; +import java.util.Set; +import org.springframework.core.env.Environment; /** * Operational runtime settings bound from {@code app.runtime.*}. * *

      Only implemented controls belong here. Internal error-detail exposure and HTTP body logging - * have no runtime implementation and therefore no reserved configuration switch. {@code - * migration-on-startup} is read by the JPA module that runs the migration, not here. + * have no runtime implementation and therefore no reserved configuration switch. + * + *

      Bound strictly (07-10): a misspelt key under {@code app.runtime} fails startup instead of + * leaving its default silently in force. {@code migration-on-startup} is the JPA module's — it runs + * the migration — so this binding leaves it to that module. + * + * @param multiInstanceEnabled whether several instances serve the same data */ -@ConfigurationProperties(prefix = "app.runtime") -public record RuntimeSafetySettings(boolean multiInstanceEnabled) {} +public record RuntimeSafetySettings(boolean multiInstanceEnabled) { + + static final String PREFIX = "app.runtime"; + + /** Keys under the prefix another module binds for itself. */ + static final Set FOREIGN_KEYS = Set.of("migration-on-startup"); + + /** + * Binds the prefix strictly. + * + * @param environment the environment to bind from + * @return the settings + */ + public static RuntimeSafetySettings bind(Environment environment) { + return StrictSettingsBinder.bindExcept( + environment, PREFIX, RuntimeSafetySettings.class, FOREIGN_KEYS); + } +} diff --git a/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index be37db73..77863904 100644 --- a/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,2 +1 @@ dev.caskeleton.bootstrap.autoconfigure.common.BootstrapClockAutoConfiguration -dev.caskeleton.bootstrap.autoconfigure.operation.DurableOperationConfig diff --git a/src/app-bootstrap/src/main/resources/application-local.yml b/src/app-bootstrap/src/main/resources/application-local.yml index 14061d34..f19af5bc 100644 --- a/src/app-bootstrap/src/main/resources/application-local.yml +++ b/src/app-bootstrap/src/main/resources/application-local.yml @@ -3,10 +3,8 @@ # # This file is a complete standalone configuration, not a patch. application.yml resolves ~70 # values from ${APP_*} placeholders that carry no inline default, so a launcher that does not -# inject src/.env dies during property binding — and because logback-spring.xml reads the same -# unresolved app.logging.* values, the logging system fails first and swallows the console -# output that would have said so. The observable symptom is a process that exits 1 having printed -# nothing. +# inject src/.env dies during property binding. The observable symptom is a process that exits 1 +# having printed little that says why. # # Only `./gradlew :app-bootstrap:bootRun` injects src/.env (see app-bootstrap/build.gradle). An IDE # Run/Debug on CaSkeletonApplication, `java -jar`, and a bare container do not. Restating the @@ -124,7 +122,10 @@ spring: timeout-per-shutdown-phase: 30s server: - port: 8080 + # The one server value local takes from the environment (09-10): two services — or the default + # composition and the sample — on one machine need different ports, and a literal here made + # APP_SERVER_PORT=18080 still start on 8080. + port: ${APP_SERVER_PORT:8080} shutdown: graceful # No proxy in front of a local run, so trusting X-Forwarded-* would let a caller forge its own # client IP. dev/prod sit behind a load balancer and set this to framework via env. @@ -181,23 +182,7 @@ app: allowed-headers: "*" allow-credentials: true max-age-seconds: 3600 - logging: - file: - # Console only. A local run should not quietly grow a logs/ directory in the working - # directory, which differs between a Gradle run and an IDE run. - enabled: false - path: logs/ca-skeleton.json - max-size: 100MB - max-history: 14 - total-size-cap: 3GB - async: - enabled: true - queue-size: 512 - discarding-threshold: 20 - json: - timezone: UTC - timestamp-pattern: "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" - include-caller-data: false - logger-name-length: 0 - # Keep every log line locally; prod samples <=INFO down to 10%. - sampling-rate: 1.0 + # No app.logging block: config/observability.yml already defaults every knob to what local wants + # (console only, no file, every line kept), and leaving it there keeps APP_LOG_* able to change a + # local run. Logback reads app.logging.* since 07-06, so a literal here would have been the one + # value an environment variable could not override. diff --git a/src/app-bootstrap/src/main/resources/application-prod.yml b/src/app-bootstrap/src/main/resources/application-prod.yml index 58c856b9..5a670b56 100644 --- a/src/app-bootstrap/src/main/resources/application-prod.yml +++ b/src/app-bootstrap/src/main/resources/application-prod.yml @@ -8,7 +8,7 @@ # forbidden value has to fail whether it arrives from this file, an env var, or a container # override — a YAML default only wins against the sources that are quieter than it: # -# JpaSchemaSafetyValidator ddl-auto must be none|validate (exit 71) +# JpaDangerousConfigurationGuard ddl-auto must be none|validate (persistence-jpa) # FlywayProdSafetyValidator baseline-on-migrate / out-of-order / clean stay disarmed # ErrorDetailExposureSafetyValidator spring.web.error.include-* stay never/false (exit 71) # PostgreSqlTransportSecurityValidator pgJDBC sslmode=verify-full diff --git a/src/app-bootstrap/src/main/resources/config/runtime.yml b/src/app-bootstrap/src/main/resources/config/runtime.yml index b8db71f2..3309b75c 100644 --- a/src/app-bootstrap/src/main/resources/config/runtime.yml +++ b/src/app-bootstrap/src/main/resources/config/runtime.yml @@ -8,9 +8,9 @@ app: # required, non-blank — startup fails if blank (see BootstrapSettings) app-name: ${APP_NAME} runtime: - # feature-env-driven-runtime-configuration D8: enforced at startup by - # the prod profile; multi-instance fails startup if its coordination beans are absent. - # true | false (requires the 5 instance-coordination beans when true) + # true | false. When true, startup fails (exit 72) unless a cross-instance DistributedLockPort + # bean named distributedLockProvider is declared (StartupSafetyValidator). The persistence-jpa + # module provides it. multi-instance-enabled: ${APP_MULTI_INSTANCE_ENABLED:false} presentation: # feature-api-contract-baseline D2: API version prefix. Default is the URI diff --git a/src/app-bootstrap/src/main/resources/config/security.yml b/src/app-bootstrap/src/main/resources/config/security.yml index f0919642..4ed3b8a6 100644 --- a/src/app-bootstrap/src/main/resources/config/security.yml +++ b/src/app-bootstrap/src/main/resources/config/security.yml @@ -29,35 +29,14 @@ app: path: ${APP_SESSION_COOKIE_PATH:/} csrf-cookie-name: ${APP_SESSION_CSRF_COOKIE_NAME:XSRF-TOKEN} csrf-header-name: ${APP_SESSION_CSRF_HEADER_NAME:X-XSRF-TOKEN} - authz: - # feature-authentication-authorization-contract D2/D3/D8: app-side role→permission - # mapping (the default source; IdP-issued permission claims are an out-of-scope - # alternative). Keys are RAW IdP role names (no ROLE_ prefix — that prefix only - # exists on Spring authorities, not on the principal's raw role set), looked up - # case-insensitively. Values are explicitly enumerated `resource:action` permissions - # (no wildcards — least-privilege, OWASP-AUTHZ-C4). The production defaults only grant - # platform-owned permissions; sample-domain permissions live in sample-portfolio fixtures. - role-permissions: - # The notification platform's own two permissions, granted to two roles rather than one. - # Publishing a template changes what every future submission renders, so a service that may - # send notifications is not thereby a service that may rewrite them; a deployment that wants - # both grants both roles. - notification-submit: notification:submit - notification-template-publish: notification-template:publish - # Durable operations (/operations, on with the JPA module and the outbox). One role for both: - # a caller that may start an operation may cancel its own, and reading one needs no - # permission beyond being the one who submitted it. - operation-submit: operation:submit,operation:cancel - # Fileserver (/v1/files, /v1/uploads, /internal/fileserver; on with the fileserver module). - # Keyed by the fileserver's own default tier roles (app.fileserver-platform.security.*-roles), - # so one role grants both halves of a fileserver write: the permission here, checked on the - # use case, and the tier FileAccessPolicyPort checks inside it along with ownership. The - # brackets keep the underscores, which unbracketed map keys lose in binding. A deployment that - # renames those roles maps its own names here too. The tiers do not inherit, and neither do - # these: a writer that also reads holds both roles. - "[ROLE_FILE_READ]": file:read - "[ROLE_FILE_WRITE]": file:upload,file:delete,file:copy,file:move - "[ROLE_FILE_ADMIN]": file:admin + # app.authz.role-permissions — no entry in this file. App-side role→permission mapping + # (feature-authentication-authorization-contract D2/D3/D8): keys are RAW IdP role names (no ROLE_ + # prefix), looked up case-insensitively; values are enumerated `resource:action` permissions (no + # wildcards — least-privilege, OWASP-AUTHZ-C4). A capability's own permissions arrive with it, in + # that module's config/module-defaults file (notification, fileserver, durable-operation), and + # leave with its build line (07-08). Map entries from every source merge, so a deployment adds its + # own roles in its profile file or environment beside them. Sample-domain permissions live in + # sample-portfolio. cors: # true | false enabled: ${APP_SECURITY_CORS_ENABLED:false} diff --git a/src/app-bootstrap/src/main/resources/config/server.yml b/src/app-bootstrap/src/main/resources/config/server.yml index 4fa79f01..6b0e4b0d 100644 --- a/src/app-bootstrap/src/main/resources/config/server.yml +++ b/src/app-bootstrap/src/main/resources/config/server.yml @@ -12,8 +12,14 @@ server: # Never framework — it believes every peer, so a caller can pick its own getRemoteAddr(). forward-headers-strategy: ${APP_SERVER_FORWARD_HEADERS_STRATEGY:none} tomcat: + # With virtual threads on (spring.threads.virtual.enabled, the default in application.yml) + # Tomcat runs each request on a new virtual thread and threads.max / min-spare stop bounding + # concurrency: the number of requests in progress is bounded by max-connections below and by + # what each request waits on — the datasource pool, rate limits. Lower max-connections, or put a + # limit in front of the scarce resource, to shed load; lowering threads.max does nothing then. + # (Boot behaviour, not measured in this repository — 07-12.) threads: - # integer >= 1 + # integer >= 1. Platform-thread pool size; a concurrency bound only with virtual threads off. max: ${APP_SERVER_TOMCAT_MAX_THREADS:200} # integer >= 0 min-spare: ${APP_SERVER_TOMCAT_MIN_SPARE_THREADS:10} diff --git a/src/app-bootstrap/src/main/resources/logback-spring.xml b/src/app-bootstrap/src/main/resources/logback-spring.xml index 21aad2d0..a4004341 100644 --- a/src/app-bootstrap/src/main/resources/logback-spring.xml +++ b/src/app-bootstrap/src/main/resources/logback-spring.xml @@ -2,7 +2,11 @@ - + + source="app.logging.file.enabled" defaultValue="false"/> + source="app.logging.file.path" defaultValue="logs/ca-skeleton.json"/> + source="app.logging.file.max-size" defaultValue="100MB"/> + source="app.logging.file.max-history" defaultValue="14"/> + source="app.logging.file.total-size-cap" defaultValue="3GB"/> + source="app.logging.async.enabled" defaultValue="true"/> + source="app.logging.async.queue-size" defaultValue="512"/> + source="app.logging.async.discarding-threshold" defaultValue="20"/> + source="app.logging.json.timezone" defaultValue="UTC"/> + source="app.logging.json.include-caller-data" defaultValue="false"/> + source="app.logging.json.logger-name-length" defaultValue="0"/> + source="app.logging.sampling-rate" defaultValue="1.0"/> diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/DefaultCompositionBootTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/DefaultCompositionBootTest.java index 030b04f1..2668a777 100644 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/DefaultCompositionBootTest.java +++ b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/DefaultCompositionBootTest.java @@ -45,11 +45,12 @@ class DefaultCompositionBootTest { "dev.caskeleton.adapter.inbound.websocket", "dev.caskeleton.adapter.inbound.grpc", // composition:service-runtime (`composition.runtime`) is part of the default composition; - // the outbox relay and idempotency modules are selected but build nothing until their - // store or provider is there. + // the outbox relay, durable-operation and idempotency modules are selected but build + // nothing until their store or provider is there. "dev.caskeleton.composition.fileserver", "dev.caskeleton.composition.notification", "dev.caskeleton.composition.outbox", + "dev.caskeleton.composition.operation", "dev.caskeleton.composition.idempotency"); /** Infrastructure a capability connects to; a bean of any of these would open a connection. */ diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/logging/LoggingSettingsSourceSystemTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/logging/LoggingSettingsSourceSystemTest.java new file mode 100644 index 00000000..da5101db --- /dev/null +++ b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/logging/LoggingSettingsSourceSystemTest.java @@ -0,0 +1,64 @@ +package dev.caskeleton.bootstrap.logging; + +import static org.assertj.core.api.Assertions.assertThat; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.core.Appender; +import dev.caskeleton.bootstrap.composition.ShippedCompositionHarness; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.slf4j.LoggerFactory; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * Logback reads {@code app.logging.*} from the Spring environment, so a value set in YAML, a + * profile file or on the command line takes effect — not only the {@code APP_LOG_*} variable the + * shipped YAML maps onto it (07-06). + */ +class LoggingSettingsSourceSystemTest { + + @Test + @DisplayName("app.logging.file.enabled를 환경 변수가 아닌 설정으로 켜도 파일 appender가 붙는다") + void fileLoggingTurnedOnThroughTheSettingAttachesTheFileAppender(@TempDir Path directory) { + // given + Path logFile = directory.resolve("app.json"); + String[] arguments = + Stream.concat( + Stream.of(ShippedCompositionHarness.requiredOperatorInputs()), + Stream.of( + "--server.port=0", + "--management.server.port=0", + "--app.logging.file.enabled=true", + "--app.logging.file.path=" + logFile)) + .toArray(String[]::new); + + // when + try (ConfigurableApplicationContext context = + ShippedCompositionHarness.shippedComposition("dev").run(arguments)) { + + // then + assertThat(rootAppenderNames()).contains("ASYNC_FILE"); + assertThat(Files.exists(logFile)).isTrue(); + } + } + + private static List rootAppenderNames() { + Logger root = + ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger(Logger.ROOT_LOGGER_NAME); + List names = new ArrayList<>(); + for (Iterator> it = + root.iteratorForAppenders(); + it.hasNext(); ) { + names.add(it.next().getName()); + } + return names; + } +} 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 4b2414d3..51f1abc3 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 @@ -2,14 +2,17 @@ package dev.caskeleton.bootstrap.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; import java.util.Map; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.source.ConfigurationPropertySource; import org.springframework.boot.context.properties.source.MapConfigurationPropertySource; +import org.springframework.mock.env.MockEnvironment; /** * Contract test for {@link AsyncExecutorSettings} (feature-background-job-async-contract D7 — pool @@ -45,6 +48,20 @@ class AsyncExecutorSettingsTest { assertThat(settings.queueCapacity()).isEqualTo(64); } + @Test + @DisplayName("app.async.executor 아래 오타 키는 기본값으로 넘어가지 않고 기동을 실패시킨다") + void aMisspelledKeyFailsInsteadOfFallingBackToTheDefault() { + // given + MockEnvironment environment = + new MockEnvironment().withProperty("app.async.executor.core-sise", "4"); + + // when + Throwable thrown = catchThrowable(() -> AsyncExecutorSettings.bind(environment)); + + // then + assertThat(thrown).hasStackTraceContaining("core-sise"); + } + // ---- positive_int (core) ------------------------------------------------- @Test diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/LocalJpaVendorParityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/LocalJpaVendorParityTest.java index 8023e196..d6379c20 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/LocalJpaVendorParityTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/LocalJpaVendorParityTest.java @@ -2,11 +2,13 @@ package dev.caskeleton.bootstrap.autoconfigure.jpa; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; @@ -32,6 +34,7 @@ import org.springframework.mock.env.MockEnvironment; * available as {@code :app-bootstrap:bootRunH2}. What changed is that choosing it is now visible in * the command somebody typed, rather than being what {@code local} quietly meant. */ +@Tag("repository-contract") class LocalJpaVendorParityTest { /** @@ -136,14 +139,9 @@ class LocalJpaVendorParityTest { } private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/PortResolutionContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/PortResolutionContractTest.java index 9e4e1ee8..fdaa8249 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/PortResolutionContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/PortResolutionContractTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.bootstrap.composition; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -14,6 +15,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -38,6 +40,7 @@ import org.junit.jupiter.api.Test; * multi-instance-enabled} is false or absent, the JDBC-backed one when it is true. Those cannot * coexist, so nothing is being preferred — one of them simply is not there. */ +@Tag("repository-contract") class PortResolutionContractTest { /** `@Bean` methods, with the annotations that precede them. */ @@ -151,15 +154,10 @@ class PortResolutionContractTest { } private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } private record ProductionSource(Path path, String text) {} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BackgroundJobErrorCodeContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BackgroundJobErrorCodeContractTest.java index 9c36f5d6..64ac66e4 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BackgroundJobErrorCodeContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BackgroundJobErrorCodeContractTest.java @@ -11,6 +11,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -27,6 +28,7 @@ import org.yaml.snakeyaml.Yaml; *

      The registry SSOT and linked runbooks are checked-in resources. A missing resource or a * mismatched row is a hard FAIL. */ +@Tag("document-contract") class BackgroundJobErrorCodeContractTest { private static Path registry; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java index 717ed2ed..912a3975 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java @@ -26,7 +26,9 @@ class BootstrapCapabilityAutoConfigurationReachabilityTest { // idempotency executor: `composition:outbox-relay` and `composition:idempotency`, which // the sample composes too. Tracing, metrics, domain context, pseudonymization and the // actuator chain are `composition:service-runtime`, which proves its own registration. - "dev.caskeleton.bootstrap.autoconfigure.operation.DurableOperationConfig"); + // Durable operations moved out last (07-08): `composition:durable-operation`. What is + // left is the clock every composition needs. + "dev.caskeleton.bootstrap.autoconfigure.common.BootstrapClockAutoConfiguration"); @Test void everyBootstrapOwnedCapabilityRootIsDiscoverableByBoot() { diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BusinessRuleValidationContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BusinessRuleValidationContractTest.java index 587945a8..5c70ff21 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BusinessRuleValidationContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BusinessRuleValidationContractTest.java @@ -12,7 +12,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Pattern; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -41,7 +41,6 @@ class BusinessRuleValidationContractTest { private static List> registryRows; - @BeforeAll static void loadRegistry() throws Exception { Path registry = RepositoryContractResources.fromSystemProperty() @@ -75,8 +74,10 @@ class BusinessRuleValidationContractTest { assertThat(OperationalError.PRECONDITION_FAILED.category()).isEqualTo(Category.CONFLICT); } + @Tag("document-contract") @Test - void persistenceIntegrityCodesMapToDataIntegrityOrConflictCategory() { + void persistenceIntegrityCodesMapToDataIntegrityOrConflictCategory() throws Exception { + loadRegistry(); // C3/C4: the SQLState integrity matrix (owned by feature-persistence-failure-baseline) // must land in DATA_INTEGRITY or CONFLICT — never INTERNAL (which would hide a client- // correctable conflict as a server fault) and never VALIDATION. @@ -105,8 +106,10 @@ class BusinessRuleValidationContractTest { // ---- C5: category × retryable consistency (registry, every row) ---- + @Tag("document-contract") @Test - void deterministicClientErrorRowsAreNeverRetryable() { + void deterministicClientErrorRowsAreNeverRetryable() throws Exception { + loadRegistry(); // C5: VALIDATION / AUTHZ / NOT_FOUND are deterministic client errors — the same request // can never succeed, so retryable=true would be a busy-loop trap. AUTH is excluded: it is // context-dependent (e.g. AUTH_KID_UNKNOWN is retryable=true once the JWKS key set @@ -125,8 +128,10 @@ class BusinessRuleValidationContractTest { } } + @Tag("document-contract") @Test - void registryCategoriesAreAllMembersOfTheSharedEnum() { + void registryCategoriesAreAllMembersOfTheSharedEnum() throws Exception { + loadRegistry(); // The registry's category column may not drift from the 10-value Category SSOT. for (Map row : registryRows) { String category = (String) row.get("category"); @@ -140,8 +145,10 @@ class BusinessRuleValidationContractTest { // ---- C7 / D9: client_safe_message leak scan (registry, every row) ---- + @Tag("document-contract") @Test - void noClientSafeMessageLeaksSqlConstraintOrInternals() { + void noClientSafeMessageLeaksSqlConstraintOrInternals() throws Exception { + loadRegistry(); // D9: "safe field errors only" — a client-facing message must never carry a raw SQL // fragment, a DB constraint/index name, a SQLState code, an exception class name, or an // internal package path. This is the registry-wide DLP gate complementing the runtime diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStatusDocumentTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStatusDocumentTest.java index da666ed0..f1279cb4 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStatusDocumentTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStatusDocumentTest.java @@ -2,11 +2,13 @@ package dev.caskeleton.bootstrap.contract; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -20,6 +22,7 @@ import org.junit.jupiter.api.Test; * the source of truth for a judgement, which is the shape of verification this repository's own * review says to stop adding. */ +@Tag("document-contract") class CapabilityStatusDocumentTest { private static final String DOCUMENT = "docs/capability-status.md"; @@ -46,12 +49,9 @@ class CapabilityStatusDocumentTest { } private static Path repositoryRoot() { - for (Path path = Path.of("").toAbsolutePath(); path != null; path = path.getParent()) { - if (Files.isRegularFile(path.resolve("AGENTS.md")) - && Files.isRegularFile(path.resolve("src/settings.gradle"))) { - return path; - } - } - throw new IllegalStateException("repository root not found"); + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } } 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 ee37dee0..208be2f3 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 @@ -2,6 +2,7 @@ package dev.caskeleton.bootstrap.contract; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import dev.caskeleton.bootstrap.contract.support.ShippedConfiguration; import java.io.IOException; import java.nio.file.Files; @@ -15,6 +16,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -97,6 +99,7 @@ class ConfigurationNamespaceContractTest { .contains("app", "spring"); } + @Tag("repository-contract") @Test @DisplayName("app-bootstrap이 선언한 설정 prefix는 모두 이 계약에 기록돼 있다") void everyBootstrapPrefixIsRecorded() throws IOException { @@ -110,6 +113,7 @@ class ConfigurationNamespaceContractTest { .isSubsetOf(BOOTSTRAP_PREFIXES); } + @Tag("repository-contract") @Test @DisplayName("모든 leaf의 설정 prefix는 app 아래에 있다") void everyLeafPrefixSitsUnderTheApplicationRoot() throws IOException { @@ -148,14 +152,9 @@ class ConfigurationNamespaceContractTest { } private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ContainerRuntimeOomContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ContainerRuntimeOomContractTest.java index 39572eb9..c77618e4 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ContainerRuntimeOomContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ContainerRuntimeOomContractTest.java @@ -11,7 +11,7 @@ import java.nio.file.Path; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -34,7 +34,6 @@ class ContainerRuntimeOomContractTest { private static Map> rowsByCode; - @BeforeAll static void loadRegistry() throws Exception { Path registry = RepositoryContractResources.fromSystemProperty() @@ -70,8 +69,10 @@ class ContainerRuntimeOomContractTest { // ---- registry-row leg ------------------------------------------------------ + @Tag("document-contract") @Test - void registryRowMatchesJvmOomEnum() { + void registryRowMatchesJvmOomEnum() throws Exception { + loadRegistry(); Map row = rowsByCode.get("JVM_OOM"); assertThat(row) .as("error-codes.yaml must contain a JVM_OOM row (feature-container-runtime-contract §5)") @@ -93,8 +94,10 @@ class ContainerRuntimeOomContractTest { assertThat(code.retryable()).isEqualTo((boolean) row.get("retryable")); } + @Tag("document-contract") @Test - void registryRowHasCorrectRunbookLinkFormat() { + void registryRowHasCorrectRunbookLinkFormat() throws Exception { + loadRegistry(); Map row = rowsByCode.get("JVM_OOM"); assertThat(row).as("JVM_OOM row must exist").isNotNull(); @@ -103,8 +106,10 @@ class ContainerRuntimeOomContractTest { .isEqualTo(EXPECTED_RUNBOOK_LINK); } + @Tag("document-contract") @Test - void runbookFileExistsWhenPresentOnDisk() { + void runbookFileExistsWhenPresentOnDisk() throws Exception { + loadRegistry(); Path runbookFile = RepositoryContractResources.fromSystemProperty() .requireTrackedFile("docs/runbooks/runtime-jvm-oom.md"); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ContractRegistrySchemaGovernanceTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ContractRegistrySchemaGovernanceTest.java index e0bf3766..bed07c83 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ContractRegistrySchemaGovernanceTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ContractRegistrySchemaGovernanceTest.java @@ -8,6 +8,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Set; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -19,6 +20,7 @@ import org.junit.jupiter.api.io.TempDir; * leaf test. This gate owns the exact artifact catalog, strict YAML envelope, unique identities, * and truthful repository/semantic owner provenance. */ +@Tag("document-contract") class ContractRegistrySchemaGovernanceTest { private static final Set EXACT_REGISTRY_FILES = diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java index 129fb127..8ff57184 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java @@ -3,21 +3,30 @@ package dev.caskeleton.bootstrap.contract; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.bootstrap.async.AsyncExecutorConfig; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; -/** Pins the executable local-developer entrypoint and its documentation/CI guardrails. */ +/** + * Pins the executable local-developer entrypoint and its documentation/CI guardrails. + * + *

      Every test here reads the repository, so each one names its lane: workflow, Docker and Compose + * structure is {@code repository-contract} and blocks the pull request, because a release or + * signing regression must not merge; a sentence in a guidance document is {@code document-contract} + * and runs in the main stage (review 2026-11-01 08-03). + */ class DeveloperExperienceContractTest { private static final Path REPOSITORY_ROOT = repositoryRoot(); @@ -29,11 +38,13 @@ class DeveloperExperienceContractTest { // spelling — a YAML parser written in bash, tested from a Java application's test suite. @Test + @Tag("repository-contract") void toolVersionsPinTemurin21() throws IOException { assertThat(read(".tool-versions")).containsPattern("(?m)^java temurin-21\\.[^\\s]+$"); } @Test + @Tag("repository-contract") @DisplayName("로컬 기동 진입점은 네 단계를 순서대로 밟는 scripts/bootstrap-local.sh 하나다") void theLocalBootstrapEntrypointIsOneScriptWithFourOrderedStages() throws IOException { // given @@ -57,6 +68,7 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") void localComposeSupportsDatabaseMigrationAndPublicHealthSmoke() throws IOException { String base = read("docker-compose.yml"); String local = read("docker-compose.local.yml"); @@ -80,6 +92,7 @@ class DeveloperExperienceContractTest { * contract this asserts is unchanged; only the file that owns it is. */ @Test + @Tag("repository-contract") void localComposePublishesTheHostPortTheCommittedDatasourceUrlTargets() throws IOException { String datasourceUrl = envValue("APP_DATASOURCE_URL"); Matcher target = Pattern.compile("^jdbc:postgresql://([^:/]+):(\\d+)/").matcher(datasourceUrl); @@ -106,6 +119,7 @@ class DeveloperExperienceContractTest { } @Test + @Tag("document-contract") void readmeDocumentsOneFirstRunEntrypoint() throws IOException { // The `verifyReadmeCommands` half of this is gone with the task. That gate parsed the README's // ```bash blocks and resolved every `./gradlew`, `docker compose` and `make` token against the @@ -123,6 +137,7 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") void linkCheckIsBlockingAndUsesThePinnedLycheeAction() throws IOException { String workflow = read(".github/workflows/link-check.yml"); @@ -130,6 +145,7 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") void linkCheckTriggersAndScansTheExactDocumentationScope() throws IOException { List expectedPaths = List.of( @@ -179,6 +195,7 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") void testcontainersReuseIsLocalOptInAndExplicitlyDisabledInCi() throws IOException { assertThat(read("testcontainers.properties.example")) .contains("testcontainers.reuse.enable=true"); @@ -187,6 +204,7 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") void gradleWrapperIsCheckedInAndValidatedByTheOfficialAction() throws IOException { // Twenty-four tests stood here, and every one of them tested .github/scripts/ // verify-gradle-wrapper.sh — an 799-line shell script that this suite exercised by writing @@ -225,11 +243,13 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") void dockerDependencyCacheStagesDeclareTheCompleteConfigurationRegistry() throws IOException { assertDockerDependencyCacheContract("src/Dockerfile", read("src/Dockerfile")); } @Test + @Tag("repository-contract") void dockerDependencyCacheStagesEveryIncludedBuildBeforeGradle() throws IOException { String settings = read("src/settings.gradle"); String dockerfile = read("src/Dockerfile"); @@ -258,6 +278,7 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") void architectureWorkflowSelectorsUseTheArchitectureSourceSetTask() throws IOException { String staleSelector = ":app-bootstrap:test --tests 'dev.caskeleton.bootstrap.architecture.*'"; @@ -276,8 +297,17 @@ class DeveloperExperienceContractTest { .as("the release workflow runs the tag-only checks through releaseCheck") .contains("./gradlew :releaseCheck") .doesNotContain(staleSelector); + } - assertThat(read("CLAUDE.md")) + @Test + @Tag("document-contract") + @DisplayName("루트 안내 문서는 아키텍처 suite를 그 source set의 태스크 이름으로 안내한다") + void guidanceNamesTheArchitectureSourceSetTask() throws IOException { + // when + String guidance = read("CLAUDE.md"); + + // then + assertThat(guidance) .as("the operator/developer command must match the shipped architecture source set") .contains("./gradlew :app-bootstrap:architectureTest") .doesNotContain( @@ -285,6 +315,7 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") @DisplayName("릴리스 이미지는 서명 job 하나만 OIDC 토큰을 받아 digest를 keyless 서명하고 검증한다") void onlyTheSigningJobHoldsAnOidcTokenAndItSignsAndVerifiesTheDigest() throws IOException { // given @@ -327,6 +358,7 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") void everyOptionalPlatformIntegrationLaneHasAnExecutingWorkflowCaller() throws IOException { // `grpc-operation-ledger-jpa` declares a Testcontainers PostgreSQL lane that certifies the // atomic claim durable mutation idempotency rests on. It was registered in `strictTestLanes`, @@ -350,6 +382,114 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") + @DisplayName("샘플 이미지의 의존성 단계는 릴리스 이미지와 같은 파일을 같은 순서로 복사한다") + void theSampleImageDependencyStageCopiesWhatTheReleaseImageCopies() throws IOException { + // given + String release = read("src/Dockerfile"); + String sample = read("src/Dockerfile.sample"); + + // when + List releaseCopies = dependencyStageCopies(release); + List sampleCopies = dependencyStageCopies(sample); + + // then + // The sample's copy of this stage once missed gradle.properties and build-logic/, so settings + // could not resolve the convention plugins and the image did not build at all (07-04). + assertThat(sampleCopies).isNotEmpty().isEqualTo(releaseCopies); + assertDockerDependencyCacheContract("src/Dockerfile.sample", sample); + } + + @Test + @Tag("repository-contract") + @DisplayName("compose 종료 유예 시간은 웹 drain, async 대기, preStop, 여유를 모두 더한 값 이상이다") + void theComposeStopGraceCoversEveryShutdownWaitInSequence() throws IOException { + // given + Map app = + requireMap(requireMap(parseYamlMap(read("docker-compose.yml")), "services"), "app"); + int webDrainSeconds = 30; + int preStopSeconds = 5; + int marginSeconds = 5; + + // when + String grace = requireString(app, "stop_grace_period"); + + // then + // Spring finishes the lifecycle phase (the web server's graceful drain) before it destroys the + // async executor, which then waits for its queue: the two run one after the other (07-07). + assertThat(Integer.parseInt(grace.replace("s", ""))) + .isGreaterThanOrEqualTo( + webDrainSeconds + + AsyncExecutorConfig.AWAIT_TERMINATION_SECONDS + + preStopSeconds + + marginSeconds); + } + + @Test + @Tag("repository-contract") + @DisplayName("compose는 관리 포트 9001을 호스트의 loopback에만 연다") + void composePublishesTheManagementPortOnLoopbackOnly() throws IOException { + // given + List composeFiles = + List.of("docker-compose.yml", "docker-compose.dev.yml", "docker-compose.local.yml"); + + // when + List exposed = + composeFiles.stream() + .flatMap( + file -> { + try { + return portMappings(read(file)).stream().map(port -> file + ": " + port); + } catch (IOException unreadable) { + throw new java.io.UncheckedIOException(unreadable); + } + }) + .filter(mapping -> mapping.endsWith(":9001")) + .filter(mapping -> !mapping.contains(" 127.0.0.1:")) + .toList(); + + // then + // health, info (with build revision and capability list) and prometheus answer without + // authentication on that port; published on every interface they reach the whole LAN (07-13). + assertThat(exposed).isEmpty(); + } + + /** + * The port mappings of a Compose file, read as list items under a {@code ports:} key. Read as + * text because the override files use Compose's {@code !override} tag, which a plain YAML parser + * refuses. + */ + private static List portMappings(String compose) { + List mappings = new java.util.ArrayList<>(); + boolean inPorts = false; + int portsIndent = -1; + for (String line : compose.lines().toList()) { + String trimmed = line.strip(); + int indent = line.length() - line.stripLeading().length(); + if (trimmed.startsWith("ports:")) { + inPorts = true; + portsIndent = indent; + continue; + } + if (inPorts && !trimmed.isEmpty() && !trimmed.startsWith("#")) { + if (indent <= portsIndent || !trimmed.startsWith("- ")) { + inPorts = false; + continue; + } + String item = trimmed.substring(2).replaceAll("\\s+#.*$", "").replace("\"", "").strip(); + mappings.add(item); + } + } + return mappings; + } + + private static List dependencyStageCopies(String dockerfile) { + String prefix = dockerfile.substring(0, dockerfile.indexOf("./gradlew")); + return prefix.lines().filter(line -> line.startsWith("COPY ")).toList(); + } + + @Test + @Tag("repository-contract") void dockerBuildConsumesOnlyTheGradleStagedExecutableJar() throws IOException { String dockerfile = "src/Dockerfile"; String module = "app-bootstrap"; @@ -364,6 +504,7 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") void dockerContractRejectsAWorkdirOverrideBeforeTheFirstGradleInvocation() throws IOException { String dockerfile = "src/Dockerfile"; String content = read(dockerfile); @@ -380,6 +521,7 @@ class DeveloperExperienceContractTest { } @Test + @Tag("repository-contract") void dockerContractRejectsJarSelectorsRegardlessOfRunCommandPrefix() throws IOException { String dockerfile = "src/Dockerfile"; String content = read(dockerfile); @@ -499,13 +641,9 @@ class DeveloperExperienceContractTest { } private static Path repositoryRoot() { - for (Path path = Paths.get("").toAbsolutePath(); path != null; path = path.getParent()) { - if (Files.isRegularFile(path.resolve("AGENTS.md")) - && Files.isRegularFile(path.resolve("src/settings.gradle"))) { - return path; - } - } - throw new IllegalStateException( - "repository root not found from " + Paths.get("").toAbsolutePath()); + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } } 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 912ef5fa..e2c594d3 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 @@ -23,7 +23,7 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.slf4j.MDC; import org.springframework.beans.factory.support.DefaultListableBeanFactory; @@ -55,7 +55,6 @@ class DistributedTracingContractTest { private static Map metricsRoot; private static Map mdcRoot; - @BeforeAll static void loadRegistries() throws Exception { RepositoryContractResources resources = RepositoryContractResources.fromSystemProperty(); Path headersPath = resources.requireTrackedFile("docs/registries/headers.yaml"); @@ -135,8 +134,10 @@ class DistributedTracingContractTest { * tracestate} row exists with {@code generated_if_missing: false}; AND that code agrees: {@code * MdcKeys.TRACE_ID == "trace_id"} and {@link ResponseMeta} has a {@code traceId} component. */ + @Tag("document-contract") @Test - void traceparentHeaderRowMatchesCodeContract() { + void traceparentHeaderRowMatchesCodeContract() throws Exception { + loadRegistries(); @SuppressWarnings("unchecked") List> headers = (List>) headersRoot.get("headers"); @@ -189,8 +190,10 @@ class DistributedTracingContractTest { * local]}; AND registers {@link TracingSamplingRateGauge} against a {@link SimpleMeterRegistry} * and asserts exactly one {@code tracing.sampling.rate} series exists (cardinality 1 ≤ 4). */ + @Tag("document-contract") @Test - void tracingSamplingRateGaugeRegistryContract() { + void tracingSamplingRateGaugeRegistryContract() throws Exception { + loadRegistries(); @SuppressWarnings("unchecked") List> metrics = (List>) metricsRoot.get("metrics"); @@ -267,8 +270,10 @@ class DistributedTracingContractTest { assertThat(MdcKeys.SPAN_ID).isEqualTo("span_id"); } + @Tag("document-contract") @Test - void mdcKeysYamlListsTraceIdAndSpanId() { + void mdcKeysYamlListsTraceIdAndSpanId() throws Exception { + loadRegistries(); @SuppressWarnings("unchecked") List> keys = (List>) mdcRoot.get("mdc_keys"); Set keyNames = diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/EnvProfileMatrixContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/EnvProfileMatrixContractTest.java index 015ea0c8..60521746 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/EnvProfileMatrixContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/EnvProfileMatrixContractTest.java @@ -8,6 +8,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -16,6 +17,7 @@ import org.junit.jupiter.api.Test; *

      Reserved switches for unimplemented error-detail exposure and body logging are intentionally * absent; profile-matrix tests must not treat nonexistent features as safety controls. */ +@Tag("document-contract") class EnvProfileMatrixContractTest { @Test diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ErrorCodeRegistryMappingTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ErrorCodeRegistryMappingTest.java index c4a86338..0fc6b494 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ErrorCodeRegistryMappingTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ErrorCodeRegistryMappingTest.java @@ -12,6 +12,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -26,6 +27,7 @@ import org.yaml.snakeyaml.Yaml; * (405/406/412/413/414/415) are actually present in the registry — a missing row is a FAIL, never a * silent SKIP (design record §Edge). */ +@Tag("document-contract") class ErrorCodeRegistryMappingTest { private static Map registryHttpStatusByCode; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/HeaderRegistryRuntimeAlignmentTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/HeaderRegistryRuntimeAlignmentTest.java index 6d87719b..02a0a03b 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/HeaderRegistryRuntimeAlignmentTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/HeaderRegistryRuntimeAlignmentTest.java @@ -10,10 +10,12 @@ import java.nio.file.Path; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.yaml.snakeyaml.Yaml; +@Tag("document-contract") class HeaderRegistryRuntimeAlignmentTest { private static List> headers; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockAcquisitionTimeoutClassificationContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockAcquisitionTimeoutClassificationContractTest.java index 09742d78..bd60c7a7 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockAcquisitionTimeoutClassificationContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockAcquisitionTimeoutClassificationContractTest.java @@ -13,7 +13,7 @@ import java.time.Duration; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -32,7 +32,6 @@ class LockAcquisitionTimeoutClassificationContractTest { private static Map> errorRegistryByCode; private static List> metricsRows; - @BeforeAll static void loadRegistries() throws Exception { RepositoryContractResources resources = RepositoryContractResources.fromSystemProperty(); Path errorRegistry = resources.requireTrackedFile("docs/registries/error-codes.yaml"); @@ -93,8 +92,10 @@ class LockAcquisitionTimeoutClassificationContractTest { // ---- registry-row leg ----------------------------------------------------- + @Tag("document-contract") @Test - void registryRowAgreesWithTheEnumClassification() { + void registryRowAgreesWithTheEnumClassification() throws Exception { + loadRegistries(); Map row = errorRegistryByCode.get("LOCK_ACQUISITION_TIMEOUT"); assertThat(row) .as("registry must define LOCK_ACQUISITION_TIMEOUT (feature-distributed-lock-contract D7)") @@ -112,8 +113,10 @@ class LockAcquisitionTimeoutClassificationContractTest { // ---- metrics-row leg ------------------------------------------------------ + @Tag("document-contract") @Test - void metricsRegistryContainsLockAcquisitionWithBoundedOutcomeTag() { + void metricsRegistryContainsLockAcquisitionWithBoundedOutcomeTag() throws Exception { + loadRegistries(); Map lockAcquisitionRow = metricsRows.stream() .filter(row -> "lock.acquisition".equals(row.get("name"))) diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockFailureClassificationContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockFailureClassificationContractTest.java index ce0bc18b..a4d19cca 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockFailureClassificationContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockFailureClassificationContractTest.java @@ -12,7 +12,7 @@ import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -61,7 +61,6 @@ class LockFailureClassificationContractTest { private static Map> registryByCode; - @BeforeAll static void loadRegistry() throws Exception { Path registry = RepositoryContractResources.fromSystemProperty() @@ -155,8 +154,10 @@ class LockFailureClassificationContractTest { // ---- required registry rows agree with the classified policy (fail-closed) ---- + @Tag("document-contract") @Test - void registryRowsAgreeWithTheLockClassificationPolicy() { + void registryRowsAgreeWithTheLockClassificationPolicy() throws Exception { + loadRegistry(); RETRYABLE_LOCK_CONFLICTS.forEach(code -> assertRegistryRow(code, "CONFLICT", 409, true)); assertRegistryRow(NON_RETRYABLE_CONFLICT, "CONFLICT", 409, false); assertRegistryRow(OPTIMISTIC_CONFLICT, "CONFLICT", 409, false); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ManagementActuatorSecurityContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ManagementActuatorSecurityContractTest.java index e9e73b4d..b94041c6 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ManagementActuatorSecurityContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ManagementActuatorSecurityContractTest.java @@ -14,7 +14,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; import org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties; @@ -48,16 +48,16 @@ import org.yaml.snakeyaml.Yaml; class ManagementActuatorSecurityContractTest { // ---- Required registry cross-check ---- + // Only the registry row comparison reads the repository, so only it carries the + // document-contract tag and runs in the main stage; the actuator exposure contracts below stay in + // the pull request's `test` (review 2026-11-01 08-03). private static RepositoryContractResources repositoryResources; - private static Path registry; - private static Map> rowsByCode; - @BeforeAll - static void loadRegistry() throws Exception { + private static Map> loadRegistry() throws Exception { repositoryResources = RepositoryContractResources.fromSystemProperty(); - registry = repositoryResources.requireTrackedFile("docs/registries/error-codes.yaml"); - rowsByCode = new LinkedHashMap<>(); + Path registry = repositoryResources.requireTrackedFile("docs/registries/error-codes.yaml"); + Map> rowsByCode = new LinkedHashMap<>(); try (InputStream in = Files.newInputStream(registry)) { Map root = new Yaml().load(in); @SuppressWarnings("unchecked") @@ -66,6 +66,7 @@ class ManagementActuatorSecurityContractTest { rowsByCode.put((String) row.get("code"), row); } } + return rowsByCode; } // ---- contract-verification:management-actuator @@ -81,8 +82,9 @@ class ManagementActuatorSecurityContractTest { } @Test - void actuatorForbiddenMatchesRegistryRow() { - Map row = rowsByCode.get("ACTUATOR_FORBIDDEN"); + @Tag("document-contract") + void actuatorForbiddenMatchesRegistryRow() throws Exception { + Map row = loadRegistry().get("ACTUATOR_FORBIDDEN"); assertThat(row).as("error-codes.yaml must contain row ACTUATOR_FORBIDDEN").isNotNull(); assertThat(row.get("category")).as("ACTUATOR_FORBIDDEN category").isEqualTo("AUTHZ"); assertThat(((Number) row.get("http_status")).intValue()) diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/MetricsAlertingContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/MetricsAlertingContractTest.java index 7b7f903d..304d293a 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/MetricsAlertingContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/MetricsAlertingContractTest.java @@ -18,8 +18,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -39,7 +39,6 @@ class MetricsAlertingContractTest { private static Map metricsRoot; private static List> metrics; - @BeforeAll @SuppressWarnings( "unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the // metrics.yaml contract @@ -57,9 +56,11 @@ class MetricsAlertingContractTest { // Global checks — every row // ================================================================ + @Tag("document-contract") @Test @DisplayName("D2: every metric name passes MetricNaming.isValidName()") - void everyMetricNameIsValidDotCase() { + void everyMetricNameIsValidDotCase() throws Exception { + loadRegistry(); for (Map row : metrics) { String name = (String) row.get("name"); assertThat(MetricNaming.isValidName(name)) @@ -68,9 +69,11 @@ class MetricsAlertingContractTest { } } + @Tag("document-contract") @Test @DisplayName("D2: every metric unit is in {seconds, bytes, total}") - void everyMetricUnitIsAllowed() { + void everyMetricUnitIsAllowed() throws Exception { + loadRegistry(); for (Map row : metrics) { String name = (String) row.get("name"); String unit = (String) row.get("unit"); @@ -80,12 +83,14 @@ class MetricsAlertingContractTest { } } + @Tag("document-contract") @Test @DisplayName("D8: no row has a tag whose name is in ForbiddenMetricTags.FORBIDDEN") @SuppressWarnings( "unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the // metrics.yaml contract - void noRowHasForbiddenTag() { + void noRowHasForbiddenTag() throws Exception { + loadRegistry(); for (Map row : metrics) { String metricName = (String) row.get("name"); List> tags = (List>) row.get("tags"); @@ -102,9 +107,11 @@ class MetricsAlertingContractTest { } } + @Tag("document-contract") @Test @DisplayName("every row's required_test equals 'contract-verification:metrics-cardinality'") - void everyRowHasCorrectRequiredTest() { + void everyRowHasCorrectRequiredTest() throws Exception { + loadRegistry(); for (Map row : metrics) { String name = (String) row.get("name"); assertThat(row.get("required_test")) @@ -113,13 +120,15 @@ class MetricsAlertingContractTest { } } + @Tag("document-contract") @Test @DisplayName( "§Cardinality Bounds: tag cardinality_limit <= CardinalityBounds.limitFor() where defined") @SuppressWarnings( "unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the // metrics.yaml contract - void tagCardinalityLimitsRespectBounds() { + void tagCardinalityLimitsRespectBounds() throws Exception { + loadRegistry(); for (Map row : metrics) { String metricName = (String) row.get("name"); List> tags = (List>) row.get("tags"); @@ -145,12 +154,14 @@ class MetricsAlertingContractTest { } } + @Tag("document-contract") @Test @DisplayName("§P1/P2/P3: alert_severity_thresholds keys must parse via AlertSeverity.fromKey()") @SuppressWarnings( "unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the // metrics.yaml contract - void alertSeverityThresholdKeysAreValid() { + void alertSeverityThresholdKeysAreValid() throws Exception { + loadRegistry(); for (Map row : metrics) { String metricName = (String) row.get("name"); Map thresholds = (Map) row.get("alert_severity_thresholds"); @@ -173,13 +184,15 @@ class MetricsAlertingContractTest { } } + @Tag("document-contract") @Test @DisplayName( "D9: every row with histogram_buckets='slo_driven' also declares non-empty percentiles") @SuppressWarnings( "unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the // metrics.yaml contract - void sloDrivenTimersDeclarePercentiles() { + void sloDrivenTimersDeclarePercentiles() throws Exception { + loadRegistry(); for (Map row : metrics) { String metricName = (String) row.get("name"); Object histBuckets = row.get("histogram_buckets"); @@ -200,9 +213,11 @@ class MetricsAlertingContractTest { // Row-specific checks — §테스트 계약 explicit bullets // ================================================================ + @Tag("document-contract") @Test @DisplayName("§테스트 계약 #1: http.server.requests row exists with method/status/uri_template tags") - void httpServerRequestsRowExistsWithRequiredTags() { + void httpServerRequestsRowExistsWithRequiredTags() throws Exception { + loadRegistry(); Map row = findRow("http.server.requests"); assertThat(row).as("metrics.yaml must contain an 'http.server.requests' row").isNotNull(); @@ -212,13 +227,15 @@ class MetricsAlertingContractTest { .contains("method", "status", "uri_template"); } + @Tag("document-contract") @Test @DisplayName( "§테스트 계약 #2: dependency.client.requests row exists with dependency_name/dependency_type tags and P1 alert") @SuppressWarnings( "unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the // metrics.yaml contract - void dependencyClientRequestsRowExistsWithRequiredTagsAndP1Alert() { + void dependencyClientRequestsRowExistsWithRequiredTagsAndP1Alert() throws Exception { + loadRegistry(); Map row = findRow("dependency.client.requests"); assertThat(row).as("metrics.yaml must contain a 'dependency.client.requests' row").isNotNull(); @@ -239,13 +256,15 @@ class MetricsAlertingContractTest { .containsKey("p1"); } + @Tag("document-contract") @Test @DisplayName( "§테스트 계약 #3: hikaricp.connections.acquire row exists with outcome tag containing TIMEOUT and non-empty alerts") @SuppressWarnings( "unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the // metrics.yaml contract - void hikaricpConnectionsAcquireRowExistsWithTimeoutOutcome() { + void hikaricpConnectionsAcquireRowExistsWithTimeoutOutcome() throws Exception { + loadRegistry(); Map row = findRow("hikaricp.connections.acquire"); assertThat(row) .as( @@ -274,12 +293,14 @@ class MetricsAlertingContractTest { .isNotEmpty(); } + @Tag("document-contract") @Test @DisplayName("every row owned by this branch has non-empty alert_severity_thresholds") @SuppressWarnings( "unchecked") // SnakeYAML returns untyped Object; the registry shape is fixed by the // metrics.yaml contract - void everyBranchOwnedRowHasAlertSeverityThresholds() { + void everyBranchOwnedRowHasAlertSeverityThresholds() throws Exception { + loadRegistry(); for (Map row : metrics) { if (!"feature-metrics-alerting-contract".equals(row.get("owner_branch"))) { continue; @@ -354,10 +375,12 @@ class MetricsAlertingContractTest { .isNull(); } + @Tag("document-contract") @Test @DisplayName( "registry↔filter coverage: every owned slo_driven timer in metrics.yaml is configured by MetricsDistributionMeterFilter") - void everyOwnedSloDrivenTimerIsConfiguredByDistributionFilter() { + void everyOwnedSloDrivenTimerIsConfiguredByDistributionFilter() throws Exception { + loadRegistry(); var filter = new MetricsDistributionMeterFilter(); for (Map row : metrics) { diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java index 9f2956ea..5f561936 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.bootstrap.contract; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.ClientErrorMessages; import java.io.IOException; @@ -16,6 +17,7 @@ import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; @@ -35,6 +37,7 @@ import org.yaml.snakeyaml.constructor.SafeConstructor; * shared-contract} is Java-stdlib-only by policy and this repository already parses the same * registry here for the runbook coverage contract. */ +@Tag("document-contract") class OperationalErrorRegistryContractTest { private static final String REGISTRY = "docs/registries/error-codes.yaml"; @@ -161,12 +164,9 @@ class OperationalErrorRegistryContractTest { } private static Path repositoryRoot() { - for (Path path = Path.of("").toAbsolutePath(); path != null; path = path.getParent()) { - if (Files.isRegularFile(path.resolve("AGENTS.md")) - && Files.isRegularFile(path.resolve("src/settings.gradle"))) { - return path; - } - } - throw new IllegalStateException("repository root not found"); + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/PersistenceFailureMappingContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/PersistenceFailureMappingContractTest.java index e178c345..4c9a4600 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/PersistenceFailureMappingContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/PersistenceFailureMappingContractTest.java @@ -18,7 +18,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; @@ -65,7 +65,6 @@ class PersistenceFailureMappingContractTest { private static Map> registryByCode; - @BeforeAll static void loadRegistry() throws Exception { Path registry = RepositoryContractResources.fromSystemProperty() @@ -102,8 +101,10 @@ class PersistenceFailureMappingContractTest { // ---- each classified code agrees with the required registry row ---- + @Tag("document-contract") @Test - void everyClassifiedCodeAgreesWithTheRegistryRow() { + void everyClassifiedCodeAgreesWithTheRegistryRow() throws Exception { + loadRegistry(); MATRIX.forEach( (sqlState, expected) -> { Map row = registryByCode.get(expected.code()); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/PiiTokenBodyForbiddenContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/PiiTokenBodyForbiddenContractTest.java index 7001ff66..7b315726 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/PiiTokenBodyForbiddenContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/PiiTokenBodyForbiddenContractTest.java @@ -12,6 +12,7 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.regex.Pattern; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -108,6 +109,7 @@ class PiiTokenBodyForbiddenContractTest { .doesNotContain("eyJhbGciOiJIUzI1NiInPayload"); } + @Tag("repository-contract") @Test void requestLoggingHasNoBodyCapturePath() throws IOException { Path filter = diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java index 407d8447..3280dc8f 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java @@ -2,11 +2,11 @@ package dev.caskeleton.bootstrap.contract; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import dev.caskeleton.bootstrap.contract.support.ShippedConfiguration; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; @@ -17,6 +17,7 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -40,6 +41,7 @@ import org.yaml.snakeyaml.constructor.SafeConstructor; * test guards, is the wiring between them drifting — a profile quietly changing vendor, or local * regaining a migration expectation it cannot satisfy. */ +@Tag("repository-contract") class ProfileSeparationContractTest { private static final Path REPOSITORY_ROOT = repositoryRoot(); @@ -177,14 +179,10 @@ class ProfileSeparationContractTest { } private static Path repositoryRoot() { - for (Path path = Paths.get("").toAbsolutePath(); path != null; path = path.getParent()) { - if (Files.isRegularFile(path.resolve("AGENTS.md")) - && Files.isRegularFile(path.resolve("src/settings.gradle"))) { - return path; - } - } - throw new IllegalStateException( - "repository root not found from " + Paths.get("").toAbsolutePath()); + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } /** diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RepositoryAccessCapabilityRegistryTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RepositoryAccessCapabilityRegistryTest.java index ecec9a2c..b0514591 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RepositoryAccessCapabilityRegistryTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RepositoryAccessCapabilityRegistryTest.java @@ -12,7 +12,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -45,7 +45,6 @@ class RepositoryAccessCapabilityRegistryTest { private static Set registryCapabilityNames; - @BeforeAll static void loadRegistry() throws Exception { Path registry = RepositoryContractResources.fromSystemProperty() @@ -75,8 +74,10 @@ class RepositoryAccessCapabilityRegistryTest { } } + @Tag("document-contract") @Test - void registryCapabilityNamesMatchTheAsBuiltModelOneToOne() { + void registryCapabilityNamesMatchTheAsBuiltModelOneToOne() throws Exception { + loadRegistry(); Set expected = asBuiltVocabulary(); assertThat(registryCapabilityNames) diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java index b23eefd1..c89a5109 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RunbookCoverageContractTest.java @@ -15,6 +15,7 @@ import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.yaml.snakeyaml.Yaml; @@ -45,6 +46,7 @@ import org.yaml.snakeyaml.Yaml; *

      {@code template.md} is excluded from coverage and stub enforcement — it is the canonical * runbook template, not a real runbook. */ +@Tag("document-contract") class RunbookCoverageContractTest { /** diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SampleRuntimeDefaultsContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SampleRuntimeDefaultsContractTest.java new file mode 100644 index 00000000..543e31cb --- /dev/null +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SampleRuntimeDefaultsContractTest.java @@ -0,0 +1,108 @@ +package dev.caskeleton.bootstrap.contract; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; + +/** + * The sample keeps the default composition's runtime defaults, so a number measured on the sample — + * thread count, pool wait — says something about the composition a service ships (09-08). It reads + * two configuration files, so it runs in the pull-request {@code repository-contract} lane (08-03). + */ +@Tag("repository-contract") +class SampleRuntimeDefaultsContractTest { + + private static final Path REPOSITORY_ROOT = repositoryRoot(); + private static final Pattern DEFAULT = Pattern.compile("^\\$\\{[A-Z0-9_]+:(.*)}$"); + + @Test + @DisplayName("샘플은 가상 스레드와 앱 로그 레벨 기본값을 기본 조합과 같게 둔다") + void theSampleKeepsTheDefaultCompositionRuntimeDefaults() throws IOException { + // given + Map bootstrap = new LinkedHashMap<>(); + flatten("", load("src/app-bootstrap/src/main/resources/application.yml"), bootstrap); + flatten("", load("src/app-bootstrap/src/main/resources/config/observability.yml"), bootstrap); + Map sample = new LinkedHashMap<>(); + flatten("", load("src/sample-portfolio/src/main/resources/application.yml"), sample); + + // when + Map differing = new LinkedHashMap<>(); + for (String key : + new String[] {"spring.threads.virtual.enabled", "logging.level.dev.caskeleton"}) { + String expected = defaultOf(bootstrap.get(key)); + String actual = defaultOf(sample.get(key)); + if (actual != null && !actual.equals(expected)) { + differing.put(key, actual + " (default composition: " + expected + ")"); + } + } + + // then + assertThat(differing).isEmpty(); + } + + @Test + @DisplayName("샘플은 persistence-jpa 모듈의 풀 대기 시간 기본값을 덮어쓰지 않는다") + void theSampleDoesNotOverrideTheModulePoolWait() throws IOException { + // given + Map sample = new LinkedHashMap<>(); + flatten("", load("src/sample-portfolio/src/main/resources/application.yml"), sample); + + // when + Object connectionTimeout = sample.get("spring.datasource.hikari.connection-timeout"); + + // then + // The module's 5000 ms is a fail-fast decision; the sample's 30000 made a dry pool wait six + // times longer there than in the default composition. + assertThat(connectionTimeout).isNull(); + } + + private static String defaultOf(Object value) { + if (value == null) { + return null; + } + String text = String.valueOf(value).trim(); + Matcher matcher = DEFAULT.matcher(text); + return matcher.matches() ? matcher.group(1) : text; + } + + private static Map load(String relative) throws IOException { + LoaderOptions options = new LoaderOptions(); + options.setMaxAliasesForCollections(0); + Object first = + new Yaml(new SafeConstructor(options)) + .loadAll(Files.readString(REPOSITORY_ROOT.resolve(relative))) + .iterator() + .next(); + assertThat(first).as(relative).isInstanceOf(Map.class); + return (Map) first; + } + + private static void flatten(String prefix, Map map, Map into) { + map.forEach( + (key, value) -> { + String name = prefix.isEmpty() ? String.valueOf(key) : prefix + "." + key; + if (value instanceof Map child) { + flatten(name, child, into); + } else { + into.put(name, value); + } + }); + } + + private static Path repositoryRoot() { + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); + } +} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java index c4e13c94..5e8c33bf 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -28,6 +29,7 @@ import org.yaml.snakeyaml.Yaml; * Mirrors the {@code RepositoryAccessCapabilityRegistryTest} / {@code ErrorCodeRegistryMappingTest} * registry-drift pattern. */ +@Tag("document-contract") class SecretsClassificationRegistryTest { private static final Set VALID_TIERS = diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SqlLoggingForbiddenContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SqlLoggingForbiddenContractTest.java index 99b84552..547fd304 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SqlLoggingForbiddenContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SqlLoggingForbiddenContractTest.java @@ -7,6 +7,7 @@ import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Properties; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -19,6 +20,7 @@ import org.junit.jupiter.api.Test; *

      {@code src/.env} is the committed runtime defaults file. Missing or unreadable defaults are a * hard contract failure. */ +@Tag("repository-contract") class SqlLoggingForbiddenContractTest { private Properties loadEnv() throws Exception { diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/StructuredLogFieldContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/StructuredLogFieldContractTest.java index 46a0b0f9..799bfeb5 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/StructuredLogFieldContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/StructuredLogFieldContractTest.java @@ -12,6 +12,8 @@ import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -41,6 +43,7 @@ class StructuredLogFieldContractTest { private static final Set REQUIRED_CORRELATION_FIELDS = Set.of("request_id", "trace_id", "correlation_id"); + @Tag("document-contract") @Test void structuredAppenderEmitsOnlyRegisteredSnakeCaseFields() throws IOException { Set emittedFields = includeMdcKeyNames(); @@ -70,18 +73,31 @@ class StructuredLogFieldContractTest { } @Test - void logbackEarlyPropertiesDoNotResolveApplicationYamlPlaceholders() throws IOException { + @DisplayName("Logback은 로깅 설정을 app.logging.* 한 곳에서 읽고, 프로필·앱 이름은 env 이름으로 읽는다") + void logbackReadsLoggingKnobsFromTheSettingsTreeAndIdentityFromTheEnvironment() + throws IOException { + // given String logback = logbackText(); + // when + boolean readsLoggingVariablesDirectly = logback.contains("source=\"APP_LOG_"); + + // then + // The logging knobs are springProperty reads of the Spring Environment, so app.logging.* in a + // profile file or on the command line reaches Logback the same way APP_LOG_* does through the + // YAML mapping (07-06). Both spellings are read at the same moment, so neither sees a value + // that arrives later than Logback's initialisation. + assertThat(readsLoggingVariablesDirectly).isFalse(); + assertThat(logback) + .contains("source=\"app.logging.file.enabled\"") + .contains("source=\"app.logging.sampling-rate\""); + // The profile is corrected after resolution by ResolvedProfileLoggingContextListener, and the + // early value must not be read from spring.profiles.active, which is empty at that point. assertThat(logback) - .as("Logback initializes before dotenv-backed application.yml placeholders are reliable") .doesNotContain("source=\"spring.application.name\"") .doesNotContain("source=\"spring.profiles.active\"") - .doesNotContain("source=\"app.logging."); - assertThat(logback) .contains("source=\"APP_NAME\"") - .contains("source=\"SPRING_PROFILES_ACTIVE\"") - .contains("source=\"APP_LOG_FILE_ENABLED\""); + .contains("source=\"SPRING_PROFILES_ACTIVE\""); } /** Distinct {@code } values from the structured JSON appenders. */ diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java index 3208e755..d1f2468c 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java @@ -2,11 +2,13 @@ package dev.caskeleton.bootstrap.contract.graphql; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -28,6 +30,7 @@ import org.junit.jupiter.api.Test; * /graphql} and reads the body rather than the status, because a failed resolution is a {@code 200} * carrying an {@code errors} array. */ +@Tag("repository-contract") class GraphQlResolverReachabilityTest { @Test @@ -77,14 +80,9 @@ class GraphQlResolverReachabilityTest { } private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java index a981da95..143039be 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.bootstrap.contract.messaging; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -10,6 +11,7 @@ import java.util.List; import java.util.regex.Pattern; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -35,6 +37,7 @@ import org.junit.jupiter.api.Test; * and the starter, which is the boundary working. A test that could see both would be evidence the * boundary had gone. */ +@Tag("repository-contract") class MessagingAuthorityContractTest { private static final Pattern MESSAGING_PREFIX = @@ -143,15 +146,10 @@ class MessagingAuthorityContractTest { } private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } private record ProductionSource(Path path, String text) {} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingPublicSurfaceContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingPublicSurfaceContractTest.java index 00756f7d..922d9399 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingPublicSurfaceContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingPublicSurfaceContractTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.bootstrap.contract.messaging; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -16,6 +17,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -41,6 +43,7 @@ import org.junit.jupiter.api.Test; * composition boundary, where the container constructs the types rather than an adopter naming * them, and that boundary is where the family policy already confines them. */ +@Tag("repository-contract") class MessagingPublicSurfaceContractTest { /** @@ -375,14 +378,9 @@ class MessagingPublicSurfaceContractTest { } private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("the repository root is not above the working directory"); - } - return candidate; + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/outbox/OutboxStatusRegistryContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/outbox/OutboxStatusRegistryContractTest.java index 5e70c8df..d8bf639c 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/outbox/OutboxStatusRegistryContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/outbox/OutboxStatusRegistryContractTest.java @@ -13,6 +13,7 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -21,6 +22,7 @@ import org.yaml.snakeyaml.Yaml; * outbox.pending.size} allowed_values, and {@code OUTBOX_*} 2 error codes ↔ {@code * error-codes.yaml} category/retryable. */ +@Tag("document-contract") class OutboxStatusRegistryContractTest { private static Map metricsRoot; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/RepositoryContractResources.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/RepositoryContractResources.java index a241a654..7df584ee 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/RepositoryContractResources.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/RepositoryContractResources.java @@ -7,7 +7,15 @@ import java.nio.file.Path; import java.util.List; import java.util.Objects; -/** Resolves checked-in repository resources for fail-closed contract tests. */ +/** + * Resolves checked-in repository resources for fail-closed contract tests. + * + *

      Gradle passes the root only to the two lanes that declare the files they read as inputs: + * {@code documentContractTest} (tag {@code document-contract}, main stage) and {@code + * repositoryContractTest} (tag {@code repository-contract}, pull request). The plain {@code test} + * lane gets no root, so an untagged test that reads the repository fails here rather than passing + * on a stale up-to-date result (review 2026-11-01 08-03). + */ public final class RepositoryContractResources { public static final String ROOT_PROPERTY = "ca.repository.root"; @@ -36,7 +44,10 @@ public final class RepositoryContractResources { String configuredRoot = System.getProperty(ROOT_PROPERTY); if (configuredRoot == null || configuredRoot.isBlank()) { throw new IllegalStateException( - "Required system property '" + ROOT_PROPERTY + "' is missing or blank"); + "Required system property '" + + ROOT_PROPERTY + + "' is missing or blank. Only the document-contract and repository-contract lanes" + + " receive it: tag a test that reads the repository with one of the two."); } try { return new RepositoryContractResources(Path.of(configuredRoot)); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/RepositoryContractResourcesTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/RepositoryContractResourcesTest.java index 5395220e..cb2360a9 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/RepositoryContractResourcesTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/RepositoryContractResourcesTest.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -25,6 +26,7 @@ class RepositoryContractResourcesTest { } @Test + @Tag("repository-contract") void gradleInjectsTheCanonicalRepositoryRoot() { RepositoryContractResources resources = RepositoryContractResources.fromSystemProperty(); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/logging/LoggingConfigurationRuleTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/logging/LoggingConfigurationRuleTest.java new file mode 100644 index 00000000..4b45d8a2 --- /dev/null +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/logging/LoggingConfigurationRuleTest.java @@ -0,0 +1,91 @@ +package dev.caskeleton.bootstrap.logging; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.mock.env.MockEnvironment; + +class LoggingConfigurationRuleTest { + + private final LoggingConfigurationRule rule = new LoggingConfigurationRule(); + + @Test + @DisplayName("기본값 그대로면 위반이 없다") + void theShippedDefaultsHaveNoViolation() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty("app.logging.file.enabled", "false") + .withProperty("app.logging.async.enabled", "true") + .withProperty("app.logging.async.queue-size", "512") + .withProperty("app.logging.async.discarding-threshold", "20") + .withProperty("app.logging.json.timezone", "UTC") + .withProperty("app.logging.json.logger-name-length", "0") + .withProperty("app.logging.sampling-rate", "1.0"); + + // when + List violations = rule.violations(environment); + + // then + assertThat(violations).isEmpty(); + } + + @Test + @DisplayName("파일 로그를 켰는데 경로가 비고 보관 일수가 0이면 둘 다 env 키 이름으로 보고한다") + void fileLoggingWithABlankPathAndZeroHistoryReportsBoth() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty("app.logging.file.enabled", "true") + .withProperty("app.logging.file.path", " ") + .withProperty("app.logging.file.max-history", "0"); + + // when + List violations = rule.violations(environment); + + // then + assertThat(violations) + .anyMatch(violation -> violation.startsWith("APP_LOG_FILE_PATH")) + .anyMatch(violation -> violation.startsWith("APP_LOG_FILE_MAX_HISTORY")); + } + + @Test + @DisplayName("파일 로그가 꺼져 있으면 파일 설정 값은 보지 않는다") + void fileSettingsAreIgnoredWhileFileLoggingIsOff() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty("app.logging.file.enabled", "false") + .withProperty("app.logging.file.max-history", "0"); + + // when + List violations = rule.violations(environment); + + // then + assertThat(violations).isEmpty(); + } + + @Test + @DisplayName("비동기 큐 크기 0, 잘못된 시간대, 범위 밖 샘플링 비율을 모두 한 번에 보고한다") + void everyInvalidValueIsReportedAtOnce() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty("app.logging.async.enabled", "true") + .withProperty("app.logging.async.queue-size", "0") + .withProperty("app.logging.json.timezone", "Mars/Base") + .withProperty("app.logging.sampling-rate", "1.5"); + + // when + List violations = rule.violations(environment); + + // then + assertThat(violations) + .hasSize(3) + .anyMatch(violation -> violation.startsWith("APP_LOG_ASYNC_QUEUE_SIZE")) + .anyMatch(violation -> violation.startsWith("APP_LOG_JSON_TIMEZONE")) + .anyMatch(violation -> violation.startsWith("APP_LOG_SAMPLING_RATE")); + } +} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/MongoRegistryPermissionParityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/MongoRegistryPermissionParityTest.java index 89b6c3b2..d42fa12d 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/MongoRegistryPermissionParityTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/MongoRegistryPermissionParityTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -14,6 +15,7 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -30,6 +32,7 @@ import org.junit.jupiter.api.Test; * widens both the build and the registry in the same change, which is the review this exists to * force; freezing the list at zero would only move the argument to this file. */ +@Tag("repository-contract") class MongoRegistryPermissionParityTest { private static final String MODULE_ID = "adapter-outbound-persistence-mongo"; @@ -108,15 +111,9 @@ class MongoRegistryPermissionParityTest { } private static Path repositoryRoot() { - Path directory = Path.of("").toAbsolutePath(); - while (directory != null - && !Files.isRegularFile(directory.resolve(Path.of("src", "settings.gradle")))) { - directory = directory.getParent(); - } - if (directory == null) { - throw new AssertionError( - "cannot locate the repository root from " + Path.of("").toAbsolutePath()); - } - return directory; + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/ReleaseManifestTaskExistenceTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/ReleaseManifestTaskExistenceTest.java index 1c3a6cea..82746f04 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/ReleaseManifestTaskExistenceTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/ReleaseManifestTaskExistenceTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -12,6 +13,7 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -27,6 +29,7 @@ import org.junit.jupiter.api.Test; * tail wagging the dog. They now sit under {@code experimental_contracts}, which this test does not * read, and {@code contracts} means "blocking, and therefore must exist". */ +@Tag("repository-contract") class ReleaseManifestTaskExistenceTest { private static final Pattern REGISTERED_TASK = @@ -114,14 +117,9 @@ class ReleaseManifestTaskExistenceTest { } private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } } 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 b435b223..4b193fcf 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 @@ -5,27 +5,30 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets; import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; +import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration; import java.util.Arrays; import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.ConfigurableEnvironment; /** * Contract test for the secret/config-source startup fail-fast guard * (feature-secrets-config-source-contract §2 / C1). Pairs with the {@link SecretSourceValidator} * runtime mechanism so a regression in either the {@code __LOCAL_DEV_} sentinel check (D9) or the - * required-secret-presence check (§테스트 계약) fails the build. Mirrors the {@code - * StartupSafetyValidatorTest} {@code ApplicationContextRunner} pattern. + * required-secret-presence check (§테스트 계약) fails the build. Runs the production wiring ({@link + * SecretSourceConfig}) under support's startup-rule runner, as the application does. */ class SecretSourceValidatorTest { private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(StartupRuleAutoConfiguration.class)) + .withUserConfiguration(SecretSourceConfig.class); /** All required prod secrets set to real (non-sentinel) values. */ private static String[] allRequiredSecretsPresent() { @@ -191,17 +194,55 @@ class SecretSourceValidatorTest { .run(context -> assertThat(context).hasNotFailed()); } - @Configuration - static class ValidatorConfig { + // ---- timing: before any other singleton exists (07-02) ----------------------------------- + + @Test + @DisplayName("prod에서 비밀값이 비어 있으면 다른 싱글턴을 만들기 전에 기동이 실패한다") + void aMissingProdSecretFailsTheBootBeforeAnyOtherSingletonIsCreated() { + // given + AtomicInteger otherSingletons = new AtomicInteger(); + + // when + runner + .withBean("databaseClient", Object.class, () -> otherSingletons.incrementAndGet()) + .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) + .run( + context -> { + // then + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("APP_PRIVACY_PSEUDONYMIZATION_SALT is missing/blank"); + assertThat(otherSingletons).hasValue(0); + }); + } + + @Test + @DisplayName("prod에서 모듈이 기여한 비밀값이 비어 있으면 다른 싱글턴을 만들기 전에 기동이 실패한다") + void aMissingContributedSecretFailsTheBootBeforeAnyOtherSingletonIsCreated() { + // given + AtomicInteger otherSingletons = new AtomicInteger(); + + // when + runner + .withUserConfiguration(ModuleSecretConfig.class) + .withBean("databaseClient", Object.class, () -> otherSingletons.incrementAndGet()) + .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) + .withPropertyValues(allRequiredSecretsPresent()) + .run( + context -> { + // then + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("APP_MODULE_KEY is missing/blank"); + assertThat(otherSingletons).hasValue(0); + }); + } + + @Configuration(proxyBeanMethods = false) + static class ModuleSecretConfig { @Bean - SecretSourceValidator secretSourceValidator( - ConfigurableEnvironment environment, - ObjectProvider contributed) { - // Default backend (ENVIRONMENT) — the presence check resolves through the port. - return new SecretSourceValidator( - environment, - SecretSourceFactory.create(SecretSourceStrategy.ENVIRONMENT, environment), - contributed.orderedStream().toList()); + static RequiredProductionSecrets moduleSecrets() { + return environment -> List.of("APP_MODULE_KEY"); } } } 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 d00b0130..bbd0e594 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 @@ -4,11 +4,13 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; +import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration; import dev.caskeleton.application.lock.DistributedLockPort; -import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.ListableBeanFactory; -import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.assertj.AssertableApplicationContext; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -23,7 +25,9 @@ import org.springframework.context.annotation.Configuration; class StartupSafetyValidatorTest { private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(StartupRuleAutoConfiguration.class)) + .withUserConfiguration(ValidatorConfig.class); @Test void multiInstanceEnabledWithMissingDistributedLockProviderFailsStartup() { @@ -62,11 +66,44 @@ class StartupSafetyValidatorTest { }); } + @Test + @DisplayName("app.runtime 아래 오타 키는 무시되지 않고 기동을 실패시킨다") + void aMisspelledRuntimeKeyFailsStartup() { + // when + runner + .withPropertyValues("app.runtime.multi-instance-enabeld=true") + .run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasStackTraceContaining("multi-instance-enabeld"); + }); + } + @Test void multiInstanceDisabledIsAllowed() { runner.run(context -> assertThat(context).hasNotFailed()); } + @Test + @DisplayName("다중 인스턴스인데 분산 락이 없으면 다른 싱글턴을 만들기 전에 종료 코드 72로 기동이 실패한다") + void aMissingLockProviderFailsTheBootBeforeAnyOtherSingletonIsCreated() { + // given + AtomicInteger otherSingletons = new AtomicInteger(); + + // when + runner + .withBean("databaseClient", Object.class, () -> otherSingletons.incrementAndGet()) + .withPropertyValues("app.runtime.multi-instance-enabled=true") + .run( + context -> { + // then + assertThat(startupFailure(context).getExitCode()).isEqualTo(72); + assertThat(otherSingletons).hasValue(0); + }); + } + private static StartupFailureException startupFailure(AssertableApplicationContext context) { Throwable failure = context.getStartupFailure(); while (failure != null && !(failure instanceof StartupFailureException)) { @@ -76,13 +113,11 @@ class StartupSafetyValidatorTest { return (StartupFailureException) failure; } - @Configuration - @EnableConfigurationProperties(RuntimeSafetySettings.class) + @Configuration(proxyBeanMethods = false) static class ValidatorConfig { @Bean - StartupSafetyValidator startupSafetyValidator( - RuntimeSafetySettings settings, ListableBeanFactory beanFactory) { - return new StartupSafetyValidator(settings, beanFactory); + static StartupSafetyValidator startupSafetyValidator(ListableBeanFactory beanFactory) { + return new StartupSafetyValidator(beanFactory); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java index 2f7983a4..b0766891 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java @@ -49,8 +49,9 @@ class StartupOrderContractTest { @Test void validationAndDefaultingBandIsStrictlyOrdered() { - assertThat(StartupOrder.RUNTIME_ENVIRONMENT_PROFILE).isLessThan(StartupOrder.TRACING_SAMPLING); - assertThat(StartupOrder.TRACING_SAMPLING).isEqualTo(Ordered.LOWEST_PRECEDENCE); + assertThat(StartupOrder.RUNTIME_ENVIRONMENT_PROFILE) + .isLessThan(StartupOrder.TRACING_PROPERTIES); + assertThat(StartupOrder.TRACING_PROPERTIES).isEqualTo(Ordered.LOWEST_PRECEDENCE); } private static Map registeredEnvironmentPostProcessorOrders() throws Exception { diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/PublicHealthPathAgreementTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/PublicHealthPathAgreementTest.java index 0ca7c394..53760e35 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/PublicHealthPathAgreementTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/PublicHealthPathAgreementTest.java @@ -2,12 +2,13 @@ package dev.caskeleton.bootstrap.security; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import dev.caskeleton.bootstrap.contract.support.ShippedConfiguration; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; @@ -27,6 +28,7 @@ import org.springframework.mock.env.MockEnvironment; * which is the failure arriving in the least useful place. The allowlist is derived from the base * path now; this holds it derived. */ +@Tag("repository-contract") class PublicHealthPathAgreementTest { @Test @@ -92,14 +94,9 @@ class PublicHealthPathAgreementTest { } private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; + // Gradle hands the root only to the lanes that declare the repository files as inputs; the + // plain `test` lane gets none, so a test that reads the repository without a lane tag fails + // here instead of going stale behind an up-to-date check (review 2026-11-01 08-03). + return RepositoryContractResources.fromSystemProperty().repositoryRoot(); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/BootstrapSettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/BootstrapSettingsTest.java index b2f992bc..5f3a0f99 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/BootstrapSettingsTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/BootstrapSettingsTest.java @@ -2,19 +2,14 @@ package dev.caskeleton.bootstrap.settings; import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.validation.autoconfigure.ValidationAutoConfiguration; -import org.springframework.context.annotation.Configuration; class BootstrapSettingsTest { private final ApplicationContextRunner runner = - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .withUserConfiguration(EnableProperties.class); + new ApplicationContextRunner().withUserConfiguration(BootstrapSettingsConfig.class); @Test void appNameValidBinds() { @@ -48,7 +43,17 @@ class BootstrapSettingsTest { }); } - @Configuration - @EnableConfigurationProperties(BootstrapSettings.class) - static class EnableProperties {} + @Test + @DisplayName("app.bootstrap 아래 오타 키는 무시되지 않고 기동을 실패시킨다") + void aMisspelledKeyFailsStartup() { + // when + runner + .withPropertyValues("app.bootstrap.app-name=ca-skeleton", "app.bootstrap.app-nmae=typo") + .run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).hasStackTraceContaining("app-nmae"); + }); + } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/LoggingSettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/LoggingSettingsTest.java deleted file mode 100644 index e234e848..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/LoggingSettingsTest.java +++ /dev/null @@ -1,132 +0,0 @@ -package dev.caskeleton.bootstrap.settings; - -import static org.assertj.core.api.Assertions.assertThat; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.read.ListAppender; -import java.util.List; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.context.annotation.Configuration; - -/** - * Verifies the warn-and-default validation policy of {@link LoggingSettings}. - * - *

      Warnings are asserted via a logback {@link ListAppender} attached directly to the settings - * package logger rather than Spring's {@code CapturedOutput}. Reason: {@code LoggingSettings} emits - * warnings through SLF4J, and when the full app-bootstrap suite has already initialised logback - * with the async console appender ({@code ASYNC_CONSOLE} in {@code logback-spring.xml}), the - * warning is written to stdout by the async worker thread. A synchronous {@code - * CapturedOutput.getOut()} read right after {@code .run(...)} then races that flush and fails - * intermittently (passes in isolation, fails inside the full suite). A {@code ListAppender} bound - * to the logger receives each event synchronously on the logging thread, independent of appender - * topology, so the assertion is deterministic. This unit boundary also matches the record's real - * responsibility — "did it warn?" — not "did logback route it to a console". - */ -class LoggingSettingsTest { - - private static final String SETTINGS_LOGGER = "dev.caskeleton.bootstrap.runtime"; - - private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(EnableProperties.class); - - private Logger settingsLogger; - private ListAppender warnings; - - @BeforeEach - void attachWarningCapture() { - settingsLogger = (Logger) LoggerFactory.getLogger(SETTINGS_LOGGER); - warnings = new ListAppender<>(); - warnings.start(); - settingsLogger.addAppender(warnings); - // Ensure WARN passes regardless of the level logback was left at by prior tests. - settingsLogger.setLevel(Level.WARN); - } - - @AfterEach - void detachWarningCapture() { - settingsLogger.detachAppender(warnings); - warnings.stop(); - } - - @Test - void badTimezoneWarnsAndFallsBack() { - runner - .withPropertyValues( - "app.logging.json.timezone=Mars/Olympus_Mons", - "app.logging.json.timestamp-pattern=yyyy-MM-dd'T'HH:mm:ss.SSSXXX", - "app.logging.json.include-caller-data=false", - "app.logging.json.logger-name-length=0", - "app.logging.async.enabled=false", - "app.logging.file.enabled=false") - .run( - context -> { - assertThat(context).hasNotFailed(); - LoggingSettings settings = context.getBean(LoggingSettings.class); - assertThat(settings.json().timezone()).isEqualTo("UTC"); - assertThat(warningMessages()) - .anyMatch( - m -> - m.contains("APP_LOG_JSON_TIMEZONE") && m.contains("'Mars/Olympus_Mons'")); - }); - } - - @Test - void badAsyncQueueSizeWarnsAndFallsBack() { - runner - .withPropertyValues( - "app.logging.async.enabled=true", - "app.logging.async.queue-size=-1", - "app.logging.async.discarding-threshold=20", - "app.logging.file.enabled=false", - "app.logging.json.timezone=UTC", - "app.logging.json.timestamp-pattern=yyyy-MM-dd'T'HH:mm:ss.SSSXXX", - "app.logging.json.include-caller-data=false", - "app.logging.json.logger-name-length=0") - .run( - context -> { - assertThat(context).hasNotFailed(); - LoggingSettings settings = context.getBean(LoggingSettings.class); - assertThat(settings.async().queueSize()).isEqualTo(512); - assertThat(warningMessages()).anyMatch(m -> m.contains("APP_LOG_ASYNC_QUEUE_SIZE")); - }); - } - - @Test - void validValuesNoWarning() { - runner - .withPropertyValues( - "app.logging.async.enabled=true", - "app.logging.async.queue-size=1024", - "app.logging.async.discarding-threshold=10", - "app.logging.file.enabled=false", - "app.logging.json.timezone=Asia/Seoul", - "app.logging.json.timestamp-pattern=yyyy-MM-dd'T'HH:mm:ss.SSSXXX", - "app.logging.json.include-caller-data=false", - "app.logging.json.logger-name-length=0") - .run( - context -> { - assertThat(context).hasNotFailed(); - LoggingSettings settings = context.getBean(LoggingSettings.class); - assertThat(settings.async().queueSize()).isEqualTo(1024); - assertThat(settings.json().timezone()).isEqualTo("Asia/Seoul"); - assertThat(warningMessages()) - .noneMatch(m -> m.contains("APP_LOG_JSON_TIMEZONE")) - .noneMatch(m -> m.contains("APP_LOG_ASYNC_QUEUE_SIZE")); - }); - } - - private List warningMessages() { - return warnings.list.stream().map(ILoggingEvent::getFormattedMessage).toList(); - } - - @Configuration - @EnableConfigurationProperties(LoggingSettings.class) - static class EnableProperties {} -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/adapter/outbound/persistence/repository/FeatureAggregateRepositoryAdapter.java b/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/adapter/outbound/persistence/repository/FeatureAggregateRepositoryAdapter.java index c73e9ea0..7e30b8ab 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/adapter/outbound/persistence/repository/FeatureAggregateRepositoryAdapter.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/adapter/outbound/persistence/repository/FeatureAggregateRepositoryAdapter.java @@ -2,10 +2,10 @@ package dev.caskeleton.onboarding.adapter.outbound.persistence.repository; import dev.caskeleton.onboarding.adapter.outbound.persistence.entity.FeatureAggregateEntity; import dev.caskeleton.onboarding.adapter.outbound.persistence.mapper.FeatureAggregateEntityMapper; -import dev.caskeleton.onboarding.application.port.FeatureAggregateWritePort; import dev.caskeleton.onboarding.domain.feature.FeatureAggregate; +import dev.caskeleton.onboarding.domain.feature.FeatureAggregateRepository; -public final class FeatureAggregateRepositoryAdapter implements FeatureAggregateWritePort { +public final class FeatureAggregateRepositoryAdapter implements FeatureAggregateRepository { private final FeatureAggregateEntityMapper mapper; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/application/port/FeatureAggregateWritePort.java b/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/application/port/FeatureAggregateWritePort.java deleted file mode 100644 index 5c8c253b..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/application/port/FeatureAggregateWritePort.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.onboarding.application.port; - -import dev.caskeleton.onboarding.domain.feature.FeatureAggregate; - -public interface FeatureAggregateWritePort { - - FeatureAggregate save(FeatureAggregate featureAggregate); -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/application/usecase/CreateFeatureAggregateUseCase.java b/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/application/usecase/CreateFeatureAggregateUseCase.java index 781a6437..096f2b21 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/application/usecase/CreateFeatureAggregateUseCase.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/application/usecase/CreateFeatureAggregateUseCase.java @@ -8,27 +8,27 @@ import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.CommandUseCase; import dev.caskeleton.onboarding.application.command.CreateFeatureAggregateCommand; -import dev.caskeleton.onboarding.application.port.FeatureAggregateWritePort; import dev.caskeleton.onboarding.domain.feature.FeatureAggregate; import dev.caskeleton.onboarding.domain.feature.FeatureAggregateIdFactory; +import dev.caskeleton.onboarding.domain.feature.FeatureAggregateRepository; @RequiresPermission("feature-aggregate:write") @UseCaseCapability( transactionMode = TransactionMode.WRITE, idempotency = Idempotency.NOT_IDEMPOTENT, repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) -public final class CreateFeatureAggregateUseCase +public class CreateFeatureAggregateUseCase implements CommandUseCase { - private final FeatureAggregateWritePort writePort; + private final FeatureAggregateRepository repository; private final FeatureAggregateIdFactory idFactory; private final TransactionPort tx; public CreateFeatureAggregateUseCase( - FeatureAggregateWritePort writePort, + FeatureAggregateRepository repository, FeatureAggregateIdFactory idFactory, TransactionPort tx) { - this.writePort = writePort; + this.repository = repository; this.idFactory = idFactory; this.tx = tx; } @@ -36,6 +36,6 @@ public final class CreateFeatureAggregateUseCase @Override public FeatureAggregate handle(CreateFeatureAggregateCommand command) { return tx.inWrite( - () -> writePort.save(FeatureAggregate.create(idFactory.newId(), command.name()))); + () -> repository.save(FeatureAggregate.create(idFactory.newId(), command.name()))); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateId.java b/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateId.java index 6fe08a07..1b19a197 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateId.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateId.java @@ -1,9 +1,10 @@ package dev.caskeleton.onboarding.domain.feature; +import dev.caskeleton.domain.identifier.ResourceId; import dev.caskeleton.domain.stereotype.ValueObject; @ValueObject -public record FeatureAggregateId(String value) { +public record FeatureAggregateId(String value) implements ResourceId { public FeatureAggregateId { if (value == null || value.isBlank()) { throw new IllegalArgumentException("feature aggregate id must not be blank"); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateIdFactory.java b/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateIdFactory.java index e78c8612..b65fd66b 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateIdFactory.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateIdFactory.java @@ -1,6 +1,8 @@ package dev.caskeleton.onboarding.domain.feature; -public interface FeatureAggregateIdFactory { +import dev.caskeleton.domain.identifier.IdFactory; - FeatureAggregateId newId(); -} +/** + * Server-assigned id generation for {@link FeatureAggregate}; an identifier adapter implements it. + */ +public interface FeatureAggregateIdFactory extends IdFactory {} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateRepository.java b/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateRepository.java new file mode 100644 index 00000000..24b168b7 --- /dev/null +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/domain/feature/FeatureAggregateRepository.java @@ -0,0 +1,11 @@ +package dev.caskeleton.onboarding.domain.feature; + +/** + * Aggregate-level persistence for {@link FeatureAggregate}. The domain owns it because it stores + * and returns whole aggregates — the {@code *Repository} side of the naming rule in {@code + * application-core/CLAUDE.md}; a technical store the application owns is a {@code *StorePort}. + */ +public interface FeatureAggregateRepository { + + FeatureAggregate save(FeatureAggregate featureAggregate); +} diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index 97136749..50b3353e 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -83,18 +83,37 @@ under `dev.caskeleton.application.notification` were removed on 2026-09-25; only ## Naming convention -- Inbound port implementations end with `UseCase` (e.g. `RegisterUserUseCase`). Enforced by ArchUnit. -- Outbound port interfaces end with `Port` (e.g. `NotificationPort`). -- Command records end with `Command`; query records end with `Query`. +This section is the repository's naming rule book. `NamingConventionTest` (app-bootstrap +architectureTest) enforces the machine-checkable rows; the rest are review rules, and a review checks +them against this table. A new feature follows the "new code" column; the "existing exceptions" are +named so nobody copies them by accident. + +| Role | Name | Where | Existing exceptions (do not copy) | +|---|---|---|---| +| Use case (inbound port implementation) | `UseCase`, enforced by ArchUnit | `application` package of the feature | `*ApplicationUseCase` (application-fileserver, application-notification), `*Service` (notification, fileserver) | +| Command / query record | `*Command` / `*Query` | next to its use case | — | +| Aggregate persistence (stores and returns whole aggregates) | `Repository` | **domain** package of the aggregate, owned by the domain | — | +| Technical store the application owns (outbox, idempotency, operation rows) | `StorePort` | application package | `*WritePort` (old onboarding fixture, removed) | +| Read model that returns projections, not aggregates | `QueryPort` | application package; returns projections only (ArchUnit) | — | +| Any other outbound port | `Port` | application package | — | +| Server-assigned id generation | `IdFactory extends IdFactory<Id>` | domain package; the id record `implements ResourceId` | `OutboxEventIdFactory` (sample; event ids are not resource ids) | +| Configuration binding | `*Settings` (operational) or `*Policy` (authorization / domain policy), enforced by ArchUnit | the leaf that binds it | — | +| Throwable | `*Exception`, enforced by ArchUnit | — | — | +| Contract test kit for a port | abstract `Contract` in the port owner's testFixtures; the fake's and each adapter's test extend it | testFixtures | value-type tests were once named `*ContractTest`; they are `*ValueTypesTest` now | + +The one-line rule for stores: **if the domain would recognise the thing it stores, it is a +`Repository` in the domain; if it is plumbing the application needs, it is a `StorePort` in the +application.** ## Canonical use case shape ```java +@RequiresPermission("user:register") @UseCaseCapability( transactionMode = TransactionMode.WRITE, idempotency = Idempotency.KEYED, repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) -public final class RegisterUserUseCase implements CommandUseCase { +public class RegisterUserUseCase implements CommandUseCase { private final UserRepository users; private final TransactionPort tx; @@ -114,7 +133,13 @@ public final class RegisterUserUseCase implements CommandUseCase= maxAttempts` 면 - `markDead`, 아니면 `markFailed(nextAttemptAt)`. 예산은 이 경우에만 쓴다 — payload 자체 결함일 - 수 있는 실패가 aggregate를 영원히 막지 않게 하는 장치다. `attemptCount`는 일시적 실패의 claim도 - 센다. 그래서 장애를 오래 기다린 행은 그 뒤 첫 발행 예외에서 바로 DEAD가 된다(알려진 한계). + - 발행 예외(`RuntimeException`, adapter가 분류하지 못한 실패): `budgetedAttemptCount() >= + maxAttempts` 면 `markDead`, 아니면 `markFailed(nextAttemptAt)`. 예산은 이 경우에만 쓴다 — + payload 자체 결함일 수 있는 실패가 aggregate를 영원히 막지 않게 하는 장치다. + `budgetedAttemptCount() = attemptCount - deferredAttemptCount`: 미룬(일시적 실패) claim은 빼고, + 결과를 남기지 못하고 죽은 claim(lease 만료)은 센다. 그래서 장애를 오래 기다린 행도 그 뒤 예산을 + 온전히 받는다(예전 한계: `attemptCount`가 일시 실패 claim까지 세어 첫 발행 예외에서 바로 DEAD). + 재시도 지연은 계속 전체 `attemptCount`로 늘어나 긴 장애에서도 최대 5분 간격을 유지한다. + - 멈춤 요청(`PublishPendingOutboxEventsCommand.stopRequested`, 종료 중인 scheduler가 건다): 지금 + 발행을 끝낸 뒤 남은 claim은 발행하지 않고 `releaseLease(now)`로 놓는다 → `PENDING`, 시도 수에서 + 그 claim을 빼고 바로 claim 가능. 결과는 `RELEASED`. - 전이를 먼저 성공시킨 뒤 해당 typed failure report를 보낸다. - `nextAttemptAt` 의 기준 시각은 **그 행이 실패한 시각**(`clock.instant()`)이다. 회차 시작 시각을 쓰면 broker가 멈춘 동안 publish 하나가 deadline(약 5초)을 다 쓰므로 배치 뒤쪽 행은 @@ -395,16 +401,16 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. 흡수(at-least-once). 배치 중간의 상태 갱신 실패가 그 tick 의 남은 배치를 중단시키는 것은 허용된다 — DB 가 실패 중이면 뒤따르는 갱신도 실패할 테고, 다음 tick 이 모든 `IN_FLIGHT` 고아를 재시도하기 때문. -- **수동 와이어링(@Service 아님, context 빈 아님)**: `app-bootstrap` 이 수동으로 생성한다 +- **수동 와이어링(@Service 아님, context 빈 아님)**: outbox-relay composition이 직접 생성한다 (`batchSize`·`inFlightTimeout` 같은 설정값이 필요해서 자동 등록이 안 된다). `UseCaseCapability` 는 빈 등록 방식과 무관하게 필수다(ArchUnit 강제). 그리고 **Spring 빈으로 등록하면 안 된다**: - 클래스 레벨 `@RequiresPermission` pointcut(web `MethodSecurityConfig`)이 이 타입 빈을 CGLIB - 프록시하려 드는데, `final` 클래스라 불가능하고, 스케줄러 스레드엔 `Authentication` 이 없어 매 - relay tick 이 fail-closed 거부될 것이다. -- **권한**: `"outbox:relay"` 는 시스템 내부 권한이다. relay 는 엔드유저가 아니라 스케줄러 빈이 - 호출한다. `@RequiresPermission` 선언은 ArchUnit `mutating_use_cases_declare_required_permission` - (D4) 을 충족시키기 위함이고, 스케줄러 컨텍스트에서의 실제 강제는 관례에 맡긴다(스케줄러는 - app-bootstrap 내부). + relay를 부르는 것은 스케줄러뿐이고, 스케줄러 스레드에는 `Authentication`이 없다. 빈으로 + 노출하면 전송 계층이 권한 검사 없이 닿을 수 있다. +- **권한 선언 없음 — `@SystemInvoked`**: relay는 엔드유저가 아니라 시스템이 부르는 유스케이스라 + `@RequiresPermission`을 달지 않고 `@SystemInvoked(reason = ...)`로 그 사실을 적는다. 예전의 + `@RequiresPermission("outbox:relay")`는 D4 규칙을 통과시키려고 붙인 장식이었다(빈이 아니라 한 + 번도 검사되지 않았고, 빈이었다면 매 tick 거부됐다). ArchUnit D4는 `@SystemInvoked`를 권한 선언 + 대신 받고, `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`이 둘을 함께 다는 것을 막는다. ### OutboxBackoffPolicy @@ -420,7 +426,7 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. - 버린 대안: `MAX_ATTEMPTS` 만 늘리기(장애 길이에 비례해 계속 키워야 하고 진짜 poison 행이 늦게 격리된다), 예산을 설정 키로 외부화(I10 — registry·runbook과 어긋난다; 일시적 실패가 예산을 쓰지 않으므로 장애 길이에 맞춰 예산을 조정할 이유도 사라졌다), 일시적 실패 시 `attempt_count` 되돌리기 - (store 포트·SQL·계약 테스트를 넓히고, 지수 간격을 키울 근거가 사라진다). + (지수 간격을 키울 근거가 사라진다 — 그래서 별도 열 `deferred_attempt_count`(V20)로 센다). - 더하는 spread 는 한 base 짜리 full jitter(`Backoff#fullJitter`, `[0, base]` 균등)이며 주입된 `RandomGenerator` 로 뽑는다. 0 을 반환하는 generator 를 주면 테스트가 결정적이 된다(I10). - **상수는 고정이다(I10)**: `BASE_DELAY`·`MAX_ATTEMPTS`·jitter 범위는 설정 프로퍼티가 아니다. @@ -579,3 +585,18 @@ R1 오케스트레이션 타입(`dev.caskeleton.application.notification` 직속 - **계층**: 순수 Java 인터페이스다. 구현은 application-core/domain-core 에서 참조하면 안 된다. consumer(`adapter-web` 의 `RequestLoggingFilter`)가 이 포트를 주입받아 `AuthenticatedPrincipal.idpUserId()` 를 가명화한 뒤 `MDC.put("user_principal", ...)` 한다. + +### OutboxAggregateSequencePort (2026-11-01 리뷰 06-07) + +- aggregate의 다음 순서 번호(`AggregateOrder.sequence`)를 append와 같은 caller 쓰기 트랜잭션에서 준다. + claim gate와 소비자가 이 번호로 "어느 변경이 나중인가"를 판단하므로 번호는 커밋 순서를 따라야 한다. + 벽시계(예전 샘플의 epoch 마이크로초)는 인스턴스 사이 시계 차이·NTP 되돌림·같은 마이크로초 두 건에서 + 커밋 순서와 달라진다. +- 계약(`OutboxAggregateSequenceContract`, fake `InMemoryOutboxAggregateSequences`와 JPA 구현이 공유): + aggregate마다 1부터 하나씩 커지고 aggregate끼리 독립이다. JPA 구현(`JpaOutboxStore`, V21 + `outbox_aggregate_sequence`)은 counter row lock으로 같은 aggregate 쓰기를 직렬화하고, 기존 outbox + row의 최대 번호 다음에서 시작하며, reaper가 row를 지워도 번호를 다시 쓰지 않는다. 같은 + `(tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index)` 두 번째 append는 V21 + 유일 인덱스가 append 시점에 거부한다. +- aggregate가 자체 version 열(낙관적 락)을 가지면 그 값을 써도 된다. 이 포트는 counter가 없는 + aggregate를 위한 것이다. diff --git a/src/application-core/build.gradle b/src/application-core/build.gradle index a8ce03b7..2317c633 100644 --- a/src/application-core/build.gradle +++ b/src/application-core/build.gradle @@ -16,6 +16,10 @@ dependencies { testFixturesImplementation project(':shared-contract') testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' testFixturesImplementation 'org.assertj:assertj-core' + + // Use case tests run over the domain ports' fakes (a feature's in-memory repository and id + // factory), which live with their owner in domain-core's test fixtures. + testImplementation testFixtures(project(':domain-core')) } // Half of the root `verifyMessagingContracts`: the integration-event contract, run by name, no skips. @@ -26,6 +30,5 @@ strictTestLanes { 'dev.caskeleton.application.messaging.event.IntegrationEventDraftTest', 'dev.caskeleton.application.messaging.event.ValidatedIntegrationEventTest' rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRecordMetadata.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRecordMetadata.java index 2acdb465..6798f860 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRecordMetadata.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRecordMetadata.java @@ -2,7 +2,15 @@ package dev.caskeleton.application.cache; import java.util.Objects; -/** Source revision plus an optional opaque condition captured by the preceding cache lookup. */ +/** + * Source revision plus an optional opaque condition captured by the preceding cache lookup. + * + *

      A usable {@code writeCondition} is checked before the intent: the write applies only while the + * entry is still in the state the lookup that issued the condition saw. That is what rejects a slow + * source load which began before an {@link CacheRegionPort#invalidate invalidation} and finished + * after it. {@link CacheRecordIntent#ONLY_IF_SOURCE_REVISION_NEWER} orders revisions by {@link + * CacheSourceRevisionOrder}. + */ public record CacheRecordMetadata( String sourceRevision, CacheRecordIntent intent, @@ -33,6 +41,14 @@ public record CacheRecordMetadata( throw new IllegalArgumentException( "ONLY_IF_OBSERVED requires a usable cache observation token"); } + if (intent == CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER + && !CacheSourceRevisionOrder.isOrdered(sourceRevision)) { + // Refused here, for every provider alike: "newer" needs the order the contract defines, and + // a provider that quietly fell back to text order would rank revision 10 below revision 9. + throw new IllegalArgumentException( + "ONLY_IF_SOURCE_REVISION_NEWER needs a source revision that is a non-negative decimal" + + " integer without leading zeros"); + } if (intent != CacheRecordIntent.ONLY_IF_OBSERVED && observedToken.usable()) { throw new IllegalArgumentException( "a cache observation token is valid only for ONLY_IF_OBSERVED"); diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRegionPort.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRegionPort.java index 46a28bf3..07c1be0f 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRegionPort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRegionPort.java @@ -12,6 +12,21 @@ public interface CacheRegionPort { CacheRecordOutcome recordAbsent(K key, AuthoritativeAbsence reason, CacheRecordMetadata metadata); + /** + * Makes the key's entry invisible and refuses, for a bounded time, records based on lookups made + * before this call. + * + *

      A source load that began before the invalidation and finishes after it must not put the old + * value back. A record whose {@link CacheWriteCondition} came from an earlier lookup is therefore + * rejected with {@link CacheRecordOutcome#NOT_RECORDED_CONDITION}, and so is an unconditioned + * {@link CacheRecordIntent#ONLY_IF_ABSENT} or {@link + * CacheRecordIntent#ONLY_IF_SOURCE_REVISION_NEWER} while the invalidation marker lives. A lookup + * made after the invalidation returns a condition that records normally. {@link + * CacheRecordIntent#UPSERT} without a condition is unconditional and overwrites the marker. + * + *

      There is no stampede protection: concurrent misses on one key each load from the source. + * Single-flight, where it matters, is the caller's. + */ CacheInvalidationOutcome invalidate(K key); /** diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSourceRevisionOrder.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSourceRevisionOrder.java new file mode 100644 index 00000000..2937ff30 --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSourceRevisionOrder.java @@ -0,0 +1,69 @@ +package dev.caskeleton.application.cache; + +import java.util.Objects; + +/** + * The order {@link CacheRecordIntent#ONLY_IF_SOURCE_REVISION_NEWER} compares source revisions by. + * + *

      Part of the cache contract, not of any provider: "newer" means the same thing to every adapter + * and fake, and to the application that produces the revisions. A source revision that takes part + * in this order is a canonical non-negative decimal integer — digits only, no sign, no leading zero + * except {@code "0"} itself — and revisions compare numerically at any length. Text order would + * rank {@code "10"} below {@code "9"}; a floating-point parse would stop distinguishing revisions + * above 2^53. + * + *

      A provider that cannot run Java at the comparison point (Redis compares inside a Lua program, + * so the check and the replacement are one atomic step) reimplements this rule there. The shared + * {@code CacheRegionContract} in this module's test fixtures is what keeps those copies equal to + * this one. + */ +public final class CacheSourceRevisionOrder { + + private CacheSourceRevisionOrder() {} + + /** + * Whether a revision takes part in the order. + * + * @param revision the source revision + * @return true for a canonical non-negative decimal integer + */ + public static boolean isOrdered(String revision) { + Objects.requireNonNull(revision, "revision must be non-null"); + if (revision.isEmpty()) { + return false; + } + for (int index = 0; index < revision.length(); index++) { + char digit = revision.charAt(index); + if (digit < '0' || digit > '9') { + return false; + } + } + return revision.length() == 1 || revision.charAt(0) != '0'; + } + + /** + * Whether a candidate revision is strictly newer than a stored one. + * + *

      Compared by length first and then digit by digit, which for canonical decimals is numeric + * order. A stored revision outside the order is never proven older, so the answer is false. + * + * @param candidate the revision the caller wants to record; must be ordered + * @param stored the revision already recorded + * @return true only when both are ordered and the candidate is numerically greater + * @throws IllegalArgumentException when the candidate is not ordered + */ + public static boolean isStrictlyNewer(String candidate, String stored) { + if (!isOrdered(candidate)) { + throw new IllegalArgumentException( + "a source revision compared for ONLY_IF_SOURCE_REVISION_NEWER must be a non-negative" + + " decimal integer without leading zeros"); + } + if (!isOrdered(stored)) { + return false; + } + if (candidate.length() != stored.length()) { + return candidate.length() > stored.length(); + } + return candidate.compareTo(stored) > 0; + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/AggregateIdentity.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/AggregateIdentity.java index aafb695e..70d0faa5 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/AggregateIdentity.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/AggregateIdentity.java @@ -15,9 +15,8 @@ public record AggregateIdentity(String tenantScope, String aggregateType, String || !aggregateType.matches("[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*")) { throw new IllegalArgumentException("aggregateType must be a canonical lower-case identifier"); } - if (aggregateId == null - || aggregateId.length() > 160 - || !aggregateId.matches("[A-Za-z0-9][A-Za-z0-9._:-]*")) { + if (!IntegrationIdentity.isCanonical( + aggregateId, IntegrationIdentity.AGGREGATE_ID_MAX_LENGTH)) { throw new IllegalArgumentException("aggregateId must be a canonical bounded identifier"); } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/AggregateOrder.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/AggregateOrder.java index eec44187..434de9fe 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/AggregateOrder.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/AggregateOrder.java @@ -1,8 +1,23 @@ package dev.caskeleton.application.messaging.event; -/** Total order within one aggregate identity. */ +/** + * Total order within one aggregate identity. + * + *

      The sequence must follow the commit order of the aggregate's writes: the outbox claim gate + * releases an aggregate's events in this order and consumers read it as "which change came last". + * Three ways to choose it, named so a feature picks one instead of inventing a fourth: {@link + * #first()} for an aggregate that only ever emits one event; the aggregate's own version column, + * passed to the constructor; or, for an aggregate that keeps no counter, {@code + * OutboxAggregateSequencePort#nextSequence} in the appending transaction. + * + *

      Not the occurrence time. A wall clock is not the commit order when two instances' clocks + * differ or NTP steps back, and two events in one microsecond share it (review 2026-11-01 06-07); + * the {@code ofOccurrence} factory that encoded that rule was removed for the sequence port. + */ public record AggregateOrder(long sequence, int eventIndex) { + private static final AggregateOrder FIRST = new AggregateOrder(1, 0); + public AggregateOrder { if (sequence <= 0) { throw new IllegalArgumentException("aggregate sequence must be positive"); @@ -11,4 +26,9 @@ public record AggregateOrder(long sequence, int eventIndex) { throw new IllegalArgumentException("eventIndex must be non-negative"); } } + + /** The order of the only event an aggregate emits: sequence 1, index 0. */ + public static AggregateOrder first() { + return FIRST; + } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/EventId.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/EventId.java index d2f38d7c..f52284d8 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/EventId.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/EventId.java @@ -1,14 +1,17 @@ package dev.caskeleton.application.messaging.event; -/** Canonical integration-event identity. */ +/** + * Canonical integration-event identity: {@link IntegrationIdentity#GRAMMAR}, at most 96 characters. + */ public record EventId(String value) { - private static final String GRAMMAR = "[A-Za-z0-9][A-Za-z0-9._:-]*"; - public EventId { - if (value == null || value.length() > 96 || !value.matches(GRAMMAR)) { + if (!IntegrationIdentity.isCanonical(value, IntegrationIdentity.EVENT_ID_MAX_LENGTH)) { throw new IllegalArgumentException( - "eventId must be 1-96 US-ASCII characters matching " + "[A-Za-z0-9][A-Za-z0-9._:-]*"); + "eventId must be 1-" + + IntegrationIdentity.EVENT_ID_MAX_LENGTH + + " US-ASCII characters matching " + + IntegrationIdentity.GRAMMAR); } } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDraft.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDraft.java index 99b6c011..b09a2360 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDraft.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDraft.java @@ -19,8 +19,6 @@ public record IntegrationEventDraft

      ( Optional causationId, P featurePayload) { - private static final String CORRELATION_GRAMMAR = "[A-Za-z0-9][A-Za-z0-9._:-]*"; - public IntegrationEventDraft { if (eventId == null || contractId == null @@ -35,19 +33,13 @@ public record IntegrationEventDraft

      ( if (occurredAt == null) { throw new IllegalArgumentException("occurredAt must not be null"); } - requireCanonicalCorrelationIdentity("correlationId", correlationId); + IntegrationIdentity.requireCorrelation("correlationId", correlationId); if (causationId == null) { throw new IllegalArgumentException("causationId Optional must not be null"); } - causationId.ifPresent(value -> requireCanonicalCorrelationIdentity("causationId", value)); + causationId.ifPresent(value -> IntegrationIdentity.requireCorrelation("causationId", value)); if (featurePayload == null) { throw new IllegalArgumentException("featurePayload must not be null"); } } - - private static void requireCanonicalCorrelationIdentity(String field, String value) { - if (value == null || value.length() > 96 || !value.matches(CORRELATION_GRAMMAR)) { - throw new IllegalArgumentException(field + " must be a canonical bounded US-ASCII identity"); - } - } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDrafts.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDrafts.java new file mode 100644 index 00000000..e198eac1 --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDrafts.java @@ -0,0 +1,80 @@ +package dev.caskeleton.application.messaging.event; + +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.contract.IntegrationPayload; +import java.time.Instant; +import java.util.Optional; + +/** + * Builds an {@link IntegrationEventDraft} from a contract with the rules every feature shares, so a + * feature decides only what is really its own: the aggregate, the order and the payload. + * + *

      Fixed here, once: + * + *

        + *
      • Contract id, payload version and destination come from the contract, never typed again. + *
      • The correlation id is the request's when it fits {@link IntegrationIdentity}, and otherwise + * the event id. An unusable correlation header must not fail the business write, and an event + * with no request behind it (a scheduler, a relay) correlates to itself. + *
      • A single-tenant feature uses {@link #SINGLE_TENANT_SCOPE}. Before this, the sample said + * {@code portfolio} and durable operations said {@code global} for the same meaning. + *
      + * + *

      The order rule is the feature's choice between the two {@link AggregateOrder} factories. + */ +public final class IntegrationEventDrafts { + + /** + * The tenant scope of an event that belongs to no tenant. Carrying a {@code TenantId} instead + * needs a mapping into the lower-case scope grammar, which the messaging platform owns. + */ + public static final String SINGLE_TENANT_SCOPE = "global"; + + private IntegrationEventDrafts() {} + + /** + * A draft of {@code contract} with no causation. + * + * @param contract the contract the event follows + * @param eventId the event id consumers deduplicate on + * @param aggregate tenant scope, aggregate type and id + * @param order the order within the aggregate + * @param occurredAt when it happened + * @param requestCorrelationId the caller's correlation id, if there is one + * @param payload the payload record + * @param

      the payload type + * @return the draft, ready for {@link IntegrationEventEncoderPort#encode} + */ + public static

      IntegrationEventDraft

      draft( + IntegrationEventContractContribution

      contract, + EventId eventId, + AggregateIdentity aggregate, + AggregateOrder order, + Instant occurredAt, + Optional requestCorrelationId, + P payload) { + if (contract == null || eventId == null || requestCorrelationId == null) { + throw new IllegalArgumentException("contract, eventId and requestCorrelationId are required"); + } + return new IntegrationEventDraft<>( + eventId, + contract.contractId(), + contract.payloadVersion(), + contract.descriptor().logicalDestination(), + aggregate, + order, + occurredAt, + correlationId(requestCorrelationId, eventId), + Optional.empty(), + payload); + } + + /** The request's correlation id when it is canonical, otherwise the event id. */ + static String correlationId(Optional requestCorrelationId, EventId eventId) { + return requestCorrelationId + .filter( + value -> + IntegrationIdentity.isCanonical(value, IntegrationIdentity.CORRELATION_MAX_LENGTH)) + .orElse(eventId.value()); + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java new file mode 100644 index 00000000..dd1663bd --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java @@ -0,0 +1,57 @@ +package dev.caskeleton.application.messaging.event; + +import java.util.regex.Pattern; + +/** + * The one identity grammar integration events use: event ids, correlation and causation ids and + * aggregate ids. + * + *

      Five places used to spell {@code [A-Za-z0-9][A-Za-z0-9._:-]} out themselves with two different + * length bounds, so a correlation id could pass one path and be refused by another. The grammar and + * the bounds live here; a caller that needs to test a value before building an event (a request + * correlation id that may not fit, an operation id that may be too long) asks {@link + * #isCanonical(String, int)} instead of copying the pattern. + */ +public final class IntegrationIdentity { + + /** US-ASCII letters and digits, then any of {@code . _ : -}; never starts with a separator. */ + public static final String GRAMMAR = "[A-Za-z0-9][A-Za-z0-9._:-]*"; + + /** Upper bound of an event id. */ + public static final int EVENT_ID_MAX_LENGTH = 96; + + /** + * Upper bound of a correlation or causation id: the width of the outbox {@code correlation_id} + * and {@code causation_id} columns. A draft and a stored event share it, so an event read back + * from the outbox is never refused on the way in. + */ + public static final int CORRELATION_MAX_LENGTH = 128; + + /** Upper bound of an aggregate id. */ + public static final int AGGREGATE_ID_MAX_LENGTH = 160; + + private static final Pattern PATTERN = Pattern.compile(GRAMMAR); + + private IntegrationIdentity() {} + + /** + * Whether {@code value} is a canonical identity of at most {@code maxLength} characters. + * + * @param value the candidate; {@code null} is not canonical + * @param maxLength the bound for this kind of identity + * @return {@code true} when it matches {@link #GRAMMAR} within the bound + */ + public static boolean isCanonical(String value, int maxLength) { + return value != null + && !value.isEmpty() + && value.length() <= maxLength + && PATTERN.matcher(value).matches(); + } + + /** Refuses a correlation or causation id outside the grammar or the bound. */ + static void requireCorrelation(String field, String value) { + if (!isCanonical(value, CORRELATION_MAX_LENGTH)) { + throw new IllegalArgumentException(field + " must be a canonical bounded US-ASCII identity"); + } + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEvent.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEvent.java index b438adc2..ef39ae0a 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEvent.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/ValidatedIntegrationEvent.java @@ -33,8 +33,6 @@ public record ValidatedIntegrationEvent( String contractCatalogRevision, String destinationBindingRevision) { - // 128 characters: the width of the outbox correlation_id and causation_id columns. - private static final String CORRELATION_GRAMMAR = "[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"; private static final String REVISION_GRAMMAR = "[a-z0-9][a-z0-9._:-]{0,95}"; private static final String CONTENT_TYPE_GRAMMAR = "[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+"; @@ -52,12 +50,11 @@ public record ValidatedIntegrationEvent( if (occurredAt == null) { throw new IllegalArgumentException("occurredAt must not be null"); } - requireCanonicalIdentity("correlationId", correlationId, CORRELATION_GRAMMAR); + IntegrationIdentity.requireCorrelation("correlationId", correlationId); if (causationId == null) { throw new IllegalArgumentException("causationId Optional must not be null"); } - causationId.ifPresent( - value -> requireCanonicalIdentity("causationId", value, CORRELATION_GRAMMAR)); + causationId.ifPresent(value -> IntegrationIdentity.requireCorrelation("causationId", value)); if (partitionKeyText == null || !partitionKeyText.matches("[0-9a-f]{64}")) { throw new IllegalArgumentException( "partitionKeyText must contain exactly 64 lower-case hexadecimal characters"); diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationIdFactory.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationIdFactory.java new file mode 100644 index 00000000..5d669bfe --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationIdFactory.java @@ -0,0 +1,21 @@ +package dev.caskeleton.application.operation; + +/** + * Mints the id of a newly submitted durable operation. Identifier generation stays out of the + * transport and the application layer; an infrastructure adapter implements this. + * + *

      The id is a canonical lower-case UUIDv7. It becomes the submission event's id ({@link + * SubmitDurableOperationUseCase}), and the messaging platform carries an event id only as a UUIDv7 + * message id: any other id is refused at publish time and the event is dead-lettered after the + * business transaction already committed (review 2026-11-01 06-06). + */ +@FunctionalInterface +public interface DurableOperationIdFactory { + + /** + * Returns a new operation id. + * + * @return a canonical lower-case UUIDv7 id + */ + DurableOperationId newOperationId(); +} 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 8ecb3d5a..5f3e7469 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 @@ -7,7 +7,9 @@ import dev.caskeleton.application.messaging.event.AggregateIdentity; import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.EventId; import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.IntegrationEventDrafts; import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; +import dev.caskeleton.application.messaging.event.IntegrationIdentity; import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.security.RequiresPermission; import dev.caskeleton.application.transaction.TransactionMode; @@ -17,7 +19,6 @@ import dev.caskeleton.shared.digest.Sha256; import java.time.Clock; import java.util.Objects; import java.util.Optional; -import java.util.regex.Pattern; /** * Accepts long-running work: one transaction that writes the operation row and the outbox row. @@ -61,11 +62,9 @@ import java.util.regex.Pattern; public class SubmitDurableOperationUseCase implements CommandUseCase { - private static final String TENANT_SCOPE = "global"; private static final String AGGREGATE_TYPE = "durable-operation"; - private static final AggregateOrder FIRST_EVENT = new AggregateOrder(1, 0); - private static final int MAXIMUM_EVENT_ID_LENGTH = 96; - private static final Pattern EVENT_ID_GRAMMAR = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]*"); + private static final DurableOperationSubmittedContract CONTRACT = + new DurableOperationSubmittedContract(); private final DurableOperationStorePort operations; private final OutboxAppendPort outbox; @@ -143,15 +142,17 @@ public class SubmitDurableOperationUseCase private static IntegrationEventDraft submittedEvent( DurableOperation operation) { String identity = canonicalIdentity(operation.operationId()); - return new IntegrationEventDraft<>( + // Single-tenant scope even when the command names a tenant: the event only wakes a worker, the + // tenant travels in the stored operation, and mapping a TenantId into the lower-case scope + // grammar is the messaging platform's decision, not this use case's. + // No request correlation: the event correlates to the operation itself, so a retry under the + // same operation id produces the same event. + return IntegrationEventDrafts.draft( + CONTRACT, new EventId(identity), - DurableOperationSubmittedContract.CONTRACT_ID, - 1, - DurableOperationSubmittedContract.DESTINATION, - new AggregateIdentity(TENANT_SCOPE, AGGREGATE_TYPE, identity), - FIRST_EVENT, + new AggregateIdentity(IntegrationEventDrafts.SINGLE_TENANT_SCOPE, AGGREGATE_TYPE, identity), + AggregateOrder.first(), operation.submittedAt(), - identity, Optional.empty(), new DurableOperationSubmitted(operation.operationId().value(), operation.operationName())); } @@ -166,7 +167,7 @@ public class SubmitDurableOperationUseCase */ static String canonicalIdentity(DurableOperationId operationId) { String value = operationId.value(); - if (value.length() <= MAXIMUM_EVENT_ID_LENGTH && EVENT_ID_GRAMMAR.matcher(value).matches()) { + if (IntegrationIdentity.isCanonical(value, IntegrationIdentity.EVENT_ID_MAX_LENGTH)) { return value; } return "operation-" + Sha256.ofUtf8(value).hex(); diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/ClaimedOutboxEvent.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/ClaimedOutboxEvent.java index a115caa9..bafa1b5e 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/ClaimedOutboxEvent.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/ClaimedOutboxEvent.java @@ -14,10 +14,17 @@ import java.util.Objects; * * @param event the appended event * @param status the row's lifecycle status; {@link OutboxEventStatus#IN_FLIGHT} right after a claim - * @param attemptCount delivery attempts made, counting the claim that returned this row + * @param attemptCount claims made, counting the claim that returned this row; the retry delay grows + * with it + * @param deferredAttemptCount earlier claims that ended in a transient outcome ({@link + * OutboxPublishOutcome#retryable()}) and were marked with {@link OutboxStorePort#markDeferred}; + * they are about the moment, not the message, so they do not count against the attempt budget */ public record ClaimedOutboxEvent( - ValidatedIntegrationEvent event, OutboxEventStatus status, int attemptCount) { + ValidatedIntegrationEvent event, + OutboxEventStatus status, + int attemptCount, + int deferredAttemptCount) { public ClaimedOutboxEvent { Objects.requireNonNull(event, "event must not be null"); @@ -25,6 +32,28 @@ public record ClaimedOutboxEvent( if (attemptCount < 0) { throw new IllegalArgumentException("attemptCount must be >= 0, was " + attemptCount); } + if (deferredAttemptCount < 0 || deferredAttemptCount > attemptCount) { + throw new IllegalArgumentException( + "deferredAttemptCount must be between 0 and attemptCount (" + + attemptCount + + "), was " + + deferredAttemptCount); + } + } + + /** A row none of whose earlier claims was deferred. */ + public ClaimedOutboxEvent( + ValidatedIntegrationEvent event, OutboxEventStatus status, int attemptCount) { + this(event, status, attemptCount, 0); + } + + /** + * The attempts that count against {@link OutboxBackoffPolicy#MAX_ATTEMPTS}: every claim except + * the deferred ones. A claim whose relay died before writing a result counts, because a message + * that kills the relay is exactly what the budget exists to isolate. + */ + public int budgetedAttemptCount() { + return attemptCount - deferredAttemptCount; } public String eventId() { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java new file mode 100644 index 00000000..a042012f --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java @@ -0,0 +1,39 @@ +package dev.caskeleton.application.outbox; + +import dev.caskeleton.application.messaging.event.AggregateIdentity; + +/** + * Hands out an aggregate's next order number ({@code AggregateOrder.sequence}) for an event about + * to be appended to the outbox. + * + *

      The claim gate releases an aggregate's events in this order, and consumers read it as "which + * change came last". So the number must grow with the commit order of the aggregate's writes. A + * wall clock does not: two instances whose clocks differ, an NTP step back, or two events in one + * microsecond each produce an order that is not the commit order, and the gate then releases a + * later change first or two events in no defined order (review 06-07). An aggregate whose own + * version column already counts its writes may use that instead; this port is for the aggregates + * that keep no counter. + * + *

      Contract, which {@code OutboxAggregateSequenceContract} holds every implementation to: + * + *

        + *
      • Called inside the caller's write transaction ({@code TransactionPort.inWrite}), the same + * one that appends the event. The number is taken under a lock on the aggregate's counter, so + * a second writer of the same aggregate waits for the first to commit or roll back; a rolled + * back number is handed out again. + *
      • Strictly greater than every number this port returned for the aggregate before, including + * for events the retention reaper has since deleted, and greater than any number an earlier + * outbox row of the aggregate carries. + *
      • Independent per aggregate identity: one aggregate's numbers say nothing about another's. + *
      + */ +public interface OutboxAggregateSequencePort { + + /** + * Returns the aggregate's next order number, at least 1. + * + * @param aggregate the aggregate the event is about + * @return the number to put in the event's {@code AggregateOrder} + */ + long nextSequence(AggregateIdentity aggregate); +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java index 2edc90f8..3f2ce264 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java @@ -20,6 +20,14 @@ public record OutboxRelayResult(int claimedCount, List outcomes) { outcomes = List.copyOf(Objects.requireNonNull(outcomes, "outcomes must not be null")); } + /** + * True when at least one row was published. Publishing the head of an aggregate is what makes its + * next row claimable, so a cycle that published something may have more work right behind it. + */ + public boolean publishedAny() { + return outcomes.stream().anyMatch(outcome -> outcome.outcome() == Outcome.PUBLISHED); + } + /** * Outcome of a single event during one relay cycle. * @@ -60,6 +68,13 @@ public record OutboxRelayResult(int claimedCount, List outcomes) { * written, so nothing was written. The other relay owns the row's outcome; the broker may have * seen this relay's attempt as well. */ - STALE + STALE, + + /** + * The relay was asked to stop before it reached this row, so it gave the claim back without + * publishing ({@link OutboxStorePort#releaseLease}). Nothing was sent and no attempt was spent; + * the row is claimable again at once, by this relay after a restart or by another instance. + */ + RELEASED } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java index 2ce8bd00..fc2b49fc 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java @@ -41,8 +41,9 @@ public interface OutboxStorePort { /** * Marks the leased event as failed and schedules the next retry attempt. Must be called inside - * {@code TransactionPort.inWrite(...)} when a publish fails transiently and {@code attemptCount < - * maxAttempts}. + * {@code TransactionPort.inWrite(...)} when a publish failed in a way the adapter could not + * classify and the budget is not spent ({@code budgetedAttemptCount < maxAttempts}). This claim + * counts against the budget; a transient outcome uses {@link #markDeferred} instead. * * @param lease the claim this relay holds * @param nextAttemptAt the earliest instant at which the event may be re-claimed @@ -50,6 +51,33 @@ public interface OutboxStorePort { */ OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt); + /** + * Marks the leased event as failed for a reason that belongs to the moment — the broker did not + * answer, or refused for now ({@link OutboxPublishOutcome#retryable()}) — and schedules the next + * attempt. Same transition as {@link #markFailed}, but the row records that this claim was + * deferred, so it does not count against the attempt budget ({@link + * ClaimedOutboxEvent#budgetedAttemptCount()}). Must be called inside {@code + * TransactionPort.inWrite(...)}. + * + * @param lease the claim this relay holds + * @param nextAttemptAt the earliest instant at which the event may be re-claimed + * @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row + */ + OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt); + + /** + * Gives a claimed row back without having tried to publish it: the row is claimable again from + * {@code claimableAt}, by any relay, and the claim that is released does not count as an attempt. + * The relay calls it for the rows it claimed but will not get to — it was asked to stop — so they + * do not wait out the in-flight timeout. Must be called inside {@code + * TransactionPort.inWrite(...)}. + * + * @param lease the claim this relay holds and has not used + * @param claimableAt when the row may be claimed again; normally now + * @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row + */ + OutboxCompletion releaseLease(OutboxLease lease, Instant claimableAt); + /** * Marks the leased event as dead-lettered after all retry attempts are exhausted. Must be called * inside {@code TransactionPort.inWrite(...)}. A DEAD row blocks its aggregate's FIFO queue until diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsCommand.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsCommand.java index a6b46393..92c978f2 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsCommand.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsCommand.java @@ -1,15 +1,27 @@ package dev.caskeleton.application.outbox; import dev.caskeleton.application.command.Command; +import java.util.Objects; +import java.util.function.BooleanSupplier; /** - * Command marker for the outbox relay use case. The relay is scheduler-driven and carries no caller - * parameters (operational params are injected at construction); the {@link #INSTANCE} singleton - * conveys the intent. See README. + * Command for the outbox relay use case. The relay is scheduler-driven and carries no caller + * parameters (operational params are injected at construction). See README. + * + *

      It carries one thing the scheduler knows and the use case does not: whether the relay has been + * asked to stop. A cycle that is asked to stop finishes the publish it is in, then releases the + * rows it claimed and did not reach ({@link OutboxStorePort#releaseLease}) instead of publishing + * them into a platform that is about to close its admission. + * + * @param stopRequested read before each row; true once the relay is stopping */ -public record PublishPendingOutboxEventsCommand() implements Command { +public record PublishPendingOutboxEventsCommand(BooleanSupplier stopRequested) implements Command { - /** Canonical no-parameter instance — the relay command carries no parameters. */ + /** A cycle that is never asked to stop: it handles every row it claims. */ public static final PublishPendingOutboxEventsCommand INSTANCE = - new PublishPendingOutboxEventsCommand(); + new PublishPendingOutboxEventsCommand(() -> false); + + public PublishPendingOutboxEventsCommand { + Objects.requireNonNull(stopRequested, "stopRequested must not be null"); + } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java index 799d4685..0b7f5f9b 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java @@ -3,7 +3,7 @@ package dev.caskeleton.application.outbox; import dev.caskeleton.application.capability.Idempotency; import dev.caskeleton.application.capability.RepositoryAccess; import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.security.SystemInvoked; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.CommandUseCase; @@ -24,11 +24,17 @@ import java.util.function.Supplier; * failures are never rethrown; a status-update failure after a successful publish propagates and * the row is recovered via the in-flight timeout. A completion runs only under the claim's {@link * OutboxLease}; when that claim has been superseded the result is recorded as {@code STALE} and - * reported, never written. Wired manually by {@code app-bootstrap} (not a Spring bean). See README - * for the full algorithm, failure semantics, manual-wiring rationale, and the {@code - * "outbox:relay"} permission. + * reported, never written. See README for the full algorithm and failure semantics. + * + *

      Do not make this a Spring bean. Only the relay scheduler calls it, on a thread with no + * {@code Authentication}; it is {@link SystemInvoked} and carries no permission gate, and the + * outbox-relay composition constructs it directly. Exposed as a bean, a transport could reach it + * with no authorization at all. */ -@RequiresPermission("outbox:relay") +@SystemInvoked( + reason = + "the outbox relay scheduler calls it on a thread with no Authentication; a bean with a" + + " permission gate would be refused on every tick") @UseCaseCapability( transactionMode = TransactionMode.WRITE, idempotency = Idempotency.IDEMPOTENT, @@ -51,7 +57,7 @@ public class PublishPendingOutboxEventsUseCase /** * Constructs the relay use case with all required collaborators (wired manually by {@code - * app-bootstrap}; see README). + * composition:outbox-relay}; see README). * * @param store outbox store port (claim + status update) * @param publishPort fail-closed broker publish port @@ -111,9 +117,15 @@ public class PublishPendingOutboxEventsUseCase List sorted = new ArrayList<>(claimed); sorted.sort(Comparator.comparing(lease -> lease.event().occurredAt())); - // Step 3: Publish each event outside any transaction; drive status machine per result. + // Step 3: Publish each event outside any transaction; drive status machine per result. A relay + // asked to stop finishes the publish it is in and gives the rest of its claims back. List outcomes = new ArrayList<>(sorted.size()); - for (OutboxLease lease : sorted) { + for (int i = 0; i < sorted.size(); i++) { + if (command.stopRequested().getAsBoolean()) { + outcomes.addAll(release(sorted.subList(i, sorted.size()))); + break; + } + OutboxLease lease = sorted.get(i); OutboxRelayResult.Outcome outcome = publishOne(lease); outcomes.add( new OutboxRelayResult.EventOutcome(lease.eventId(), lease.event().eventType(), outcome)); @@ -122,6 +134,26 @@ public class PublishPendingOutboxEventsUseCase return new OutboxRelayResult(claimed.size(), outcomes); } + /** + * Gives back claims this cycle will not use. Without it a stopping relay either publishes them + * into a platform that is closing its admission — each refusal schedules a retry at least a base + * delay away and is reported as a failure — or leaves them IN_FLIGHT until the in-flight timeout, + * five minutes by default, before any other instance may take them. + */ + private List release(List unused) { + Instant claimableAt = clock.instant(); + List released = new ArrayList<>(unused.size()); + for (OutboxLease lease : unused) { + OutboxRelayResult.Outcome outcome = + tx.inWrite(() -> store.releaseLease(lease, claimableAt)) == OutboxCompletion.STALE + ? OutboxRelayResult.Outcome.STALE + : OutboxRelayResult.Outcome.RELEASED; + released.add( + new OutboxRelayResult.EventOutcome(lease.eventId(), lease.event().eventType(), outcome)); + } + return released; + } + /** * Attempts to publish one event and drives the FAILED/DEAD state machine on publish failure. A * publish failure is caught here and never rethrown; a {@code markPublished} failure after a @@ -152,13 +184,13 @@ public class PublishPendingOutboxEventsUseCase // idempotency key, and the alternative — parking it — loses a message that was delivered. // It does not spend the attempt budget: a broker that stopped answering fails every row this // way, and parking them after three tries is what turned a short outage into DEAD rows. - return retryLater(lease, clock.instant(), new OutboxPublishAmbiguousException()); + return retryLater(lease, clock.instant(), new OutboxPublishAmbiguousException(), false); } if (achieved == OutboxPublishOutcome.REJECTED_RETRYABLE) { // Refused for a reason that is about the moment — shutdown, saturation, a closed transport, // a credential being rotated — not about the message. Retried like an ambiguous outcome and // for the same reason; the cause says it was a refusal, so no duplicate is suspected. - return retryLater(lease, clock.instant(), new OutboxPublishRefusedException(achieved)); + return retryLater(lease, clock.instant(), new OutboxPublishRefusedException(achieved), false); } if (achieved != OutboxPublishOutcome.CONFIRMED) { // Definite refusal. Retrying the same payload fails the same way, so the attempt budget is @@ -181,28 +213,37 @@ public class PublishPendingOutboxEventsUseCase * *

      The attempt budget is spent here and only here: a thrown failure is one the adapter could * not classify, so it may be the message's own fault, and the budget is what keeps such a row - * from blocking its aggregate forever. {@code attemptCount} counts every claim, transient ones - * included, so a row that has already waited out an outage is dead-lettered by the first thrown - * failure after it. + * from blocking its aggregate forever. The budget counts {@link + * ClaimedOutboxEvent#budgetedAttemptCount()}, not every claim: the claims an outage deferred are + * left out, so a row that waited out a long outage still gets its whole budget afterwards instead + * of being dead-lettered by the first unclassified failure. */ private OutboxRelayResult.Outcome handlePublishFailure( OutboxLease lease, Instant failedAt, RuntimeException cause) { - if (lease.event().attemptCount() >= backoffPolicy.maxAttempts()) { + if (lease.event().budgetedAttemptCount() >= backoffPolicy.maxAttempts()) { // All attempts exhausted — DEAD-letter the event. return deadLetter(lease, cause); } - return retryLater(lease, failedAt, cause); + return retryLater(lease, failedAt, cause, true); } /** * Marks the row FAILED with its next attempt time and reports it. Never dead-letters: the caller - * has decided this failure is worth another attempt. + * has decided this failure is worth another attempt. The delay grows with every claim, deferred + * ones included, so a long outage is polled at most {@link OutboxBackoffPolicy#MAX_DELAY} apart; + * only a {@code budgeted} failure is recorded as spending the budget. */ private OutboxRelayResult.Outcome retryLater( - OutboxLease lease, Instant failedAt, RuntimeException cause) { + OutboxLease lease, Instant failedAt, RuntimeException cause, boolean budgeted) { ClaimedOutboxEvent event = lease.event(); Instant nextAttemptAt = backoffPolicy.nextAttemptAt(event.attemptCount(), failedAt); - if (tx.inWrite(() -> store.markFailed(lease, nextAttemptAt)) == OutboxCompletion.STALE) { + OutboxCompletion completion = + tx.inWrite( + () -> + budgeted + ? store.markFailed(lease, nextAttemptAt) + : store.markDeferred(lease, nextAttemptAt)); + if (completion == OutboxCompletion.STALE) { return stale(lease, OutboxRelayResult.Outcome.FAILED); } reportFailure( diff --git a/src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java b/src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java new file mode 100644 index 00000000..3b642c04 --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java @@ -0,0 +1,29 @@ +package dev.caskeleton.application.security; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marks a mutating use case that only the system calls — a scheduler, a relay — and that therefore + * carries no {@link RequiresPermission}. + * + *

      A permission gate on such a use case is decoration: the method-security advisor checks the + * caller's {@code Authentication}, a scheduler thread has none, so the gate either never runs (the + * use case is not a bean) or refuses every call (it is). This marker states that instead, and the + * architecture rule that otherwise requires a permission on every {@code WRITE_REPOSITORY} use case + * accepts it in place of one. + * + *

      A use case marked this way must not become a Spring bean that a transport can reach; the + * composition that runs it constructs it directly. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface SystemInvoked { + + /** Who calls it and why no end-user permission applies. */ + String reason(); +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/tenant/TenantId.java b/src/application-core/src/main/java/dev/caskeleton/application/tenant/TenantId.java index eefb0722..e4fdf772 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/tenant/TenantId.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/tenant/TenantId.java @@ -9,7 +9,13 @@ import java.util.regex.Pattern; *

      Opaque, short and safe to place in a log field: {@code [A-Za-z0-9][A-Za-z0-9_.-]{0,63}}. The * web and GraphQL transports each held a {@code TenantContext} with its own rule — web this * grammar, GraphQL "non-blank, at most 128 characters" — so the same tenant passed one transport - * and was refused by the other (review X2-P2-6a, S5-lead-3). Both now carry this type. + * and was refused by the other (review X2-P2-6a, S5-lead-3). Both now carry this type, and so does + * persistence-jpa's experimental tenant binding, which had a third, lower-case-only copy. A store + * that needs a narrower rule checks it on top of this type; it does not declare another one. + * + *

      application-notification still has its own lenient {@code TenantId} for rows stored before its + * writes adopted this grammar; folding it in needs those rows checked first (see that type's + * Javadoc). * *

      A tenant is a security boundary, so where one comes from matters more than its shape: a * transport builds it from verified authentication data, never from a request parameter. diff --git a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheSourceRevisionOrderTest.java b/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheSourceRevisionOrderTest.java new file mode 100644 index 00000000..67c1e47c --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheSourceRevisionOrderTest.java @@ -0,0 +1,77 @@ +package dev.caskeleton.application.cache; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class CacheSourceRevisionOrderTest { + + @Test + @DisplayName("정규 10진 정수만 순서에 참여한다") + void onlyCanonicalDecimalsAreOrdered() { + // given + String[] ordered = {"0", "9", "10", "123456789012345678901234567890"}; + String[] unordered = {"", "-1", "01", "1.0", "v1", "1e3", "1"}; + + // when + boolean anyUnorderedAccepted = false; + for (String revision : unordered) { + anyUnorderedAccepted |= CacheSourceRevisionOrder.isOrdered(revision); + } + + // then + assertThat(anyUnorderedAccepted).isFalse(); + for (String revision : ordered) { + assertThat(CacheSourceRevisionOrder.isOrdered(revision)).as(revision).isTrue(); + } + } + + @Test + @DisplayName("길이가 2^53을 넘어도 숫자 순서로 비교한다") + void comparesNumericallyBeyondDoublePrecision() { + // given + String stored = "9007199254740993"; + + // when + boolean newer = CacheSourceRevisionOrder.isStrictlyNewer("9007199254740994", stored); + + // then + assertThat(newer).isTrue(); + assertThat(CacheSourceRevisionOrder.isStrictlyNewer("10", "9")).isTrue(); + assertThat(CacheSourceRevisionOrder.isStrictlyNewer("9", "10")).isFalse(); + assertThat(CacheSourceRevisionOrder.isStrictlyNewer("10", "10")).isFalse(); + } + + @Test + @DisplayName("순서 밖의 저장 revision보다 새롭다고는 판단하지 않는다") + void anUnorderedStoredRevisionIsNeverProvenOlder() { + // given + String stored = "rev-2"; + + // when + boolean newer = CacheSourceRevisionOrder.isStrictlyNewer("99", stored); + + // then + assertThat(newer).isFalse(); + } + + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER metadata는 순서 밖의 revision을 만들 때 거부한다") + void revisionNewerMetadataRejectsAnUnorderedRevision() { + // given + String revision = "rev-2"; + + // when + Throwable refused = + catchThrowable( + () -> + new CacheRecordMetadata(revision, CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER)); + + // then + assertThat(refused) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ONLY_IF_SOURCE_REVISION_NEWER"); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheRegionContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheValueTypesTest.java similarity index 99% rename from src/application-core/src/test/java/dev/caskeleton/application/cache/CacheRegionContractTest.java rename to src/application-core/src/test/java/dev/caskeleton/application/cache/CacheValueTypesTest.java index bcb9f93f..673b7d86 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheRegionContractTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheValueTypesTest.java @@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Instant; import org.junit.jupiter.api.Test; -class CacheRegionContractTest { +class CacheValueTypesTest { private static final Instant SOFT_EXPIRES_AT = Instant.parse("2026-07-28T01:00:00Z"); private static final Instant HARD_EXPIRES_AT = Instant.parse("2026-07-28T01:05:00Z"); diff --git a/src/application-core/src/test/java/dev/caskeleton/application/cache/InMemoryCacheRegionContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/cache/InMemoryCacheRegionContractTest.java new file mode 100644 index 00000000..ab255085 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/cache/InMemoryCacheRegionContractTest.java @@ -0,0 +1,13 @@ +package dev.caskeleton.application.cache; + +import dev.caskeleton.application.cache.testkit.CacheRegionContract; +import dev.caskeleton.application.cache.testkit.InMemoryCacheRegion; + +/** The in-memory fake keeps the cache contract its use-case tests rely on. */ +class InMemoryCacheRegionContractTest extends CacheRegionContract { + + @Override + protected CacheRegionPort region() { + return new InMemoryCacheRegion<>(); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyValueTypesTest.java similarity index 98% rename from src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyContractTest.java rename to src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyValueTypesTest.java index 8bf1f463..2b180805 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyContractTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyValueTypesTest.java @@ -8,7 +8,7 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; import org.junit.jupiter.api.Test; -class IdempotencyContractTest { +class IdempotencyValueTypesTest { private static final IdempotencyScopeDigest SCOPE = new IdempotencyScopeDigest("a".repeat(64), 3, "CREATE_WORK_LOG"); diff --git a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/InMemoryIdempotencyStoreContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/InMemoryIdempotencyStoreContractTest.java new file mode 100644 index 00000000..202570fa --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/InMemoryIdempotencyStoreContractTest.java @@ -0,0 +1,13 @@ +package dev.caskeleton.application.idempotency; + +import dev.caskeleton.application.idempotency.testkit.IdempotencyStoreContract; +import dev.caskeleton.application.idempotency.testkit.InMemoryIdempotencyStore; + +/** The in-memory fake keeps the idempotency store contract its use-case tests rely on. */ +class InMemoryIdempotencyStoreContractTest extends IdempotencyStoreContract { + + @Override + protected IdempotencyStorePort store() { + return new InMemoryIdempotencyStore(); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java index 9e029c7f..b1c1f0ab 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java @@ -3,19 +3,19 @@ package dev.caskeleton.application.lock; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.application.lock.testkit.InMemoryDistributedLock; import java.time.Duration; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantLock; import org.junit.jupiter.api.Test; /** * Contract-shape test for {@link DistributedLockPort} and {@link DistributedLock}. * - *

      Uses an in-test fake backed by {@link ReentrantLock} to prove: + *

      Uses the port owner's fake, {@link InMemoryDistributedLock} (testFixtures), which also passes + * {@link dev.caskeleton.application.lock.testkit.DistributedLockContract} with the JDBC adapter, to + * prove: * *

        *
      1. {@code tryAcquire} returns a non-null handle. @@ -31,46 +31,13 @@ class DistributedLockPortContractTest { private static final Duration SHORT_WAIT = Duration.ofMillis(50); private static final Duration LEASE_TTL = Duration.ofSeconds(30); - // ----------------------------------------------------------------------- - // Fake implementation — kept in-test to avoid polluting production sources - // ----------------------------------------------------------------------- - - /** - * In-test fake backed by {@link ReentrantLock} (non-reentrant mode enforced via {@link - * ReentrantLock#tryLock(long, TimeUnit)} with the supplied waitTime). - * - *

        TTL is not enforced by the in-process fake (TTL enforcement is the JDBC registry adapter's - * responsibility). The leaseTtl parameter is accepted but ignored here, mirroring the fact that - * the port surface carries it as a contract hint to the adapter. - */ - private static final class FakeDistributedLockPort implements DistributedLockPort { - - private final ConcurrentHashMap locks = new ConcurrentHashMap<>(); - - @Override - public DistributedLock tryAcquire(String key, Duration waitTime, Duration leaseTtl) { - ReentrantLock lock = locks.computeIfAbsent(key, k -> new ReentrantLock()); - boolean acquired; - try { - acquired = lock.tryLock(waitTime.toMillis(), TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new LockAcquisitionTimeoutException(key, waitTime); - } - if (!acquired) { - throw new LockAcquisitionTimeoutException(key, waitTime); - } - return () -> lock.unlock(); - } - } - // ----------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------- @Test void acquireReturnsNonNullHandle() { - DistributedLockPort port = new FakeDistributedLockPort(); + DistributedLockPort port = new InMemoryDistributedLock(); DistributedLock lock = port.tryAcquire("test-key", SHORT_WAIT, LEASE_TTL); assertThat(lock).isNotNull(); @@ -79,7 +46,7 @@ class DistributedLockPortContractTest { @Test void closeReleasesLockSoSubsequentAcquireSucceeds() { - DistributedLockPort port = new FakeDistributedLockPort(); + DistributedLockPort port = new InMemoryDistributedLock(); DistributedLock first = port.tryAcquire("orders/1", SHORT_WAIT, LEASE_TTL); first.close(); // release @@ -107,7 +74,7 @@ class DistributedLockPortContractTest { */ @Test void tryFinallyReleaseAfterWorkDemonstratesD4Ordering() { - DistributedLockPort port = new FakeDistributedLockPort(); + DistributedLockPort port = new InMemoryDistributedLock(); List events = new ArrayList<>(); DistributedLock lock = port.tryAcquire("payment/99", SHORT_WAIT, LEASE_TTL); @@ -123,23 +90,17 @@ class DistributedLockPortContractTest { } /** - * While the main thread holds the lock, a second attempt on the same key (same thread — - * ReentrantLock is non-reentrant when used via tryLock with a zero-ish wait) must time out and - * throw {@link LockAcquisitionTimeoutException} carrying the correct key. + * While the lock is held, a second attempt on the same key must time out and throw {@link + * LockAcquisitionTimeoutException} carrying the correct key. * - *

        We hold the lock on the main thread and call tryAcquire again immediately with a very short - * waitTime. Because the fake uses a {@link ReentrantLock} and the second attempt uses a - * different {@link ReentrantLock#tryLock(long, TimeUnit)} call (not the re-entrant - * path), this is deterministic without needing a second thread. - * - *

        Note: {@link ReentrantLock} IS re-entrant by design, so for true non-reentrancy the fake - * uses a second thread here to keep the test deterministic. + *

        The lock is held on a second thread, so the timeout does not depend on whether the fake is + * thread-bound. */ @Test void timeoutWhileKeyIsHeldThrowsLockAcquisitionTimeoutExceptionWithCorrectKey() throws InterruptedException { - FakeDistributedLockPort port = new FakeDistributedLockPort(); + InMemoryDistributedLock port = new InMemoryDistributedLock(); String key = "inventory/sku-99"; // Hold the lock in a background thread until the main thread's test completes. @@ -180,7 +141,7 @@ class DistributedLockPortContractTest { @Test void tryWithResourcesCompilesAndReleases() { - DistributedLockPort port = new FakeDistributedLockPort(); + DistributedLockPort port = new InMemoryDistributedLock(); // DistributedLock extends AutoCloseable — must compile with try-with-resources try (DistributedLock ignored = port.tryAcquire("key", SHORT_WAIT, LEASE_TTL)) { diff --git a/src/application-core/src/test/java/dev/caskeleton/application/lock/testkit/InMemoryDistributedLockContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/lock/testkit/InMemoryDistributedLockContractTest.java new file mode 100644 index 00000000..4607e7b4 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/lock/testkit/InMemoryDistributedLockContractTest.java @@ -0,0 +1,19 @@ +package dev.caskeleton.application.lock.testkit; + +import dev.caskeleton.application.lock.DistributedLockPort; + +class InMemoryDistributedLockContractTest extends DistributedLockContract { + + private final InMemoryDistributedLock first = new InMemoryDistributedLock(); + private final InMemoryDistributedLock second = InMemoryDistributedLock.sharingStateWith(first); + + @Override + protected DistributedLockPort firstInstance() { + return first; + } + + @Override + protected DistributedLockPort secondInstance() { + return second; + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java index 469e8494..24f219ab 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java @@ -154,7 +154,7 @@ class IntegrationEventContractContributionTest { new ContractDescriptor( "sample-portfolio", new LogicalDestinationId("portfolio-domain-events"), - "json-schema-envelope-v1", + "json-envelope-v1", true, 0, 128 * 1024, @@ -167,7 +167,7 @@ class IntegrationEventContractContributionTest { return new ContractDescriptor( "sample-portfolio", new LogicalDestinationId("portfolio-domain-events"), - "json-schema-envelope-v1", + "json-envelope-v1", true, 64 * 1024, 128 * 1024, diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftsTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftsTest.java new file mode 100644 index 00000000..2e73b071 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftsTest.java @@ -0,0 +1,110 @@ +package dev.caskeleton.application.messaging.event; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.messaging.event.testkit.EncoderContractKitContract; +import java.time.Instant; +import java.util.Optional; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class IntegrationEventDraftsTest { + + private static final EventId EVENT_ID = new EventId("event-1"); + private static final Instant OCCURRED_AT = Instant.parse("2026-11-01T00:00:00.000001Z"); + private static final AggregateIdentity AGGREGATE = + new AggregateIdentity(IntegrationEventDrafts.SINGLE_TENANT_SCOPE, "kit", "kit-1"); + + @Test + void aDraftTakesItsContractIdVersionAndDestinationFromTheContract() { + // when + IntegrationEventDraft draft = draft(Optional.of("corr-1")); + + // then + assertThat(draft) + .extracting( + IntegrationEventDraft::contractId, + IntegrationEventDraft::payloadVersion, + IntegrationEventDraft::destinationId, + IntegrationEventDraft::correlationId) + .containsExactly( + EncoderContractKitContract.CONTRACT_ID, + 1, + EncoderContractKitContract.DESTINATION, + "corr-1"); + } + + @ParameterizedTest + @ValueSource(strings = {"", " ", "not canonical", "-leading-dash"}) + @DisplayName("쓸 수 없는 요청 correlation id는 쓰기를 실패시키지 않고 이벤트 id로 대신한다") + void anUnusableRequestCorrelationIdFallsBackToTheEventId(String requested) { + // when + IntegrationEventDraft draft = draft(Optional.of(requested)); + + // then + assertThat(draft.correlationId()).isEqualTo(EVENT_ID.value()); + } + + @Test + void anEventWithNoRequestBehindItCorrelatesToItself() { + assertThat(draft(Optional.empty()).correlationId()).isEqualTo(EVENT_ID.value()); + } + + @Test + @DisplayName("128자 요청 correlation id는 저장 열 폭과 같아서 그대로 쓴다") + void aRequestCorrelationIdAsLongAsTheStoredColumnIsKept() { + // given + String longest = "c".repeat(IntegrationIdentity.CORRELATION_MAX_LENGTH); + + // when + IntegrationEventDraft draft = draft(Optional.of(longest)); + + // then + assertThat(draft.correlationId()).isEqualTo(longest); + } + + @Test + @DisplayName("한 번만 이벤트를 내는 aggregate의 순서는 1번 0번째다") + void theOrderOfAnAggregatesOnlyEventIsSequenceOneIndexZero() { + // when + AggregateOrder order = AggregateOrder.first(); + + // then + assertThat(order).isEqualTo(new AggregateOrder(1, 0)); + } + + @Test + void aDraftWithoutAContractIsRefused() { + // when + Throwable thrown = + catchThrowable( + () -> + IntegrationEventDrafts.draft( + null, + EVENT_ID, + AGGREGATE, + AggregateOrder.first(), + OCCURRED_AT, + Optional.empty(), + new EncoderContractKitContract.Payload("a"))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("contract, eventId and requestCorrelationId are required"); + } + + private static IntegrationEventDraft draft(Optional requested) { + return IntegrationEventDrafts.draft( + new EncoderContractKitContract(), + EVENT_ID, + AGGREGATE, + AggregateOrder.first(), + OCCURRED_AT, + requested, + new EncoderContractKitContract.Payload("a")); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationIdentityTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationIdentityTest.java new file mode 100644 index 00000000..e044c662 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationIdentityTest.java @@ -0,0 +1,90 @@ +package dev.caskeleton.application.messaging.event; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.messaging.contract.ContractId; +import dev.caskeleton.application.messaging.contract.IntegrationPayload; +import dev.caskeleton.application.messaging.contract.LogicalDestinationId; +import java.time.Instant; +import java.util.Optional; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class IntegrationIdentityTest { + + @ParameterizedTest + @ValueSource(strings = {"a", "A0:event.id-1", "0190bd6e-7c3e-7abc-8def-0123456789ff"}) + void aValueInTheGrammarIsCanonical(String value) { + assertThat(IntegrationIdentity.isCanonical(value, 96)).isTrue(); + } + + @ParameterizedTest + @ValueSource(strings = {"", "-a", ".a", "a b", "a/b", "한글"}) + void aValueOutsideTheGrammarIsNotCanonical(String value) { + assertThat(IntegrationIdentity.isCanonical(value, 96)).isFalse(); + } + + @Test + void aValueLongerThanItsBoundIsNotCanonical() { + assertThat(IntegrationIdentity.isCanonical("a".repeat(97), 96)).isFalse(); + } + + @Test + @DisplayName("draft의 correlation id 상한은 저장된 이벤트와 같은 128자다") + void aDraftAcceptsTheSameCorrelationLengthAStoredEventDoes() { + // when + IntegrationEventDraft draft = draftWithCorrelation("c".repeat(128)); + + // then + assertThat(draft.correlationId()).hasSize(128); + } + + @Test + @DisplayName("129자 correlation id는 draft에서 거부한다") + void aDraftRefusesACorrelationIdLongerThanTheStoredColumn() { + // when + Throwable thrown = catchThrowable(() -> draftWithCorrelation("c".repeat(129))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("correlationId must be a canonical bounded US-ASCII identity"); + } + + @Test + @DisplayName("97자 event id는 거부한다") + void anEventIdLongerThanNinetySixCharactersIsRefused() { + // when + Throwable thrown = catchThrowable(() -> new EventId("e".repeat(97))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "eventId must be 1-96 US-ASCII characters matching " + IntegrationIdentity.GRAMMAR); + } + + @Test + void anEventIdOfNinetySixCharactersIsAccepted() { + assertThat(new EventId("e".repeat(96)).value()).hasSize(96); + } + + private static IntegrationEventDraft draftWithCorrelation(String correlationId) { + return new IntegrationEventDraft<>( + new EventId("event-1"), + new ContractId("portfolio.worklog.reserved"), + 1, + new LogicalDestinationId("portfolio-domain-events"), + new AggregateIdentity("tenant-a", "worklog", "worklog-42"), + AggregateOrder.first(), + Instant.parse("2026-07-28T05:10:30.123Z"), + correlationId, + Optional.empty(), + new TestPayload("worklog-42")); + } + + private record TestPayload(String workLogId) implements IntegrationPayload {} +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoderContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoderContractTest.java new file mode 100644 index 00000000..36067c58 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoderContractTest.java @@ -0,0 +1,14 @@ +package dev.caskeleton.application.messaging.event.testkit; + +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; +import java.util.Collection; + +class FakeIntegrationEventEncoderContractTest extends IntegrationEventEncoderContract { + + @Override + protected IntegrationEventEncoderPort encoderKnowing( + Collection> contracts) { + return new FakeIntegrationEventEncoder(contracts); + } +} 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 a3cd9d53..30a4f32d 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 @@ -39,7 +39,8 @@ class SubmitDurableOperationUseCaseTest { private final RecordingOutbox outbox = new RecordingOutbox(insideTransaction); private final RollbackAwareTransactions transactions = new RollbackAwareTransactions(operations, outbox, insideTransaction); - private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(); + private final FakeIntegrationEventEncoder encoder = + new FakeIntegrationEventEncoder(new DurableOperationSubmittedContract()); private final CommandUseCase useCase = new SubmitDurableOperationUseCase( operations, outbox, encoder, transactions, Clock.fixed(NOW, ZoneOffset.UTC)); diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/StoppingRelayReleasesItsClaimsTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/StoppingRelayReleasesItsClaimsTest.java new file mode 100644 index 00000000..52d80c92 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/StoppingRelayReleasesItsClaimsTest.java @@ -0,0 +1,98 @@ +package dev.caskeleton.application.outbox; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCaseTest.ZeroRandom; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * A relay asked to stop — the application is shutting down — finishes the publish it is in and + * gives back the rest of its claims, unspent, instead of publishing them into a platform that is + * closing its admission or leaving them IN_FLIGHT until the in-flight timeout. + */ +class StoppingRelayReleasesItsClaimsTest { + + private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z"); + + @Test + @DisplayName("멈추라는 요청을 받은 회차는 진행 중 발행을 끝내고 남은 claim을 시도 없이 놓는다") + void aStoppingCycleFinishesItsPublishAndReleasesTheRowsItDidNotReach() { + // given: three claimable rows; the stop request arrives while the first one is publishing + InMemoryOutboxStore store = new InMemoryOutboxStore(); + String first = "0193a000-0000-7000-8000-000000000001"; + String second = "0193a000-0000-7000-8000-000000000002"; + String third = "0193a000-0000-7000-8000-000000000003"; + store.append(OutboxEvents.event(first, NOW.minusSeconds(3))); + store.append(OutboxEvents.event(second, NOW.minusSeconds(2))); + store.append(OutboxEvents.event(third, NOW.minusSeconds(1))); + AtomicBoolean stopRequested = new AtomicBoolean(); + List sent = new ArrayList<>(); + OutboxMessagePublishPort port = + event -> { + sent.add(event.eventId()); + stopRequested.set(true); + }; + PublishPendingOutboxEventsUseCase relay = relay(store, port); + + // when + OutboxRelayResult result = + relay.handle(new PublishPendingOutboxEventsCommand(stopRequested::get)); + + // then + assertThat(sent).containsExactly(first); + assertThat(result.outcomes()) + .extracting(OutboxRelayResult.EventOutcome::outcome) + .containsExactly( + OutboxRelayResult.Outcome.PUBLISHED, + OutboxRelayResult.Outcome.RELEASED, + OutboxRelayResult.Outcome.RELEASED); + assertThat(List.of(store.status(second), store.status(third))) + .containsOnly(OutboxEventStatus.PENDING); + assertThat(List.of(store.attemptCount(second), store.attemptCount(third))).containsOnly(0); + assertThat(List.of(store.nextAttemptAt(second), store.nextAttemptAt(third))).containsOnly(NOW); + } + + @Test + @DisplayName("멈추라는 요청이 없으면 회차는 claim한 행을 모두 발행한다") + void aCycleThatIsNotStoppedPublishesEveryRowItClaimed() { + // given + InMemoryOutboxStore store = new InMemoryOutboxStore(); + store.append(OutboxEvents.event("0193a000-0000-7000-8000-000000000011", NOW.minusSeconds(2))); + store.append(OutboxEvents.event("0193a000-0000-7000-8000-000000000012", NOW.minusSeconds(1))); + PublishPendingOutboxEventsUseCase relay = relay(store, event -> {}); + + // when + OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then + assertThat(result.outcomes()) + .extracting(OutboxRelayResult.EventOutcome::outcome) + .containsOnly(OutboxRelayResult.Outcome.PUBLISHED); + assertThat(store.released()).isEmpty(); + } + + private static PublishPendingOutboxEventsUseCase relay( + InMemoryOutboxStore store, OutboxMessagePublishPort port) { + return new PublishPendingOutboxEventsUseCase( + store, + port, + report -> {}, + new DirectTransactionPort(), + new OutboxBackoffPolicy(new ZeroRandom()), + Clock.fixed(NOW, ZoneOffset.UTC), + 20, + Duration.ofMinutes(5), + "relay-under-test"); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java index ca9db730..3ef7dc71 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java @@ -161,6 +161,53 @@ class TransientPublishFailureRelayTest { .isEqualTo(START.plus(OutboxBackoffPolicy.MAX_DELAY)); } + @Test + @DisplayName("일시 실패를 오래 겪은 행도 처음 분류 못 한 실패에서는 DEAD가 아니라 FAILED가 된다") + void aRowThatWaitedOutAnOutageIsNotDeadLetteredByItsFirstUnclassifiedFailure() { + // given: a row that went through more transient refusals than the whole attempt budget + store.addClaimable(OutboxEvents.claimed("evt-after-outage", START.minusSeconds(1), 1)); + port.answer = OutboxPublishOutcome.REJECTED_RETRYABLE; + for (int i = 0; i <= OutboxBackoffPolicy.MAX_ATTEMPTS; i++) { + relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + clock.advance(OutboxBackoffPolicy.MAX_DELAY.plus(OutboxBackoffPolicy.BASE_DELAY)); + } + port.thrown = new IllegalStateException("a failure the adapter could not classify"); + + // when + OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then: only budgeted attempts count, and this is the first one + assertThat(result.outcomes()) + .extracting(OutboxRelayResult.EventOutcome::outcome) + .containsExactly(OutboxRelayResult.Outcome.FAILED); + assertThat(store.dead()).isEmpty(); + } + + @Test + @DisplayName("분류 못 한 실패는 일시 실패와 섞여도 예산만큼만 재시도하고 DEAD가 된다") + void unclassifiedFailuresStillExhaustTheBudgetBetweenTransientOnes() { + // given: transient refusals interleaved with failures the adapter could not classify + store.addClaimable(OutboxEvents.claimed("evt-poison", START.minusSeconds(1), 1)); + port.thrown = new IllegalStateException("payload the adapter cannot classify"); + for (int i = 1; i < OutboxBackoffPolicy.MAX_ATTEMPTS; i++) { + relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + clock.advance(OutboxBackoffPolicy.MAX_DELAY.plus(OutboxBackoffPolicy.BASE_DELAY)); + port.thrown = null; + port.answer = OutboxPublishOutcome.REJECTED_RETRYABLE; + relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + clock.advance(OutboxBackoffPolicy.MAX_DELAY.plus(OutboxBackoffPolicy.BASE_DELAY)); + port.thrown = new IllegalStateException("payload the adapter cannot classify"); + } + + // when + OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then + assertThat(result.outcomes()) + .extracting(OutboxRelayResult.EventOutcome::outcome) + .containsExactly(OutboxRelayResult.Outcome.DEAD); + } + private void runRelayEvery(Duration pollInterval, Instant until) { while (clock.instant().isBefore(until)) { relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -179,6 +226,9 @@ class TransientPublishFailureRelayTest { private Duration costPerPublish = Duration.ZERO; + /** When set, every publish throws it instead of answering. */ + private RuntimeException thrown; + void script(String eventId, OutboxPublishOutcome outcome) { scripted.put(eventId, outcome); } @@ -197,6 +247,9 @@ class TransientPublishFailureRelayTest { public OutboxPublishOutcome publishForOutcome(ClaimedOutboxEvent event) { Instant calledAt = clock.instant(); clock.advance(costPerPublish); + if (thrown != null) { + throw thrown; + } OutboxPublishOutcome outcome = scripted.get(event.eventId()); if (outcome != null) { return outcome; diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequenceContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequenceContractTest.java new file mode 100644 index 00000000..499a43cb --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequenceContractTest.java @@ -0,0 +1,20 @@ +package dev.caskeleton.application.outbox.testkit; + +import dev.caskeleton.application.outbox.OutboxAggregateSequencePort; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; + +class InMemoryOutboxAggregateSequenceContractTest extends OutboxAggregateSequenceContract { + + private final InMemoryOutboxAggregateSequences sequences = new InMemoryOutboxAggregateSequences(); + + @Override + protected OutboxAggregateSequencePort sequences() { + return sequences; + } + + @Override + protected TransactionPort transactions() { + return new DirectTransactionPort(); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/tenant/TenantIdTest.java b/src/application-core/src/test/java/dev/caskeleton/application/tenant/TenantIdTest.java index b21fbc7b..2012adcf 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/tenant/TenantIdTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/tenant/TenantIdTest.java @@ -18,8 +18,21 @@ class TenantIdTest { } @ParameterizedTest - @ValueSource(strings = {"", " ", "-acme", ".acme", "ac me", "acme\n", "../public", "테넌트"}) - @DisplayName("문법 밖의 tenant(선행 구분자, 공백, 줄바꿈, 경로, 비ASCII)는 거부한다") + @ValueSource( + strings = { + "", + " ", + "-acme", + ".acme", + "ac me", + "acme\n", + "../public", + "acme/eu", + "acme\\eu", + "acme:eu", + "테넌트" + }) + @DisplayName("문법 밖의 tenant(선행 구분자, 공백, 줄바꿈, 경로 구분자, 콜론, 비ASCII)는 거부한다") void aTenantOutsideTheGrammarIsRefused(String value) { // when Throwable thrown = catchThrowable(() -> new TenantId(value)); diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/CacheRegionContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/CacheRegionContract.java new file mode 100644 index 00000000..3d03e322 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/CacheRegionContract.java @@ -0,0 +1,315 @@ +package dev.caskeleton.application.cache.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.cache.AuthoritativeAbsence; +import dev.caskeleton.application.cache.CacheInvalidationOutcome; +import dev.caskeleton.application.cache.CacheLookup; +import dev.caskeleton.application.cache.CacheObservationToken; +import dev.caskeleton.application.cache.CacheRecordIntent; +import dev.caskeleton.application.cache.CacheRecordMetadata; +import dev.caskeleton.application.cache.CacheRecordOutcome; +import dev.caskeleton.application.cache.CacheRegionPort; +import dev.caskeleton.application.cache.CacheWriteCondition; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The behaviour every {@link CacheRegionPort} owes its callers, run unchanged against the in-memory + * fake and every adapter. + * + *

        Each implementation extends this class and supplies a fresh, empty region. A rule that lives + * only in one adapter's tests is a rule the fake does not keep, and a use case tested on the fake + * would then be tested against a different cache than the one it runs on. + */ +public abstract class CacheRegionContract { + + /** + * Returns a fresh, empty region; called once per test. + * + * @return the region under test + */ + protected abstract CacheRegionPort region(); + + private static CacheRecordMetadata upsert(String revision) { + return new CacheRecordMetadata(revision, CacheRecordIntent.UPSERT); + } + + private static CacheRecordMetadata conditioned( + String revision, CacheRecordIntent intent, CacheWriteCondition condition) { + return new CacheRecordMetadata( + revision, intent, CacheObservationToken.unavailable(), condition); + } + + private static CacheRecordMetadata newerThanStored(String revision) { + return new CacheRecordMetadata(revision, CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER); + } + + private static CacheWriteCondition conditionOf(CacheLookup lookup) { + return switch (lookup) { + case CacheLookup.Miss miss -> miss.writeCondition(); + case CacheLookup.Hit hit -> hit.writeCondition(); + default -> throw new AssertionError("expected a miss or a hit, got " + lookup); + }; + } + + private static String valueOf(CacheLookup lookup) { + assertThat(lookup).isInstanceOf(CacheLookup.Hit.class); + return ((CacheLookup.Hit) lookup).value(); + } + + @Test + @DisplayName("기록한 값은 다음 조회에서 같은 값과 revision의 hit으로 돌아온다") + void aRecordedValueIsReturnedAsAHit() { + // given + CacheRegionPort region = region(); + region.record("k", "v1", upsert("7")); + + // when + CacheLookup lookup = region.lookup("k"); + + // then + assertThat(valueOf(lookup)).isEqualTo("v1"); + assertThat(((CacheLookup.Hit) lookup).sourceRevision()).isEqualTo("7"); + } + + @Test + @DisplayName("비어 있는 키의 miss는 기록에 쓸 수 있는 write condition을 돌려준다") + void aMissCarriesAUsableWriteCondition() { + // given + CacheRegionPort region = region(); + + // when + CacheLookup lookup = region.lookup("k"); + + // then + assertThat(lookup).isInstanceOf(CacheLookup.Miss.class); + assertThat(conditionOf(lookup).usable()).isTrue(); + } + + @Test + @DisplayName("ONLY_IF_ABSENT는 이미 있는 항목을 덮어쓰지 않는다") + void onlyIfAbsentKeepsAnExistingEntry() { + // given + CacheRegionPort region = region(); + region.record("k", "first", upsert("1")); + + // when + CacheRecordOutcome outcome = + region.record( + "k", "second", new CacheRecordMetadata("2", CacheRecordIntent.ONLY_IF_ABSENT)); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + assertThat(valueOf(region.lookup("k"))).isEqualTo("first"); + } + + @Test + @DisplayName("ONLY_IF_OBSERVED는 읽은 뒤 바뀐 항목을 덮어쓰지 않는다") + void onlyIfObservedRefusesAChangedEntry() { + // given + CacheRegionPort region = region(); + region.record("k", "first", upsert("1")); + CacheLookup.Hit observed = (CacheLookup.Hit) region.lookup("k"); + region.record("k", "second", upsert("2")); + + // when + CacheRecordOutcome outcome = + region.record( + "k", + "third", + new CacheRecordMetadata( + "3", CacheRecordIntent.ONLY_IF_OBSERVED, observed.observationToken())); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + assertThat(valueOf(region.lookup("k"))).isEqualTo("second"); + } + + @Test + @DisplayName("ONLY_IF_OBSERVED는 읽은 뒤 바뀌지 않은 항목을 교체한다") + void onlyIfObservedReplacesAnUnchangedEntry() { + // given + CacheRegionPort region = region(); + region.record("k", "first", upsert("1")); + CacheLookup.Hit observed = (CacheLookup.Hit) region.lookup("k"); + + // when + CacheRecordOutcome outcome = + region.record( + "k", + "second", + new CacheRecordMetadata( + "2", CacheRecordIntent.ONLY_IF_OBSERVED, observed.observationToken())); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED); + assertThat(valueOf(region.lookup("k"))).isEqualTo("second"); + } + + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 저장된 것보다 작거나 같은 revision을 기록하지 않는다") + void onlyIfSourceRevisionNewerRefusesAnOlderOrEqualRevision() { + // given + CacheRegionPort region = region(); + region.record("k", "at-10", upsert("10")); + + // when + CacheRecordOutcome older = region.record("k", "at-9", newerThanStored("9")); + + // then + assertThat(older).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + assertThat(region.record("k", "again-10", newerThanStored("10"))) + .isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + assertThat(valueOf(region.lookup("k"))).isEqualTo("at-10"); + } + + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 revision을 글자 순서가 아니라 숫자 순서로 비교한다") + void onlyIfSourceRevisionNewerComparesNumerically() { + // given + CacheRegionPort region = region(); + region.record("k", "at-9", upsert("9")); + + // when + CacheRecordOutcome outcome = region.record("k", "at-10", newerThanStored("10")); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED); + assertThat(valueOf(region.lookup("k"))).isEqualTo("at-10"); + } + + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 비어 있는 키에 기록한다") + void onlyIfSourceRevisionNewerRecordsIntoAnEmptyKey() { + // given + CacheRegionPort region = region(); + + // when + CacheRecordOutcome outcome = region.record("k", "at-1", newerThanStored("1")); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED); + } + + @Test + @DisplayName("miss 뒤 원본을 읽는 사이 무효화되면 그 miss의 condition으로 한 기록은 거부된다") + void aLoadThatBeganBeforeAnInvalidationCannotRecordAfterIt() { + // given + CacheRegionPort region = region(); + CacheWriteCondition beforeInvalidation = conditionOf(region.lookup("k")); + region.invalidate("k"); + + // when + CacheRecordOutcome outcome = + region.record("k", "old", conditioned("1", CacheRecordIntent.UPSERT, beforeInvalidation)); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + assertThat(region.lookup("k")).isInstanceOf(CacheLookup.Miss.class); + } + + @Test + @DisplayName("hit 뒤 원본을 읽는 사이 무효화되면 그 hit의 condition으로 한 기록은 거부된다") + void aRefreshThatBeganBeforeAnInvalidationCannotRecordAfterIt() { + // given + CacheRegionPort region = region(); + region.record("k", "v1", upsert("1")); + CacheWriteCondition beforeInvalidation = conditionOf(region.lookup("k")); + region.invalidate("k"); + + // when + CacheRecordOutcome outcome = + region.record("k", "old", conditioned("2", CacheRecordIntent.UPSERT, beforeInvalidation)); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + assertThat(region.lookup("k")).isInstanceOf(CacheLookup.Miss.class); + } + + @Test + @DisplayName("무효화 뒤 다시 조회한 miss의 condition으로는 정상 기록된다") + void aLoadThatBeganAfterAnInvalidationRecords() { + // given + CacheRegionPort region = region(); + region.record("k", "v1", upsert("1")); + region.invalidate("k"); + CacheLookup afterInvalidation = region.lookup("k"); + + // when + CacheRecordOutcome outcome = + region.record( + "k", + "v2", + conditioned("2", CacheRecordIntent.ONLY_IF_ABSENT, conditionOf(afterInvalidation))); + + // then + assertThat(afterInvalidation).isInstanceOf(CacheLookup.Miss.class); + assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED); + assertThat(valueOf(region.lookup("k"))).isEqualTo("v2"); + } + + @Test + @DisplayName("무효화 표시가 남은 동안 condition 없는 ONLY_IF_ABSENT와 revision 조건 기록은 거부된다") + void anInvalidationRefusesUnconditionedLoadsWhileItsMarkerLives() { + // given + CacheRegionPort region = region(); + region.record("k", "v1", upsert("1")); + region.invalidate("k"); + + // when + CacheRecordOutcome absent = + region.record("k", "old", new CacheRecordMetadata("1", CacheRecordIntent.ONLY_IF_ABSENT)); + + // then + assertThat(absent).isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + assertThat(region.record("k", "old", newerThanStored("1"))) + .isEqualTo(CacheRecordOutcome.NOT_RECORDED_CONDITION); + } + + @Test + @DisplayName("있는 키를 무효화하면 INVALIDATED, 다시 무효화하면 ALREADY_ABSENT다") + void invalidatingTwiceReportsAbsenceTheSecondTime() { + // given + CacheRegionPort region = region(); + region.record("k", "v1", upsert("1")); + region.invalidate("k"); + + // when + CacheInvalidationOutcome second = region.invalidate("k"); + + // then + assertThat(second).isEqualTo(CacheInvalidationOutcome.ALREADY_ABSENT); + } + + @Test + @DisplayName("region 무효화 뒤 이전 항목은 miss다") + void aRegionInvalidationHidesEarlierEntries() { + // given + CacheRegionPort region = region(); + region.record("k", "v1", upsert("1")); + + // when + CacheInvalidationOutcome outcome = region.invalidateRegion(); + + // then + assertThat(outcome).isEqualTo(CacheInvalidationOutcome.INVALIDATED); + assertThat(region.lookup("k")).isInstanceOf(CacheLookup.Miss.class); + } + + @Test + @DisplayName("권위 있는 부재는 miss가 아니라 negative hit이다") + void anAuthoritativeAbsenceIsANegativeHit() { + // given + CacheRegionPort region = region(); + region.recordAbsent("k", AuthoritativeAbsence.NOT_FOUND, upsert("1")); + + // when + CacheLookup lookup = region.lookup("k"); + + // then + assertThat(lookup).isInstanceOf(CacheLookup.NegativeHit.class); + assertThat(((CacheLookup.NegativeHit) lookup).reason()) + .isEqualTo(AuthoritativeAbsence.NOT_FOUND); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/InMemoryCacheRegion.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/InMemoryCacheRegion.java new file mode 100644 index 00000000..ab3a3383 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/InMemoryCacheRegion.java @@ -0,0 +1,212 @@ +package dev.caskeleton.application.cache.testkit; + +import dev.caskeleton.application.cache.AuthoritativeAbsence; +import dev.caskeleton.application.cache.CacheInvalidationOutcome; +import dev.caskeleton.application.cache.CacheLookup; +import dev.caskeleton.application.cache.CacheObservationToken; +import dev.caskeleton.application.cache.CacheRecordMetadata; +import dev.caskeleton.application.cache.CacheRecordOutcome; +import dev.caskeleton.application.cache.CacheRegionPort; +import dev.caskeleton.application.cache.CacheSourceRevisionOrder; +import dev.caskeleton.application.cache.CacheWriteCondition; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + * The one in-memory fake of {@link CacheRegionPort}, for use-case tests that need a cache. + * + *

        It keeps the contract's consistency rules — write conditions, invalidation markers, the {@link + * CacheSourceRevisionOrder} — and leaves out everything provider-specific: no codec, no schema + * versions, no outage. {@code CacheRegionContract} runs against it exactly as against a real + * adapter. + * + * @param the semantic key type + * @param the cached value type + */ +public final class InMemoryCacheRegion implements CacheRegionPort { + + private static final String ABSENT = "absent"; + + private final Map> slots = new HashMap<>(); + private final Clock clock; + private final Duration softTtl; + private final Duration hardTtl; + private final Duration negativeTtl; + private final Duration invalidationTtl; + private long generation; + private long versions; + + /** + * Creates the fake. + * + * @param clock the clock expiries are measured against + * @param softTtl how long an entry stays fresh + * @param hardTtl how long an entry stays usable + * @param negativeTtl how long an authoritative absence is cached + * @param invalidationTtl how long an invalidation marker refuses older records + */ + public InMemoryCacheRegion( + Clock clock, + Duration softTtl, + Duration hardTtl, + Duration negativeTtl, + Duration invalidationTtl) { + this.clock = Objects.requireNonNull(clock, "clock must be non-null"); + this.softTtl = Objects.requireNonNull(softTtl, "soft TTL must be non-null"); + this.hardTtl = Objects.requireNonNull(hardTtl, "hard TTL must be non-null"); + this.negativeTtl = Objects.requireNonNull(negativeTtl, "negative TTL must be non-null"); + this.invalidationTtl = + Objects.requireNonNull(invalidationTtl, "invalidation TTL must be non-null"); + } + + /** Creates the fake on the system clock with the template's default lifetimes. */ + public InMemoryCacheRegion() { + this( + Clock.systemUTC(), + Duration.ofSeconds(30), + Duration.ofMinutes(5), + Duration.ofSeconds(10), + Duration.ofSeconds(30)); + } + + @Override + public synchronized CacheLookup lookup(K key) { + Objects.requireNonNull(key, "key must be non-null"); + Instant now = clock.instant(); + Slot slot = live(key, now); + if (slot == null) { + return new CacheLookup.Miss<>(CacheLookup.MissReason.ABSENT, new CacheWriteCondition(ABSENT)); + } + CacheWriteCondition vacant = new CacheWriteCondition("vacant-" + slot.version()); + if (slot.tombstone() || slot.generation() != generation) { + return new CacheLookup.Miss<>(CacheLookup.MissReason.INVALIDATED, vacant); + } + if (slot.absence() != null) { + return new CacheLookup.NegativeHit<>(slot.absence(), slot.hardExpiresAt()); + } + CacheObservationToken token = tokenOf(slot); + return new CacheLookup.Hit<>( + slot.value(), + slot.softExpiresAt().isAfter(now) + ? CacheLookup.Freshness.FRESH + : CacheLookup.Freshness.STALE, + slot.revision(), + slot.softExpiresAt(), + slot.hardExpiresAt(), + token, + new CacheWriteCondition("present-" + slot.version())); + } + + @Override + public CacheRecordOutcome record(K key, V value, CacheRecordMetadata metadata) { + Objects.requireNonNull(value, "value must be non-null"); + return write(key, value, null, metadata, hardTtl); + } + + @Override + public CacheRecordOutcome recordAbsent( + K key, AuthoritativeAbsence reason, CacheRecordMetadata metadata) { + Objects.requireNonNull(reason, "reason must be non-null"); + return write(key, null, reason, metadata, negativeTtl); + } + + private synchronized CacheRecordOutcome write( + K key, V value, AuthoritativeAbsence absence, CacheRecordMetadata metadata, Duration ttl) { + Objects.requireNonNull(key, "key must be non-null"); + Objects.requireNonNull(metadata, "metadata must be non-null"); + Instant now = clock.instant(); + Slot current = live(key, now); + CacheWriteCondition condition = metadata.writeCondition(); + boolean conditioned = condition.usable(); + if (conditioned && !condition.value().equals(conditionOf(current))) { + return CacheRecordOutcome.NOT_RECORDED_CONDITION; + } + boolean vacant = current == null || current.tombstone() || current.generation() != generation; + boolean applies = + switch (metadata.intent()) { + case UPSERT -> true; + // An invalidation marker is vacant only to a writer who saw it: without a condition + // nothing proves the load began after the invalidation. + case ONLY_IF_ABSENT -> current == null || (vacant && conditioned); + case ONLY_IF_OBSERVED -> + current != null + && !vacant + && tokenOf(current).value().equals(metadata.observedToken().value()); + case ONLY_IF_SOURCE_REVISION_NEWER -> + current == null + || (vacant && (conditioned || !current.tombstone())) + || (!vacant + && CacheSourceRevisionOrder.isStrictlyNewer( + metadata.sourceRevision(), current.revision())); + }; + if (!applies) { + return CacheRecordOutcome.NOT_RECORDED_CONDITION; + } + Duration soft = softTtl.compareTo(ttl) > 0 ? ttl : softTtl; + slots.put( + key, + new Slot<>( + value, + absence, + false, + metadata.sourceRevision(), + generation, + ++versions, + now.plus(soft), + now.plus(ttl))); + return CacheRecordOutcome.RECORDED; + } + + @Override + public synchronized CacheInvalidationOutcome invalidate(K key) { + Objects.requireNonNull(key, "key must be non-null"); + Instant now = clock.instant(); + Slot current = live(key, now); + Instant until = now.plus(invalidationTtl); + slots.put(key, new Slot<>(null, null, true, "0", generation, ++versions, until, until)); + return current == null || current.tombstone() + ? CacheInvalidationOutcome.ALREADY_ABSENT + : CacheInvalidationOutcome.INVALIDATED; + } + + @Override + public synchronized CacheInvalidationOutcome invalidateRegion() { + generation++; + return CacheInvalidationOutcome.INVALIDATED; + } + + private Slot live(K key, Instant now) { + Slot slot = slots.get(key); + if (slot != null && !slot.hardExpiresAt().isAfter(now)) { + slots.remove(key); + return null; + } + return slot; + } + + private String conditionOf(Slot slot) { + if (slot == null) { + return ABSENT; + } + boolean vacant = slot.tombstone() || slot.generation() != generation; + return (vacant ? "vacant-" : "present-") + slot.version(); + } + + private static CacheObservationToken tokenOf(Slot slot) { + return new CacheObservationToken(String.format("observation-%016d", slot.version())); + } + + private record Slot( + V value, + AuthoritativeAbsence absence, + boolean tombstone, + String revision, + long generation, + long version, + Instant softExpiresAt, + Instant hardExpiresAt) {} +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java new file mode 100644 index 00000000..c5e2a5d7 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java @@ -0,0 +1,274 @@ +package dev.caskeleton.application.idempotency.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; +import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; +import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; +import dev.caskeleton.application.idempotency.IdempotencyCompleteOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailureDisposition; +import dev.caskeleton.application.idempotency.IdempotencyOwner; +import dev.caskeleton.application.idempotency.IdempotencyReleaseOutcome; +import dev.caskeleton.application.idempotency.IdempotencyRenewOutcome; +import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; +import dev.caskeleton.application.idempotency.IdempotencyStartOutcome; +import dev.caskeleton.application.idempotency.IdempotencyStorePort; +import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.idempotency.StoredResponse; +import dev.caskeleton.application.transaction.OperationId; +import java.time.Duration; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The owner-safe state machine every {@link IdempotencyStorePort} owes its callers, run unchanged + * against the in-memory fake and every store. + * + *

        Time-free on purpose: lease expiry and take-over depend on whose clock the store trusts, and + * those cases stay with each store's own tests. What is here is what a caller of the port relies on + * whichever store is composed. + */ +public abstract class IdempotencyStoreContract { + + private static final IdempotencyScopeDigest SCOPE = + new IdempotencyScopeDigest("a".repeat(64), 1, "CHARGE_CARD"); + + private static final RequestFingerprint FINGERPRINT = new RequestFingerprint("b".repeat(64)); + + private static final RequestFingerprint OTHER_FINGERPRINT = + new RequestFingerprint("c".repeat(64)); + + private static final OperationId OPERATION = new OperationId("operation-aaaaaaaaaa"); + + private static final OperationId OTHER_OPERATION = new OperationId("operation-bbbbbbbbbb"); + + /** + * Returns a fresh, empty store; called once per test. + * + * @return the store under test + */ + protected abstract IdempotencyStorePort store(); + + private static IdempotencyClaimRequest claim( + IdempotencyClaimAttempt attempt, RequestFingerprint fingerprint) { + return new IdempotencyClaimRequest( + SCOPE, fingerprint, attempt, Duration.ofSeconds(30), Duration.ofHours(24), "json-v2", 1); + } + + private static IdempotencyOwner acquire(IdempotencyStorePort store) { + return ((IdempotencyClaimOutcome.Acquired) + store.claim(claim(store.newClaimAttempt(OPERATION), FINGERPRINT))) + .owner(); + } + + private static IdempotencyOwner executing(IdempotencyStorePort store) { + return store.markExecutionStarted(acquire(store), OPERATION).owner().orElseThrow(); + } + + @Test + @DisplayName("먼저 claim한 쪽이 얻고 다른 요청은 진행 중으로 막힌다") + void aFirstClaimExcludesTheSecond() { + // given + IdempotencyStorePort store = store(); + acquire(store); + + // when + IdempotencyClaimOutcome second = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT)); + + // then + assertThat(second).isInstanceOf(IdempotencyClaimOutcome.InProgress.class); + } + + @Test + @DisplayName("같은 attempt로 다시 claim하면 새로 얻지 않고 재생한다") + void theSameAttemptReplaysItsAcquire() { + // given + IdempotencyStorePort store = store(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + store.claim(claim(attempt, FINGERPRINT)); + + // when + IdempotencyClaimOutcome again = store.claim(claim(attempt, FINGERPRINT)); + + // then + assertThat(again).isInstanceOf(IdempotencyClaimOutcome.ReplayedAcquire.class); + } + + @Test + @DisplayName("같은 scope의 다른 요청 본문은 재생이 아니라 fingerprint 불일치다") + void aDifferentRequestUnderTheSameScopeIsAMismatch() { + // given + IdempotencyStorePort store = store(); + acquire(store); + + // when + IdempotencyClaimOutcome other = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), OTHER_FINGERPRINT)); + + // then + assertThat(other).isInstanceOf(IdempotencyClaimOutcome.FingerprintMismatch.class); + } + + @Test + @DisplayName("완료한 결과는 다음 claim에서 그대로 재생된다") + void aCompletedResultReplays() { + // given + IdempotencyStorePort store = store(); + store.complete( + executing(store), new StoredResponse("{\"ok\":true}"), Duration.ofHours(1), OPERATION); + + // when + IdempotencyClaimOutcome replay = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT)); + + // then + assertThat(replay).isInstanceOf(IdempotencyClaimOutcome.CompletedReplay.class); + assertThat(((IdempotencyClaimOutcome.CompletedReplay) replay).response().payload()) + .isEqualTo("{\"ok\":true}"); + } + + @Test + @DisplayName("전이 전에 받은 오래된 owner 핸들로는 complete할 수 없다") + void aStaleHandleCannotComplete() { + // given + IdempotencyStorePort store = store(); + IdempotencyOwner stale = acquire(store); + store.markExecutionStarted(stale, OPERATION); + + // when + IdempotencyCompleteOutcome outcome = + store.complete(stale, new StoredResponse("{}"), Duration.ofHours(1), OPERATION); + + // then + assertThat(outcome).isEqualTo(IdempotencyCompleteOutcome.NOT_OWNER); + } + + @Test + @DisplayName("renew는 RENEWED와 더 새 revision의 핸들을 돌려주고 그 핸들로 complete할 수 있다") + void renewReturnsANewerHandleThatCanComplete() { + // given + IdempotencyStorePort store = store(); + IdempotencyOwner executing = executing(store); + + // when + var renewed = store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.RENEWED); + IdempotencyOwner current = renewed.owner().orElseThrow(); + assertThat(current.stateRevision()).isGreaterThan(executing.stateRevision()); + assertThat(store.complete(current, new StoredResponse("{}"), Duration.ofHours(1), OPERATION)) + .isEqualTo(IdempotencyCompleteOutcome.COMPLETED); + } + + @Test + @DisplayName("실행을 시작하기 전 claim은 renew할 수 없다") + void aClaimNotYetExecutingCannotBeRenewed() { + // given + IdempotencyStorePort store = store(); + IdempotencyOwner claimed = acquire(store); + + // when + var renewed = store.renew(claimed, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(renewed.outcome()).isNotEqualTo(IdempotencyRenewOutcome.RENEWED); + assertThat(renewed.owner()).isEmpty(); + } + + @Test + @DisplayName("재시도 가능한 실패는 다음 claim이 attempt 2로 넘겨받게 한다") + void aRetryableFailureLetsTheNextClaimTakeOver() { + // given + IdempotencyStorePort store = store(); + store.markFailed( + executing(store), + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + + // when + IdempotencyClaimOutcome next = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT)); + + // then + assertThat(next).isInstanceOf(IdempotencyClaimOutcome.TakenOverClaimed.class); + assertThat(((IdempotencyClaimOutcome.TakenOverClaimed) next).owner().attempt()).isEqualTo(2); + } + + @Test + @DisplayName("효과가 불명인 채 포기한 작업은 다시 돌리지 않고 복구를 요구한다") + void anAbandonedOperationRequiresRecovery() { + // given + IdempotencyStorePort store = store(); + IdempotencyFailOutcome marked = + store.markFailed( + executing(store), + IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED, + Duration.ofHours(1), + OPERATION); + + // when + IdempotencyClaimOutcome next = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT)); + + // then + assertThat(marked).isEqualTo(IdempotencyFailOutcome.MARKED_ABANDONED); + assertThat(next).isInstanceOf(IdempotencyClaimOutcome.RecoveryRequired.class); + } + + @Test + @DisplayName("실행 전 release는 scope를 비우고 실행 뒤 release는 거부된다") + void releaseFreesTheScopeOnlyBeforeExecution() { + // given + IdempotencyStorePort store = store(); + IdempotencyOwner claimed = acquire(store); + + // when + IdempotencyReleaseOutcome released = store.releaseBeforeExecution(claimed, OPERATION); + + // then + assertThat(released).isEqualTo(IdempotencyReleaseOutcome.RELEASED_BEFORE_EXECUTION); + IdempotencyOwner executing = executing(store); + assertThat(store.releaseBeforeExecution(executing, OPERATION)) + .isEqualTo(IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED); + } + + @Test + @DisplayName("같은 결과로 두 번 complete하면 멱등이고 다른 결과면 충돌이다") + void completingTwiceIsIdempotentOnlyForTheSameResult() { + // given + IdempotencyStorePort store = store(); + IdempotencyOwner executing = executing(store); + store.complete(executing, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION); + + // when + IdempotencyCompleteOutcome same = + store.complete(executing, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION); + + // then + assertThat(same).isEqualTo(IdempotencyCompleteOutcome.ALREADY_COMPLETED_SAME_RESULT); + assertThat( + store.complete( + executing, new StoredResponse("{\"v\":2}"), Duration.ofHours(1), OPERATION)) + .isEqualTo(IdempotencyCompleteOutcome.RESPONSE_CONFLICT); + } + + @Test + @DisplayName("STARTED 전이는 새 revision의 핸들을 돌려준다") + void startingAdvancesTheRevision() { + // given + IdempotencyStorePort store = store(); + IdempotencyOwner claimed = acquire(store); + + // when + var started = store.markExecutionStarted(claimed, OPERATION); + + // then + assertThat(started.outcome()).isEqualTo(IdempotencyStartOutcome.STARTED); + assertThat(started.owner().orElseThrow().stateRevision()) + .isGreaterThan(claimed.stateRevision()); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java index 40da620f..7ac056d2 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java @@ -100,9 +100,17 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { public synchronized IdempotencyMutationResult renew( IdempotencyOwner owner, Duration processingLeaseTtl, OperationId operationId) { Row row = rows.get(owner.scope().digest()); - if (row == null || !row.owner.equals(owner) || !row.inProgress()) { - IdempotencyRenewOutcome refused = - row == null ? IdempotencyRenewOutcome.ABSENT : IdempotencyRenewOutcome.NOT_OWNER; + // Only a running execution has a processing lease to extend; the stores answer a claim that + // has not started with NOT_IN_PROGRESS, and IdempotencyStoreContract holds the fake to that. + IdempotencyRenewOutcome refused = + row == null + ? IdempotencyRenewOutcome.ABSENT + : !row.owner.equals(owner) + ? IdempotencyRenewOutcome.NOT_OWNER + : row.state != IdempotencyState.EXECUTING + ? IdempotencyRenewOutcome.NOT_IN_PROGRESS + : null; + if (refused != null) { return new IdempotencyMutationResult<>(refused, null, IdempotencyRenewOutcome::carriesOwner); } row.advance(row.state); @@ -120,6 +128,13 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyCompleteOutcome.ABSENT; } + if (row.state == IdempotencyState.COMPLETED && owner.equals(row.completedBy)) { + // The completing handle retried, as after a lost reply: the same result is a no-op, another + // result is a conflict, exactly as the stores answer. + return row.response.equals(response) + ? IdempotencyCompleteOutcome.ALREADY_COMPLETED_SAME_RESULT + : IdempotencyCompleteOutcome.RESPONSE_CONFLICT; + } if (!row.owner.equals(owner)) { return IdempotencyCompleteOutcome.NOT_OWNER; } @@ -127,6 +142,7 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { return IdempotencyCompleteOutcome.NOT_IN_PROGRESS; } row.response = response; + row.completedBy = owner; row.advance(IdempotencyState.COMPLETED); return IdempotencyCompleteOutcome.COMPLETED; } @@ -232,6 +248,7 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { private IdempotencyOwner owner; private IdempotencyState state = IdempotencyState.CLAIMED; private StoredResponse response; + private IdempotencyOwner completedBy; Row(RequestFingerprint fingerprint, IdempotencyClaimRequest request, long attempt, long rev) { this.fingerprint = fingerprint; @@ -244,10 +261,6 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { request.claimAttempt().operationId()); } - boolean inProgress() { - return state == IdempotencyState.CLAIMED || state == IdempotencyState.EXECUTING; - } - void advance(IdempotencyState next) { owner = owner.withStateRevision(owner.stateRevision() + 1); state = next; diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java new file mode 100644 index 00000000..d2b5c9e7 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java @@ -0,0 +1,82 @@ +package dev.caskeleton.application.lock.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.lock.DistributedLock; +import dev.caskeleton.application.lock.DistributedLockPort; +import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; +import java.time.Duration; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +/** + * What every {@link DistributedLockPort} promises, run by the fake's test and the JDBC adapter's + * PostgreSQL test alike. + * + *

        Contention is between two instances — two ports over one lock store — because that is + * what the lock exists for. Two acquires through one instance from one thread prove nothing: a + * thread-bound lock lets them both through. + */ +public abstract class DistributedLockContract { + + /** How long a contested acquire waits before giving up. */ + protected static final Duration SHORT_WAIT = Duration.ofMillis(100); + + /** A lease long enough not to expire during a test. */ + protected static final Duration LEASE = Duration.ofSeconds(30); + + /** The first instance. */ + protected abstract DistributedLockPort firstInstance(); + + /** A second instance over the same lock store as {@link #firstInstance()}. */ + protected abstract DistributedLockPort secondInstance(); + + @Test + void aKeyHeldByOneInstanceTimesOutForAnotherWithTheKeyNamed() { + // given + String key = uniqueKey(); + DistributedLock held = firstInstance().tryAcquire(key, SHORT_WAIT, LEASE); + + // when + Throwable refused = catchThrowable(() -> secondInstance().tryAcquire(key, SHORT_WAIT, LEASE)); + + // then + held.close(); + assertThat(refused) + .isInstanceOfSatisfying( + LockAcquisitionTimeoutException.class, e -> assertThat(e.key()).isEqualTo(key)); + } + + @Test + void aReleasedKeyCanBeAcquiredByAnotherInstance() { + // given + String key = uniqueKey(); + firstInstance().tryAcquire(key, SHORT_WAIT, LEASE).close(); + + // when + Throwable thrown = + catchThrowable(() -> secondInstance().tryAcquire(key, SHORT_WAIT, LEASE).close()); + + // then + assertThat(thrown).isNull(); + } + + @Test + void differentKeysDoNotContend() { + // given + DistributedLock held = firstInstance().tryAcquire(uniqueKey(), SHORT_WAIT, LEASE); + + // when + Throwable thrown = + catchThrowable(() -> secondInstance().tryAcquire(uniqueKey(), SHORT_WAIT, LEASE).close()); + + // then + held.close(); + assertThat(thrown).isNull(); + } + + private static String uniqueKey() { + return "contract-" + UUID.randomUUID(); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/InMemoryDistributedLock.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/InMemoryDistributedLock.java new file mode 100644 index 00000000..9908199b --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/InMemoryDistributedLock.java @@ -0,0 +1,65 @@ +package dev.caskeleton.application.lock.testkit; + +import dev.caskeleton.application.lock.DistributedLock; +import dev.caskeleton.application.lock.DistributedLockPort; +import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; +import java.time.Duration; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * The {@link DistributedLockPort} fake: one permit per key, held by the handle rather than by a + * thread. + * + *

        The earlier fake, private to a test, used a {@code ReentrantLock}, so a second acquire from + * the same thread succeeded and a release from another thread threw — neither is how a lock shared + * by several instances behaves. Ports made with {@link #sharingStateWith(InMemoryDistributedLock)} + * stand for several instances of one service sharing a lock store, which is what {@link + * DistributedLockContract} contends with. + * + *

        The lease TTL is accepted and not enforced: expiry needs a clock the store owns, and the JDBC + * adapter's tests cover it. + */ +public final class InMemoryDistributedLock implements DistributedLockPort { + + private final Map permits; + + public InMemoryDistributedLock() { + this(new ConcurrentHashMap<>()); + } + + private InMemoryDistributedLock(Map permits) { + this.permits = permits; + } + + /** Another instance over the same lock store. */ + public static InMemoryDistributedLock sharingStateWith(InMemoryDistributedLock other) { + return new InMemoryDistributedLock(other.permits); + } + + @Override + public DistributedLock tryAcquire(String key, Duration waitTime, Duration leaseTtl) { + Objects.requireNonNull(key, "key"); + Semaphore permit = permits.computeIfAbsent(key, k -> new Semaphore(1)); + boolean acquired; + try { + acquired = permit.tryAcquire(waitTime.toMillis(), TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new LockAcquisitionTimeoutException(key, waitTime); + } + if (!acquired) { + throw new LockAcquisitionTimeoutException(key, waitTime); + } + AtomicBoolean released = new AtomicBoolean(); + return () -> { + if (released.compareAndSet(false, true)) { + permit.release(); + } + }; + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/EncoderContractKitContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/EncoderContractKitContract.java new file mode 100644 index 00000000..ac343f21 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/EncoderContractKitContract.java @@ -0,0 +1,95 @@ +package dev.caskeleton.application.messaging.event.testkit; + +import dev.caskeleton.application.messaging.contract.ContractDescriptor; +import dev.caskeleton.application.messaging.contract.ContractId; +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.contract.IntegrationPayload; +import dev.caskeleton.application.messaging.contract.LogicalDestinationId; +import dev.caskeleton.application.messaging.contract.SchemaResourceId; +import dev.caskeleton.shared.digest.Sha256; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.time.Duration; +import java.util.List; + +/** + * The one contract {@link IntegrationEventEncoderContract} encodes against: {@code + * testkit.encoder-contract} v1 to {@link #DESTINATION}, payload {@link Payload}. + * + *

        Its schema is a testFixtures resource and its hash is read from that resource, so any encoder + * that checks a declared hash against the classpath accepts it. + */ +public final class EncoderContractKitContract + implements IntegrationEventContractContribution { + + /** The contract id. */ + public static final ContractId CONTRACT_ID = new ContractId("testkit.encoder-contract"); + + /** The destination the contract declares. */ + public static final LogicalDestinationId DESTINATION = + new LogicalDestinationId("testkit-encoder-contract"); + + /** The serializer id the template's encoders know. */ + public static final String SERIALIZER_ID = "json-envelope-v1"; + + private static final SchemaResourceId SCHEMA = + new SchemaResourceId("contracts/messaging/testkit.encoder-contract/v1.schema.json"); + + /** The payload record the contract declares. */ + public record Payload(String name) implements IntegrationPayload {} + + /** A payload record the contract does not declare. */ + public record OtherPayload(String name) implements IntegrationPayload {} + + @Override + public ContractId contractId() { + return CONTRACT_ID; + } + + @Override + public int payloadVersion() { + return 1; + } + + @Override + public Class exactPayloadRecordType() { + return Payload.class; + } + + @Override + public List canonicalRecordComponentOrder() { + return List.of("name"); + } + + @Override + public SchemaResourceId payloadSchemaResource() { + return SCHEMA; + } + + @Override + public Sha256 payloadSchemaHash() { + try (InputStream in = + EncoderContractKitContract.class.getClassLoader().getResourceAsStream(SCHEMA.value())) { + if (in == null) { + throw new IllegalStateException("missing " + SCHEMA.value()); + } + return Sha256.of(in.readAllBytes()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + @Override + public ContractDescriptor descriptor() { + return new ContractDescriptor( + "application-core", + DESTINATION, + SERIALIZER_ID, + false, + 4 * 1024, + 16 * 1024, + ContractDescriptor.SensitivityClassification.INTERNAL, + Duration.ofDays(1)); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java index 18771a2c..d28d6dee 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventEncoder.java @@ -1,17 +1,26 @@ package dev.caskeleton.application.messaging.event.testkit; +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; import dev.caskeleton.application.messaging.event.IntegrationEventDraft; import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; import java.util.HexFormat; import java.util.List; +import java.util.Map; /** - * The encoder fake: keeps every draft it was given and returns a validated event that carries the - * draft's identities unchanged. + * The encoder fake: knows a closed set of contracts like the real encoder, keeps every draft it was + * given and returns a validated event that carries the draft's identities unchanged. + * + *

        It refuses what the real encoder refuses because the server assembled it wrong — an + * unregistered contract, another destination, another payload record — with the same {@link + * IllegalStateException}; {@link IntegrationEventEncoderContract} holds both to that. It does not + * render JSON, so the payload and envelope size bounds are the real encoder's alone. * *

        The envelope bytes are the draft's {@code toString()}, which is enough for a use-case test to * tell two events apart and nothing more; the canonical JSON rendering is the real encoder's @@ -22,10 +31,45 @@ public final class FakeIntegrationEventEncoder implements IntegrationEventEncode private static final Sha256 SCHEMA_HASH = Sha256.of("fake-integration-event-schema".getBytes(StandardCharsets.UTF_8)); + private final Map> contracts = new HashMap<>(); private final List> drafts = new ArrayList<>(); + /** + * A fake that knows exactly {@code contracts}, as the deployment's encoder would. + * + * @param contracts the contracts the use case under test is registered with + */ + public FakeIntegrationEventEncoder( + Collection> contracts) { + for (IntegrationEventContractContribution contract : contracts) { + this.contracts.put(key(contract.contractId().value(), contract.payloadVersion()), contract); + } + } + + /** A fake that knows {@code contracts}. */ + public FakeIntegrationEventEncoder(IntegrationEventContractContribution... contracts) { + this(List.of(contracts)); + } + @Override public ValidatedIntegrationEvent encode(IntegrationEventDraft draft) { + String key = key(draft.contractId().value(), draft.payloadVersion()); + IntegrationEventContractContribution contract = contracts.get(key); + if (contract == null) { + throw new IllegalStateException("no integration event contract is registered for " + key); + } + if (!draft.destinationId().equals(contract.descriptor().logicalDestination())) { + throw new IllegalStateException( + "draft destination " + + draft.destinationId().value() + + " is not the destination contract " + + key + + " declares"); + } + if (draft.featurePayload().getClass() != contract.exactPayloadRecordType()) { + throw new IllegalStateException( + "draft payload must be exactly " + contract.exactPayloadRecordType()); + } drafts.add(draft); byte[] envelope = draft.toString().getBytes(StandardCharsets.UTF_8); String partitionKey = @@ -60,4 +104,8 @@ public final class FakeIntegrationEventEncoder implements IntegrationEventEncode public List> drafts() { return List.copyOf(drafts); } + + private static String key(String contractId, int payloadVersion) { + return contractId + ":v" + payloadVersion; + } } diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventEncoderContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventEncoderContract.java new file mode 100644 index 00000000..2f5a4182 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventEncoderContract.java @@ -0,0 +1,146 @@ +package dev.caskeleton.application.messaging.event.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.messaging.contract.ContractId; +import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; +import dev.caskeleton.application.messaging.contract.IntegrationPayload; +import dev.caskeleton.application.messaging.contract.LogicalDestinationId; +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.messaging.event.AggregateOrder; +import dev.caskeleton.application.messaging.event.EventId; +import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import java.time.Instant; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; + +/** + * What every {@link IntegrationEventEncoderPort} promises, run by the real encoder's test and the + * fake's test alike. + * + *

        The fake used to accept any draft. A feature whose contract was never registered — or whose + * payload record changed without its contract — passed every use-case test and failed every request + * in a deployment. These are the refusals a use-case test now sees too, and they are {@link + * IllegalStateException}: a server assembly fault, which the transports report as 500 with a log + * line, not a 400 that tells the client to fix a request it got right. + */ +public abstract class IntegrationEventEncoderContract { + + private static final Instant OCCURRED_AT = Instant.parse("2026-11-01T00:00:00Z"); + + private static final EncoderContractKitContract KNOWN = new EncoderContractKitContract(); + + /** An encoder that knows exactly {@code contracts}. */ + protected abstract IntegrationEventEncoderPort encoderKnowing( + Collection> contracts); + + @Test + void aDraftOfARegisteredContractKeepsItsIdentities() { + // given + IntegrationEventDraft draft = + draft(EncoderContractKitContract.DESTINATION, new EncoderContractKitContract.Payload("a")); + + // when + ValidatedIntegrationEvent event = encoderKnowing(List.of(KNOWN)).encode(draft); + + // then + assertThat(event) + .extracting( + ValidatedIntegrationEvent::eventId, + ValidatedIntegrationEvent::contractId, + ValidatedIntegrationEvent::payloadVersion, + ValidatedIntegrationEvent::logicalDestinationId, + ValidatedIntegrationEvent::aggregate, + ValidatedIntegrationEvent::order, + ValidatedIntegrationEvent::correlationId) + .containsExactly( + draft.eventId(), + draft.contractId(), + draft.payloadVersion(), + draft.destinationId(), + draft.aggregate(), + draft.order(), + draft.correlationId()); + } + + @Test + void aDraftOfAnUnregisteredContractIsRefusedAsAServerFault() { + // given + IntegrationEventEncoderPort encoder = encoderKnowing(List.of()); + + // when + Throwable refused = + catchThrowable( + () -> + encoder.encode( + draft( + EncoderContractKitContract.DESTINATION, + new EncoderContractKitContract.Payload("a")))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessage("no integration event contract is registered for testkit.encoder-contract:v1"); + } + + @Test + void aDraftAddressedToAnotherDestinationIsRefusedAsAServerFault() { + // given + IntegrationEventEncoderPort encoder = encoderKnowing(List.of(KNOWN)); + + // when + Throwable refused = + catchThrowable( + () -> + encoder.encode( + draft( + new LogicalDestinationId("somewhere-else"), + new EncoderContractKitContract.Payload("a")))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("draft destination somewhere-else is not the destination"); + } + + @Test + void aDraftWhosePayloadIsNotTheContractRecordIsRefusedAsAServerFault() { + // given + IntegrationEventEncoderPort encoder = encoderKnowing(List.of(KNOWN)); + + // when + Throwable refused = + catchThrowable( + () -> + encoder.encode( + draft( + EncoderContractKitContract.DESTINATION, + new EncoderContractKitContract.OtherPayload("a")))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessage("draft payload must be exactly " + EncoderContractKitContract.Payload.class); + } + + private static IntegrationEventDraft draft( + LogicalDestinationId destination, IntegrationPayload payload) { + ContractId contractId = EncoderContractKitContract.CONTRACT_ID; + return new IntegrationEventDraft<>( + new EventId("event-1"), + contractId, + 1, + destination, + new AggregateIdentity("global", "kit", "kit-1"), + AggregateOrder.first(), + OCCURRED_AT, + "correlation-1", + Optional.empty(), + payload); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequences.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequences.java new file mode 100644 index 00000000..dff55d5b --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequences.java @@ -0,0 +1,17 @@ +package dev.caskeleton.application.outbox.testkit; + +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.outbox.OutboxAggregateSequencePort; +import java.util.HashMap; +import java.util.Map; + +/** In-memory {@link OutboxAggregateSequencePort}: one counter per aggregate identity. */ +public final class InMemoryOutboxAggregateSequences implements OutboxAggregateSequencePort { + + private final Map last = new HashMap<>(); + + @Override + public synchronized long nextSequence(AggregateIdentity aggregate) { + return last.merge(aggregate, 1L, Long::sum); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java index 73c6292c..7ccdbc9b 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java @@ -21,8 +21,9 @@ import java.util.Set; /** * In-memory outbox store with the relay semantics of the SQL one: claim eligibility by status and * {@code nextAttemptAt}, in-flight reclaim after the timeout, and completions fenced by lease owner - * and token. It does not model the per-aggregate FIFO gate; that lives in the claim SQL and is - * covered against PostgreSQL. + * and token, deferred claims kept out of the attempt budget, and released claims returned unspent. + * It does not model the per-aggregate FIFO gate; that lives in the claim SQL and is covered against + * PostgreSQL. * *

        Not final so a test can override one operation to inject a storage failure. */ @@ -35,6 +36,7 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { private final List published = new ArrayList<>(); private final Map failed = new LinkedHashMap<>(); private final List dead = new ArrayList<>(); + private final List released = new ArrayList<>(); @Override public void append(ValidatedIntegrationEvent event) { @@ -85,7 +87,8 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { row.leaseToken++; leases.add( new OutboxLease( - new ClaimedOutboxEvent(row.event, row.status, row.attemptCount), + new ClaimedOutboxEvent( + row.event, row.status, row.attemptCount, row.deferredAttemptCount), owner, row.leaseToken)); } @@ -110,6 +113,27 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { return completion; } + @Override + public OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt) { + OutboxCompletion completion = complete(lease, OutboxEventStatus.FAILED, nextAttemptAt); + if (completion == OutboxCompletion.APPLIED) { + rows.get(lease.eventId()).deferredAttemptCount++; + failed.put(lease.eventId(), nextAttemptAt); + } + return completion; + } + + @Override + public OutboxCompletion releaseLease(OutboxLease lease, Instant claimableAt) { + OutboxCompletion completion = complete(lease, OutboxEventStatus.PENDING, claimableAt); + if (completion == OutboxCompletion.APPLIED) { + Row row = rows.get(lease.eventId()); + row.attemptCount--; + released.add(lease.eventId()); + } + return completion; + } + @Override public OutboxCompletion markDead(OutboxLease lease) { OutboxCompletion completion = complete(lease, OutboxEventStatus.DEAD, null); @@ -166,6 +190,11 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { return row(eventId).attemptCount; } + /** Claims of the row that ended deferred ({@link #markDeferred}), outside the attempt budget. */ + public int deferredAttemptCount(String eventId) { + return row(eventId).deferredAttemptCount; + } + public Instant nextAttemptAt(String eventId) { return row(eventId).nextAttemptAt; } @@ -180,6 +209,11 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { return new LinkedHashMap<>(failed); } + /** Event ids whose lease release applied, in order. */ + public List released() { + return List.copyOf(released); + } + /** Event ids whose DEAD completion applied, in order. */ public List dead() { return List.copyOf(dead); @@ -197,6 +231,7 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { private final ValidatedIntegrationEvent event; private OutboxEventStatus status = OutboxEventStatus.PENDING; private int attemptCount; + private int deferredAttemptCount; private Instant nextAttemptAt; private String leaseOwner; private long leaseToken; diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAggregateSequenceContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAggregateSequenceContract.java new file mode 100644 index 00000000..1a3cd869 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAggregateSequenceContract.java @@ -0,0 +1,59 @@ +package dev.caskeleton.application.outbox.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.outbox.OutboxAggregateSequencePort; +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link OutboxAggregateSequencePort} promises, run against the in-memory fake and the + * JPA adapter alike. Each test uses aggregates of its own, so a subclass may share one store. + */ +public abstract class OutboxAggregateSequenceContract { + + protected abstract OutboxAggregateSequencePort sequences(); + + protected abstract TransactionPort transactions(); + + @Test + @DisplayName("같은 aggregate의 순서 번호는 1부터 커밋마다 하나씩 커진다") + void anAggregatesNumbersStartAtOneAndGrowByOnePerCommittedWrite() { + // given + AggregateIdentity aggregate = aggregate(); + List numbers = new ArrayList<>(); + + // when + for (int i = 0; i < 3; i++) { + numbers.add(transactions().inWrite(() -> sequences().nextSequence(aggregate))); + } + + // then + assertThat(numbers).containsExactly(1L, 2L, 3L); + } + + @Test + @DisplayName("aggregate마다 순서 번호를 따로 센다") + void eachAggregateCountsOnItsOwn() { + // given + AggregateIdentity first = aggregate(); + AggregateIdentity second = aggregate(); + transactions().inWrite(() -> sequences().nextSequence(first)); + transactions().inWrite(() -> sequences().nextSequence(first)); + + // when + long secondsFirst = transactions().inWrite(() -> sequences().nextSequence(second)); + + // then + assertThat(secondsFirst).isEqualTo(1L); + } + + private static AggregateIdentity aggregate() { + return new AggregateIdentity("default", "contract", "aggregate-" + UUID.randomUUID()); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java index 6deb761b..ff17746b 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java @@ -25,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** @@ -155,6 +156,70 @@ public abstract class OutboxLeaseFencingContract { .isEqualTo(Map.entry(OutboxCompletion.STALE, OutboxEventStatus.PUBLISHED)); } + @Test + @DisplayName("놓은 claim은 시도로 세지 않고 곧바로 다시 claim할 수 있다") + void aReleasedClaimIsClaimableAtOnceAndSpendsNoAttempt() { + // given + String eventId = appendEvent("release"); + OutboxLease lease = claim("relay-a", CLAIMED_AT); + + // when + OutboxCompletion released = + transactions().inWrite(() -> store().releaseLease(lease, CLAIMED_AT)); + + // then: another relay takes it at the same instant, as its first attempt + OutboxLease next = claim("relay-b", CLAIMED_AT); + assertThat(List.of(released, statusOf(eventId))) + .containsExactly(OutboxCompletion.APPLIED, OutboxEventStatus.IN_FLIGHT); + assertThat(next.eventId()).isEqualTo(eventId); + assertThat(next.event().attemptCount()).isEqualTo(1); + } + + @Test + @DisplayName("다른 relay가 넘겨받은 claim은 놓을 수 없다") + void aSupersededLeaseCannotReleaseTheRowItLost() { + // given + String eventId = appendEvent("release-stale"); + OutboxLease expired = claim("relay-a", CLAIMED_AT); + claim("relay-b", AFTER_EXPIRY); + + // when + OutboxCompletion released = + transactions().inWrite(() -> store().releaseLease(expired, AFTER_EXPIRY)); + + // then + assertThat(List.of(released, statusOf(eventId))) + .containsExactly(OutboxCompletion.STALE, OutboxEventStatus.IN_FLIGHT); + } + + @Test + @DisplayName("미룬 시도는 다음 claim에서 예산 밖으로 집계된다") + void aDeferredClaimIsCountedOutsideTheAttemptBudget() { + // given + appendEvent("deferred"); + OutboxLease first = claim("relay-a", CLAIMED_AT); + Instant retryAt = CLAIMED_AT.plusSeconds(30); + + // when + OutboxCompletion deferred = transactions().inWrite(() -> store().markDeferred(first, retryAt)); + + // then + OutboxLease second = claim("relay-a", retryAt); + assertThat(deferred).isEqualTo(OutboxCompletion.APPLIED); + assertThat( + List.of( + second.event().attemptCount(), + second.event().deferredAttemptCount(), + second.event().budgetedAttemptCount())) + .containsExactly(2, 1, 1); + } + + private OutboxLease claim(String owner, Instant now) { + return transactions() + .inWrite(() -> store().claimBatch(owner, 1, now, IN_FLIGHT_TIMEOUT)) + .getFirst(); + } + private String appendEvent(String scenario) { String eventId = "lease-fencing-" + scenario + "-" + UUID.randomUUID(); transactions() @@ -241,6 +306,16 @@ public abstract class OutboxLeaseFencingContract { return count(delegate.markFailed(lease, nextAttemptAt)); } + @Override + public OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt) { + return count(delegate.markDeferred(lease, nextAttemptAt)); + } + + @Override + public OutboxCompletion releaseLease(OutboxLease lease, Instant claimableAt) { + return count(delegate.releaseLease(lease, claimableAt)); + } + @Override public OutboxCompletion markDead(OutboxLease lease) { return count(delegate.markDead(lease)); diff --git a/src/application-core/src/testFixtures/resources/contracts/messaging/testkit.encoder-contract/v1.schema.json b/src/application-core/src/testFixtures/resources/contracts/messaging/testkit.encoder-contract/v1.schema.json new file mode 100644 index 00000000..3cffc84d --- /dev/null +++ b/src/application-core/src/testFixtures/resources/contracts/messaging/testkit.encoder-contract/v1.schema.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:dev-caskeleton:contracts:messaging:testkit.encoder-contract:v1", + "title": "Encoder contract kit payload v1", + "type": "object", + "required": ["name"], + "properties": { + "name": {"type": "string"} + }, + "unevaluatedProperties": false +} diff --git a/src/application-fileserver/build.gradle b/src/application-fileserver/build.gradle index 081717b6..43f7cc40 100644 --- a/src/application-fileserver/build.gradle +++ b/src/application-fileserver/build.gradle @@ -1,5 +1,6 @@ plugins { id 'ca.java-library' + id 'java-test-fixtures' } // Optional fileserver application product. Shared error codes are part of its public failure @@ -7,4 +8,12 @@ plugins { dependencies { implementation project(':application-core') implementation project(':shared-contract') + + // Port contracts (`*Contract`) are abstract JUnit classes that the in-memory fakes here and the + // JPA adapters in persistence-fileserver both extend, so a use-case test that passes against a + // fake is passing against the behaviour the real store is held to (AGENTS.md test rule 6). + // FileserverException's error code is a shared-contract type; the contracts assert on it. + testFixturesImplementation project(':shared-contract') + testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' + testFixturesImplementation 'org.assertj:assertj-core' } diff --git a/src/application-fileserver/gradle.lockfile b/src/application-fileserver/gradle.lockfile index e2c95854..13a5babd 100644 --- a/src/application-fileserver/gradle.lockfile +++ b/src/application-fileserver/gradle.lockfile @@ -1,40 +1,40 @@ # 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,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,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,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,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,testAnnotationProcessor +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,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,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,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,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,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,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs @@ -50,32 +50,32 @@ org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath,testFixturesCompileClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit:junit-bom:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.ow2.asm:asm-analysis:9.10.1=spotbugs org.ow2.asm:asm-commons:9.10.1=spotbugs org.ow2.asm:asm-tree:9.10.1=spotbugs org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.pcollections:pcollections:4.0.1=annotationProcessor,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 diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/CleanupItem.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/CleanupItem.java index 17169fb8..63055045 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/CleanupItem.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/CleanupItem.java @@ -4,17 +4,28 @@ import java.util.Objects; import java.util.UUID; /** - * A persisted unit of deferred physical work. + * A claimed unit of deferred physical work. * *

        The queue owns {@code cleanupId}; the application only ever supplies the {@link * CleanupRequest}. The worker re-checks state, version, and lease before deleting, so an item can * never remove content an active upload still owns. + * + *

        {@code claimToken} is the fence of the claim that produced this item. Settling the item + * ({@link CleanupQueuePort#markDone}, {@link CleanupQueuePort#markFailed}, {@link + * CleanupQueuePort#markAbandoned}) applies only while the queue still records this token, so a + * worker that wakes up after its lease expired and the item was reclaimed settles nothing. The + * token used to live in a map inside the JPA adapter, which kept the fence out of this contract: + * nothing but that one adapter knew it existed, and a fake could not be held to it (review 04-13). + * + *

        {@code attempt} is how many attempts were already recorded before this claim. The retry budget + * is the application's decision ({@link DefaultCleanupService}); the queue only counts. */ -public record CleanupItem(UUID cleanupId, CleanupRequest request, int attempt) { +public record CleanupItem(UUID cleanupId, CleanupRequest request, int attempt, UUID claimToken) { public CleanupItem { Objects.requireNonNull(cleanupId, "cleanupId"); Objects.requireNonNull(request, "request"); + Objects.requireNonNull(claimToken, "claimToken"); if (attempt < 0) { throw new IllegalArgumentException("attempt must not be negative"); } diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/CleanupQueuePort.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/CleanupQueuePort.java index 52aee8ec..4577fec0 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/CleanupQueuePort.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/CleanupQueuePort.java @@ -1,5 +1,6 @@ package dev.caskeleton.application.fileserver.cleanup; +import java.time.Duration; import java.time.Instant; import java.util.List; @@ -9,23 +10,56 @@ import java.util.List; *

        Enqueuing is always the last step of a state transition that already succeeded, so a queued * item never implies that the logical operation is still pending. The queue assigns each item's * identity, keeping identifier generation out of the application layer. + * + *

        The queue stores and fences; it does not decide. How long a claim lasts is an argument of + * {@link #claimDue}, and when an item has failed often enough to stop retrying is the caller's + * decision, expressed by calling {@link #markAbandoned} instead of {@link #markFailed}. Both used + * to be constants inside the JPA adapter (review 04-13). + * + *

        Every settlement is conditional on the item's {@link CleanupItem#claimToken()}: once the claim + * it came from has been reclaimed, settling it changes nothing. */ public interface CleanupQueuePort { void enqueue(CleanupRequest request); - List claimDue(Instant now, int limit); + /** + * Claims due items for this caller. + * + *

        Due means PENDING or FAILED with its next attempt at or before {@code now}. A claimed item + * is out of the due set until it is settled or its lease expires and {@link + * #reclaimExpiredClaims} hands it back. Two callers claiming at once receive disjoint items, and + * one does not wait for the other's claim to commit. + * + * @param now the moment due-ness and the lease are measured from + * @param limit how many items one call may claim + * @param lease how long the claim holds before a reaper may take the item over + * @return the claimed items, each carrying its claim token + */ + List claimDue(Instant now, int limit, Duration lease); + /** Records a successful attempt, if {@code item}'s claim is still the current one. */ void markDone(CleanupItem item); + /** Records a failed attempt and when to try again, if {@code item}'s claim is still current. */ void markFailed(CleanupItem item, String reasonCode, Instant nextAttemptAt); + /** + * Parks an item for good, if {@code item}'s claim is still current. + * + *

        An abandoned item is never claimed again but stays visible to an operator. It is parked, not + * discarded. + */ + void markAbandoned(CleanupItem item, String reasonCode); + /** * Returns items whose worker died mid-claim to the queue. * *

        A claim moves an item out of the due set, so an item whose worker performed the physical * delete and then died is invisible to {@link #claimDue}: nothing reclaims it, and the file's - * quota and lifecycle stay unsettled for good. This is the only path back. + * quota and lifecycle stay unsettled for good. This is the only path back. A reclaimed item + * counts as one more attempt, so an item whose worker dies every time runs out of the same retry + * budget as one that fails outright. * * @param now the moment expiry is judged against * @param limit how many items one pass may reclaim diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/DefaultCleanupService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/DefaultCleanupService.java index 983791b9..d28a7d40 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/DefaultCleanupService.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/DefaultCleanupService.java @@ -31,6 +31,24 @@ import java.util.Optional; */ public final class DefaultCleanupService implements CleanupService { + /** + * After this many recorded attempts an item is parked instead of rescheduled. + * + *

        A poison entry that never succeeds would otherwise occupy a slot in every batch and starve + * the work behind it. This is retry policy, so it is decided here rather than in the queue's + * adapter, where it used to be a constant nothing outside the persistence leaf could see (review + * 04-13). + */ + public static final int MAXIMUM_ATTEMPTS = 8; + + /** + * How long a claim holds before a reaper may hand the item to another worker. + * + *

        Long enough for one delete against slow storage; short enough that a worker that died + * mid-item does not hold the quota and lifecycle of that file unsettled for long. + */ + public static final Duration CLAIM_LEASE = Duration.ofMinutes(10); + private final CleanupQueuePort queue; private final CleanupContentPort contentGateway; private final FileMetadataPort metadataStore; @@ -76,7 +94,7 @@ public final class DefaultCleanupService implements CleanupService { // reclaimed it, and the file's quota and lifecycle stayed unsettled for good. Reclaiming before // claiming means the recovered items are eligible in this same pass. transactions.inWrite(() -> queue.reclaimExpiredClaims(now, maxItems)); - List due = transactions.inWrite(() -> queue.claimDue(now, maxItems)); + List due = transactions.inWrite(() -> queue.claimDue(now, maxItems, CLAIM_LEASE)); int deleted = 0; int skippedActiveLease = 0; @@ -85,6 +103,16 @@ public final class DefaultCleanupService implements CleanupService { long reclaimed = 0; for (CleanupItem item : due) { + if (item.attempt() >= MAXIMUM_ATTEMPTS) { + // Only a reclaimed claim reaches this: its worker died mid-item often enough to spend the + // whole budget without ever reporting a failure, so markFailed never got to park it. + transactions.inWrite( + () -> { + queue.markAbandoned(item, "CLEANUP_ATTEMPTS_EXHAUSTED"); + }); + failed++; + continue; + } if (reclaimed >= maxBytes) { // The byte budget is spent; the remaining claims are released for the next batch rather // than being marked done, so nothing is silently dropped. @@ -302,10 +330,21 @@ public final class DefaultCleanupService implements CleanupService { }); } + /** + * Reschedules an item, or parks it once this failure spends its retry budget. + * + *

        {@code item.attempt()} counts the attempts recorded before this one, so this failure is + * attempt {@code attempt + 1}. + */ private void markFailed(CleanupItem item, String reasonCode, Instant now) { + boolean exhausted = item.attempt() + 1 >= MAXIMUM_ATTEMPTS; transactions.inWrite( () -> { - queue.markFailed(item, reasonCode, now.plus(retryBackoff)); + if (exhausted) { + queue.markAbandoned(item, reasonCode); + } else { + queue.markFailed(item, reasonCode, now.plus(retryBackoff)); + } }); } diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/observability/SafeFileFingerprint.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/observability/SafeFileFingerprint.java index 64024118..2802af05 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/observability/SafeFileFingerprint.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/observability/SafeFileFingerprint.java @@ -1,11 +1,7 @@ package dev.caskeleton.application.fileserver.observability; -import java.nio.charset.StandardCharsets; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; +import dev.caskeleton.shared.digest.HmacSha256; import java.util.HexFormat; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; /** * Keyed pseudonym for correlating telemetry without disclosing an identifier. @@ -16,10 +12,12 @@ import javax.crypto.spec.SecretKeySpec; * *

        The output is truncated deliberately. A full digest is longer than any operator needs and * makes a rainbow table over the truncated space no easier. + * + *

        The MAC itself is shared-contract's {@link HmacSha256}; this class adds only the key-length + * floor and the truncation. */ public final class SafeFileFingerprint { - private static final String ALGORITHM = "HmacSHA256"; private static final int FINGERPRINT_HEX_LENGTH = 16; private final byte[] key; @@ -33,13 +31,8 @@ public final class SafeFileFingerprint { /** Derives a keyed fingerprint from a canonical identifier. */ public String of(String canonicalIdentifier) { - try { - Mac mac = Mac.getInstance(ALGORITHM); - mac.init(new SecretKeySpec(key, ALGORITHM)); - byte[] digest = mac.doFinal(canonicalIdentifier.getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(digest).substring(0, FINGERPRINT_HEX_LENGTH); - } catch (NoSuchAlgorithmException | InvalidKeyException failure) { - throw new IllegalStateException("HMAC-SHA256 is required by the platform", failure); - } + return HexFormat.of() + .formatHex(HmacSha256.sign(key, canonicalIdentifier)) + .substring(0, FINGERPRINT_HEX_LENGTH); } } diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/admin/FileserverAdminUseCasesTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/admin/FileserverAdminUseCasesTest.java index f2e48fc3..ef65f6f9 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/admin/FileserverAdminUseCasesTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/admin/FileserverAdminUseCasesTest.java @@ -263,10 +263,7 @@ class FileserverAdminUseCasesTest { uploading.fileId(), "LEGAL_TAKEDOWN_2026_08", FileserverFixtures.context())); // then - assertThat( - List.of( - sessions.find(uploadId).orElseThrow().terminal(), - queue.queued().stream().map(item -> item.request()).toList())) + assertThat(List.of(sessions.find(uploadId).orElseThrow().terminal(), queue.queued())) .containsExactly( true, List.of( diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/cleanup/CleanupServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/cleanup/CleanupServiceTest.java index ef9ef8ba..c0d4b042 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/cleanup/CleanupServiceTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/cleanup/CleanupServiceTest.java @@ -28,6 +28,7 @@ import java.time.Duration; import java.time.ZoneOffset; import java.util.OptionalLong; import java.util.UUID; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class CleanupServiceTest { @@ -441,6 +442,62 @@ class CleanupServiceTest { assertThat(content.quarantineHolds(orphan)).isFalse(); } + /** The retry budget is the service's decision; the queue only counts (review 04-13). */ + @Test + @DisplayName("시도 한도를 다 쓰는 실패는 재시도 예약 대신 포기로 기록된다") + void theFailureThatSpendsTheLastAttemptParksTheItemInsteadOfReschedulingIt() { + // given + UploadId uploadId = UploadId.of(UUID.randomUUID()); + FileId fileId = FileId.of(UUID.randomUUID()); + leasedSession(uploadId, fileId); + content.storeStaging(uploadId); + queue.enqueue(CleanupRequest.forStaging(CleanupType.CANCELLED_STAGING, fileId, uploadId)); + failPreviousAttempts(DefaultCleanupService.MAXIMUM_ATTEMPTS - 1); + + // when + cleanup.runBatch(100, 1L << 30); + + // then + assertThat(queue.abandoned().values()).containsExactly("ACTIVE_WRITER_LEASE"); + assertThat(queue.queued()).isEmpty(); + } + + /** + * A reclaimed claim counts as an attempt but never reaches markFailed, so an item whose worker + * dies every time would otherwise be claimed forever. + */ + @Test + @DisplayName("이미 시도 한도를 다 쓴 채 claim된 항목은 처리하지 않고 포기한다") + void anItemClaimedWithItsBudgetAlreadySpentIsParkedWithoutBeingProcessed() { + // given + FileRecord deleting = deletingRecord(); + content.store(ContentKey.of(ReadyFileFixture.CONTENT_KEY)); + queue.enqueue( + CleanupRequest.forContent( + CleanupType.DELETED_READY_CONTENT, + deleting.fileId(), + ContentKey.of(ReadyFileFixture.CONTENT_KEY))); + failPreviousAttempts(DefaultCleanupService.MAXIMUM_ATTEMPTS); + + // when + CleanupBatchResult result = cleanup.runBatch(100, 1L << 30); + + // then + assertThat(result.failed()).isEqualTo(1); + assertThat(queue.abandoned().values()).containsExactly("CLEANUP_ATTEMPTS_EXHAUSTED"); + assertThat(content.exists(ContentKey.of(ReadyFileFixture.CONTENT_KEY))).isTrue(); + } + + /** Records {@code attempts} failures against every queued item, each due again at once. */ + private void failPreviousAttempts(int attempts) { + for (int attempt = 0; attempt < attempts; attempt++) { + for (CleanupItem item : + queue.claimDue(FileserverFixtures.NOW, 100, DefaultCleanupService.CLAIM_LEASE)) { + queue.markFailed(item, "EARLIER_ATTEMPT", FileserverFixtures.NOW); + } + } + } + private UploadId expiredSession(FileId fileId) { UploadId uploadId = UploadId.of(UUID.randomUUID()); sessions.create( diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java index f8062a71..437435f5 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java @@ -141,10 +141,7 @@ class FileLifecycleUseCasesTest { new DeleteFileCommand(uploading.fileId(), Optional.empty(), FileserverFixtures.context())); // then - assertThat( - List.of( - sessions.find(uploadId).orElseThrow().terminal(), - cleanup.queued().stream().map(item -> item.request()).toList())) + assertThat(List.of(sessions.find(uploadId).orElseThrow().terminal(), cleanup.queued())) .containsExactly( true, List.of( diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/observability/SafeFileFingerprintTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/observability/SafeFileFingerprintTest.java new file mode 100644 index 00000000..ee4d35e0 --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/observability/SafeFileFingerprintTest.java @@ -0,0 +1,29 @@ +package dev.caskeleton.application.fileserver.observability; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +class SafeFileFingerprintTest { + + private static final byte[] KEY = "0123456789abcdef".getBytes(StandardCharsets.US_ASCII); + + /** Pinned so a change of implementation cannot silently change every logged fingerprint. */ + @Test + void theFingerprintIsTheFirstSixteenHexDigitsOfTheHmacSha256() { + assertThat(new SafeFileFingerprint(KEY).of("file-1")).isEqualTo("36ab85774f9cd9ce"); + } + + @Test + void aKeyShorterThanSixteenBytesIsRefused() { + // when + Throwable thrown = catchThrowable(() -> new SafeFileFingerprint(new byte[15])); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("fingerprint key must be at least 16 bytes"); + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueue.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueue.java deleted file mode 100644 index 0a50ddb0..00000000 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueue.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.application.fileserver.testkit; - -import dev.caskeleton.application.fileserver.cleanup.CleanupItem; -import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; -import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; -import java.time.Instant; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * Hand-rolled cleanup queue that records what was scheduled. - * - *

        Like the durable queue, it assigns the item identity on enqueue. Claim leases are recorded - * rather than enforced: the fencing they exist for is a database property, and a fake that pretends - * to have it would report success for a guarantee only real PostgreSQL can give. - */ -public final class InMemoryCleanupQueue implements CleanupQueuePort { - - private final List queued = new ArrayList<>(); - private final List done = new ArrayList<>(); - private final Map failed = new LinkedHashMap<>(); - private final List reclaimSweeps = new ArrayList<>(); - private final List claimSweeps = new ArrayList<>(); - - @Override - public void enqueue(CleanupRequest request) { - queued.add(new CleanupItem(UUID.randomUUID(), request, 0)); - } - - @Override - public int reclaimExpiredClaims(Instant now, int limit) { - reclaimSweeps.add(now); - return 0; - } - - /** The moments a batch asked for abandoned claims back, in order. */ - public List reclaimSweeps() { - return List.copyOf(reclaimSweeps); - } - - @Override - public List claimDue(Instant now, int limit) { - claimSweeps.add(now); - return List.copyOf(queued.subList(0, Math.min(limit, queued.size()))); - } - - @Override - public void markDone(CleanupItem item) { - queued.remove(item); - done.add(item); - } - - @Override - public void markFailed(CleanupItem item, String reasonCode, Instant nextAttemptAt) { - failed.put(item, reasonCode); - } - - /** The moments a batch claimed due items, in order. */ - public List claimSweeps() { - return List.copyOf(claimSweeps); - } - - public List queued() { - return List.copyOf(queued); - } - - public List done() { - return List.copyOf(done); - } - - public Map failed() { - return Map.copyOf(failed); - } -} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueueContractTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueueContractTest.java new file mode 100644 index 00000000..3aa5d3d2 --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueueContractTest.java @@ -0,0 +1,19 @@ +package dev.caskeleton.application.fileserver.testkit; + +import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; +import java.time.Instant; + +class InMemoryCleanupQueueContractTest extends CleanupQueuePortContract { + + private final InMemoryCleanupQueue queue = new InMemoryCleanupQueue(); + + @Override + protected CleanupQueuePort queue() { + return queue; + } + + @Override + protected Instant enqueueInstant() { + return FileserverFixtures.NOW; + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStoreContractTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStoreContractTest.java new file mode 100644 index 00000000..d4def503 --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStoreContractTest.java @@ -0,0 +1,13 @@ +package dev.caskeleton.application.fileserver.testkit; + +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; + +class InMemoryFileMetadataStoreContractTest extends FileMetadataPortContract { + + private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore(); + + @Override + protected FileMetadataPort metadata() { + return metadata; + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/ResumableUploadUseCasesTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/ResumableUploadUseCasesTest.java index 04abdfe9..e3f1423e 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/ResumableUploadUseCasesTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/ResumableUploadUseCasesTest.java @@ -130,7 +130,7 @@ class ResumableUploadUseCasesTest { // then assertThat(cleanup.queued()) - .extracting(item -> item.request().type()) + .extracting(request -> request.type()) .contains(CleanupType.DELETED_READY_CONTENT); } diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/CleanupQueuePortContract.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/CleanupQueuePortContract.java new file mode 100644 index 00000000..0db36011 --- /dev/null +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/CleanupQueuePortContract.java @@ -0,0 +1,241 @@ +package dev.caskeleton.application.fileserver.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.fileserver.api.ContentKey; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.cleanup.CleanupItem; +import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; +import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; +import dev.caskeleton.application.fileserver.cleanup.CleanupType; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link CleanupQueuePort} promises, run against the in-memory fake and the PostgreSQL + * adapter alike. + * + *

        The queue stores and fences; the retry budget and the lease length are the caller's. So this + * contract is about the mechanics the cleanup worker relies on: a claim takes an item out of the + * due set and hands it a token, a settlement applies only under that token, and an expired claim + * comes back as one more attempt. Concurrency between transactions ({@code SKIP LOCKED}) is a + * database property and is proved by the PostgreSQL test on its own. + * + *

        Every test enqueues its own items; the subclass supplies an empty queue per test. + */ +public abstract class CleanupQueuePortContract { + + private static final Duration LEASE = Duration.ofMinutes(1); + + protected abstract CleanupQueuePort queue(); + + /** + * An instant, fixed for the duration of one test, by which every item the test enqueues is due by + * the queue's own clock. The contract claims one second after it. + */ + protected abstract Instant enqueueInstant(); + + /** Runs one store call inside the caller transaction the adapter requires. */ + protected T transactionally(Supplier action) { + return action.get(); + } + + @Test + @DisplayName("넣은 항목은 요청과 시도 0회, claim 토큰을 실어 claim된다") + void anEnqueuedItemIsClaimedWithItsRequestNoAttemptsAndAClaimToken() { + // given + CleanupRequest request = contentCleanup(); + enqueue(request); + + // when + List claimed = claim(due(), 10); + + // then + assertThat(claimed) + .singleElement() + .satisfies( + item -> { + assertThat(item.request()).isEqualTo(request); + assertThat(item.attempt()).isZero(); + assertThat(item.claimToken()).isNotNull(); + }); + } + + @Test + @DisplayName("한 번의 claim은 limit보다 많은 항목을 가져가지 않는다") + void aClaimTakesNoMoreItemsThanItsLimit() { + // given + enqueue(contentCleanup()); + enqueue(contentCleanup()); + enqueue(contentCleanup()); + + // when + List claimed = claim(due(), 2); + + // then + assertThat(claimed).hasSize(2); + } + + @Test + @DisplayName("claim된 항목은 lease가 남아 있는 동안 다른 claim에 다시 나오지 않는다") + void aClaimedItemIsNotHandedToASecondClaimWhileItsLeaseHolds() { + // given + enqueue(contentCleanup()); + claim(due(), 10); + + // when + List second = claim(due().plusSeconds(1), 10); + + // then + assertThat(second).isEmpty(); + } + + @Test + @DisplayName("실패 처리된 항목은 다음 시도 시각 이후에만 시도 횟수 1을 달고 다시 claim된다") + void aFailedItemComesBackOnlyAfterItsNextAttemptWithTheAttemptCounted() { + // given + enqueue(contentCleanup()); + CleanupItem item = claim(due(), 10).get(0); + Instant retryAt = due().plus(Duration.ofMinutes(5)); + settle(() -> queue().markFailed(item, "STORAGE_UNAVAILABLE", retryAt)); + assertThat(claim(retryAt.minusSeconds(1), 10)).isEmpty(); + + // when + List retried = claim(retryAt, 10); + + // then + assertThat(retried) + .singleElement() + .satisfies( + again -> { + assertThat(again.cleanupId()).isEqualTo(item.cleanupId()); + assertThat(again.attempt()).isEqualTo(1); + assertThat(again.claimToken()).isNotEqualTo(item.claimToken()); + }); + } + + @Test + @DisplayName("완료된 항목은 다시 claim되지 않는다") + void aDoneItemIsNeverClaimedAgain() { + // given + enqueue(contentCleanup()); + CleanupItem item = claim(due(), 10).get(0); + settle(() -> queue().markDone(item)); + + // when + List later = claim(due().plus(Duration.ofDays(1)), 10); + + // then + assertThat(later).isEmpty(); + } + + @Test + @DisplayName("포기된 항목은 다시 claim되지 않는다") + void anAbandonedItemIsNeverClaimedAgain() { + // given + enqueue(contentCleanup()); + CleanupItem item = claim(due(), 10).get(0); + settle(() -> queue().markAbandoned(item, "CLEANUP_ATTEMPTS_EXHAUSTED")); + + // when + List later = claim(due().plus(Duration.ofDays(1)), 10); + + // then + assertThat(later).isEmpty(); + } + + @Test + @DisplayName("lease가 끝나기 전의 claim은 회수되지 않는다") + void aClaimIsNotReclaimedBeforeItsLeaseEnds() { + // given + enqueue(contentCleanup()); + claim(due(), 10); + + // when + int reclaimed = transactionally(() -> queue().reclaimExpiredClaims(due().plus(LEASE), 10)); + + // then + assertThat(reclaimed).isZero(); + } + + @Test + @DisplayName("lease가 끝난 claim은 회수되어 시도 하나를 더 센 채 다시 claim된다") + void anExpiredClaimIsReclaimedAndComesBackWithOneMoreAttempt() { + // given + enqueue(contentCleanup()); + CleanupItem stalled = claim(due(), 10).get(0); + Instant afterLease = due().plus(LEASE).plusSeconds(1); + assertThat(transactionally(() -> queue().reclaimExpiredClaims(afterLease, 10))).isEqualTo(1); + + // when + List takenOver = claim(afterLease, 10); + + // then + assertThat(takenOver) + .singleElement() + .satisfies( + item -> { + assertThat(item.cleanupId()).isEqualTo(stalled.cleanupId()); + assertThat(item.attempt()).isEqualTo(1); + }); + } + + /** + * The fence: a worker that wakes up after its claim was reclaimed and handed to another worker + * settles nothing. Had its DONE landed, the second worker's claim would be gone and its item + * would never be reclaimed again. + */ + @Test + @DisplayName("회수된 claim의 토큰으로 한 완료는 새 claim을 덮어쓰지 않는다") + void aCompletionUnderAReclaimedTokenDoesNotOverwriteTheNewClaim() { + // given + enqueue(contentCleanup()); + CleanupItem stalled = claim(due(), 10).get(0); + Instant afterFirstLease = due().plus(LEASE).plusSeconds(1); + transactionally(() -> queue().reclaimExpiredClaims(afterFirstLease, 10)); + claim(afterFirstLease, 10); + + // when + settle(() -> queue().markDone(stalled)); + + // then + Instant afterSecondLease = afterFirstLease.plus(LEASE).plusSeconds(1); + assertThat(transactionally(() -> queue().reclaimExpiredClaims(afterSecondLease, 10))) + .as("the second claim is still the one the queue holds") + .isEqualTo(1); + } + + private void enqueue(CleanupRequest request) { + settle(() -> queue().enqueue(request)); + } + + private List claim(Instant now, int limit) { + return transactionally(() -> queue().claimDue(now, limit, LEASE)); + } + + private void settle(Runnable action) { + transactionally( + () -> { + action.run(); + return null; + }); + } + + /** A moment at which everything enqueued so far is due. */ + private Instant due() { + return enqueueInstant().plusSeconds(1); + } + + private static CleanupRequest contentCleanup() { + String flat = UUID.randomUUID().toString().replace("-", ""); + return CleanupRequest.forContent( + CleanupType.DELETED_READY_CONTENT, + FileId.of(UUID.randomUUID()), + ContentKey.of(flat.substring(0, 2) + '/' + flat.substring(2, 4) + '/' + flat)); + } +} diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileMetadataPortContract.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileMetadataPortContract.java new file mode 100644 index 00000000..ed9a9abf --- /dev/null +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileMetadataPortContract.java @@ -0,0 +1,157 @@ +package dev.caskeleton.application.fileserver.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.FileState; +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileOwner; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecordDraft; +import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; +import java.util.Optional; +import java.util.OptionalLong; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link FileMetadataPort} promises, run against the in-memory fake and the PostgreSQL + * adapter alike. + * + *

        Use-case tests run on the fake. They are only worth something if the fake answers the way the + * database does — the same version after insert and transition, the same refusal for a stale + * version, and the same refusal for an id that already exists — so both are held to this. + * + *

        Every test inserts its own records under fresh ids. + */ +public abstract class FileMetadataPortContract { + + protected abstract FileMetadataPort metadata(); + + /** Runs one store call inside the caller transaction the adapter requires, and commits it. */ + protected T transactionally(Supplier action) { + return action.get(); + } + + @Test + @DisplayName("새 레코드는 CREATED 상태, 버전 0으로 저장되고 그대로 다시 읽힌다") + void anInsertedRecordIsStoredAsCreatedAtVersionZeroAndReadBack() { + // given + FileId fileId = FileId.of(UUID.randomUUID()); + + // when + FileRecord inserted = transactionally(() -> metadata().insert(draft(fileId, "report.bin"))); + + // then + FileRecord found = transactionally(() -> metadata().find(fileId)).orElseThrow(); + assertThat(inserted.state()).isEqualTo(FileState.CREATED); + assertThat(inserted.version()).isZero(); + assertThat(found.version()).isZero(); + assertThat(found.originalName()).isEqualTo("report.bin"); + } + + @Test + @DisplayName("상태 전이는 상태를 바꾸고 버전을 하나 올린다") + void aTransitionChangesTheStateAndAdvancesTheVersion() { + // given + FileRecord created = insert(); + + // when + FileRecord uploading = + transactionally( + () -> + metadata() + .transition( + created.fileId(), + created.version(), + FileState.CREATED, + FileState.UPLOADING, + FileRecordMutation.none())); + + // then + assertThat(uploading.state()).isEqualTo(FileState.UPLOADING); + assertThat(uploading.version()).isEqualTo(created.version() + 1); + } + + @Test + @DisplayName("지난 버전으로 한 전이는 동시 수정으로 거절되고 레코드는 그대로다") + void aTransitionFromAStaleVersionIsRefusedAsAConcurrentModification() { + // given + FileRecord created = insert(); + transactionally( + () -> + metadata() + .transition( + created.fileId(), + created.version(), + FileState.CREATED, + FileState.UPLOADING, + FileRecordMutation.none())); + + // when + Throwable refused = + catchThrowable( + () -> + transactionally( + () -> + metadata() + .transition( + created.fileId(), + created.version(), + FileState.CREATED, + FileState.UPLOADING, + FileRecordMutation.none()))); + + // then + assertThat(refused) + .isInstanceOfSatisfying( + FileserverException.class, + failure -> + assertThat(failure.code()).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION)); + assertThat(transactionally(() -> metadata().find(created.fileId())).orElseThrow().version()) + .isEqualTo(created.version() + 1); + } + + /** + * An id is assigned before the insert, so a second insert under it is a caller bug or a replay. + * It has to fail. The JPA adapter used to merge it into the existing row instead — the second + * draft silently replaced the first record (review 04-17). + */ + @Test + @DisplayName("이미 있는 id로 다시 넣으면 거절되고 처음 레코드가 그대로 남는다") + void insertingASecondRecordUnderAnExistingIdIsRefusedAndKeepsTheFirst() { + // given + FileId fileId = FileId.of(UUID.randomUUID()); + transactionally(() -> metadata().insert(draft(fileId, "report.bin"))); + + // when + Throwable refused = + catchThrowable(() -> transactionally(() -> metadata().insert(draft(fileId, "other.bin")))); + + // then + assertThat(refused).isNotNull(); + assertThat(transactionally(() -> metadata().find(fileId)).orElseThrow().originalName()) + .isEqualTo("report.bin"); + } + + private FileRecord insert() { + return transactionally( + () -> metadata().insert(draft(FileId.of(UUID.randomUUID()), "report.bin"))); + } + + private static FileRecordDraft draft(FileId fileId, String originalName) { + return new FileRecordDraft( + fileId, + StorageNamespace.of("tenant-a"), + originalName, + Optional.of("application/octet-stream"), + OptionalLong.of(10), + new FileOwner("user-1", Optional.of("tenant-a"))); + } +} diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueue.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueue.java new file mode 100644 index 00000000..50edd600 --- /dev/null +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryCleanupQueue.java @@ -0,0 +1,191 @@ +package dev.caskeleton.application.fileserver.testkit; + +import dev.caskeleton.application.fileserver.cleanup.CleanupItem; +import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; +import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +/** + * Hand-rolled cleanup queue with the durable queue's claim, fencing and settlement rules. + * + *

        It is held to {@link CleanupQueuePortContract}, the same contract the JPA adapter passes + * against PostgreSQL: claims hand out tokens, a settlement with a token the row no longer carries + * changes nothing, and an expired lease is taken back by {@link #reclaimExpiredClaims}. What it + * cannot reproduce is concurrency between transactions — {@code SKIP LOCKED} only exists in the + * database — so that part of the contract is proved by the PostgreSQL test alone. + * + *

        Like the durable queue, it assigns the item identity on enqueue, and an enqueued item is due + * at the queue clock's instant. + */ +public final class InMemoryCleanupQueue implements CleanupQueuePort { + + private static final Instant DEFAULT_NOW = Instant.parse("2026-08-07T10:00:00Z"); + + private final Clock clock; + private final Map rows = new LinkedHashMap<>(); + private final List done = new ArrayList<>(); + private final Map failed = new LinkedHashMap<>(); + private final Map abandoned = new LinkedHashMap<>(); + private final List reclaimSweeps = new ArrayList<>(); + private final List claimSweeps = new ArrayList<>(); + + public InMemoryCleanupQueue() { + this(Clock.fixed(DEFAULT_NOW, ZoneOffset.UTC)); + } + + public InMemoryCleanupQueue(Clock clock) { + this.clock = Objects.requireNonNull(clock, "clock"); + } + + @Override + public void enqueue(CleanupRequest request) { + UUID cleanupId = UUID.randomUUID(); + rows.put(cleanupId, new Row(cleanupId, request, clock.instant())); + } + + @Override + public List claimDue(Instant now, int limit, Duration lease) { + if (limit < 1) { + throw new IllegalArgumentException("limit must be positive"); + } + if (lease == null || lease.isNegative() || lease.isZero()) { + throw new IllegalArgumentException("lease must be positive"); + } + claimSweeps.add(now); + List claimed = new ArrayList<>(); + rows.values().stream() + .filter(row -> row.status == Status.PENDING || row.status == Status.FAILED) + .filter(row -> !row.nextAttemptAt.isAfter(now)) + .sorted(Comparator.comparing((Row row) -> row.nextAttemptAt)) + .limit(limit) + .forEach( + row -> { + row.status = Status.IN_PROGRESS; + row.claimToken = UUID.randomUUID(); + row.leaseUntil = now.plus(lease); + claimed.add(new CleanupItem(row.cleanupId, row.request, row.attempt, row.claimToken)); + }); + return List.copyOf(claimed); + } + + @Override + public int reclaimExpiredClaims(Instant now, int limit) { + reclaimSweeps.add(now); + int reclaimed = 0; + for (Row row : rows.values()) { + if (reclaimed >= limit) { + break; + } + if (row.status == Status.IN_PROGRESS && row.leaseUntil.isBefore(now)) { + row.settle(Status.FAILED, now); + reclaimed++; + } + } + return reclaimed; + } + + @Override + public void markDone(CleanupItem item) { + if (settle(item, Status.DONE, clock.instant())) { + done.add(item); + } + } + + @Override + public void markFailed(CleanupItem item, String reasonCode, Instant nextAttemptAt) { + if (settle(item, Status.FAILED, nextAttemptAt)) { + failed.put(item, reasonCode); + } + } + + @Override + public void markAbandoned(CleanupItem item, String reasonCode) { + if (settle(item, Status.ABANDONED, clock.instant())) { + abandoned.put(item, reasonCode); + } + } + + private boolean settle(CleanupItem item, Status status, Instant nextAttemptAt) { + Row row = rows.get(item.cleanupId()); + if (row == null || !item.claimToken().equals(row.claimToken)) { + return false; + } + row.settle(status, nextAttemptAt); + return true; + } + + /** The moments a batch asked for abandoned claims back, in order. */ + public List reclaimSweeps() { + return List.copyOf(reclaimSweeps); + } + + /** The moments a batch claimed due items, in order. */ + public List claimSweeps() { + return List.copyOf(claimSweeps); + } + + /** The requests of every item not yet done or abandoned, in enqueue order. */ + public List queued() { + return rows.values().stream() + .filter(row -> row.status != Status.DONE && row.status != Status.ABANDONED) + .map(row -> row.request) + .toList(); + } + + public List done() { + return List.copyOf(done); + } + + /** Items whose last settlement was a reschedule, with the reason given. */ + public Map failed() { + return Map.copyOf(failed); + } + + /** Items the caller parked for good, with the reason given. */ + public Map abandoned() { + return Map.copyOf(abandoned); + } + + private enum Status { + PENDING, + IN_PROGRESS, + DONE, + FAILED, + ABANDONED + } + + private static final class Row { + + private final UUID cleanupId; + private final CleanupRequest request; + private Status status = Status.PENDING; + private int attempt; + private Instant nextAttemptAt; + private UUID claimToken; + private Instant leaseUntil; + + private Row(UUID cleanupId, CleanupRequest request, Instant nextAttemptAt) { + this.cleanupId = cleanupId; + this.request = request; + this.nextAttemptAt = nextAttemptAt; + } + + private void settle(Status status, Instant nextAttemptAt) { + this.status = status; + this.attempt++; + this.nextAttemptAt = nextAttemptAt; + this.claimToken = null; + this.leaseUntil = null; + } + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStore.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStore.java similarity index 93% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStore.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStore.java index bb4a5eac..f55836d9 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStore.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStore.java @@ -23,7 +23,8 @@ import java.util.concurrent.atomic.AtomicInteger; * Hand-rolled metadata store with the same optimistic-transition semantics as the JPA adapter. * *

        Application tests must observe identical conflict behaviour, so this fake enforces the - * expected state and version rather than accepting any write. + * expected state and version rather than accepting any write. It is held to {@link + * FileMetadataPortContract}, the contract the JPA adapter passes against PostgreSQL. */ public final class InMemoryFileMetadataStore implements FileMetadataPort { @@ -42,6 +43,11 @@ public final class InMemoryFileMetadataStore implements FileMetadataPort { @Override public FileRecord insert(FileRecordDraft draft) { + if (records.containsKey(draft.fileId())) { + // The database refuses this on the primary key; a fake that overwrote would let a caller + // pass every unit test with an insert that fails in production (FileMetadataPortContract). + throw new IllegalStateException("a file record already exists under " + draft.fileId()); + } FileRecord record = new FileRecord( draft.fileId(), diff --git a/src/application-notification/build.gradle b/src/application-notification/build.gradle index 8c141de9..4ac05967 100644 --- a/src/application-notification/build.gradle +++ b/src/application-notification/build.gradle @@ -1,5 +1,6 @@ plugins { id 'ca.java-library' + id 'java-test-fixtures' } // Optional notification application product. The generic application contracts remain in @@ -7,4 +8,10 @@ plugins { dependencies { implementation project(':application-core') implementation project(':shared-contract') + + // Port contracts (`*Contract`) are abstract JUnit classes that the in-memory fakes here and the + // PostgreSQL adapters (persistence-jpa's postgresqlIntegrationTest lane) both extend, so a use + // case test passing on a fake says something about the real store (review 04-14). + testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' + testFixturesImplementation 'org.assertj:assertj-core' } diff --git a/src/application-notification/gradle.lockfile b/src/application-notification/gradle.lockfile index e2c95854..13a5babd 100644 --- a/src/application-notification/gradle.lockfile +++ b/src/application-notification/gradle.lockfile @@ -1,40 +1,40 @@ # 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,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,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,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,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,testAnnotationProcessor +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,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,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,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,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,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,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs @@ -50,32 +50,32 @@ org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath,testFixturesCompileClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit:junit-bom:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.ow2.asm:asm-analysis:9.10.1=spotbugs org.ow2.asm:asm-commons:9.10.1=spotbugs org.ow2.asm:asm-tree:9.10.1=spotbugs org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.pcollections:pcollections:4.0.1=annotationProcessor,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 diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/TenantId.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/TenantId.java index 6427c400..73a8e891 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/TenantId.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/TenantId.java @@ -1,6 +1,19 @@ package dev.caskeleton.application.notification.platform.api; -/** Tenant boundary every repository query must carry. */ +/** + * Tenant boundary every repository query must carry. + * + *

        A second tenant type, kept on purpose and only for now. The repository's tenant grammar + * is application-core's {@link dev.caskeleton.application.tenant.TenantId}, and every new write + * here already has to match it ({@code WritableTenant}). This type stays lenient — non-blank, at + * most 100 characters — because it is also what stored rows are read back into, and a row written + * before writes adopted the shared grammar (a space, a path character) must stay readable. + * + *

        To fold it into the shared type: run, on every deployment's notification schema, a query for + * {@code tenant_id} values outside {@code ^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$} in each table that has + * the column; once none exist, add a CHECK constraint migration and replace this type. The template + * default writes only {@code default}, which already matches. + */ public record TenantId(String value) { private static final int MAX_LENGTH = 100; diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryPreferenceStoreTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryPreferenceStoreTest.java new file mode 100644 index 00000000..2164c56a --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryPreferenceStoreTest.java @@ -0,0 +1,26 @@ +package dev.caskeleton.application.notification.platform.policy.testkit; + +import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeEach; + +/** The in-memory fake held to the same contract as the PostgreSQL adapter. */ +class InMemoryPreferenceStoreTest extends PreferenceStoreContract { + + private InMemoryPreferenceStore store; + + @BeforeEach + void freshStore() { + store = new InMemoryPreferenceStore(); + } + + @Override + protected PreferenceStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemorySuppressionStoreTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemorySuppressionStoreTest.java new file mode 100644 index 00000000..4628fc58 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemorySuppressionStoreTest.java @@ -0,0 +1,26 @@ +package dev.caskeleton.application.notification.platform.policy.testkit; + +import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeEach; + +/** The in-memory fake held to the same contract as the PostgreSQL adapter. */ +class InMemorySuppressionStoreTest extends SuppressionStoreContract { + + private InMemorySuppressionStore store; + + @BeforeEach + void freshStore() { + store = new InMemorySuppressionStore(); + } + + @Override + protected SuppressionStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryPreferenceStore.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryPreferenceStore.java new file mode 100644 index 00000000..5f127877 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryPreferenceStore.java @@ -0,0 +1,35 @@ +package dev.caskeleton.application.notification.platform.policy.testkit; + +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.policy.PreferenceRecord; +import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * A preference store with the semantics the PostgreSQL adapter must also have: one record per + * tenant and recipient, and a later save replaces the earlier one. {@link PreferenceStoreContract} + * holds this fake and the adapter to the same cases. + */ +public final class InMemoryPreferenceStore implements PreferenceStorePort { + + private record Key(TenantId tenantId, String recipientRef) {} + + private final Map records = new ConcurrentHashMap<>(); + + @Override + public Optional find(TenantId tenantId, String recipientRef) { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(recipientRef, "recipientRef"); + return Optional.ofNullable(records.get(new Key(tenantId, recipientRef))); + } + + @Override + public PreferenceRecord save(PreferenceRecord record) { + Objects.requireNonNull(record, "record"); + records.put(new Key(record.tenantId(), record.recipientRef()), record); + return record; + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemorySuppressionStore.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemorySuppressionStore.java new file mode 100644 index 00000000..0b851366 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemorySuppressionStore.java @@ -0,0 +1,77 @@ +package dev.caskeleton.application.notification.platform.policy.testkit; + +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.policy.SuppressionEntry; +import dev.caskeleton.application.notification.platform.policy.SuppressionId; +import dev.caskeleton.application.notification.platform.policy.SuppressionReason; +import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** + * A suppression store with the semantics the PostgreSQL adapter must also have. + * + *

        One entry per tenant, target fingerprint and reason. A second upsert of the same key refreshes + * the window and the source of the entry already there and keeps its id, scope and category — the + * same columns the adapter's {@code ON CONFLICT} branch leaves alone. {@link + * SuppressionStoreContract} holds this fake and the adapter to the same cases. + */ +public final class InMemorySuppressionStore implements SuppressionStorePort { + + private record Key(TenantId tenantId, String normalizedTargetHmac, SuppressionReason reason) {} + + private final Map entries = new LinkedHashMap<>(); + + @Override + public synchronized List activeFor( + TenantId tenantId, String targetFingerprint, Instant at) { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(targetFingerprint, "targetFingerprint"); + Objects.requireNonNull(at, "at"); + return entries.values().stream() + .filter(entry -> entry.tenantId().equals(tenantId)) + .filter(entry -> entry.normalizedTargetHmac().equals(targetFingerprint)) + .filter(entry -> entry.activeAt(at)) + .toList(); + } + + @Override + public synchronized SuppressionEntry upsert(SuppressionEntry entry) { + Objects.requireNonNull(entry, "entry"); + Key key = new Key(entry.tenantId(), entry.normalizedTargetHmac(), entry.reason()); + SuppressionEntry stored = + Optional.ofNullable(entries.get(key)) + .map( + existing -> + new SuppressionEntry( + existing.id(), + existing.tenantId(), + existing.scope(), + entry.reason(), + existing.normalizedTargetHmac(), + existing.notificationCategory(), + entry.effectiveAt(), + entry.expiresAt(), + entry.source())) + .orElse(entry); + entries.put(key, stored); + return stored; + } + + @Override + public synchronized Optional remove(TenantId tenantId, SuppressionId id) { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(id, "id"); + Optional key = + entries.entrySet().stream() + .filter(candidate -> candidate.getValue().tenantId().equals(tenantId)) + .filter(candidate -> candidate.getValue().id().equals(id)) + .map(Map.Entry::getKey) + .findFirst(); + return key.map(entries::remove); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/OverlappingWrites.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/OverlappingWrites.java new file mode 100644 index 00000000..7c04d6e8 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/OverlappingWrites.java @@ -0,0 +1,93 @@ +package dev.caskeleton.application.notification.platform.policy.testkit; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * Two writes of the same key whose transactions overlap, in an order that does not depend on luck. + * + *

        The first write runs and then holds its transaction open. The second starts while the first is + * still uncommitted — the moment a find-then-insert reads "absent" twice — and the first commits + * only once the second has either finished or had time to block on the first's row. A store that + * has no transactions simply runs the two one after the other, which is the answer it must give + * anyway. + */ +final class OverlappingWrites { + + private static final Duration SECOND_WRITE_HEAD_START = Duration.ofMillis(500); + private static final Duration LIMIT = Duration.ofSeconds(30); + + private OverlappingWrites() {} + + /** + * Runs both writes and returns their results, first then second. + * + * @param inTransaction runs one unit of work in one committed transaction of the store + * @param first the write whose transaction is held open + * @param second the write that starts while the first is uncommitted + * @return both results; a write that failed fails this call with its cause + */ + static List run( + Function, T> inTransaction, Supplier first, Supplier second) { + CountDownLatch firstWrote = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + ExecutorService threads = Executors.newFixedThreadPool(2); + try { + Future firstResult = + threads.submit( + () -> + inTransaction.apply( + () -> { + T written = first.get(); + firstWrote.countDown(); + await(releaseFirst); + return written; + })); + if (!firstWrote.await(LIMIT.toMillis(), TimeUnit.MILLISECONDS)) { + throw new IllegalStateException("the first write never finished its statement"); + } + Future secondResult = threads.submit(() -> inTransaction.apply(second)); + try { + secondResult.get(SECOND_WRITE_HEAD_START.toMillis(), TimeUnit.MILLISECONDS); + } catch (TimeoutException blockedOnTheFirst) { + // Expected on a database: the second write waits for the first's uncommitted row. + } catch (ExecutionException failed) { + // Reported below, after the first transaction has been allowed to finish. + } + releaseFirst.countDown(); + return List.of( + firstResult.get(LIMIT.toMillis(), TimeUnit.MILLISECONDS), + secondResult.get(LIMIT.toMillis(), TimeUnit.MILLISECONDS)); + } catch (ExecutionException failed) { + throw new AssertionError("an overlapping write failed", failed.getCause()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError("interrupted while racing two writes", interrupted); + } catch (TimeoutException stuck) { + throw new AssertionError("an overlapping write did not finish", stuck); + } finally { + releaseFirst.countDown(); + threads.shutdownNow(); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(LIMIT.toMillis(), TimeUnit.MILLISECONDS)) { + throw new IllegalStateException("the first write was never released"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/PreferenceStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/PreferenceStoreContract.java new file mode 100644 index 00000000..995732d5 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/PreferenceStoreContract.java @@ -0,0 +1,107 @@ +package dev.caskeleton.application.notification.platform.policy.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.api.routing.Channel; +import dev.caskeleton.application.notification.platform.policy.PreferenceRecord; +import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link PreferenceStorePort} promises, run against the in-memory fake and the + * PostgreSQL adapter alike. + * + *

        {@code updatedAt} is not compared: the adapter stamps it from its own clock. + */ +public abstract class PreferenceStoreContract { + + private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z"); + private static final TenantId TENANT = new TenantId("tenant-a"); + private static final TenantId OTHER_TENANT = new TenantId("tenant-b"); + private static final String RECIPIENT = "user-1"; + + /** The store under test, empty at the start of each test. */ + protected abstract PreferenceStorePort store(); + + /** Runs {@code work} in one committed write transaction of the store under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + @DisplayName("저장한 적 없는 수신자의 선호 설정은 비어 있다") + void aRecipientWithoutAPreferenceHasNone() { + // when + Optional found = store().find(TENANT, RECIPIENT); + + // then + assertThat(found).isEmpty(); + } + + @Test + @DisplayName("저장한 선호 설정을 같은 테넌트에서 다시 읽는다") + void aSavedPreferenceIsFoundInItsTenant() { + // given + save(preference(List.of(Channel.PUSH, Channel.EMAIL), Set.of(Channel.SMS))); + + // when + Optional found = store().find(TENANT, RECIPIENT); + + // then + assertThat(found) + .get() + .extracting(PreferenceRecord::preferredOrder, PreferenceRecord::mutedChannels) + .containsExactly(List.of(Channel.PUSH, Channel.EMAIL), Set.of(Channel.SMS)); + assertThat(store().find(OTHER_TENANT, RECIPIENT)).isEmpty(); + } + + @Test + @DisplayName("다시 저장하면 나중 값이 이전 값을 대신한다") + void aLaterSaveReplacesTheEarlierOne() { + // given + save(preference(List.of(Channel.PUSH), Set.of())); + + // when + save(preference(List.of(Channel.EMAIL, Channel.SMS), Set.of(Channel.PUSH))); + + // then + assertThat(store().find(TENANT, RECIPIENT)) + .get() + .extracting(PreferenceRecord::preferredOrder, PreferenceRecord::mutedChannels) + .containsExactly(List.of(Channel.EMAIL, Channel.SMS), Set.of(Channel.PUSH)); + } + + @Test + @DisplayName("첫 선호 설정 저장이 동시에 두 번 와도 둘 다 성공하고 나중 값이 남는다") + void twoOverlappingFirstSavesBothSucceedAndTheLaterWins() { + // given + PreferenceRecord first = preference(List.of(Channel.PUSH), Set.of()); + PreferenceRecord second = preference(List.of(Channel.EMAIL), Set.of(Channel.PUSH)); + + // when + List results = + OverlappingWrites.run( + this::inTransaction, () -> store().save(first), () -> store().save(second)); + + // then + assertThat(results).hasSize(2); + assertThat(store().find(TENANT, RECIPIENT)) + .as("the write that committed last is the preference") + .get() + .extracting(PreferenceRecord::preferredOrder) + .isEqualTo(List.of(Channel.EMAIL)); + } + + private PreferenceRecord save(PreferenceRecord record) { + return inTransaction(() -> store().save(record)); + } + + private static PreferenceRecord preference(List preferred, Set muted) { + return new PreferenceRecord(TENANT, RECIPIENT, preferred, muted, NOW); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/SuppressionStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/SuppressionStoreContract.java new file mode 100644 index 00000000..e48b15f2 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/SuppressionStoreContract.java @@ -0,0 +1,190 @@ +package dev.caskeleton.application.notification.platform.policy.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.policy.SuppressionEntry; +import dev.caskeleton.application.notification.platform.policy.SuppressionId; +import dev.caskeleton.application.notification.platform.policy.SuppressionReason; +import dev.caskeleton.application.notification.platform.policy.SuppressionScope; +import dev.caskeleton.application.notification.platform.policy.SuppressionSource; +import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link SuppressionStorePort} promises, run against the in-memory fake and the + * PostgreSQL adapter alike. + * + *

        Writes go through {@link #inTransaction}, because the real store refuses a write without a + * caller transaction, and because the race case needs two transactions that overlap. + */ +public abstract class SuppressionStoreContract { + + private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z"); + private static final TenantId TENANT = new TenantId("tenant-a"); + private static final TenantId OTHER_TENANT = new TenantId("tenant-b"); + private static final String TARGET = "a".repeat(64); + + /** The store under test, empty at the start of each test. */ + protected abstract SuppressionStorePort store(); + + /** Runs {@code work} in one committed write transaction of the store under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + @DisplayName("저장한 수신 거부는 유효 기간 안에서 조회된다") + void anUpsertedEntryIsActiveInsideItsWindow() { + // given + SuppressionEntry stored = upsert(entry(SuppressionReason.HARD_BOUNCE, NOW, null)); + + // when + List active = store().activeFor(TENANT, TARGET, NOW.plusSeconds(1)); + + // then + assertThat(active).containsExactly(stored); + } + + @Test + @DisplayName("같은 대상과 사유를 다시 저장하면 기존 항목의 기간과 출처만 갱신된다") + void aSecondUpsertOfTheSameKeyRefreshesTheExistingEntry() { + // given + SuppressionEntry first = upsert(entry(SuppressionReason.HARD_BOUNCE, NOW, null)); + SuppressionEntry refresh = + new SuppressionEntry( + new SuppressionId(UUID.randomUUID()), + TENANT, + SuppressionScope.RECIPIENT, + SuppressionReason.HARD_BOUNCE, + TARGET, + Optional.of("marketing"), + NOW.plus(Duration.ofHours(1)), + Optional.of(NOW.plus(Duration.ofDays(1))), + SuppressionSource.ADMIN); + + // when + SuppressionEntry refreshed = upsert(refresh); + + // then + assertThat(refreshed) + .isEqualTo( + new SuppressionEntry( + first.id(), + TENANT, + first.scope(), + SuppressionReason.HARD_BOUNCE, + TARGET, + first.notificationCategory(), + NOW.plus(Duration.ofHours(1)), + Optional.of(NOW.plus(Duration.ofDays(1))), + SuppressionSource.ADMIN)); + assertThat(store().activeFor(TENANT, TARGET, NOW.plus(Duration.ofHours(2)))) + .containsExactly(refreshed); + } + + @Test + @DisplayName("사유가 다르면 같은 대상이라도 별도 항목으로 남는다") + void aDifferentReasonIsADifferentEntry() { + // given + SuppressionEntry bounce = upsert(entry(SuppressionReason.HARD_BOUNCE, NOW, null)); + + // when + SuppressionEntry complaint = upsert(entry(SuppressionReason.COMPLAINT, NOW, null)); + + // then + assertThat(store().activeFor(TENANT, TARGET, NOW.plusSeconds(1))) + .containsExactlyInAnyOrder(bounce, complaint); + } + + @Test + @DisplayName("만료됐거나 아직 시작하지 않은 수신 거부는 조회되지 않는다") + void anEntryOutsideItsWindowIsNotActive() { + // given + upsert(entry(SuppressionReason.TEMPORARY_SUPPRESSION, NOW, NOW.plus(Duration.ofHours(1)))); + + // when + List before = store().activeFor(TENANT, TARGET, NOW.minusSeconds(1)); + + // then + assertThat(before).isEmpty(); + assertThat(store().activeFor(TENANT, TARGET, NOW.plus(Duration.ofHours(1)))).isEmpty(); + } + + @Test + @DisplayName("다른 테넌트의 수신 거부는 조회되지도 삭제되지도 않는다") + void anotherTenantNeitherSeesNorRemovesTheEntry() { + // given + SuppressionEntry stored = upsert(entry(SuppressionReason.HARD_BOUNCE, NOW, null)); + + // when + Optional removed = + inTransaction(() -> store().remove(OTHER_TENANT, stored.id())); + + // then + assertThat(removed).isEmpty(); + assertThat(store().activeFor(OTHER_TENANT, TARGET, NOW.plusSeconds(1))).isEmpty(); + assertThat(store().activeFor(TENANT, TARGET, NOW.plusSeconds(1))).containsExactly(stored); + } + + @Test + @DisplayName("삭제한 수신 거부는 돌려받고 더는 조회되지 않는다") + void aRemovedEntryIsReturnedAndNoLongerActive() { + // given + SuppressionEntry stored = upsert(entry(SuppressionReason.HARD_BOUNCE, NOW, null)); + + // when + Optional removed = inTransaction(() -> store().remove(TENANT, stored.id())); + + // then + assertThat(removed).contains(stored); + assertThat(store().activeFor(TENANT, TARGET, NOW.plusSeconds(1))).isEmpty(); + } + + @Test + @DisplayName("같은 대상의 첫 수신 거부가 동시에 두 번 와도 둘 다 성공하고 항목은 하나다") + void twoOverlappingFirstUpsertsBothSucceedAndLeaveOneEntry() { + // given + SuppressionEntry fromFirstWebhook = entry(SuppressionReason.HARD_BOUNCE, NOW, null); + SuppressionEntry fromSecondWebhook = + entry(SuppressionReason.HARD_BOUNCE, NOW.plusSeconds(5), null); + + // when + List results = + OverlappingWrites.run( + this::inTransaction, + () -> store().upsert(fromFirstWebhook), + () -> store().upsert(fromSecondWebhook)); + + // then + assertThat(results.get(1).id()) + .as("both calls name the one stored entry") + .isEqualTo(results.get(0).id()); + assertThat(store().activeFor(TENANT, TARGET, NOW.plusSeconds(10))) + .as("the second webhook refreshed the entry rather than adding a duplicate") + .containsExactly(results.get(1)); + } + + private SuppressionEntry upsert(SuppressionEntry entry) { + return inTransaction(() -> store().upsert(entry)); + } + + private static SuppressionEntry entry( + SuppressionReason reason, Instant effectiveAt, Instant expiresAt) { + return new SuppressionEntry( + new SuppressionId(UUID.randomUUID()), + TENANT, + SuppressionScope.CONTACT_POINT, + reason, + TARGET, + Optional.empty(), + effectiveAt, + Optional.ofNullable(expiresAt), + SuppressionSource.PROVIDER); + } +} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/ModuleRegistry.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/ModuleRegistry.java index ecea43c2..a917abb6 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/ModuleRegistry.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/ModuleRegistry.java @@ -4,7 +4,11 @@ import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; +import java.nio.file.FileVisitResult; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; @@ -182,6 +186,73 @@ public record ModuleRegistry(List modules, File source) { return modules.stream().filter(module -> module.id().equals(id)).findFirst().orElse(null); } + /** + * Build scripts under {@code gradleRoot} that no registered module owns, relative to it. + * + *

        The settings plugin includes only registered modules, so a leaf directory nobody registered + * is not compiled, not tested and not compared by any gate, while {@code ci} stays green (review + * 2026-11-01 08-05). The walk skips the root's own script, every directory with its own settings + * script (a separate build, such as build-logic or optional-platforms), build output, and the + * inside of a module's {@code src} tree, where a build script is a test fixture. + */ + public List unregisteredBuildScripts(File gradleRoot) { + Path root = canonical(gradleRoot).toPath(); + Set owned = new HashSet<>(); + for (Module module : modules) { + owned.add(canonical(module.sourceDirectory()).toPath()); + } + List unregistered = new ArrayList<>(); + try { + Files.walkFileTree( + root, + new SimpleFileVisitor<>() { + @Override + public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) { + String name = directory.getFileName().toString(); + boolean otherBuild = + !directory.equals(root) + && (Files.isRegularFile(directory.resolve("settings.gradle")) + || Files.isRegularFile(directory.resolve("settings.gradle.kts"))); + boolean moduleSources = + name.equals("src") && owned.contains(directory.getParent()); + if (otherBuild + || moduleSources + || name.equals("build") + // IDE compiler output (Eclipse/VS Code `bin/`, git-ignored as `src/**/bin/`) copies + // resource build scripts such as grpc-codegen's consumer fixtures; it is not source. + || name.equals("bin") + || name.startsWith(".")) { + return FileVisitResult.SKIP_SUBTREE; + } + if (!directory.equals(root) + && !owned.contains(directory) + && (Files.isRegularFile(directory.resolve("build.gradle")) + || Files.isRegularFile(directory.resolve("build.gradle.kts")))) { + String script = + Files.isRegularFile(directory.resolve("build.gradle")) + ? "build.gradle" + : "build.gradle.kts"; + unregistered.add( + root.relativize(directory.resolve(script)).toString().replace(File.separatorChar, '/')); + } + return FileVisitResult.CONTINUE; + } + }); + } catch (IOException exception) { + throw new UncheckedIOException("failed to walk " + root, exception); + } + unregistered.sort(null); + return List.copyOf(unregistered); + } + + private static File canonical(File file) { + try { + return file.getCanonicalFile(); + } catch (IOException exception) { + throw new UncheckedIOException("failed to canonicalize " + file, exception); + } + } + public List modulesForBuild(String buildName) { return modules.stream().filter(module -> module.buildName().equals(buildName)).toList(); } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java index 8027a8f6..3e5d1008 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java @@ -57,6 +57,13 @@ public final class ArchitecturePlugin implements Plugin { task.setDescription("Verifies Clean Architecture project dependency direction."); task.getRegistryFile().fileValue(registryFile); task.getRegistryViolations().set(registryViolations); + // The main build owns the whole Gradle root; optional-platforms is a directory + // inside it with its own settings, which the walk skips. + task.getUnregisteredBuildScripts() + .set( + optionalGrpcBuild + ? List.of() + : registry.unregisteredBuildScripts(root.getProjectDir())); }); var purity = project diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/VerifyCleanArchitectureDependenciesTask.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/VerifyCleanArchitectureDependenciesTask.java index dbe80145..5535631b 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/VerifyCleanArchitectureDependenciesTask.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/VerifyCleanArchitectureDependenciesTask.java @@ -45,6 +45,14 @@ public abstract class VerifyCleanArchitectureDependenciesTask extends DefaultTas @Input public abstract ListProperty getGovernedModules(); + /** + * Build scripts under the Gradle root that no registry entry owns. The settings plugin includes + * registered modules only, so such a leaf never reaches {@link #getDeclaredModules()} and the + * comparison below cannot see it (review 2026-11-01 08-05). + */ + @Input + public abstract ListProperty getUnregisteredBuildScripts(); + @TaskAction public void verifyDependencies() { List registryViolations = getRegistryViolations().get(); @@ -54,6 +62,15 @@ public abstract class VerifyCleanArchitectureDependenciesTask extends DefaultTas + String.join("\n ", registryViolations)); } + List unregistered = getUnregisteredBuildScripts().get(); + if (!unregistered.isEmpty()) { + throw new GradleException( + "These build scripts have no registry entry, so the build does not include them and no" + + " gate compiles or tests them. Register each in config/architecture/modules.json" + + " or delete it:\n " + + String.join("\n ", unregistered)); + } + Set declared = getDeclaredModules().get(); Set governed = new HashSet<>(getGovernedModules().get()); Set missingFromBuild = new TreeSet<>(governed); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java index a16df84c..8b36b456 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java @@ -43,6 +43,19 @@ public final class ConfigContractPlugin implements Plugin { tree.exclude("app-bootstrap/**"); tree.exclude("**/build/**"); })); + // What an operator edits or runs: the root Compose files and the Logback + // configuration. Their APP_ names must be registered and read (07-10). + task.getOperatorFiles() + .from( + root.fileTree( + root.file(".."), + tree -> { + tree.include("docker-compose*.yml"); + // The infrastructure stack: its APP_* variables belong to smoke-test + // clients and other services, not to this application. + tree.exclude("docker-compose.infra.yml"); + }), + root.file("app-bootstrap/src/main/resources/logback-spring.xml")); task.getRegistryFile().fileValue(root.file("../docs/registries/env-keys.yaml")); task.getRedisSdkMetadata() .fileValue( diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java index d62965a8..07b645ec 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java @@ -30,6 +30,12 @@ public final class EnvContractVerifier { private static final Pattern REGISTRY_FIELD = Pattern.compile("^\\s*([a-z_]+):\\s*(\\S.*)?$"); private static final Pattern APP_KEY = Pattern.compile("APP_[A-Z][A-Z0-9_]*"); + /** A variable a Compose service sets: an {@code APP_*} key of an {@code environment:} map. */ + private static final Pattern COMPOSE_ENVIRONMENT_KEY = + Pattern.compile("(?m)^\\s+(APP_[A-Z][A-Z0-9_]*):"); + /** A variable Logback reads directly: {@code }. */ + private static final Pattern LOGBACK_SOURCE = + Pattern.compile("source=\"(APP_[A-Z][A-Z0-9_]*)\""); private static final ObjectMapper JSON = JsonMapper.builder().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build(); @@ -42,6 +48,36 @@ public final class EnvContractVerifier { Collection productionSources, Collection metadataScopes, Collection enforcedPrefixes) { + return verify( + envFile, + configurationFiles, + registryFile, + productionSources, + metadataScopes, + enforcedPrefixes, + List.of()); + } + + /** + * Verifies the contract, and also every {@code APP_*} name the operator-facing files set. + * + *

        Operator files are what an operator edits or runs to supply values — the root Compose files + * that run the application and {@code logback-spring.xml}. A Compose file contributes the keys of + * its {@code environment:} maps, Logback its {@code springProperty} sources. A name there must be registered, and something must read it: + * a shipped-configuration placeholder, a production source, or a typed property. A variable set + * in a Compose file that nothing reads is a setting the operator believes is in force and is not + * ({@code APP_LOG_JSON_ENABLED} in the prod-smoke file, 07-10). + * + * @param operatorFiles the operator-facing files whose {@code APP_*} names are checked + */ + public static EnvContractResult verify( + File envFile, + Collection configurationFiles, + File registryFile, + Collection productionSources, + Collection metadataScopes, + Collection enforcedPrefixes, + Collection operatorFiles) { requireFile( envFile, "missing " @@ -158,6 +194,35 @@ public final class EnvContractVerifier { Set consumed = new TreeSet<>(applicationAppReferences); consumed.addAll(scanProductionSourceConsumers(productionSources)); + Set operatorReferences = new TreeSet<>(); + for (File operatorFile : operatorFiles) { + requireFile(operatorFile, "missing operator file " + operatorFile); + Matcher matcher = + (operatorFile.getName().endsWith(".xml") ? LOGBACK_SOURCE : COMPOSE_ENVIRONMENT_KEY) + .matcher(read(operatorFile)); + while (matcher.find()) { + operatorReferences.add(matcher.group(1)); + } + } + failUnlessEmpty( + difference(operatorReferences, registryAppKeys), + "operator files (Compose, logback-spring.xml) set APP_ keys absent from " + + "docs/registries/env-keys.yaml: "); + Set typedRows = new TreeSet<>(); + registryRows.stream() + .filter(row -> row.property().isPresent()) + .forEach(row -> typedRows.add(row.name())); + Set unreadOperatorReferences = new TreeSet<>(); + for (String name : operatorReferences) { + if (!consumed.contains(name) && !typedRows.contains(name)) { + unreadOperatorReferences.add(name); + } + } + failUnlessEmpty( + unreadOperatorReferences, + "operator files (Compose, logback-spring.xml) set APP_ keys nothing reads — no shipped " + + "configuration placeholder, production source or typed property: "); + Set unconsumed = new TreeSet<>(); for (EnvRegistryRow row : registryRows) { if (!consumed.contains(row.name()) && row.property().isEmpty() && !row.deprecatedOrphaned()) { diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java index b9466a08..ce79b83a 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java @@ -42,6 +42,10 @@ public abstract class VerifyEnvKeysTask extends DefaultTask { @PathSensitive(PathSensitivity.RELATIVE) public abstract ConfigurableFileCollection getProductionSources(); + @InputFiles + @PathSensitive(PathSensitivity.RELATIVE) + public abstract ConfigurableFileCollection getOperatorFiles(); + @TaskAction public void verifyContract() { EnvContractResult result; @@ -55,7 +59,8 @@ public abstract class VerifyEnvKeysTask extends DefaultTask { List.of( new MetadataScope( "app.redis.", getRedisSdkMetadata().get().getAsFile())), - ENFORCED_PREFIXES); + ENFORCED_PREFIXES, + getOperatorFiles().getFiles()); } catch (IllegalStateException invalidContract) { throw new GradleException(invalidContract.getMessage(), invalidContract); } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java index 6736dca9..8452995f 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java @@ -1,9 +1,16 @@ package dev.caskeleton.buildlogic.java; import io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension; +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.TreeMap; import org.gradle.api.GradleException; import org.gradle.api.Plugin; import org.gradle.api.Project; @@ -13,6 +20,7 @@ import org.gradle.api.artifacts.dsl.LockMode; import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.plugins.jvm.JvmTestSuite; import org.gradle.api.provider.ProviderFactory; +import org.gradle.api.tasks.PathSensitivity; import org.gradle.api.tasks.bundling.AbstractArchiveTask; import org.gradle.api.tasks.bundling.Jar; import org.gradle.api.tasks.compile.JavaCompile; @@ -132,8 +140,12 @@ public final class JavaConventionsPlugin implements Plugin { }); // Spring dependency-management reads Maven BOM property overrides from project extra properties. + // commons-lang3: the Boot BOM manages 3.19.0, and the SpotBugs worker (which shares the + // buildscript's commons-lang3) fails with NoClassDefFoundError on it; 3.20.0 is what it needs. + // Delete the override once the BOM manages 3.20.0 or later. (A `netty.version` override sat + // here too and was removed: it pinned the version the BOM already manages, review 2026-11-01 + // O-11c.) project.getExtensions().getExtraProperties().set("commons-lang3.version", "3.20.0"); - project.getExtensions().getExtraProperties().set("netty.version", "4.2.17.Final"); DependencyManagementExtension dependencyManagement = project.getExtensions().getByType(DependencyManagementExtension.class); dependencyManagement.imports( @@ -231,6 +243,28 @@ public final class JavaConventionsPlugin implements Plugin { }) .get(); project.getDependencies().add(agentDependencies.getName(), "org.mockito:mockito-core"); + // Every Test JVM runs in UTC, so a timestamp test does not depend on the host's zone. A system + // property rather than a JVM argument: a strict lane's own `jvmArgs` replace the argument list, + // and this used to be repeated in 28 lanes for that reason (review 2026-11-01 O-10b). + // + // The container images the lanes start come from config/testing/container-images.properties, + // each as `ca.test.image.`, with the file as an input (review 2026-11-01 08-04). + File images = containerImageCatalog(project); + Map containerImages = containerImages(images); + project.getExtensions().getExtraProperties().set("testContainerImages", containerImages); + project + .getTasks() + .withType(Test.class) + .configureEach( + test -> { + test.systemProperty("user.timezone", "UTC"); + containerImages.forEach( + (key, image) -> test.systemProperty(CONTAINER_IMAGE_PROPERTY_PREFIX + key, image)); + test.getInputs() + .file(images) + .withPathSensitivity(PathSensitivity.NONE) + .withPropertyName("containerImageCatalog"); + }); project .getTasks() .withType(Test.class) @@ -243,4 +277,32 @@ public final class JavaConventionsPlugin implements Plugin { test.getJvmArgumentProviders().add(provider); }); } + + /** The system property prefix under which every Test JVM receives the catalog's images. */ + public static final String CONTAINER_IMAGE_PROPERTY_PREFIX = "ca.test.image."; + + private static File containerImageCatalog(Project project) { + File root = project.getRootProject().getProjectDir(); + File catalog = new File(root, "config/testing/container-images.properties"); + if (!catalog.isFile()) { + // The optional-platforms build's root is a directory inside the main build. + catalog = new File(root.getParentFile(), "config/testing/container-images.properties"); + } + if (!catalog.isFile()) { + throw new GradleException("Missing test container image catalog: " + catalog); + } + return catalog; + } + + private static Map containerImages(File catalog) { + Properties properties = new Properties(); + try (var in = Files.newInputStream(catalog.toPath())) { + properties.load(in); + } catch (IOException exception) { + throw new UncheckedIOException("failed to read " + catalog, exception); + } + Map images = new TreeMap<>(); + properties.stringPropertyNames().forEach(key -> images.put(key, properties.getProperty(key))); + return Map.copyOf(images); + } } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java index 2c6cbaf8..8df5c113 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java @@ -61,6 +61,19 @@ public final class QualityConventionsPlugin implements Plugin { SpotBugsExtension spotBugs = project.getExtensions().getByType(SpotBugsExtension.class); spotBugs.getToolVersion().set(version(catalog, "spotbugs")); + // HIGH, measured (review 2026-11-01 08-07). One `qualityCheck --continue` at MEDIUM over the 53 + // analysed leaves reported 298 findings, all priority 2, against 0 at HIGH: + // 252 EI_EXPOSE_REP / EI_EXPOSE_REP2 / CT_CONSTRUCTOR_THROW — mutable-field exposure and + // throwing constructors, which records, Spring beans and fail-fast value constructors + // produce by design; + // 25 SECURITY — REDOS 11 (identifier patterns), UNSAFE_HASH_EQUALS 7 (content checksums, not + // secrets), SQL_INJECTION_* 3, PREDICTABLE_RANDOM 2 (sampling, backoff jitter), XSS 1, + // WEAK_MESSAGE_DIGEST_SHA1 1; + // 21 others — NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE 12, AT_NONATOMIC 2, RV_RETURN_VALUE 2, + // MS_EXPOSE_REP 2, BC_IMPOSSIBLE_INSTANCEOF 1, BX_UNBOXING 1, NP_NULL_ON_SOME_PATH 1. + // MEDIUM is the target once the 46 findings outside the first three patterns are each fixed in + // their owning leaf or excluded in config/spotbugs/exclude.xml with a reason, and the three + // patterns are excluded there with theirs. Until then MEDIUM would fail every pull request. spotBugs.getReportLevel().set(Confidence.HIGH); spotBugs.getExcludeFilter().set(new File(repositoryConfigDirectory, "spotbugs/exclude.xml")); // Keep local check fast; qualityCheck is the explicit bytecode-analysis lane. diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java index 2824a052..fea9b6a4 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java @@ -103,7 +103,7 @@ public final class StrictLaneStagesPlugin implements Plugin { private static List problems( Project root, TaskExecutionGraph graph, List stages, File workflowDirectory) { - List problems = new ArrayList<>(); + List problems = new ArrayList<>(foldedCommandBreaks(workflowDirectory)); List invocations = invocations(workflowDirectory); List executedStages = new ArrayList<>(); for (String stage : stages) { @@ -161,7 +161,22 @@ public final class StrictLaneStagesPlugin implements Plugin { return seen; } - private static List invocations(File workflowDirectory) { + /** A folded run block broken by a blank line runs its options as commands; see the reader. */ + private static List foldedCommandBreaks(File workflowDirectory) { + List problems = new ArrayList<>(); + for (File file : workflowFiles(workflowDirectory)) { + try { + WorkflowGradleInvocations.foldedCommandBreaks( + Files.readString(file.toPath(), StandardCharsets.UTF_8)) + .forEach(problem -> problems.add(file.getName() + " " + problem)); + } catch (IOException exception) { + throw new UncheckedIOException("failed to read " + file, exception); + } + } + return problems; + } + + private static File[] workflowFiles(File workflowDirectory) { File[] files = workflowDirectory.listFiles( file -> file.getName().endsWith(".yml") || file.getName().endsWith(".yaml")); @@ -169,9 +184,13 @@ public final class StrictLaneStagesPlugin implements Plugin { throw new GradleException( TASK_NAME + ": no workflow files in " + workflowDirectory + "; nothing could run a stage."); } - List invocations = new ArrayList<>(); Arrays.sort(files); - for (File file : files) { + return files; + } + + private static List invocations(File workflowDirectory) { + List invocations = new ArrayList<>(); + for (File file : workflowFiles(workflowDirectory)) { try { invocations.addAll( WorkflowGradleInvocations.read(Files.readString(file.toPath(), StandardCharsets.UTF_8))); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java index e24a578f..6ef01c97 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java @@ -184,11 +184,13 @@ public final class StrictTestLanePlugin implements Plugin { StrictTestLaneSpec lane, Test test) { SourceSet sourceSet = java.getSourceSets().getByName(lane.getSourceSet()); - if (lane.getCategory() != TestLaneCategory.TEST) { - // Everything that is not a hermetic unit lane starts a server, a container or both, and + if (startsARealServer(lane)) { + // INTEGRATION, SYSTEM and PERFORMANCE lanes start a server, a container or both, and // several of those at once under `org.gradle.parallel` makes the machine decide the result. // One slot for all of them, build-wide — ordering them inside a leaf was not enough, because - // the web and websocket lanes contend with each other across leaves. + // the web and websocket lanes contend with each other across leaves. An ARCHITECTURE lane + // imports classes and starts nothing, so it does not wait for that slot (review 2026-11-01 + // 08-06). test.usesService( project .getGradle() @@ -218,7 +220,15 @@ public final class StrictTestLanePlugin implements Plugin { }); } test.getFailOnNoDiscoveredTests().set(true); - test.getOutputs().upToDateWhen(ignored -> false); + // A lane whose result follows from its declared inputs may be up to date or come from the + // build cache: the result it reuses was produced by a run that passed the checks below (no test + // ran, a skip, a required test missing), with the same classes, filter and properties. A lane + // whose result depends on what Gradle cannot see runs every time (review 2026-11-01 08-02). + String rerunReason = rerunReason(lane); + if (rerunReason != null) { + test.getOutputs().upToDateWhen(ignored -> false); + test.getOutputs().doNotCacheIf(rerunReason, ignored -> true); + } if (lane.getMaxHeapSize() != null && !lane.getMaxHeapSize().isBlank()) { test.setMaxHeapSize(lane.getMaxHeapSize()); } @@ -294,6 +304,34 @@ public final class StrictTestLanePlugin implements Plugin { } } + private static boolean startsARealServer(StrictTestLaneSpec lane) { + return lane.getCategory() != TestLaneCategory.TEST + && lane.getCategory() != TestLaneCategory.ARCHITECTURE; + } + + /** + * Why this lane's earlier result may not stand for this run, or {@code null} when it may. + * + *

          + *
        • INTEGRATION, SYSTEM, PERFORMANCE: a container image pulled by tag, the network, the clock + * and the machine's load are not task inputs, so the same inputs prove nothing about the + * same result. + *
        • A main-stage lane: it compares the leaf with repository documents it does not declare as + * inputs, and it is the stage whose run is the evidence. + *
        + */ + private static String rerunReason(StrictTestLaneSpec lane) { + if (startsARealServer(lane)) { + return "a " + + lane.getCategory() + + " lane depends on images, network and time that are not task inputs"; + } + if (lane.isMainStage()) { + return "a main-stage lane reads repository documents that are not task inputs"; + } + return null; + } + private static boolean isOwnSuiteTask(Project project, StrictTestLaneSpec lane) { TestingExtension testing = project.getExtensions().findByType(TestingExtension.class); return testing != null diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java index 7e681592..61edc631 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java @@ -83,6 +83,53 @@ public final class WorkflowGradleInvocations { return List.copyOf(invocations); } + /** + * Lines of a folded ({@code >}) {@code run:} block that start with an option right after a blank + * line. YAML turns the blank line into a line break, so the option becomes a shell command of its + * own — {@code --stacktrace: command not found} — and the step fails before or after the Gradle + * command it was meant for. Twenty-two such steps were found across five workflows (review + * 2026-11-01, round 1 follow-up). + * + * @return one description per broken line, with its 1-based line number in the workflow + */ + public static List foldedCommandBreaks(String workflow) { + List lines = workflow.lines().toList(); + List problems = new ArrayList<>(); + for (int index = 0; index < lines.size(); index++) { + Matcher run = RUN_KEY.matcher(lines.get(index)); + if (!run.matches()) { + continue; + } + Matcher header = BLOCK_HEADER.matcher(run.group(2).trim()); + if (!header.matches() || !header.group(1).equals(">")) { + continue; + } + int keyIndent = run.group(1).length(); + boolean afterBlank = false; + for (int next = index + 1; + next < lines.size() + && (lines.get(next).isBlank() || indentOf(lines.get(next)) > keyIndent); + next++) { + String line = lines.get(next).trim(); + if (line.isEmpty()) { + afterBlank = true; + continue; + } + if (afterBlank && line.startsWith("-")) { + problems.add( + "line " + + (next + 1) + + ": '" + + line + + "' follows a blank line inside a folded run block, so it runs as a separate" + + " shell command instead of an argument of the command above"); + } + afterBlank = false; + } + } + return List.copyOf(problems); + } + static List runScripts(String workflow) { List lines = workflow.lines().toList(); List scripts = new ArrayList<>(); diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java index cd75959d..6a135273 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java @@ -9,6 +9,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -114,6 +115,32 @@ class ModuleRegistryTest { assertTrue(failure.getMessage().contains("nonblank string 'build'"), failure.getMessage()); } + @Test + @DisplayName("registry에 없는 디렉터리의 build 스크립트는 찾아내고, 등록된 leaf·루트·다른 빌드·build 산출물은 무시한다") + void buildScriptsOutsideTheRegistryAreReported() throws Exception { + // given + Path gradleRoot = root.resolve("src"); + Files.writeString(gradleRoot.resolve("build.gradle"), ""); + Files.writeString(gradleRoot.resolve("alpha/build.gradle"), ""); + Files.writeString(gradleRoot.resolve("beta/build.gradle"), ""); + Files.createDirectories(gradleRoot.resolve("adapter/gamma")); + Files.writeString(gradleRoot.resolve("adapter/gamma/build.gradle"), ""); + Files.createDirectories(gradleRoot.resolve("other-build")); + Files.writeString(gradleRoot.resolve("other-build/settings.gradle"), ""); + Files.writeString(gradleRoot.resolve("other-build/build.gradle"), ""); + Files.createDirectories(gradleRoot.resolve("alpha/build/tmp/fixture")); + Files.writeString(gradleRoot.resolve("alpha/build/tmp/fixture/build.gradle"), ""); + Files.createDirectories(gradleRoot.resolve("alpha/src/test/resources/fixture")); + Files.writeString(gradleRoot.resolve("alpha/src/test/resources/fixture/build.gradle"), ""); + ModuleRegistry registry = read(valid()); + + // when + List unregistered = registry.unregisteredBuildScripts(gradleRoot.toFile()); + + // then + assertEquals(List.of("adapter/gamma/build.gradle"), unregistered); + } + private File write(String json) { try { Path file = root.resolve("modules.json"); diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java index f8b39004..6936c661 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java @@ -8,6 +8,7 @@ import java.nio.file.Files; import java.nio.file.Path; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -90,6 +91,22 @@ class CleanArchitectureResolvedClasspathFunctionalTest { assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); } + @Test + @DisplayName("registry에 등록하지 않은 leaf 디렉터리에 build 스크립트가 있으면 방향 게이트가 그 경로로 실패한다") + void aLeafDirectoryMissingFromTheRegistryFailsTheGate(@TempDir Path temporaryRoot) + throws IOException { + // given + Path project = fixture(temporaryRoot, true); + Files.createDirectories(project.resolve("d")); + Files.writeString(project.resolve("d/build.gradle"), "plugins { id 'java' }\n", UTF_8); + + // when + BuildResult result = runner(project, "verifyCleanArchitectureDependencies").buildAndFail(); + + // then + assertThat(result.getOutput()).contains("d/build.gradle").contains("no registry entry"); + } + private static Path fixture(Path temporaryRoot, boolean allowTransitiveA) throws IOException { Path repository = temporaryRoot.resolve("repository"); Path project = repository.resolve("src"); diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java index 5f68b385..bc3410be 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java @@ -151,6 +151,85 @@ class EnvContractVerifierTest { assertTrue(failure.getMessage().contains("APP_REQUIRED")); } + @Test + void anOperatorFileKeyNothingReadsFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.envFile(), Files.readString(fixture.envFile()) + "APP_LOG_JSON_ENABLED=true\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: APP_LOG_JSON_ENABLED\n type: boolean\n default: true\n"); + Path compose = fixture.repositoryRoot().resolve("docker-compose.yml"); + Files.writeString(compose, "services:\n app:\n environment:\n APP_LOG_JSON_ENABLED: \"true\"\n"); + + // when + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> + EnvContractVerifier.verify( + fixture.envFile().toFile(), + List.of(fixture.applicationYaml().toFile()), + fixture.registry().toFile(), + List.of(), + List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())), + List.of("APP_REDIS_"), + List.of(compose.toFile()))); + + // then + assertTrue(failure.getMessage().contains("nothing reads")); + assertTrue(failure.getMessage().contains("APP_LOG_JSON_ENABLED")); + } + + @Test + void anOperatorFileKeyMissingFromTheRegistryFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Path compose = fixture.repositoryRoot().resolve("docker-compose.yml"); + Files.writeString(compose, "services:\n app:\n environment:\n APP_UNREGISTERED: x\n"); + + // when + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> + EnvContractVerifier.verify( + fixture.envFile().toFile(), + List.of(fixture.applicationYaml().toFile()), + fixture.registry().toFile(), + List.of(), + List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())), + List.of("APP_REDIS_"), + List.of(compose.toFile()))); + + // then + assertTrue(failure.getMessage().contains("APP_UNREGISTERED")); + } + + @Test + void anOperatorFileKeyTheConfigurationReadsPasses(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Path compose = fixture.repositoryRoot().resolve("docker-compose.yml"); + Files.writeString(compose, "services:\n app:\n environment:\n APP_REQUIRED: x\n"); + + // when + EnvContractResult result = + EnvContractVerifier.verify( + fixture.envFile().toFile(), + List.of(fixture.applicationYaml().toFile()), + fixture.registry().toFile(), + List.of(), + List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())), + List.of("APP_REDIS_"), + List.of(compose.toFile())); + + // then + assertEquals(2, result.envKeyCount()); + } + private static Fixture fixture(Path temp) throws Exception { Path repositoryRoot = temp.resolve("repository/src"); Path docsRoot = temp.resolve("repository/docs/registries"); diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/convention/PlatformModuleConventionTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/convention/PlatformModuleConventionTest.java index 5be623ae..a2c5f239 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/convention/PlatformModuleConventionTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/convention/PlatformModuleConventionTest.java @@ -17,6 +17,10 @@ class PlatformModuleConventionTest { void setUp() throws Exception { Files.createDirectories(projectDir.resolve("gradle")); writeCatalog(true); + // java-conventions refuses a build without the container image catalog (review 2026-11-01 + // 08-04); a fixture build that starts no container still has to carry one, even empty. + Files.createDirectories(projectDir.resolve("config/testing")); + Files.writeString(projectDir.resolve("config/testing/container-images.properties"), ""); Files.writeString( projectDir.resolve("settings.gradle"), """ diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java index 4d542339..c8397e41 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java @@ -160,6 +160,32 @@ class StrictLaneStagesFunctionalTest { assertThat(result.getOutput()).contains("run it with --dry-run"); } + @Test + @DisplayName("접힌 run 블록이 빈 줄 때문에 옵션을 별개 명령으로 떼어 내면 그 workflow와 줄을 보고하고 실패한다") + void failsOnAFoldedRunBlockThatABlankLineSplits() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + """); + workflow( + EXECUTING_WORKFLOW + + """ + - name: Broken + run: >- + ./gradlew + :leaf:check + + --stacktrace + """); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail(); + + // then + assertThat(result.getOutput()).contains("main.yml line 13: '--stacktrace' follows a blank line"); + } + private void leafLanes(String lanes) throws Exception { Files.writeString( gradleRoot.resolve("leaf/build.gradle"), diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java index ac1e0fd8..5a9aca60 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java @@ -1,12 +1,16 @@ package dev.caskeleton.buildlogic.strictlane; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; +import org.gradle.testkit.runner.TaskOutcome; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -498,6 +502,79 @@ class StrictTestLaneConventionTest { result.getOutput().contains("the protected credentials are not set"), result.getOutput()); } + @Test + @DisplayName("hermetic lane은 같은 입력이면 build cache에서 가져오고, 외부 상태와 문서를 보는 lane은 매번 다시 돈다") + void hermeticLanesComeFromTheBuildCacheWhileExternalAndMainStageLanesRunAgain() + throws Exception { + // given + buildFile( + junitDependencies() + + """ + tasks.register('mainCheck') + strictTestLanes { + lane('unitLane') { tag = 'unit'; description = 'Hermetic.' } + lane('rulesLane') { architecture(); tag = 'rules'; description = 'Architecture rules.' } + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + lane('documentLane') { tag = 'document-contract'; description = 'Documents.'; mainStage() } + } + """); + writeTest( + "LanesTest.java", + """ + import org.junit.jupiter.api.Tag; + import org.junit.jupiter.api.Test; + class LanesTest { + @Test @Tag("unit") void unit() {} + @Test @Tag("rules") void rules() {} + @Test @Tag("db") void database() {} + @Test @Tag("document-contract") void document() {} + } + """); + String[] lanes = {"unitLane", "rulesLane", "databaseLane", "documentLane", "--build-cache"}; + runner(lanes).build(); + runner("clean").build(); + + // when + BuildResult second = runner(lanes).build(); + + // then + assertThat( + List.of(":unitLane", ":rulesLane", ":databaseLane", ":documentLane").stream() + .map(path -> second.task(path).getOutcome()) + .toList()) + .containsExactly( + TaskOutcome.FROM_CACHE, TaskOutcome.FROM_CACHE, TaskOutcome.SUCCESS, TaskOutcome.SUCCESS); + } + + @Test + @DisplayName("서버를 띄우지 않는 TEST·ARCHITECTURE lane은 실서버 lane의 단일 슬롯을 잡지 않는다") + void onlyServerLanesTakeTheExclusiveRealServerSlot() throws Exception { + // given + buildFile( + """ + sourceSets { architecture; integration } + strictTestLanes { + lane('rulesLane') { sourceSet = 'architecture'; architecture(); description = 'Architecture rules.' } + lane('databaseLane') { sourceSet = 'integration'; integration(); description = 'Real database.' } + } + tasks.register('reportSlots') { + doLast { + ['rulesLane', 'databaseLane'].each { name -> + def lane = tasks.named(name).get() + def services = lane.requiredServices.elements*.name + logger.lifecycle(name + '=' + services.contains('exclusiveRealServerLane')) + } + } + } + """); + + // when + BuildResult result = runner("reportSlots", "--console=plain").build(); + + // then + assertThat(result.getOutput()).contains("rulesLane=false").contains("databaseLane=true"); + } + private void buildFile(String laneBlock) throws Exception { Files.writeString( projectDir.resolve("build.gradle"), diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java index 9430954f..155c53e6 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java @@ -145,4 +145,56 @@ class WorkflowGradleInvocationsTest { assertThat(invocation.tasks()).doesNotContain("*Contract*"); }); } + + @Test + @DisplayName("접힌 블록에서 빈 줄 뒤 옵션으로 시작하는 줄은 따로 떨어진 셸 명령이므로 문제로 보고한다") + void optionAfterABlankLineInAFoldedBlockIsReported() { + // given + String workflow = + """ + jobs: + gate: + steps: + - name: Lanes + run: >- + ./gradlew + :adapter:inbound:web:systemTest + + --stacktrace + """; + + // when + List problems = WorkflowGradleInvocations.foldedCommandBreaks(workflow); + + // then + assertThat(problems) + .singleElement() + .asString() + .contains("line 9") + .contains("--stacktrace"); + } + + @Test + @DisplayName("접힌 블록의 빈 줄 뒤가 새 명령이면 의도된 줄바꿈이라 문제로 보지 않는다") + void newCommandAfterABlankLineInAFoldedBlockIsNotReported() { + // given + String workflow = + """ + - run: >- + ./gradlew :ci + --stacktrace + + ./gradlew --version + - run: | + ./gradlew :ci + + --not-folded-so-not-ours + """; + + // when + List problems = WorkflowGradleInvocations.foldedCommandBreaks(workflow); + + // then + assertThat(problems).isEmpty(); + } } diff --git a/src/build.gradle b/src/build.gradle index d4a51439..964e49c6 100644 --- a/src/build.gradle +++ b/src/build.gradle @@ -70,7 +70,8 @@ tasks.register('verifyDependencyLocks') { // ci the pull-request gate: leaf checks + architectureCheck + qualityCheck // mainCheck the main-branch stage: environment contract, full-boot qualification, // sample web contract, public-path baseline, transport and messaging -// qualification lanes, and each leaf's document-contract lanes +// qualification lanes, each leaf's document-contract lanes, and the +// feature generator round trip (verifyFeatureScaffold) // integrationCheck the declared strict integration lanes (several need a container runtime) // performanceCheck the declared strict performance lanes (load, shutdown, pool and resource // bounds; real servers and containers) @@ -120,10 +121,13 @@ tasks.named('architectureCheck') { dependsOn leafPaths.collect { "${it}:architectureTestLaneCheck" } } +// app-bootstrap is left out: its `check` already runs its full-boot lane in the pull-request gate, +// and the main stage ran the same lane a second time on every main push (review 2026-11-01 08-02). +// The lane stays merge-blocking, because a composition that does not boot must not merge. tasks.register('systemTestCheck') { group = 'verification' - description = "Runs every production CI leaf's full application/system test lanes." - dependsOn leafPaths.collect { "${it}:systemTestLaneCheck" } + description = "Runs every production CI leaf's full application/system test lanes that `ci` does not already run." + dependsOn leafPaths.findAll { it != ':app-bootstrap' }.collect { "${it}:systemTestLaneCheck" } } tasks.register('qualificationCheck') { @@ -139,6 +143,17 @@ tasks.register('sampleWebContractCheck') { dependsOn ':sample-portfolio:webSystemTest' } +// The feature generator's round trip (review 2026-11-01 개선 순서 4): scripts/new-feature.sh writes +// two features into a throwaway copy of the working tree and that copy's own Gradle runs the leaf +// checks they touch plus architectureCheck. A nested build of five leaves, so the main stage, not +// the pull request. The script is the whole check; this task only gives it a stage. +tasks.register('verifyFeatureScaffold', Exec) { + group = 'verification' + description = 'Generates features with scripts/new-feature.sh in a scratch copy and runs the gates they must pass.' + workingDir = rootProject.projectDir.parentFile + commandLine 'bash', 'scripts/verify-feature-scaffold.sh' +} + // Each lane below names its tests and rejects skips; these two only aggregate them. tasks.register('conditionalTransportQualification') { group = 'verification' @@ -179,6 +194,7 @@ tasks.register('mainCheck') { dependsOn tasks.named('conditionalTransportQualification') dependsOn tasks.named('verifyMessagingContracts') dependsOn ':adapter:inbound:graphql:graphqlStableTest' + dependsOn tasks.named('verifyFeatureScaffold') } // The stages a strict lane may belong to. `verifyStrictLaneStages --dry-run` (pull-request gate) diff --git a/src/composition/durable-operation/README.md b/src/composition/durable-operation/README.md new file mode 100644 index 00000000..c6c2dc02 --- /dev/null +++ b/src/composition/durable-operation/README.md @@ -0,0 +1,26 @@ +# composition:durable-operation — durable operation 조립 + +- Module ID: `composition-durable-operation` +- Gradle path: `:composition:durable-operation` +- Package: `dev.caskeleton.composition.operation` +- 테스트: `./gradlew :composition:durable-operation:test --console=plain` + +## 제공하는 것 + +`/operations` 엔드포인트와 그 뒤의 유스케이스 셋(제출·조회·취소)을 포트로부터 조립한다. + +``` +composition:durable-operation + └─ DurableOperationAutoConfiguration servlet 웹 앱 + DurableOperationStorePort·OutboxAppendPort· + │ TransactionPort 가 모두 있을 때만 + ├─ Submit/Get/CancelDurableOperationUseCase bean 이라 @RequiresPermission 이 프록시로 검사된다 + ├─ DurableOperationSubmittedContract 제출 이벤트 계약(encoder 가 읽는다) + └─ DurableOperationController web leaf 의 HTTP 경계 +config/module-defaults/durable-operation.yml operation-submit 역할 → operation:submit, operation:cancel +``` + +- 켜지는 조건: 세 포트를 주는 모듈(지금은 persistence-jpa, outbox는 `app.outbox.enabled`)이 있어야 한다. + 없으면 아무 bean도 만들지 않는다. 그래서 기본 조합(app-bootstrap)에 한 줄로 들어 있어도 비용이 없다. +- app-bootstrap 안이 아니라 여기 있는 이유(07-08): 조립 루트가 capability 이름(조립 클래스, 권한 매핑)을 + 알면 기능을 지워도 흔적이 남는다. outbox relay·멱등성 executor를 `composition:*`로 옮긴 소유자 결정 3과 같다. +- persistence-jpa 안이 아닌 이유: driven adapter는 use case를 만들지 않는다. diff --git a/src/composition/durable-operation/build.gradle b/src/composition/durable-operation/build.gradle new file mode 100644 index 00000000..687efd0c --- /dev/null +++ b/src/composition/durable-operation/build.gradle @@ -0,0 +1,22 @@ +plugins { + id 'ca.spring-library' + id 'ca.spring-config' +} + +// Durable operations: the three use cases and their HTTP endpoints, assembled from ports when the +// selected modules provide an operation store, an outbox and a transaction port (persistence-jpa +// does). Moved out of app-bootstrap (07-08) so the composition root names no capability. +dependencies { + implementation project(':application-core') + implementation project(':adapter:inbound:web') + // The module-defaults loader that reads config/module-defaults/durable-operation.yml. + implementation project(':adapter:outbound:support') + // The UUIDv7 operation id generator (UuidV7DurableOperationIdFactory). + implementation project(':adapter:outbound:identifier') + + implementation 'org.springframework.boot:spring-boot-autoconfigure' + implementation 'org.springframework:spring-context' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.yaml:snakeyaml' +} diff --git a/src/composition/durable-operation/gradle.lockfile b/src/composition/durable-operation/gradle.lockfile new file mode 100644 index 00000000..29b62e97 --- /dev/null +++ b/src/composition/durable-operation/gradle.lockfile @@ -0,0 +1,182 @@ +# This is a Gradle generated file for dependency locking. +# Manual edits can break the build and are not advised. +# This file is expected to be part of source control. +biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath +ch.qos.logback:logback-classic:1.5.38=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml:classmate:1.7.3=runtimeClasspath,testRuntimeClasspath +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor +com.github.f4b6a3:uuid-creator:6.1.1=runtimeClasspath,testRuntimeClasspath +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs +com.github.spotbugs:spotbugs:4.10.2=spotbugs +com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor +com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs +com.google.code.gson:gson:2.13.2=spotbugs +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.38.0=testCompileClasspath +com.google.errorprone:error_prone_annotations:2.41.0=spotbugs +com.google.errorprone:error_prone_annotations:2.47.0=checkstyle +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.guava:guava:33.6.0-jre=checkstyle +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins +com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath +com.nimbusds:nimbus-jose-jwt:10.4=runtimeClasspath,testRuntimeClasspath +com.puppycrawl.tools:checkstyle:13.5.0=checkstyle +com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath +commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-collections:commons-collections:3.2.2=checkstyle +commons-io:commons-io:2.21.0=spotbugs +commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +info.picocli:picocli:4.7.7=checkstyle +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor +io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-core-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-models-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.validation:jakarta.validation-api:3.1.1=runtimeClasspath,testRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +jaxen:jaxen:2.0.6=spotbugs +net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs +org.antlr:antlr4-runtime:4.13.2=checkstyle +org.apache.bcel:bcel:6.12.0=spotbugs +org.apache.commons:commons-lang3:3.20.0=checkstyle,runtimeClasspath,spotbugs,testRuntimeClasspath +org.apache.commons:commons-text:1.15.0=spotbugs +org.apache.commons:commons-text:1.3=checkstyle +org.apache.httpcomponents:httpclient:4.5.13=checkstyle +org.apache.httpcomponents:httpcore:4.4.16=checkstyle +org.apache.logging.log4j:log4j-api:2.25.5=runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-core:2.25.5=spotbugs +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven.doxia:doxia-core:1.12.0=checkstyle +org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle +org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle +org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle +org.apache.tomcat.embed:tomcat-embed-core:11.0.24=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-el:11.0.24=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.xbean:xbean-reflect:3.7=checkstyle +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath +org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle +org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle +org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle +org.codehaus.plexus:plexus-utils:3.3.0=checkstyle +org.dom4j:dom4j:2.2.0=spotbugs +org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hibernate.validator:hibernate-validator:9.0.1.Final=runtimeClasspath,testRuntimeClasspath +org.javassist:javassist:3.28.0-GA=checkstyle +org.jboss.logging:jboss-logging:3.6.3.Final=runtimeClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath +org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath +org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath +org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit:junit-bom:6.1.0=spotbugs +org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath +org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath +org.objenesis:objenesis:3.3=testRuntimeClasspath +org.openapitools:jackson-databind-nullable:0.2.6=runtimeClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.osgi:org.osgi.annotation.bundle:2.0.0=testCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=testCompileClasspath +org.osgi:org.osgi.resource:1.0.0=testCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=testCompileClasspath +org.ow2.asm:asm-analysis:9.10.1=spotbugs +org.ow2.asm:asm-commons:9.10.1=spotbugs +org.ow2.asm:asm-tree:9.10.1=spotbugs +org.ow2.asm:asm-util:9.10.1=spotbugs +org.ow2.asm:asm:9.10.1=spotbugs +org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.reflections:reflections:0.10.2=checkstyle +org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j +org.slf4j:slf4j-simple:2.0.18=checkstyle +org.springdoc:springdoc-openapi-starter-common:3.0.0=runtimeClasspath,testRuntimeClasspath +org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.0=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor +org.springframework.boot:spring-boot-http-converter:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security-oauth2-resource-server:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-oauth2-resource-server:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-security:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-validation:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-web:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-validation:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-config:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-core:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-crypto:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-core:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-jose:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-resource-server:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-web:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.session:spring-session-core:4.0.5=runtimeClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-webmvc:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs +org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath +org.yaml:snakeyaml:2.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-core:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson:jackson-bom:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +empty= diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/operation/DurableOperationConfig.java b/src/composition/durable-operation/src/main/java/dev/caskeleton/composition/operation/DurableOperationAutoConfiguration.java similarity index 70% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/operation/DurableOperationConfig.java rename to src/composition/durable-operation/src/main/java/dev/caskeleton/composition/operation/DurableOperationAutoConfiguration.java index e1fbcc43..cab63f22 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/operation/DurableOperationConfig.java +++ b/src/composition/durable-operation/src/main/java/dev/caskeleton/composition/operation/DurableOperationAutoConfiguration.java @@ -1,8 +1,10 @@ -package dev.caskeleton.bootstrap.autoconfigure.operation; +package dev.caskeleton.composition.operation; import dev.caskeleton.adapter.inbound.web.operation.DurableOperationController; +import dev.caskeleton.adapter.outbound.identifier.UuidV7DurableOperationIdFactory; import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; import dev.caskeleton.application.operation.CancelDurableOperationUseCase; +import dev.caskeleton.application.operation.DurableOperationIdFactory; import dev.caskeleton.application.operation.DurableOperationStorePort; import dev.caskeleton.application.operation.DurableOperationSubmittedContract; import dev.caskeleton.application.operation.GetDurableOperationUseCase; @@ -12,6 +14,7 @@ import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; @@ -20,10 +23,13 @@ import org.springframework.context.annotation.Import; * Durable operations: the three use cases and their HTTP endpoints. * *

        Application composition, like the outbox relay: it builds use cases from ports, which a driven - * adapter must not do. It names no module type, only ports, and turns itself on from what the - * selected modules provide — an operation store and an outbox to announce submissions through, both - * of which the JPA module contributes (the outbox with {@code app.outbox.enabled}). Removing that - * module's build line removes the endpoints with it. + * adapter must not do. Its own module since 07-08 — it used to sit in the composition root, which + * then knew a capability by name and held its permission mapping; the sample could not reuse it + * either. The {@code operation-submit} role mapping ships beside it in {@code + * config/module-defaults/durable-operation.yml}. It names no module type, only ports, and turns + * itself on from what the selected modules provide — an operation store and an outbox to announce + * submissions through, both of which the JPA module contributes (the outbox with {@code + * app.outbox.enabled}). Removing that module's build line removes the endpoints with it. * *

        The use cases are beans rather than objects built inside the controller so that the method * security advisor proxies them: {@code @RequiresPermission} on submit and cancel is enforced by @@ -39,7 +45,7 @@ import org.springframework.context.annotation.Import; @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnBean({DurableOperationStorePort.class, OutboxAppendPort.class, TransactionPort.class}) @Import(DurableOperationController.class) -public class DurableOperationConfig { +public class DurableOperationAutoConfiguration { /** The {@code durable-operation.submitted} contract, so the encoder can validate the event. */ @Bean @@ -47,6 +53,17 @@ public class DurableOperationConfig { return new DurableOperationSubmittedContract(); } + /** + * Mints operation ids as UUIDv7. The id is also the submission event's id, and the messaging + * platform accepts only a UUIDv7 message id; the controller's former {@code UUID.randomUUID()} + * (v4) made every submission event a DEAD outbox row. + */ + @Bean + @ConditionalOnMissingBean + public DurableOperationIdFactory durableOperationIdFactory() { + return new UuidV7DurableOperationIdFactory(); + } + /** Accepts work: the operation row and its outbox event in one transaction. */ @Bean public SubmitDurableOperationUseCase submitDurableOperationUseCase( diff --git a/src/composition/durable-operation/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/composition/durable-operation/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..a7204f48 --- /dev/null +++ b/src/composition/durable-operation/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.caskeleton.composition.operation.DurableOperationAutoConfiguration diff --git a/src/composition/durable-operation/src/main/resources/config/module-defaults/durable-operation.yml b/src/composition/durable-operation/src/main/resources/config/module-defaults/durable-operation.yml new file mode 100644 index 00000000..2c3a8e6b --- /dev/null +++ b/src/composition/durable-operation/src/main/resources/config/module-defaults/durable-operation.yml @@ -0,0 +1,10 @@ +# Durable operations (/operations). composition:durable-operation 모듈이 싣고 support 의 +# ModuleDefaultsEnvironmentPostProcessor 가 읽는다. 모듈 한 줄을 빼면 이 설정도 함께 사라진다(07-08). +# 우선순위가 가장 낮다: application.yml, application-{profile}.yml, 환경 변수가 이긴다. +app: + authz: + role-permissions: + # One role for both: a caller that may start an operation may cancel its own, and reading one + # needs no permission beyond being the one who submitted it. Map entries from every source + # merge, so a deployment's own role-permissions add roles beside this one. + operation-submit: operation:submit,operation:cancel diff --git a/src/composition/durable-operation/src/test/java/dev/caskeleton/composition/operation/DurableOperationModuleTest.java b/src/composition/durable-operation/src/test/java/dev/caskeleton/composition/operation/DurableOperationModuleTest.java new file mode 100644 index 00000000..dea72c9c --- /dev/null +++ b/src/composition/durable-operation/src/test/java/dev/caskeleton/composition/operation/DurableOperationModuleTest.java @@ -0,0 +1,58 @@ +package dev.caskeleton.composition.operation; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.context.annotation.ImportCandidates; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.ClassPathResource; + +class DurableOperationModuleTest { + + @Test + @DisplayName("모듈이 classpath에 있으면 Boot가 durable operation 조립을 자동 설정으로 찾는다") + void bootDiscoversTheCompositionFromThisModule() { + // when + List candidates = + ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader()).getCandidates(); + + // then + assertThat(candidates).contains(DurableOperationAutoConfiguration.class.getName()); + } + + @Test + @DisplayName("operation store·outbox·트랜잭션 포트가 없으면 유스케이스도 엔드포인트도 만들지 않는다") + void withoutItsPortsTheModuleBuildsNothing() { + // when + new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(DurableOperationAutoConfiguration.class)) + .run( + context -> { + // then + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(DurableOperationAutoConfiguration.class); + }); + } + + @Test + @DisplayName("operation-submit 역할의 권한 매핑은 이 모듈의 기본 설정에 있다") + void theRolePermissionMappingShipsWithTheModule() throws Exception { + // given + ClassPathResource defaults = + new ClassPathResource("config/module-defaults/durable-operation.yml"); + + // when + List> loaded = new YamlPropertySourceLoader().load("defaults", defaults); + + // then + assertThat(loaded).hasSize(1); + assertThat(loaded.getFirst().getProperty("app.authz.role-permissions.operation-submit")) + .hasToString("operation:submit,operation:cancel"); + } +} diff --git a/src/composition/fileserver-platform/build.gradle b/src/composition/fileserver-platform/build.gradle index fa5c911f..4a94d6f1 100644 --- a/src/composition/fileserver-platform/build.gradle +++ b/src/composition/fileserver-platform/build.gradle @@ -5,9 +5,11 @@ plugins { // The Fileserver capability's cross-adapter assembly. // -// It exists because one capability spans four leaves that must not see each other: the HTTP surface -// in `adapter:inbound:web`, the storage and platform policy in `adapter:outbound:fileserver`, the -// quota/recovery tables in `adapter:outbound:persistence-jpa`, and identifier generation. An +// It exists because one capability spans leaves that must not see each other: the HTTP surface in +// `adapter:inbound:web-fileserver`/`web`, the storage and platform policy in +// `adapter:outbound:fileserver`, and the metadata tables in `persistence-fileserver` on the +// `persistence-jpa` platform. (It used to list identifier generation too; nothing here uses +// `adapter:outbound:identifier`, and the registry edge was removed — review 05-21.) An // outbound adapter reaching an inbound one is the direction the architecture exists to forbid, so // something has to hold the assembly — and until now that something was the composition root, which // is why every application shipped Fileserver whether or not it wanted it. diff --git a/src/composition/fileserver-platform/gradle.lockfile b/src/composition/fileserver-platform/gradle.lockfile index a7482a79..7fc899e1 100644 --- a/src/composition/fileserver-platform/gradle.lockfile +++ b/src/composition/fileserver-platform/gradle.lockfile @@ -35,7 +35,6 @@ com.google.guava:guava:33.6.0-jre=checkstyle com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor -com.h2database:h2:2.4.240=runtimeClasspath,testRuntimeClasspath com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath com.nimbusds:nimbus-jose-jwt:10.4=runtimeClasspath,testRuntimeClasspath diff --git a/src/composition/fileserver-platform/src/main/resources/config/module-defaults/fileserver.yml b/src/composition/fileserver-platform/src/main/resources/config/module-defaults/fileserver.yml index f8c5e857..9b13d71c 100644 --- a/src/composition/fileserver-platform/src/main/resources/config/module-defaults/fileserver.yml +++ b/src/composition/fileserver-platform/src/main/resources/config/module-defaults/fileserver.yml @@ -12,6 +12,19 @@ spring: max-file-size: ${APP_FILESERVER_PLATFORM_UPLOAD_MAX_FILE_SIZE:100MB} max-request-size: ${APP_FILESERVER_PLATFORM_UPLOAD_MAX_REQUEST_SIZE:110MB} app: + # Fileserver permissions (/v1/files, /v1/uploads, /internal/fileserver). Keyed by the fileserver's + # own default tier roles (app.fileserver-platform.security.*-roles), so one role grants both halves + # of a fileserver write: the permission here, checked on the use case, and the tier + # FileAccessPolicyPort checks inside it along with ownership. The brackets keep the underscores, + # which unbracketed map keys lose in binding. A deployment that renames those roles maps its own + # names too. The tiers do not inherit, and neither do these: a writer that also reads holds both + # roles. Here rather than in app-bootstrap's security.yml (07-08): the mapping goes when this + # module's line is removed; entries from every source merge. + authz: + role-permissions: + "[ROLE_FILE_READ]": file:read + "[ROLE_FILE_WRITE]": file:upload,file:delete,file:copy,file:move + "[ROLE_FILE_ADMIN]": file:admin # HTTP Fileserver platform: upload/download/lifecycle routes over HTTP. # # While enabled=false none of the detail below is bound: FileserverPlatformAutoConfiguration diff --git a/src/composition/idempotency/gradle.lockfile b/src/composition/idempotency/gradle.lockfile index 3669792f..cf315ab8 100644 --- a/src/composition/idempotency/gradle.lockfile +++ b/src/composition/idempotency/gradle.lockfile @@ -33,7 +33,6 @@ com.google.guava:guava:33.6.0-jre=checkstyle com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor -com.h2database:h2:2.4.240=testRuntimeClasspath com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle diff --git a/src/composition/notification-platform/gradle.lockfile b/src/composition/notification-platform/gradle.lockfile index a8a1638d..af577a70 100644 --- a/src/composition/notification-platform/gradle.lockfile +++ b/src/composition/notification-platform/gradle.lockfile @@ -37,7 +37,6 @@ com.google.guava:guava:33.6.0-jre=checkstyle com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor -com.h2database:h2:2.4.240=runtimeClasspath,testRuntimeClasspath com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath com.networknt:json-schema-validator:3.0.2=runtimeClasspath,testRuntimeClasspath 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 e1c6534b..a628f994 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 @@ -21,6 +21,16 @@ info: enabled: ${app.notification.platform.enabled:true} app: + # The notification platform's own two permissions, granted to two roles rather than one. + # Publishing a template changes what every future submission renders, so a service that may send + # notifications is not thereby a service that may rewrite them; a deployment that wants both + # grants both roles. Here rather than in app-bootstrap's security.yml (07-08): the mapping goes + # when this module's line is removed. Map entries from every source merge, so a deployment's own + # app.authz.role-permissions adds roles beside these and can override either key. + authz: + role-permissions: + notification-submit: notification:submit + notification-template-publish: notification-template:publish notification: platform: # The capability switch. False binds nothing at all. diff --git a/src/composition/outbox-relay/README.md b/src/composition/outbox-relay/README.md index 1c76f915..dc861755 100644 --- a/src/composition/outbox-relay/README.md +++ b/src/composition/outbox-relay/README.md @@ -16,8 +16,11 @@ composition:outbox-relay ├─ OutboxSettings app.outbox.* strict 바인딩(오타는 기동 실패) ├─ OutboxRelayScheduler relay-enabled=true + OutboxMessagePublishPort 가 있을 때만, │ PublishPendingOutboxEventsUseCase 를 fixed-delay 로 구동, - │ 종료 때 platform보다 먼저 멈춤(SmartLifecycle) - ├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag / published.total + │ 발행이 이어지는 동안 한 tick 안에서 바로 다시 claim(최대 50회차), + │ 종료 때 platform보다 먼저 멈추고 남은 claim을 놓음(SmartLifecycle) + ├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag(relay와 무관하게 + │ poll 주기마다 갱신) / published.total(relay 회차 결과) + ├─ OutboxRelayOffWarning 발행 포트가 있는데 relay가 꺼져 있으면 기동 시 WARN 한 줄 └─ OutboxLeaderElectionToken SKIP LOCKED 가 리더 선출이라는 표시(로직 없음) ``` @@ -68,11 +71,9 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a - **이 모듈은 failure reporter를 구현하지 않고 주입만 한다.** messaging bridge의 `MessagingConfig`가 정확히 하나의 `OutboxRelayFailureReportPort` 구현을 만들고, `OutboxRelayAutoConfiguration`은 이를 relay 생성자에 전달한다. -- **릴레이 use case 를 독립 컨텍스트 빈으로 등록하지 않는다.** 만약 빈으로 올리면 `adapter-web`의 - `MethodSecurityConfig` 메서드 보안 pointcut(`@RequiresPermission`)이 이 타입을 CGLIB 프록시로 - 감싼다. 그런데 use case 가 `final` 클래스라 프록시 생성 자체가 실패하고, 설령 된다 해도 스케줄러 - 스레드에는 `Authentication`이 없어 매 릴레이 틱이 fail-closed 로 거부된다. 그래서 빈으로 올리지 - 않고, `outbox:relay` 권한 확인은 스케줄러 컨텍스트에서 관례로 둔다. +- **릴레이 use case 를 독립 컨텍스트 빈으로 등록하지 않는다.** relay는 스케줄러만 부르는 + `@SystemInvoked` 유스케이스라 권한 선언이 없다. 빈으로 올리면 전송 계층이 권한 검사 없이 닿을 + 수 있다. 스케줄러 스레드에는 `Authentication`이 없으므로 권한 게이트를 달아도 매 틱 거부될 뿐이다. - **`outboxRelayScheduler` 빈은 `app.outbox.relay-enabled=true`일 때만 만든다(기본 false).** 키가 없으면 꺼진 것으로 본다. 모듈 기본값(`persistence-jpa.yml`의 `${APP_OUTBOX_RELAY_ENABLED:false}`), `@ConditionalOnProperty`, `OutboxSettings`의 null 기본값이 @@ -119,7 +120,7 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a - **합성 루트가 직접 등록하고 컴포넌트 스캔하지 않는다.** 이 스케줄러가 구동하는 릴레이 use case 가 (위 OutboxRelayAutoConfiguration 사유로) 일부러 빈이 아니기 때문에, 그 use case 를 조립하는 `OutboxRelayAutoConfiguration`가 스케줄러 등록까지 같이 소유한다. -- **릴레이 사이클에서 발생하는 예상치 못한 예외를 잡아 ERROR 로 로깅만 하고 삼킨다.** 스케줄러 +- **릴레이 사이클에서 발생하는 예상치 못한 예외를 잡아 ERROR 로 로깅만 하고 삼킨다(그 tick의 남은 회차도 건너뛴다).** 스케줄러 스레드가 죽으면 릴레이가 조용히 멈추므로, 다음 틱을 위해 스레드를 살려둔다. 단, 개별 발행 실패 (FAILED/DEAD 전이)는 relay가 persisted transition 성공 뒤 typed reporter로 canonical ERROR를 요청하고 결과에 반영하므로 이 catch 블록까지 오지 않는다 — 여기서 삼키는 것은 어디까지나 @@ -127,20 +128,39 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a - **스케줄링은 `OutboxRelayAutoConfiguration`가 직접 켜고(`@EnableScheduling`) fixed-delay 를 쓴다.** 예전에는 JDBC idempotency 설정만 스케줄링을 켰기 때문에 다른 provider 를 고르면 릴레이가 조립만 되고 돌지 않았다. fixed-delay 는 릴레이 실행 시간과 무관하게 사이클이 겹치지 않도록(non-overlapping) 보장한다. -- **종료 때는 platform보다 먼저 멈추고 진행 중 회차를 끝낸다(SmartLifecycle, phase - `Integer.MAX_VALUE`).** relay 회차는 messaging platform을 거쳐 발행한다. platform은 자기 종료 - phase(`MessagingShutdownLifecycle`, `Integer.MAX_VALUE - 1024`)에서 발행 admission을 닫고, 그 뒤 +- **종료 때는 platform보다 먼저 멈추고, 진행 중 발행 하나만 끝낸 뒤 남은 claim을 놓는다(SmartLifecycle, + phase `Integer.MAX_VALUE`).** relay 회차는 messaging platform을 거쳐 발행한다. platform은 자기 종료 + phase(`MessagingShutdownLifecycle.PHASE` = `Integer.MAX_VALUE - 1024`)에서 발행 admission을 닫고, 그 뒤 발행은 `SHUTTING_DOWN`으로 거부된다. `@Scheduled`만으로는 이 순서에 들어가지 못한다(Spring은 `ContextClosedEvent`에서 다음 tick만 취소하고 실행 중 회차는 그대로 둔다). 그래서 스케줄러가 - SmartLifecycle로 platform 위 phase(platform 자체 relay `MessagingOutboxRelayLifecycle`와 같은 값)에 - 서고, `stop`에서 새 회차를 막고 실행 중 회차가 결과를 기록할 때까지 종료를 붙잡는다. 기다리는 한도는 - Spring의 `spring.lifecycle.timeout-per-shutdown-phase`다. 한도를 넘긴 회차의 남은 row는 거부되지만 - 재시도 대상(FAILED)이고, 프로세스가 강제 종료되면 IN_FLIGHT row는 lease 만료(`in-flight-timeout`) - 뒤 다시 claim된다. 이 leaf는 messaging 타입을 이름으로 부를 수 없어 phase를 값으로 맞췄고, - `OutboxRelayShutdownOrderTest`가 같은 phase의 대역으로 순서를 고정한다. - - 버린 대안: scheduler executor phase 올리기(전역 설정이라 다른 `@Scheduled` 작업까지 바뀐다), - relay 루프를 전용 스레드로 직접 소유하기(`@Scheduled`·fixed-delay 정책과 `@EnableScheduling` - 결정까지 다시 열어야 해서 이번 범위보다 크다). + SmartLifecycle로 platform 위 phase에 선다. `stop`은 새 회차를 막고 실행 중 회차에 멈춤을 알린다 + (`PublishPendingOutboxEventsCommand.stopRequested`). 회차는 지금 하는 발행 하나를 끝내고, claim했지만 + 손대지 않은 row를 `OutboxStorePort.releaseLease`로 놓는다: PENDING, 곧바로 claim 가능, 시도 횟수에서 + 그 claim을 뺀다. 결과는 `RELEASED`로 센다. 그래서 종료 대기는 발행 하나(최대 약 10초)로 묶이고 + `spring.lifecycle.timeout-per-shutdown-phase`(기본 30초) 안에 끝난다. 놓은 row는 다른 인스턴스가 다음 + poll에서, 아니면 재시작한 이 인스턴스가 가져간다. 프로세스가 강제 종료되면 IN_FLIGHT row는 lease + 만료(`in-flight-timeout`) 뒤 다시 claim된다. `OutboxRelayShutdownOrderTest`가 platform 상수 + (`MessagingShutdownLifecycle.PHASE`, test compile-only 참조)로 순서를, 남은 claim 해제를 고정한다. + - 고른 방법: 멈춤 요청 즉시 남은 claim 해제. 버린 대안: 종료 한도까지 계속 발행하다 한도 직전에 + 해제 — 한도 값과 발행 하나의 최악 시간을 이 leaf가 알아야 하고, 그 추정이 틀리면 admission이 닫힌 + 뒤 발행해 retry 지연(30초 이상)과 FAILED 경고를 남긴다. scheduler executor phase 올리기(전역 설정이라 + 다른 `@Scheduled` 작업까지 바뀐다). +- **한 tick이 claim 한 번이 아니다(06-04).** claim gate는 aggregate마다 가장 앞 row 하나만 내보낸다. + 예전에는 tick당 claim 한 번이라 한 aggregate가 poll 주기(기본 5초)마다 한 건씩만 나갔다(이벤트 100건 ≈ + 8분). 지금은 회차가 무언가를 발행하면 같은 tick 안에서 바로 다시 claim하고, 아무것도 발행하지 못하거나 + claim이 비면 tick을 끝낸다. 한 tick의 상한은 `MAX_CYCLES_PER_TICK` = 50회차다. + - 처리량 상한(계산, 실측 아님): 한 aggregate는 poll 주기가 아니라 발행 왕복 시간에 묶인다(정상 + broker에서 회차당 claim·완료 DB 왕복 + Kafka ack). 인스턴스 하나는 tick당 최대 50 × batch 20 = + 1,000행을 보내고 다음 tick까지 5초 쉰다. 넘는 처리량이 필요하면 batch-size(NN-12의 lease 관계 확인)나 + 인스턴스 수로 늘린다. + - 버린 대안: poll 주기만 줄이기 — 빈 tick마다 claim·지표 질의가 는다. +- **지표 게이지는 relay와 따로 갱신한다(06-05).** `outbox.pending.size`·`outbox.publisher.lag`는 + `OutboxMetrics.refreshGauges`가 poll 주기마다 갱신한다(`@Scheduled`, relay가 꺼져 있어도, 회차가 매번 + 예외로 끝나도). 예전에는 relay 회차 안에서만 갱신되어, relay가 꺼진 배포(기본값)나 매 회차 실패하는 + 장애에서 게이지가 멈췄고 `outbox_publisher_lag` 경보가 울리지 않았다. 카운터 + `outbox.publisher.published.total`은 회차 결과로 relay가 기록한다. 발행 포트가 있는데 relay가 꺼져 + 있으면 `OutboxRelayOffWarning`이 기동 시 WARN 한 줄을 남긴다(별도 worker 배포가 relay를 돌리는 구성도 + 있으므로 기동 실패로 만들지 않았다). ### OutboxSettings - **튜닝 값(poll 주기·batch·timeout·보존)은 코드 리터럴 기본값을 쓰고 env placeholder 를 두지 않는다.** 신규 env key 를 diff --git a/src/composition/outbox-relay/build.gradle b/src/composition/outbox-relay/build.gradle index 9cc10118..0a700d77 100644 --- a/src/composition/outbox-relay/build.gradle +++ b/src/composition/outbox-relay/build.gradle @@ -31,6 +31,12 @@ dependencies { testImplementation 'org.springframework.boot:spring-boot-starter-test' // The shutdown-order test runs the real relay over the port owner's shared fake store. testImplementation testFixtures(project(':application-core')) + // The shutdown-order test holds the relay above the platform's admission phase by the platform's + // own constant (MessagingShutdownLifecycle.PHASE), not a copy of its value. Compile-only and + // not transitive: a compile-time constant is inlined, so the platform is not on the test runtime. + testCompileOnly(project(':messaging:messaging-spring-boot-starter')) { + transitive = false + } testImplementation 'org.mockito:mockito-core' testImplementation 'ch.qos.logback:logback-classic' testRuntimeOnly 'org.yaml:snakeyaml' diff --git a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java index c81cc154..315ba7a0 100644 --- a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java @@ -8,15 +8,25 @@ import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.MultiGauge; import io.micrometer.core.instrument.Tags; +import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.beans.factory.ObjectProvider; +import org.springframework.scheduling.annotation.Scheduled; /** - * Outbox relay metric collector. No-op when no {@link MeterRegistry} is present (resolved via - * {@link ObjectProvider}). See README for the design rationale. + * Outbox metric collector. No-op when no {@link MeterRegistry} is present (resolved via {@link + * ObjectProvider}). See README for the design rationale. + * + *

        The gauges ({@code outbox.pending.size}, {@code outbox.publisher.lag}) refresh on their own + * schedule, not from the relay. They are how an operator sees rows piling up, and the two moments + * rows pile up are exactly the ones a relay-driven refresh missed: the relay is off — it is by + * default, and a deployment that forgot {@code APP_OUTBOX_RELAY_ENABLED} looked idle — or every + * cycle throws, which skipped the refresh and froze the gauges at their last value. The counter + * ({@code outbox.publisher.published.total}) is still recorded by the relay, from each cycle's + * outcomes. */ public final class OutboxMetrics { @@ -25,12 +35,15 @@ public final class OutboxMetrics { private static final String LAG_GAUGE = "outbox.publisher.lag"; private final OutboxStorePort store; + private final Clock clock; private final MeterRegistry registry; // null when no Actuator on classpath private final MultiGauge pendingSizeGauge; private final MultiGauge publisherLagGauge; - public OutboxMetrics(OutboxStorePort store, ObjectProvider meterRegistryProvider) { + public OutboxMetrics( + OutboxStorePort store, ObjectProvider meterRegistryProvider, Clock clock) { this.store = store; + this.clock = clock; this.registry = meterRegistryProvider.getIfAvailable(); if (this.registry != null) { @@ -70,6 +83,16 @@ public final class OutboxMetrics { } } + /** + * Refreshes the gauges every poll interval, whether or not the relay runs. Store failures are + * contained per gauge (a WARN through {@link RuntimeWarnings}), so a database outage leaves the + * scheduler thread alive for the next refresh. + */ + @Scheduled(fixedDelayString = "${app.outbox.poll-interval:PT5S}") + public void refreshGauges() { + refresh(clock.instant()); + } + /** * Uses {@code overwrite=true} so stale time-series tags from removed event types are replaced * rather than left dangling. diff --git a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java index 6242b001..1571a67b 100644 --- a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java @@ -84,7 +84,7 @@ public class OutboxRelayAutoConfiguration { properties.batchSize(), properties.inFlightTimeout(), UUID.randomUUID().toString()); - return new OutboxRelayScheduler(relayUseCase, metrics, clock); + return new OutboxRelayScheduler(relayUseCase, metrics); } /** Uses a {@code java.base} RNG so the relay also starts on the slim Temurin JRE image. */ @@ -99,10 +99,30 @@ public class OutboxRelayAutoConfiguration { return new OutboxLeaderElectionToken(); } - /** Outbox metrics collector; no-op when {@link MeterRegistry} is absent. */ + /** + * Outbox metrics collector; no-op when {@link MeterRegistry} is absent. Present whenever the + * store is, relay or not: its gauges refresh on their own schedule (see {@link OutboxMetrics}). + */ @Bean public OutboxMetrics outboxMetrics( - OutboxStorePort store, ObjectProvider meterRegistryProvider) { - return new OutboxMetrics(store, meterRegistryProvider); + OutboxStorePort store, + ObjectProvider meterRegistryProvider, + ObjectProvider clock) { + return new OutboxMetrics(store, meterRegistryProvider, clock.getIfAvailable(Clock::systemUTC)); + } + + /** + * Says at startup that rows will be appended and nothing will send them: something can publish, + * but the relay is off. The default is off, so this is the deployment that selected messaging and + * forgot {@code APP_OUTBOX_RELAY_ENABLED}. + */ + @Bean + @ConditionalOnProperty( + name = "app.outbox.relay-enabled", + havingValue = "false", + matchIfMissing = true) + @ConditionalOnBean(OutboxMessagePublishPort.class) + public OutboxRelayOffWarning outboxRelayOffWarning() { + return new OutboxRelayOffWarning(); } } diff --git a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayOffWarning.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayOffWarning.java new file mode 100644 index 00000000..68e1f9a9 --- /dev/null +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayOffWarning.java @@ -0,0 +1,32 @@ +package dev.caskeleton.composition.outbox; + +import static net.logstash.logback.argument.StructuredArguments.kv; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.SmartInitializingSingleton; + +/** + * Logs one WARN at startup when the outbox store and a publish port exist but the relay is off: + * every appended event stays PENDING and nothing sends it. Registered by {@link + * OutboxRelayAutoConfiguration} only in that combination. + * + *

        A warning rather than a startup failure: an instance that appends but does not relay is a + * legitimate split (a separate worker deployment runs the relay). It is not legitimate by accident, + * and the gauge {@code outbox.publisher.lag} is the alert that catches it in production; this line + * is the one an operator reads at deploy time. + */ +public final class OutboxRelayOffWarning implements SmartInitializingSingleton { + + private static final Logger log = LoggerFactory.getLogger(OutboxRelayOffWarning.class); + + @Override + public void afterSingletonsInstantiated() { + log.warn( + "outbox relay is off although a publish port exists — appended events stay PENDING until" + + " a relay runs (set APP_OUTBOX_RELAY_ENABLED=true here or in a worker deployment)", + kv("capability", "outbox"), + kv("operation", "relay"), + kv("relay.enabled", false)); + } +} diff --git a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayScheduler.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayScheduler.java index f98b1c06..3e63351d 100644 --- a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayScheduler.java +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayScheduler.java @@ -5,22 +5,30 @@ import static net.logstash.logback.argument.StructuredArguments.kv; import dev.caskeleton.application.outbox.OutboxRelayResult; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase; -import java.time.Clock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.SmartLifecycle; import org.springframework.scheduling.annotation.Scheduled; /** - * Thin scheduler that drives the outbox relay use case on a fixed-delay polling loop, and stops - * ahead of the messaging platform on shutdown. Registered by {@link OutboxRelayAutoConfiguration}. - * See README for the design rationale. + * Drives the outbox relay use case on a fixed-delay polling loop, and stops ahead of the messaging + * platform on shutdown. Registered by {@link OutboxRelayAutoConfiguration}. See README for the + * design rationale. * *

        A cycle publishes through the platform. The platform closes publish admission when its own * shutdown phase runs ({@code MessagingShutdownLifecycle}, phase {@code Integer.MAX_VALUE - 1024}), * and every publish after that is refused. So this scheduler is a {@link SmartLifecycle} in a - * higher phase: on stop it refuses new cycles and holds the shutdown until the running cycle has - * written its outcomes, and only then lets the lower phases close admission and the transports. + * higher phase: on stop it refuses new cycles, tells the running cycle to stop — it finishes the + * publish it is in and releases the claims it did not reach — and only then lets the lower phases + * close admission and the transports. + * + *

        One tick is not one claim. The claim gate releases one row per aggregate at a time (the head), + * so a tick that claimed once moved an aggregate forward by one event per poll interval: an + * aggregate with a hundred queued events took over eight minutes to drain at the default {@code + * PT5S}. While a cycle publishes something — and so may have made the next row of an aggregate + * claimable — the tick claims again at once, up to {@link #MAX_CYCLES_PER_TICK} cycles. A cycle + * that claimed nothing, or published nothing, ends the tick: the rows left are waiting for their + * retry time, and polling for them again now would only repeat the claim query. */ public class OutboxRelayScheduler implements SmartLifecycle { @@ -31,26 +39,37 @@ public class OutboxRelayScheduler implements SmartLifecycle { */ static final int PHASE = Integer.MAX_VALUE; + /** + * How many cycles one tick may run back to back. A bound rather than "until empty" so a steady + * stream of events still returns the thread to the scheduler, and the tick's duration stays + * bounded by roughly this many batches. + */ + static final int MAX_CYCLES_PER_TICK = 50; + private static final Logger log = LoggerFactory.getLogger(OutboxRelayScheduler.class); private final PublishPendingOutboxEventsUseCase relayUseCase; private final OutboxMetrics metrics; - private final Clock clock; private final Object monitor = new Object(); private boolean running; private boolean cycleInProgress; private Runnable stopCallback; + /** Read by the running cycle before each row: the stop request reaches it without the monitor. */ + private volatile boolean stopRequested; + + private final PublishPendingOutboxEventsCommand command = + new PublishPendingOutboxEventsCommand(() -> stopRequested); + public OutboxRelayScheduler( - PublishPendingOutboxEventsUseCase relayUseCase, OutboxMetrics metrics, Clock clock) { + PublishPendingOutboxEventsUseCase relayUseCase, OutboxMetrics metrics) { this.relayUseCase = relayUseCase; this.metrics = metrics; - this.clock = clock; } /** - * Runs one relay cycle unless the scheduler is stopped. Unexpected exceptions are caught (not + * Runs relay cycles unless the scheduler is stopped. Unexpected exceptions are caught (not * propagated) so the scheduler thread stays alive for the next tick. */ @Scheduled(fixedDelayString = "${app.outbox.poll-interval:PT5S}") @@ -62,7 +81,7 @@ public class OutboxRelayScheduler implements SmartLifecycle { cycleInProgress = true; } try { - runCycle(); + runTick(); } finally { Runnable pendingStop; synchronized (monitor) { @@ -76,19 +95,21 @@ public class OutboxRelayScheduler implements SmartLifecycle { } } - private void runCycle() { + private void runTick() { try { - OutboxRelayResult result = relayUseCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); - - if (result.claimedCount() > 0) { - log.debug( - "outbox relay cycle: claimed={} outcomes={}", - result.claimedCount(), - result.outcomes().size()); - } - - metrics.recordRelayResult(result); - metrics.refresh(clock.instant()); + int cycles = 0; + OutboxRelayResult result; + do { + result = relayUseCase.handle(command); + cycles++; + if (result.claimedCount() > 0) { + log.debug( + "outbox relay cycle: claimed={} outcomes={}", + result.claimedCount(), + result.outcomes().size()); + } + metrics.recordRelayResult(result); + } while (!stopRequested && result.publishedAny() && cycles < MAX_CYCLES_PER_TICK); } catch (Exception ex) { log.error( @@ -104,6 +125,7 @@ public class OutboxRelayScheduler implements SmartLifecycle { @Override public void start() { synchronized (monitor) { + stopRequested = false; running = true; } } @@ -112,18 +134,22 @@ public class OutboxRelayScheduler implements SmartLifecycle { @Override public void stop() { synchronized (monitor) { + stopRequested = true; running = false; } } /** - * Refuses new cycles and reports stopped once the running cycle, if any, has finished. Spring - * waits for the callback up to {@code spring.lifecycle.timeout-per-shutdown-phase}; a cycle still - * running then meets a closed admission gate and its rows are retried, not lost. + * Refuses new cycles, asks the running cycle to stop, and reports stopped once it has. The cycle + * finishes the publish it is in — at most one publish deadline — and releases its other claims, + * so the wait stays well inside {@code spring.lifecycle.timeout-per-shutdown-phase} (30s by + * default) however large the batch. Were the wait to run out anyway, the publish still running + * meets a closed admission gate and is retried, not lost. */ @Override public void stop(Runnable callback) { synchronized (monitor) { + stopRequested = true; running = false; if (cycleInProgress) { stopCallback = callback; diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxMetricsTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxMetricsTest.java new file mode 100644 index 00000000..49109dce --- /dev/null +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxMetricsTest.java @@ -0,0 +1,165 @@ +package dev.caskeleton.composition.outbox; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.application.outbox.OutboxStorePort; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.search.Search; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; + +/** + * The outbox gauges are how an operator sees rows piling up. They used to refresh only from inside + * a relay cycle, so with the relay off (the default) or failing every cycle they stood still + * (review 06-05). + */ +@ExtendWith(OutputCaptureExtension.class) +class OutboxMetricsTest { + + private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z"); + + @Test + @DisplayName("relay가 꺼져 있어도 대기 행 게이지가 실제 PENDING 행 수를 보여 준다") + void withTheRelayOffThePendingGaugeShowsThePendingRows() { + // given: two rows appended, no relay + InMemoryOutboxStore store = new InMemoryOutboxStore(); + store.append(OutboxEvents.event(UUID.randomUUID().toString(), NOW.minusSeconds(30))); + store.append(OutboxEvents.event(UUID.randomUUID().toString(), NOW.minusSeconds(20))); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) + .withBean(OutboxStorePort.class, () -> store) + .withBean(MeterRegistry.class, () -> registry) + .withPropertyValues( + "app.outbox.enabled=true", + "app.outbox.relay-enabled=false", + "app.outbox.poll-interval=PT0.05S"); + + // when + runner.run( + context -> + await() + .atMost(Duration.ofSeconds(10)) + .until(() -> pending(registry) != null && pending(registry) == 2.0)); + + // then + assertThat(pending(registry)).isEqualTo(2.0); + } + + @Test + @DisplayName("게이지 갱신은 PUBLISHED를 세지 않고 지연 게이지는 가장 오래된 미발행 행의 나이다") + void aRefreshCountsUnpublishedRowsAndAgesTheOldest() { + // given + InMemoryOutboxStore store = new InMemoryOutboxStore(); + store.append(OutboxEvents.event(UUID.randomUUID().toString(), NOW.minusSeconds(90))); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + OutboxMetrics metrics = metrics(store, registry); + + // when + metrics.refreshGauges(); + + // then + assertThat(pending(registry)).isEqualTo(1.0); + assertThat(Search.in(registry).name("outbox.pending.size").tag("status", "PUBLISHED").gauge()) + .isNull(); + assertThat( + registry + .get("outbox.publisher.lag") + .tag("event_type", OutboxEvents.CONTRACT_ID) + .gauge() + .value()) + .isEqualTo(90.0); + } + + @Test + @DisplayName("저장소가 실패해도 게이지 갱신은 예외를 밖으로 던지지 않는다") + void aFailingStoreDoesNotBreakTheRefresh() { + // given + OutboxStorePort broken = Mockito.mock(OutboxStorePort.class); + Mockito.when(broken.countByStatus()).thenThrow(new IllegalStateException("database down")); + Mockito.when(broken.oldestUnpublishedAgeSecondsByEventType(Mockito.any())) + .thenThrow(new IllegalStateException("database down")); + OutboxMetrics metrics = metrics(broken, new SimpleMeterRegistry()); + + // when + Throwable thrown = org.assertj.core.api.Assertions.catchThrowable(metrics::refreshGauges); + + // then + assertThat(thrown).isNull(); + } + + @Test + @DisplayName("발행 포트가 있는데 relay가 꺼져 있으면 기동 시 WARN을 한 줄 남긴다") + void aPublishPortWithTheRelayOffWarnsAtStartup(CapturedOutput output) { + // given + ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) + .withBean(OutboxStorePort.class, InMemoryOutboxStore::new) + .withBean( + OutboxMessagePublishPort.class, () -> Mockito.mock(OutboxMessagePublishPort.class)) + .withPropertyValues("app.outbox.enabled=true", "app.outbox.poll-interval=PT1H"); + + // when + runner.run(context -> assertThat(context).hasSingleBean(OutboxRelayOffWarning.class)); + + // then + assertThat(output).contains("outbox relay is off although a publish port exists"); + } + + @Test + @DisplayName("relay가 켜져 있으면 relay 꺼짐 경고를 남기지 않는다") + void aRunningRelayDoesNotWarn() { + // given + ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) + .withBean(OutboxStorePort.class, InMemoryOutboxStore::new) + .withBean( + OutboxMessagePublishPort.class, () -> Mockito.mock(OutboxMessagePublishPort.class)) + .withBean( + dev.caskeleton.application.outbox.OutboxRelayFailureReportPort.class, + () -> report -> {}) + .withBean( + dev.caskeleton.application.transaction.TransactionPort.class, + dev.caskeleton.application.transaction.testkit.DirectTransactionPort::new) + .withBean(Clock.class, Clock::systemUTC) + .withPropertyValues( + "app.outbox.enabled=true", + "app.outbox.relay-enabled=true", + "app.outbox.poll-interval=PT1H"); + + // when & then + runner.run(context -> assertThat(context).doesNotHaveBean(OutboxRelayOffWarning.class)); + } + + private static Double pending(MeterRegistry registry) { + var gauge = Search.in(registry).name("outbox.pending.size").tag("status", "PENDING").gauge(); + return gauge == null ? null : gauge.value(); + } + + private static OutboxMetrics metrics(OutboxStorePort store, MeterRegistry registry) { + StaticListableBeanFactory registries = new StaticListableBeanFactory(); + registries.addBean("meterRegistry", registry); + return new OutboxMetrics( + store, registries.getBeanProvider(MeterRegistry.class), Clock.fixed(NOW, ZoneOffset.UTC)); + } +} diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerDrainTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerDrainTest.java new file mode 100644 index 00000000..7e77915e --- /dev/null +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerDrainTest.java @@ -0,0 +1,198 @@ +package dev.caskeleton.composition.outbox; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.outbox.OutboxBackoffPolicy; +import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.application.outbox.OutboxStorePort; +import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.support.StaticListableBeanFactory; + +/** + * One relay tick against a backlog. The claim gate releases one row per aggregate at a time, so a + * tick that claimed once moved an aggregate forward by one event per poll interval (review 06-04). + * + *

        The store below is the port owner's fake with that gate added: a row is claimable only while + * no earlier row of its aggregate is unpublished — the rule the PostgreSQL claim SQL carries. + */ +class OutboxRelaySchedulerDrainTest { + + private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z"); + + @Test + @DisplayName("한 aggregate에 쌓인 이벤트는 poll 주기를 기다리지 않고 한 tick 안에 순서대로 모두 나간다") + void oneTickDrainsAnAggregatesBacklogInOrderWithoutWaitingForThePollInterval() { + // given: thirty events of one aggregate, each claimable only after the one before it + HeadOfAggregateStore store = new HeadOfAggregateStore(); + List appended = new ArrayList<>(); + for (int sequence = 1; sequence <= 30; sequence++) { + String eventId = UUID.randomUUID().toString(); + appended.add(eventId); + store.append(OutboxEvents.event(eventId, "order-1", sequence, NOW.minusSeconds(60))); + } + List sent = new ArrayList<>(); + OutboxRelayScheduler scheduler = scheduler(store, event -> sent.add(event.eventId())); + scheduler.start(); + + // when + scheduler.relay(); + + // then + assertThat(sent).containsExactlyElementsOf(appended); + } + + @Test + @DisplayName("한 tick이 도는 회차 수에는 상한이 있다") + void aTickRunsAtMostItsBoundedNumberOfCycles() { + // given: more single-row cycles than one tick may run + HeadOfAggregateStore store = new HeadOfAggregateStore(); + int backlog = OutboxRelayScheduler.MAX_CYCLES_PER_TICK + 5; + for (int sequence = 1; sequence <= backlog; sequence++) { + store.append( + OutboxEvents.event( + UUID.randomUUID().toString(), "order-1", sequence, NOW.minusSeconds(60))); + } + List sent = new ArrayList<>(); + OutboxRelayScheduler scheduler = scheduler(store, event -> sent.add(event.eventId())); + scheduler.start(); + + // when + scheduler.relay(); + + // then + assertThat(sent).hasSize(OutboxRelayScheduler.MAX_CYCLES_PER_TICK); + } + + @Test + @DisplayName("아무것도 발행하지 못한 회차가 나오면 tick은 다시 claim하지 않고 끝난다") + void aCycleThatPublishedNothingEndsTheTick() { + // given: the broker refuses every publish for now + HeadOfAggregateStore store = new HeadOfAggregateStore(); + store.append(OutboxEvents.event(UUID.randomUUID().toString(), NOW.minusSeconds(60))); + store.append(OutboxEvents.event(UUID.randomUUID().toString(), NOW.minusSeconds(59))); + List attempted = new ArrayList<>(); + OutboxRelayScheduler scheduler = + scheduler( + store, + event -> { + attempted.add(event.eventId()); + throw new IllegalStateException("broker unavailable"); + }); + scheduler.start(); + + // when + scheduler.relay(); + + // then: each row was tried once; both now wait for their retry time + assertThat(attempted).hasSize(2).doesNotHaveDuplicates(); + } + + @Test + @DisplayName("relay는 회차마다 발행 결과를 카운터에 기록한다") + void everyCycleOfATickIsCountedInThePublishedCounter() { + // given + HeadOfAggregateStore store = new HeadOfAggregateStore(); + for (int sequence = 1; sequence <= 3; sequence++) { + store.append( + OutboxEvents.event( + UUID.randomUUID().toString(), "order-1", sequence, NOW.minusSeconds(60))); + } + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + OutboxRelayScheduler scheduler = scheduler(store, event -> {}, registry); + scheduler.start(); + + // when + scheduler.relay(); + + // then + assertThat( + registry + .get("outbox.publisher.published.total") + .tag("outcome", "PUBLISHED") + .counter() + .count()) + .isEqualTo(3.0); + } + + private static OutboxRelayScheduler scheduler( + OutboxStorePort store, OutboxMessagePublishPort port) { + return scheduler(store, port, null); + } + + private static OutboxRelayScheduler scheduler( + OutboxStorePort store, OutboxMessagePublishPort port, SimpleMeterRegistry registry) { + Clock clock = Clock.fixed(NOW, ZoneOffset.UTC); + StaticListableBeanFactory registries = new StaticListableBeanFactory(); + if (registry != null) { + registries.addBean("meterRegistry", registry); + } + PublishPendingOutboxEventsUseCase relay = + new PublishPendingOutboxEventsUseCase( + store, + port, + report -> {}, + new DirectTransactionPort(), + new OutboxBackoffPolicy(() -> 0L), + clock, + 20, + Duration.ofMinutes(5), + "relay-under-test"); + return new OutboxRelayScheduler( + relay, + new OutboxMetrics( + store, + registries.getBeanProvider(io.micrometer.core.instrument.MeterRegistry.class), + clock)); + } + + /** The fake store with the claim SQL's per-aggregate head gate. */ + private static final class HeadOfAggregateStore extends InMemoryOutboxStore { + + @Override + public List claimBatch( + String owner, int batchSize, Instant now, Duration inFlightTimeout) { + List heads = new ArrayList<>(); + List seenAggregates = new ArrayList<>(); + appended().stream() + .sorted( + java.util.Comparator.comparingLong( + (dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent e) -> + e.order().sequence())) + .forEach( + event -> { + String aggregate = event.aggregate().aggregateId(); + if (seenAggregates.contains(aggregate)) { + return; + } + OutboxEventStatus status = status(event.eventId().value()); + if (status != OutboxEventStatus.PUBLISHED) { + seenAggregates.add(aggregate); + heads.add(event.eventId().value()); + } + }); + return super.claimBatch(owner, batchSize, now, inFlightTimeout).stream() + .filter(lease -> heads.contains(lease.eventId()) || unclaim(lease)) + .toList(); + } + + /** A row the gate would not have returned: give the fake's claim back, unspent. */ + private boolean unclaim(dev.caskeleton.application.outbox.OutboxLease lease) { + releaseLease(lease, lease.event().occurredAt()); + return false; + } + } +} diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerLoggingTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerLoggingTest.java index 99482c17..3e51efe5 100644 --- a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerLoggingTest.java +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerLoggingTest.java @@ -1,6 +1,7 @@ package dev.caskeleton.composition.outbox; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -11,7 +12,6 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase; -import java.time.Clock; import java.util.Arrays; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; @@ -24,11 +24,11 @@ class OutboxRelaySchedulerLoggingTest { void outboxRelayUnexpectedFailureCarriesNextTickDispositionWithoutInventedErrorCode() { PublishPendingOutboxEventsUseCase relay = mock(PublishPendingOutboxEventsUseCase.class); OutboxMetrics metrics = mock(OutboxMetrics.class); - when(relay.handle(PublishPendingOutboxEventsCommand.INSTANCE)) + when(relay.handle(any(PublishPendingOutboxEventsCommand.class))) .thenThrow(new IllegalStateException("unexpected")); try (CapturedLogger captured = capture(OutboxRelayScheduler.class)) { - OutboxRelayScheduler scheduler = new OutboxRelayScheduler(relay, metrics, Clock.systemUTC()); + OutboxRelayScheduler scheduler = new OutboxRelayScheduler(relay, metrics); scheduler.start(); scheduler.relay(); diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java index 8c556e1b..1d038f0f 100644 --- a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java @@ -16,12 +16,15 @@ import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.application.outbox.testkit.OutboxEvents; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.messaging.autoconfigure.MessagingShutdownLifecycle; import java.time.Clock; import java.time.Instant; +import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -36,8 +39,8 @@ import org.springframework.context.SmartLifecycle; */ class OutboxRelayShutdownOrderTest { - /** {@code MessagingShutdownLifecycle#getPhase()}; this leaf may not name the messaging type. */ - private static final int PLATFORM_ADMISSION_PHASE = Integer.MAX_VALUE - 1024; + /** The platform's own constant; production code of this leaf may not name it, a test may. */ + private static final int PLATFORM_ADMISSION_PHASE = MessagingShutdownLifecycle.PHASE; private static final String EVENT_ID = "evt-shutdown-1"; @@ -49,19 +52,7 @@ class OutboxRelayShutdownOrderTest { store.addClaimable(OutboxEvents.claimed(EVENT_ID, Instant.now().minusSeconds(60), 1)); BlockingPublishPort publishPort = new BlockingPublishPort(); PlatformAdmissionStandIn platform = new PlatformAdmissionStandIn(store); - ApplicationContextRunner runner = - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) - .withBean(OutboxStorePort.class, () -> store) - .withBean(OutboxMessagePublishPort.class, () -> publishPort) - .withBean(OutboxRelayFailureReportPort.class, () -> report -> {}) - .withBean(TransactionPort.class, DirectTransactionPort::new) - .withBean(Clock.class, Clock::systemUTC) - .withBean(PlatformAdmissionStandIn.class, () -> platform) - .withPropertyValues( - "app.outbox.enabled=true", - "app.outbox.relay-enabled=true", - "app.outbox.poll-interval=PT1H"); + ApplicationContextRunner runner = runner(store, publishPort, platform); AtomicReference> closing = new AtomicReference<>(); runner.run( @@ -88,13 +79,51 @@ class OutboxRelayShutdownOrderTest { assertThat(store.status(EVENT_ID)).isEqualTo(OutboxEventStatus.PUBLISHED); } + @Test + @DisplayName("종료 시 relay는 진행 중 발행만 끝내고 나머지 claim은 시도 없이 놓은 뒤 멈춘다") + void onShutdownTheRelayReleasesTheClaimsItDidNotReachBeforeThePlatformStops() throws Exception { + // given: one cycle claims three rows and is publishing the first when the context closes + RecordingStore store = new RecordingStore(); + String publishing = "0193a000-0000-7000-8000-0000000000a1"; + String second = "0193a000-0000-7000-8000-0000000000a2"; + String third = "0193a000-0000-7000-8000-0000000000a3"; + Instant occurred = Instant.now().minusSeconds(60); + store.append(OutboxEvents.event(publishing, occurred)); + store.append(OutboxEvents.event(second, occurred.plusMillis(1))); + store.append(OutboxEvents.event(third, occurred.plusMillis(2))); + BlockingPublishPort publishPort = new BlockingPublishPort(); + PlatformAdmissionStandIn platform = new PlatformAdmissionStandIn(store); + + // when + runner(store, publishPort, platform) + .run( + context -> { + assertThat(publishPort.entered.await(10, TimeUnit.SECONDS)).isTrue(); + CompletableFuture closing = CompletableFuture.runAsync(context::close); + platform.stopped.await(300, TimeUnit.MILLISECONDS); + publishPort.release.countDown(); + closing.get(20, TimeUnit.SECONDS); + }); + + // then: the publish in progress landed, the other two are claimable again, unspent + assertThat(publishPort.calls.get()).as("no row was published after the stop").isEqualTo(1); + assertThat(store.status(publishing)).isEqualTo(OutboxEventStatus.PUBLISHED); + assertThat(store.released()).containsExactly(second, third); + assertThat(List.of(store.status(second), store.status(third))) + .containsOnly(OutboxEventStatus.PENDING); + assertThat(List.of(store.attemptCount(second), store.attemptCount(third))).containsOnly(0); + assertThat(platform.releasedWhenStopped.get()) + .as("the claims were released before the platform closed admission") + .isEqualTo(2); + } + @Test @DisplayName("멈춘 relay는 다음 tick이 와도 새 회차를 시작하지 않는다") void aStoppedRelayStartsNoNewCycle() { // given PublishPendingOutboxEventsUseCase relayUseCase = mock(PublishPendingOutboxEventsUseCase.class); OutboxRelayScheduler scheduler = - new OutboxRelayScheduler(relayUseCase, mock(OutboxMetrics.class), Clock.systemUTC()); + new OutboxRelayScheduler(relayUseCase, mock(OutboxMetrics.class)); scheduler.start(); AtomicBoolean reportedStopped = new AtomicBoolean(); scheduler.stop(() -> reportedStopped.set(true)); @@ -108,6 +137,22 @@ class OutboxRelayShutdownOrderTest { assertThat(scheduler.isRunning()).isFalse(); } + private static ApplicationContextRunner runner( + RecordingStore store, BlockingPublishPort publishPort, PlatformAdmissionStandIn platform) { + return new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) + .withBean(OutboxStorePort.class, () -> store) + .withBean(OutboxMessagePublishPort.class, () -> publishPort) + .withBean(OutboxRelayFailureReportPort.class, () -> report -> {}) + .withBean(TransactionPort.class, DirectTransactionPort::new) + .withBean(Clock.class, Clock::systemUTC) + .withBean(PlatformAdmissionStandIn.class, () -> platform) + .withPropertyValues( + "app.outbox.enabled=true", + "app.outbox.relay-enabled=true", + "app.outbox.poll-interval=PT1H"); + } + /** Records when the relay writes the row's completion. */ private static final class RecordingStore extends InMemoryOutboxStore { @@ -134,6 +179,16 @@ class OutboxRelayShutdownOrderTest { return completion; } + @Override + public synchronized OutboxCompletion releaseLease(OutboxLease lease, Instant claimableAt) { + return super.releaseLease(lease, claimableAt); + } + + @Override + public synchronized List released() { + return super.released(); + } + @Override public synchronized OutboxEventStatus status(String eventId) { return super.status(eventId); @@ -145,9 +200,11 @@ class OutboxRelayShutdownOrderTest { private final CountDownLatch entered = new CountDownLatch(1); private final CountDownLatch release = new CountDownLatch(1); + private final AtomicInteger calls = new AtomicInteger(); @Override public void publish(ClaimedOutboxEvent event) { + calls.incrementAndGet(); entered.countDown(); try { if (!release.await(20, TimeUnit.SECONDS)) { @@ -166,6 +223,7 @@ class OutboxRelayShutdownOrderTest { private final RecordingStore store; private final CountDownLatch stopped = new CountDownLatch(1); private final AtomicBoolean rowCompletedWhenStopped = new AtomicBoolean(); + private final AtomicInteger releasedWhenStopped = new AtomicInteger(); private volatile boolean running; PlatformAdmissionStandIn(RecordingStore store) { @@ -181,6 +239,7 @@ class OutboxRelayShutdownOrderTest { public void stop() { running = false; rowCompletedWhenStopped.set(store.completed.get()); + releasedWhenStopped.set(store.released().size()); stopped.countDown(); } diff --git a/src/composition/service-runtime/README.md b/src/composition/service-runtime/README.md index 95ae5f23..e2153a24 100644 --- a/src/composition/service-runtime/README.md +++ b/src/composition/service-runtime/README.md @@ -18,9 +18,18 @@ composition:service-runtime ├─ metrics/ MetricsContractConfig(cardinality deny-list + SLO 분포 filter) ├─ context/ DomainContextConfig ├─ logging/ PseudonymizationConfig, PrivacySettings (user_principal HMAC 가명화) - └─ management/security/ ManagementSecurityConfig (actuator chain) + ├─ management/security/ ManagementSecurityConfig (actuator chain) + └─ authorization/ PermissionEnforcementConfig(PermissionEnforcementGuard: @RequiresPermission + 빈이 있는데 적용되는 advisor가 없으면 기동 실패) ``` +- **권한 검사 장치 부재 = 기동 실패.** `@RequiresPermission`은 application-core 선언이고 검사는 + web leaf의 `MethodSecurityConfig` advisor가 한다. web을 뺀 조립(gRPC 전용·배치 전용)은 예전엔 + 선언만 남은 채 정상 기동했다. 이제 `PermissionEnforcementGuard`가 선언 빈마다 pointcut이 맞는 + advisor가 있는지 보고, 없으면 `REQUIRED_ADAPTER_DISABLED`(exit 72)로 기동을 멈춘다. 한계: + "어떤 advisor든 pointcut이 맞으면 통과"라 인가가 아닌 advisor를 구분하지 못한다. `new`로 만든 + 유스케이스는 검사 대상이 아니다(시스템 호출용은 `@SystemInvoked`). + - 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(설정 브리지와 tracing 스위치는 `spring.factories`의 `EnvironmentPostProcessor`·`AutoConfigurationImportFilter`). 구성 루트의 component scan에 기대지 않는다. @@ -147,7 +156,7 @@ runtimeOnly project(':composition:service-runtime') OpenTelemetry 규약대로 기준 주소에 `/v1/traces`를 붙인다(끝의 `/`는 하나로 정리). gRPC 전송이나 다른 경로가 필요하면 Boot 키(`management.opentelemetry.tracing.export.otlp.*`)를 직접 주며, 직접 준 값은 덮어쓰지 않는다. 예전 이름은 `TracingSamplingEnvironmentPostProcessor`다(순서 상수는 - `StartupOrder.TRACING_SAMPLING` 그대로). 이를 통해 "프로파일별 기본값 + env override"라는 + `StartupOrder.TRACING_PROPERTIES` 그대로). 이를 통해 "프로파일별 기본값 + env override"라는 우리 규약을 Spring Boot 의 기본 샘플링 메커니즘에 그대로 연결한다. - **샘플링 브리지 우선순위.** (1) 사용자가 `management.tracing.sampling.probability`를 이미 명시했으면 덮어쓰지 않고 그대로 둔다, (2) `app.tracing.sample-rate`가 non-blank 면 그 값 사용, (3) @@ -245,7 +254,7 @@ runtimeOnly project(':composition:service-runtime') `app.privacy.*` 바인딩(원천 `APP_PRIVACY_PSEUDONYMIZATION_SALT`). 알고리즘은 HMAC-SHA-256 + 90일 회전 salt 이고, 이 salt 는 `secret`-tier 값이라 prod 에서는 반드시 secret manager 에서 공급되어야 한다. -- **검증은 `LoggingSettings`와 일관되게 "warn-and-default"다.** blank salt 는 경고를 남기고, 명확히 +- **검증은 "warn-and-default"다.** blank salt 는 경고를 남기고, 명확히 표시된 dev sentinel(`__LOCAL_DEV_` 접두사)로 폴백해 local/test 실행이 절대 기동에 실패하지 않게 한다. - **이 sentinel 을 prod 로 승격하는 것은 별도 계약이 독립적으로 diff --git a/src/composition/service-runtime/build.gradle b/src/composition/service-runtime/build.gradle index 7c5bedaa..cacd1ff2 100644 --- a/src/composition/service-runtime/build.gradle +++ b/src/composition/service-runtime/build.gradle @@ -37,7 +37,13 @@ dependencies { // switches the whole of it off for app.tracing.enabled=false (TracingSwitchImportFilter). implementation 'io.micrometer:micrometer-tracing-bridge-otel' implementation 'org.springframework.boot:spring-boot-micrometer-tracing-opentelemetry' - implementation 'io.opentelemetry:opentelemetry-exporter-otlp' + // The OTLP exporter over the JDK's own HttpClient rather than OkHttp (09-11). The default sender + // brought okhttp, okio and kotlin-stdlib (about 3 MB) into every image for one HTTP POST the JDK + // already makes; the exporter picks whichever sender is on the classpath. + implementation('io.opentelemetry:opentelemetry-exporter-otlp') { + exclude group: 'io.opentelemetry', module: 'opentelemetry-exporter-sender-okhttp' + } + runtimeOnly 'io.opentelemetry:opentelemetry-exporter-sender-jdk' // The actuator security chain. implementation 'org.springframework.boot:spring-boot-starter-security' diff --git a/src/composition/service-runtime/gradle.lockfile b/src/composition/service-runtime/gradle.lockfile index 2c16687f..43259c53 100644 --- a/src/composition/service-runtime/gradle.lockfile +++ b/src/composition/service-runtime/gradle.lockfile @@ -10,6 +10,7 @@ com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,runtimeClasspath com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor +com.github.f4b6a3:uuid-creator:6.1.1=runtimeClasspath,testRuntimeClasspath com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs com.github.spotbugs:spotbugs:4.10.2=spotbugs @@ -36,10 +37,6 @@ com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProce com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.squareup.okhttp3:okhttp-jvm:5.2.1=runtimeClasspath,testRuntimeClasspath -com.squareup.okhttp3:okhttp:5.2.1=runtimeClasspath,testRuntimeClasspath -com.squareup.okio:okio-jvm:3.16.1=runtimeClasspath,testRuntimeClasspath -com.squareup.okio:okio:3.16.1=runtimeClasspath,testRuntimeClasspath com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-collections:commons-collections:3.2.2=checkstyle @@ -62,7 +59,7 @@ io.opentelemetry:opentelemetry-context:1.55.0=compileClasspath,runtimeClasspath, io.opentelemetry:opentelemetry-exporter-common:1.55.0=runtimeClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-exporter-otlp-common:1.55.0=runtimeClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-exporter-sender-okhttp:1.55.0=runtimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-sender-jdk:1.55.0=runtimeClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-sdk-common:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.55.0=runtimeClasspath,testRuntimeClasspath @@ -110,8 +107,6 @@ org.dom4j:dom4j:2.2.0=spotbugs org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle -org.jetbrains.kotlin:kotlin-stdlib:2.2.21=runtimeClasspath,testRuntimeClasspath -org.jetbrains:annotations:13.0=runtimeClasspath,testRuntimeClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath diff --git a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementConfig.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementConfig.java new file mode 100644 index 00000000..ac99d462 --- /dev/null +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementConfig.java @@ -0,0 +1,25 @@ +package dev.caskeleton.composition.runtime.authorization; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Role; + +/** + * Registers {@link PermissionEnforcementGuard}: a service that declares permission gates must also + * have something that enforces them. + * + *

        {@code @RequiresPermission} is an application-core declaration; the advisor that checks it is + * {@code adapter:inbound:web}'s {@code MethodSecurityConfig}. A composition without the web adapter + * — gRPC-only, batch-only — used to start normally with every gate declared and none enforced. This + * guard makes that composition fail at startup instead. + */ +@AutoConfiguration +public class PermissionEnforcementConfig { + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + static PermissionEnforcementGuard permissionEnforcementGuard() { + return new PermissionEnforcementGuard(); + } +} diff --git a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java new file mode 100644 index 00000000..9f9b0e80 --- /dev/null +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java @@ -0,0 +1,69 @@ +package dev.caskeleton.composition.runtime.authorization; + +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; +import dev.caskeleton.application.security.RequiresPermission; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import org.springframework.aop.Advisor; +import org.springframework.aop.support.AopUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.util.ClassUtils; + +/** + * Fails startup when a bean declares {@link RequiresPermission} and no advisor in the context + * applies to it. + * + *

        "Applies" is {@link AopUtils#canApply(Advisor, Class)}: the advisor's pointcut matches the + * bean's class. That is how the web adapter's advisor reaches a use case, so its absence is exactly + * the case this guard is for. The check cannot tell an authorization advisor from any other advisor + * whose pointcut happens to match; it closes the "adapter missing" gap, not every misconfiguration. + * + *

        Only beans are checked. A use case built with {@code new} is never advised whatever the + * context holds — that is what {@code @SystemInvoked} declares for the use cases the system calls. + */ +final class PermissionEnforcementGuard implements SmartInitializingSingleton, BeanFactoryAware { + + private ConfigurableListableBeanFactory beanFactory; + + @Override + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; + } + + @Override + public void afterSingletonsInstantiated() { + Collection advisors = beanFactory.getBeansOfType(Advisor.class, true, false).values(); + List unenforced = new ArrayList<>(); + for (String name : beanFactory.getBeanDefinitionNames()) { + Class type = beanFactory.getType(name, false); + if (type == null) { + continue; + } + Class userClass = ClassUtils.getUserClass(type); + if (declaresPermission(userClass) + && advisors.stream().noneMatch(advisor -> AopUtils.canApply(advisor, userClass))) { + unenforced.add(name + " (" + userClass.getName() + ")"); + } + } + if (!unenforced.isEmpty()) { + throw StartupFailures.requiredAdapterDisabled( + "beans declare @RequiresPermission but no advisor enforces it — the composition is" + + " missing the authorization adapter (adapter:inbound:web MethodSecurityConfig): " + + String.join(", ", unenforced)); + } + } + + private static boolean declaresPermission(Class type) { + return AnnotatedElementUtils.hasAnnotation(type, RequiresPermission.class) + || Arrays.stream(type.getMethods()) + .anyMatch( + method -> AnnotatedElementUtils.hasAnnotation(method, RequiresPermission.class)); + } +} diff --git a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessor.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessor.java index a128b388..dc125a69 100644 --- a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessor.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/tracing/TracingEnvironmentPostProcessor.java @@ -69,6 +69,6 @@ public class TracingEnvironmentPostProcessor implements EnvironmentPostProcessor // Declared rather than inherited. Implementing EnvironmentPostProcessor without Ordered means // LOWEST_PRECEDENCE by default, which is the same value three other post-processors returned // explicitly — four things claiming the same position, none of them saying so (BOOT-005). - return StartupOrder.TRACING_SAMPLING; + return StartupOrder.TRACING_PROPERTIES; } } diff --git a/src/composition/service-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/composition/service-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index e3a9b446..a15ac78b 100644 --- a/src/composition/service-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/composition/service-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -3,3 +3,4 @@ dev.caskeleton.composition.runtime.logging.PseudonymizationConfig dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig dev.caskeleton.composition.runtime.metrics.MetricsContractConfig dev.caskeleton.composition.runtime.tracing.TracingConfig +dev.caskeleton.composition.runtime.authorization.PermissionEnforcementConfig diff --git a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java index 6e4b35d9..051d23c2 100644 --- a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/ServiceRuntimeRegistrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort; +import dev.caskeleton.composition.runtime.authorization.PermissionEnforcementConfig; import dev.caskeleton.composition.runtime.context.DomainContextConfig; import dev.caskeleton.composition.runtime.logging.PseudonymizationConfig; import dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig; @@ -35,7 +36,8 @@ class ServiceRuntimeRegistrationTest { PseudonymizationConfig.class, ManagementSecurityConfig.class, MetricsContractConfig.class, - TracingConfig.class); + TracingConfig.class, + PermissionEnforcementConfig.class); @Test void everyRootIsAnAutoConfigurationBootDiscoversFromThisModule() { @@ -89,7 +91,7 @@ class ServiceRuntimeRegistrationTest { int order = bridge.getOrder(); // then - assertThat(order).isEqualTo(StartupOrder.TRACING_SAMPLING); + assertThat(order).isEqualTo(StartupOrder.TRACING_PROPERTIES); } @ParameterizedTest diff --git a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java new file mode 100644 index 00000000..86ea2242 --- /dev/null +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java @@ -0,0 +1,69 @@ +package dev.caskeleton.composition.runtime.authorization; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; +import dev.caskeleton.application.security.RequiresPermission; +import org.aopalliance.intercept.MethodInterceptor; +import org.junit.jupiter.api.Test; +import org.springframework.aop.Advisor; +import org.springframework.aop.support.DefaultPointcutAdvisor; +import org.springframework.aop.support.annotation.AnnotationMatchingPointcut; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +class PermissionEnforcementGuardTest { + + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(PermissionEnforcementConfig.class)); + + @Test + void aGatedBeanWithNoEnforcingAdvisorFailsStartup() { + runner + .withUserConfiguration(GatedUseCaseConfig.class) + .run( + context -> + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("no advisor enforces it") + .hasMessageContaining(GatedUseCase.class.getName())); + } + + @Test + void aGatedBeanWithAnAdvisorThatMatchesItStarts() { + runner + .withUserConfiguration(GatedUseCaseConfig.class, EnforcingAdvisorConfig.class) + .run(context -> assertThat(context).hasNotFailed().hasSingleBean(GatedUseCase.class)); + } + + @Test + void aContextWithoutGatedBeansNeedsNoAdvisor() { + runner.run(context -> assertThat(context).hasNotFailed()); + } + + @RequiresPermission("thing:write") + public static class GatedUseCase { + public void handle() {} + } + + @Configuration(proxyBeanMethods = false) + static class GatedUseCaseConfig { + @Bean + GatedUseCase gatedUseCase() { + return new GatedUseCase(); + } + } + + @Configuration(proxyBeanMethods = false) + static class EnforcingAdvisorConfig { + @Bean + static Advisor enforcingAdvisor() { + return new DefaultPointcutAdvisor( + AnnotationMatchingPointcut.forClassAnnotation(RequiresPermission.class), + (MethodInterceptor) invocation -> invocation.proceed()); + } + } +} diff --git a/src/config/architecture/modules.json b/src/config/architecture/modules.json index bfac2cef..013dea9b 100644 --- a/src/config/architecture/modules.json +++ b/src/config/architecture/modules.json @@ -164,6 +164,18 @@ "adapter-outbound-support" ] }, + { + "id": "adapter-inbound-messaging", + "gradle_path": ":adapter:inbound:messaging", + "source_path": "src/adapter/inbound/messaging", + "allowed_dependencies": [ + "application-core", + "messaging-core-api", + "messaging-reliability", + "messaging-reliability-api", + "messaging-reliability-jdbc-postgresql" + ] + }, { "id": "adapter-outbound-messaging", "gradle_path": ":adapter:outbound:messaging", @@ -277,7 +289,6 @@ "application-fileserver", "shared-contract", "adapter-outbound-fileserver", - "adapter-outbound-identifier", "adapter-outbound-support", "adapter-outbound-persistence-fileserver", "adapter-outbound-persistence-jpa", @@ -307,6 +318,17 @@ "adapter-outbound-support" ] }, + { + "id": "composition-durable-operation", + "gradle_path": ":composition:durable-operation", + "source_path": "src/composition/durable-operation", + "allowed_dependencies": [ + "application-core", + "adapter-outbound-support", + "adapter-inbound-web", + "adapter-outbound-identifier" + ] + }, { "id": "composition-idempotency", "gradle_path": ":composition:idempotency", @@ -351,7 +373,8 @@ "composition-fileserver-platform", "composition-outbox-relay", "composition-idempotency", - "composition-service-runtime" + "composition-service-runtime", + "composition-durable-operation" ] }, { diff --git a/src/config/testing/container-images.properties b/src/config/testing/container-images.properties new file mode 100644 index 00000000..71a826b0 --- /dev/null +++ b/src/config/testing/container-images.properties @@ -0,0 +1,41 @@ +# The container images the test lanes start, in one place (review 2026-11-01 08-04). +# +# ca.java-conventions reads this file and hands every key to every Test JVM as the system property +# `ca.test.image.`; the file is an input of every Test task, so changing an image reruns the +# lanes that use it. Build scripts read the same values as `testContainerImages['']`. An image +# change is a change to this file only. +# +# Each image is pinned by digest, with its tag in the comment above it: a red lane should mean this repository changed, not +# that someone pushed a new image under the same tag. A lane whose image cannot be pulled fails; it +# does not skip. +# +# Pulling through a mirror (a registry that proxies Docker Hub, or an internal registry when Docker +# Hub is blocked or rate-limited): set TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX in the environment, for +# example `registry.internal/dockerhub/`. Testcontainers puts the prefix in front of every Docker Hub +# image and still treats it as the original for its module checks. Images from other registries +# (ghcr.io below) are not rewritten by the prefix; mirror them under the same name or replace the +# value here. +# +# Not here: the MinIO qualification images (adapter:outbound:objectstorage owns their pinning and +# its unavailable-image failure), and the Compose files, which pin the development stack. + +# postgres:16-alpine +postgres-16=postgres@sha256:0cefaabd882e42bcb2a2f3dc56d3ce4770560ba62fd7f197f1a2e008fd5731ab +# The sample's poster-image migration qualification was written against this patch release. +# postgres:16.4-alpine +postgres-16-4=postgres@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c +# 17 and 18 are not digest-pinned yet: they were not pulled on the machine this catalog was made +# on, and a digest copied from elsewhere would be unverified. Pin them with the next image update. +postgres-17=postgres:17-alpine +postgres-18=postgres:18-alpine +# mongo:8.0.16 +mongo-8=mongo@sha256:4b58ebcb1dc7a7b4e84cd8ce9098d48764ae4478876898ff9551acf2ac4a6a6d +# mongo:7.0.28 +mongo-7=mongo@sha256:4510cf3d7050003e958745adb25d2deb3fb907430716162d9cc1a92eda2a6047 +# apache/kafka:4.1.0 +kafka=apache/kafka@sha256:bff074a5d0051dbc0bbbcd25b045bb1fe84833ec0d3c7c965d1797dd289ec88f +# ghcr.io/shopify/toxiproxy:2.12.0 +toxiproxy=ghcr.io/shopify/toxiproxy@sha256:9378ed52a28bc50edc1350f936f518f31fa95f0d15917d6eb40b8e376d1a214e +httpbin=kennethreitz/httpbin@sha256:599fe5e5073102dbb0ee3dbb65f049dab44fa9fc251f6835c9990f8fb196a72b +# nginx:1.27-alpine +nginx=nginx@sha256:65645c7bb6a0661892a8b03b89d0743208a18dd2f3f17a54ef4b76fb8e2f2a10 diff --git a/src/domain-core/build.gradle b/src/domain-core/build.gradle index 245498fa..50a705b3 100644 --- a/src/domain-core/build.gradle +++ b/src/domain-core/build.gradle @@ -1,7 +1,13 @@ plugins { id 'ca.java-library' + id 'java-test-fixtures' } // Pure domain layer. No Spring, no infra dependencies. dependencies { + // A domain-owned port (a feature's `*Repository`, `*IdFactory`) keeps its one fake and its + // abstract contract (`*Contract`) here, in the port owner's test fixtures (AGENTS.md test rule + // 6). `scripts/new-feature.sh` writes them; docs/manual/08-testing.md says why. + testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' + testFixturesImplementation 'org.assertj:assertj-core' } diff --git a/src/domain-core/gradle.lockfile b/src/domain-core/gradle.lockfile index e2c95854..13a5babd 100644 --- a/src/domain-core/gradle.lockfile +++ b/src/domain-core/gradle.lockfile @@ -1,40 +1,40 @@ # 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,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,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,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,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,testAnnotationProcessor +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,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,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,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,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,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,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs @@ -50,32 +50,32 @@ org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath,testFixturesCompileClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit:junit-bom:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.ow2.asm:asm-analysis:9.10.1=spotbugs org.ow2.asm:asm-commons:9.10.1=spotbugs org.ow2.asm:asm-tree:9.10.1=spotbugs org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.pcollections:pcollections:4.0.1=annotationProcessor,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 diff --git a/src/gradle/libs.versions.toml b/src/gradle/libs.versions.toml index 1ccf83b9..7ab0f90e 100644 --- a/src/gradle/libs.versions.toml +++ b/src/gradle/libs.versions.toml @@ -24,11 +24,11 @@ # pinned in two different files, which is exactly the pair this file exists to put next to each # other. # -# What is deliberately NOT here: `ext['commons-lang3.version']` and `ext['netty.version']` in -# src/build.gradle. Neither is a version this build chooses — both are overrides of a version the -# Spring Boot BOM already manages, and each is valid only next to the sentence that says what breaks -# without it (a SpotBugs worker NoClassDefFoundError, and two named CVEs on shared runtime surface). -# Moving the number here would leave the reason behind. +# What is deliberately NOT here: the `commons-lang3.version` override in build-logic's +# JavaConventionsPlugin (ca.java-conventions). It is not a version this build chooses but an override +# of one the Spring Boot BOM already manages, valid only next to the sentence that says what breaks +# without it (the SpotBugs worker's NoClassDefFoundError). Moving the number here would leave the +# reason behind. [versions] approvaltests = "31.0.0" diff --git a/src/grpc/CLAUDE.md b/src/grpc/CLAUDE.md index f056c0ab..ada4282d 100644 --- a/src/grpc/CLAUDE.md +++ b/src/grpc/CLAUDE.md @@ -96,6 +96,9 @@ application-owned port → adapter:inbound:grpc (typed service adapter) → :grp 직접 닿지 않는 규칙은 app-bootstrap ArchUnit(`INBOUND_ADAPTERS_DO_NOT_DEPEND_ON_OUTBOUND_ADAPTERS`)이 검사한다. 현재 `adapter:inbound:grpc`는 이 family에 의존하지 않는다 — registry의 `allowed_dependencies`를 보라. 배선은 별도 결정이며, 그때 registry edge와 브리지가 함께 들어간다. +starter가 `operation-ledger-enabled=true`일 때 멱등성 판단 bean을 조립하는 것(03-11)은 이 배선이 아니다 — +starter는 서버를 만들지 않고, 그 bean을 서버에 붙이는 일은 채택하는 쪽의 몫이다(아래 「Durable operation +ledger adoption」). ## 테스트 명령 @@ -130,13 +133,51 @@ the repository's `.seconds` / `.total` unit naming and the corresponding validat ### Durable operation ledger adoption -`grpc-spring-boot-starter` does not pull the JPA ledger adapter transitively. A deployment that needs -durable operation idempotency adds `:grpc:grpc-operation-ledger-jpa` explicitly, enables the ledger -configuration, and includes that adapter's Flyway location `db/migration/grpc`. A deployment that -does not adopt the ledger therefore pays no Spring Data JPA classpath cost. +`grpc-spring-boot-starter` does not pull the JPA ledger adapter transitively (11-M9). A deployment that +needs durable operation idempotency adds `:grpc:grpc-operation-ledger-jpa` explicitly, defines a +`GrpcOperationLedger` bean (`new JpaGrpcOperationLedger(repository)`), includes that adapter's Flyway +location `db/migration/grpc` (V001 table, V002 retention index), and sets the flag below. A deployment +that does not adopt the ledger pays no Spring Data JPA classpath cost. -An `IN_PROGRESS` claim expires after the claim TTL (`GrpcIdempotencyInterceptor`'s `claimTtl` -argument; no configuration key while the starter does not assemble the interceptor). A retry of the -same request then takes it over through `GrpcOperationLedger.reclaimStale`. The adopter must record -the commit in the mutation's transaction and choose a TTL longer than the slowest keyed method; both -reasons are in ADR-GRPC-004. +| Key (`app.grpc.platform.*`) | Default | What it does | +| --- | --- | --- | +| `operation-ledger-enabled` | `false` | `true`: the starter assembles `GrpcIdempotencyInterceptor` (bean `grpcIdempotencyInterceptor`) and `GrpcOperationLedgerRetention` (bean `grpcOperationLedgerRetention`) over the deployment's `GrpcOperationLedger` bean, and refuses startup when there is none. `false`: neither bean exists, and a method that is `IDEMPOTENCY_KEY_REQUIRED` refuses startup | +| `operation-ledger-claim-ttl` | `5m` | How long an `IN_PROGRESS` claim is trusted to have a live owner. After it, a retry of the same request takes the claim over (`GrpcOperationLedger.reclaimStale`). Refused at startup unless longer than every keyed method's deadline | +| `operation-ledger-retention` | `24h` | How long a finished (`COMMITTED`/`FAILED_TERMINAL`) record is kept before `GrpcOperationLedgerRetention.purgeExpired` may delete it. `IN_PROGRESS` rows are never purged | + +Defaults: the 5-minute TTL is the value the ledger contract and interceptor tests certify, far beyond +a unary deadline, and short enough that a key whose owner died unblocks within a client's retry +patience. The 24-hour retention matches the HTTP idempotency replay TTL +(`app.capabilities.idempotency.replay-ttl`). A retry of a key after its record was purged is a new +operation, so the retention must exceed the callers' retry window. + +These keys are not in `docs/registries/env-keys.yaml`: no `app.grpc.platform.*` key is, because the +optional build is not part of the shipped runtime. They join the registry when a composition root +adopts the platform. + +**Why the starter assembles the interceptor (03-11 (b)), and not (a).** The review proposed (a): +delete the flag and judge by whether a ledger bean exists. The owner chose (b): the flag stays and +means what it says — when true, the decision function is assembled and its TTL comes from +configuration. (a) would have removed the false promise but left every adopter to rebuild the same +assembly and TTL validation by hand; (b) keeps that in one place. The interceptor bean has no +`@ConditionalOnMissingBean` on purpose: a replacement would silently ignore `operation-ledger-claim-ttl`. +Duplicates of a running operation are refused (`REJECT_IN_PROGRESS`), not told to wait; a +wait-and-poll option becomes a key when a keyed method needs it. + +**Server wiring is still the adopter's, and stays a separate decision.** The starter builds no +server, so assembling the decision does not wire the platform into `adapter:inbound:grpc` (see "배선은 +별도 결정" above). `GrpcIdempotencyInterceptor` is a decision function, not an `io.grpc.ServerInterceptor`. +The adopter injects the bean by type and calls it from its own `IDEMPOTENCY` stage interceptor +(`GrpcServerInterceptorChain.builder().stage(GrpcServerInterceptorStage.IDEMPOTENCY, ...)`) or from +its typed service adapter: `decide(...)` before the mutation, `recordCommit(...)` inside the mutation's +transaction, `recordFailure(...)` on a terminal failure. + +**Purge scheduling is the adopter's.** `GrpcOperationLedgerRetention.purgeExpired(now)` deletes +expired finished rows in bounded batches (500 per statement) until a batch comes back short. The +starter does not schedule it: it owns no scheduler and cannot know which replica should run it, and a +scheduled bean would force a task scheduler onto every deployment. The adopter calls it from its own +scheduler (for example hourly); concurrent runs on several replicas are safe because the delete skips +locked rows. Running it never is safe but lets the table grow without bound. + +The commit must be recorded in the mutation's transaction and the TTL must be longer than the slowest +keyed method; both reasons are in ADR-GRPC-004. diff --git a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java index 7a4ee67c..2c275151 100644 --- a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java +++ b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java @@ -82,6 +82,27 @@ public interface GrpcOperationLedger { Instant claimedBefore, Instant now); + /** + * Deletes up to {@code limit} finished records ({@code COMMITTED} or {@code FAILED_TERMINAL}) + * that completed before {@code completedBefore}, oldest first. + * + *

        Retention, not recovery. A finished row only answers retries, so once it is older than any + * retry a caller will still send, keeping it only grows the table. Deleting it is a trade the + * deployment makes knowingly: a retry of the same key arriving after the purge is a fresh claim + * and runs the mutation again. The retention must therefore exceed the callers' retry window. + * + *

        An {@code IN_PROGRESS} record is never deleted, however old. It is either running or + * abandoned, and an abandoned one is taken over by {@link #reclaimStale}, which keeps the record + * that an attempt started; deleting it would erase that. + * + *

        Bounded so a backlog is drained in short transactions rather than one long delete that holds + * locks on the hottest table of the idempotency path. + * + * @return how many records were deleted, at most {@code limit} + * @throws IllegalArgumentException when {@code limit} is not positive + */ + int purgeCompletedBefore(Instant completedBefore, int limit); + /** * Releases a claim that will never complete, so the caller may try again. * diff --git a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java index b2839d63..0c625fc6 100644 --- a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java +++ b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java @@ -13,6 +13,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -40,6 +41,10 @@ public abstract class GrpcOperationLedgerContract { // A retry arriving after the TTL: its cutoff (LATER - TTL) is past the original claim at NOW. private static final Instant LATER = NOW.plus(CLAIM_TTL).plusSeconds(1); private static final Instant CUTOFF = LATER.minus(CLAIM_TTL); + // A purge run a day after NOW: rows finished around NOW are past retention. + private static final Instant RETENTION_CUTOFF = NOW.plus(Duration.ofDays(1)); + private static final GrpcOperationIdentity SECOND_ID = identityWithKeyHash('b'); + private static final GrpcOperationIdentity THIRD_ID = identityWithKeyHash('c'); /** The ledger under test, holding no records when a test starts. */ protected abstract GrpcOperationLedger ledger(); @@ -397,9 +402,104 @@ public abstract class GrpcOperationLedgerContract { assertThat(refused).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("cutoff"); } - private void failedClaim() { + @Test + @DisplayName("보존 기간이 지난 COMMITTED·FAILED_TERMINAL 행은 정리된다") + void finishedRecordsCompletedBeforeTheCutoffArePurged() { + // given + committedClaim(ID, NOW); + failedClaim(SECOND_ID, NOW); + + // when + int purged = ledger().purgeCompletedBefore(RETENTION_CUTOFF, 10); + + // then + assertThat(purged).isEqualTo(2); + assertThat(ledger().find(ID)).isEmpty(); + assertThat(ledger().find(SECOND_ID)).isEmpty(); + } + + @Test + @DisplayName("IN_PROGRESS 행은 아무리 오래되어도 정리하지 않는다") + void anInProgressClaimIsNeverPurgedHoweverOld() { + // given ledger().claim(ID, FINGERPRINT, NOW); - ledger().markFailed(ID, NOW.plusSeconds(1)); + + // when + int purged = ledger().purgeCompletedBefore(RETENTION_CUTOFF, 10); + + // then + assertThat(purged).isZero(); + assertThat(ledger().find(ID)) + .get() + .extracting(GrpcOperationLedgerRecord::state) + .isEqualTo(GrpcOperationLedgerState.IN_PROGRESS); + } + + @Test + @DisplayName("cutoff 이후에 끝난 행은 남긴다") + void finishedRecordsCompletedAtOrAfterTheCutoffAreKept() { + // given + committedClaim(ID, RETENTION_CUTOFF.minusSeconds(1)); + failedClaim(SECOND_ID, RETENTION_CUTOFF.minusSeconds(1)); + + // when + int purged = ledger().purgeCompletedBefore(RETENTION_CUTOFF, 10); + + // then + assertThat(purged).isZero(); + assertThat(ledger().find(ID)).isPresent(); + assertThat(ledger().find(SECOND_ID)).isPresent(); + } + + @Test + @DisplayName("한 번의 정리는 limit 개수까지만 지운다") + void onePurgeDeletesAtMostTheLimit() { + // given + committedClaim(ID, NOW); + committedClaim(SECOND_ID, NOW.plusSeconds(1)); + committedClaim(THIRD_ID, NOW.plusSeconds(2)); + + // when + int purged = ledger().purgeCompletedBefore(RETENTION_CUTOFF, 2); + + // then + assertThat(purged).isEqualTo(2); + assertThat( + Stream.of(ID, SECOND_ID, THIRD_ID) + .filter(identity -> ledger().find(identity).isPresent()) + .count()) + .isEqualTo(1); + } + + @Test + @DisplayName("limit이 양수가 아니면 정리를 거부한다") + void aNonPositivePurgeLimitIsRefused() { + // when + Throwable refused = catchThrowable(() -> ledger().purgeCompletedBefore(RETENTION_CUTOFF, 0)); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("limit"); + } + + private void failedClaim() { + failedClaim(ID, NOW); + } + + // Claimed at `claimedAt`, finished one second later, so the completion moment is what a purge + // cutoff is compared with. + private void failedClaim(GrpcOperationIdentity identity, Instant claimedAt) { + ledger().claim(identity, FINGERPRINT, claimedAt); + ledger().markFailed(identity, claimedAt.plusSeconds(1)); + } + + private void committedClaim(GrpcOperationIdentity identity, Instant claimedAt) { + ledger().claim(identity, FINGERPRINT, claimedAt); + ledger().markCommitted(identity, OUTCOME, claimedAt.plusSeconds(1)); + } + + private static GrpcOperationIdentity identityWithKeyHash(char hexDigit) { + return new GrpcOperationIdentity( + ID.callerFingerprint(), ID.method(), "sha256:" + String.valueOf(hexDigit).repeat(64)); } /** Runs {@code attempt} on two threads released together and returns both results. */ diff --git a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java index 207971b5..55479149 100644 --- a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java +++ b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java @@ -1,6 +1,8 @@ package dev.caskeleton.grpc.api.ledger; import java.time.Instant; +import java.util.Comparator; +import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -10,8 +12,8 @@ import java.util.concurrent.ConcurrentMap; * *

        {@code putIfAbsent} on a concurrent map is the in-memory equivalent of the unique constraint * the real adapter relies on, and {@code replace(key, expected, next)} of its conditional update, - * so claim, re-claim and stale takeover are atomic here for the same reason they are there. The - * transitions match the JPA adapter's because {@link GrpcOperationLedgerContract} runs against + * so claim, re-claim, stale takeover and purge are atomic here for the same reason they are there. + * The transitions match the JPA adapter's because {@link GrpcOperationLedgerContract} runs against * both; a fake that allowed more would let the policy tests pass for code the database refuses. */ public final class InMemoryOperationLedger implements GrpcOperationLedger { @@ -102,6 +104,29 @@ public final class InMemoryOperationLedger implements GrpcOperationLedger { GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now)); } + @Override + public int purgeCompletedBefore(Instant completedBefore, int limit) { + if (limit < 1) { + throw new IllegalArgumentException("a purge limit must be positive"); + } + List expired = + records.values().stream() + .filter(record -> record.state().terminal()) + .filter(record -> record.completedAt().orElseThrow().isBefore(completedBefore)) + .sorted(Comparator.comparing(record -> record.completedAt().orElseThrow())) + .limit(limit) + .toList(); + int purged = 0; + for (GrpcOperationLedgerRecord record : expired) { + // Conditional, like the database's re-checked DELETE: a row re-claimed since it was read is + // IN_PROGRESS again and stays. + if (records.remove(record.identity().storageKey(), record)) { + purged++; + } + } + return purged; + } + @Override public void release(GrpcOperationIdentity identity) { records.remove(identity.storageKey()); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java new file mode 100644 index 00000000..6e28dfa2 --- /dev/null +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java @@ -0,0 +1,37 @@ +package dev.caskeleton.grpc.ledger; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; + +/** + * The ledger's Flyway scripts in version order, as one SQL text for a test database. + * + *

        One list for every PostgreSQL lane, so a new migration is applied by all of them or by none; + * two copies of the list drift the first time someone adds a V003 to one of them. + */ +final class GrpcOperationLedgerMigrations { + + private static final List IN_ORDER = + List.of( + "db/migration/grpc/V001__create_grpc_operation_ledger.sql", + "db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql"); + + private GrpcOperationLedgerMigrations() {} + + /** Every migration's SQL, concatenated in version order. */ + static String all() throws IOException { + StringBuilder sql = new StringBuilder(); + for (String path : IN_ORDER) { + try (InputStream stream = + GrpcOperationLedgerMigrations.class.getClassLoader().getResourceAsStream(path)) { + if (stream == null) { + throw new IOException("gRPC operation-ledger migration is missing: " + path); + } + sql.append(new String(stream.readAllBytes(), StandardCharsets.UTF_8)).append('\n'); + } + } + return sql.toString(); + } +} diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerPostgresIT.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerPostgresIT.java index 98fd2f27..df1b00b7 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerPostgresIT.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerPostgresIT.java @@ -3,8 +3,6 @@ package dev.caskeleton.grpc.ledger; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -41,7 +39,7 @@ class GrpcOperationLedgerPostgresIT { @SuppressWarnings("resource") @Container private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer("postgres:16-alpine") + new PostgreSQLContainer(System.getProperty("ca.test.image.postgres-16")) .withDatabaseName("grpc") .withUsername("grpc") .withPassword("grpc"); @@ -146,14 +144,6 @@ class GrpcOperationLedgerPostgresIT { } private static String migration() throws IOException { - try (InputStream stream = - GrpcOperationLedgerPostgresIT.class - .getClassLoader() - .getResourceAsStream("db/migration/grpc/V001__create_grpc_operation_ledger.sql")) { - if (stream == null) { - throw new IOException("gRPC operation-ledger migration is missing"); - } - return new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } + return GrpcOperationLedgerMigrations.all(); } } diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java index 701b31b5..7888f7e8 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java @@ -11,8 +11,6 @@ import dev.caskeleton.grpc.core.GrpcMethodName; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.PersistenceConfiguration; import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; @@ -44,7 +42,7 @@ class JpaGrpcOperationLedgerContractIT extends GrpcOperationLedgerContract { @SuppressWarnings("resource") @Container private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer("postgres:16-alpine") + new PostgreSQLContainer(System.getProperty("ca.test.image.postgres-16")) .withDatabaseName("grpc") .withUsername("grpc") .withPassword("grpc"); @@ -169,15 +167,7 @@ class JpaGrpcOperationLedgerContractIT extends GrpcOperationLedgerContract { } private static String migration() throws IOException { - try (InputStream stream = - JpaGrpcOperationLedgerContractIT.class - .getClassLoader() - .getResourceAsStream("db/migration/grpc/V001__create_grpc_operation_ledger.sql")) { - if (stream == null) { - throw new IOException("gRPC operation-ledger migration is missing"); - } - return new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } + return GrpcOperationLedgerMigrations.all(); } /** Runs each call in its own transaction, as a caller's business transaction would. */ @@ -227,6 +217,13 @@ class JpaGrpcOperationLedgerContractIT extends GrpcOperationLedgerContract { status -> delegate.reclaimStale(identity, requestFingerprint, claimedBefore, now))); } + @Override + public int purgeCompletedBefore(Instant completedBefore, int limit) { + Integer purged = + transactions.execute(status -> delegate.purgeCompletedBefore(completedBefore, limit)); + return purged == null ? 0 : purged; + } + @Override public void release(GrpcOperationIdentity identity) { transactions.executeWithoutResult(status -> delegate.release(identity)); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java index 32d14c01..d48c61c3 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java @@ -122,6 +122,39 @@ public interface GrpcOperationLedgerRepository @Param("claimedBefore") Instant claimedBefore, @Param("claimedAt") Instant claimedAt); + /** + * Deletes up to {@code limit} finished rows that completed before {@code completedBefore}, oldest + * first. Never an {@code IN_PROGRESS} row. + * + *

        {@code FOR UPDATE SKIP LOCKED} in the bounded subquery keeps the purge out of the way of a + * concurrent {@link #tryReclaimFailed}: a row that re-claim holds is skipped, and one it already + * turned back into {@code IN_PROGRESS} no longer matches. The outer state condition says the same + * thing again so the statement cannot delete a live claim even if the subquery is edited. The + * partial index {@code ix_grpc_operation_ledger_finished_completed_at} (V002) serves the + * subquery's filter and order. + * + * @return how many rows were deleted + */ + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Transactional + @Query( + value = + """ + DELETE FROM grpc_operation_ledger + WHERE storage_key IN ( + SELECT storage_key + FROM grpc_operation_ledger + WHERE state IN ('COMMITTED', 'FAILED_TERMINAL') + AND completed_at < :completedBefore + ORDER BY completed_at + LIMIT :limit + FOR UPDATE SKIP LOCKED) + AND state <> 'IN_PROGRESS' + """, + nativeQuery = true) + int deleteFinishedBefore( + @Param("completedBefore") Instant completedBefore, @Param("limit") int limit); + /** Updates an existing claim after it has been loaded. */ GrpcOperationLedgerEntity save(GrpcOperationLedgerEntity entity); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java index d81fd669..55d80bcd 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java @@ -122,6 +122,17 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { == 1; } + @Override + public int purgeCompletedBefore(Instant completedBefore, int limit) { + if (completedBefore == null) { + throw new IllegalArgumentException("a purge needs a cutoff"); + } + if (limit < 1) { + throw new IllegalArgumentException("a purge limit must be positive"); + } + return repository.deleteFinishedBefore(completedBefore, limit); + } + @Override public void release(GrpcOperationIdentity identity) { requireIdentity(identity); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql b/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql new file mode 100644 index 00000000..a0c6d7d5 --- /dev/null +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql @@ -0,0 +1,16 @@ +-- Retention of finished ledger rows (review 2026-11-01, 03-10 follow-up). +-- +-- GrpcOperationLedgerRepository.deleteFinishedBefore deletes COMMITTED and FAILED_TERMINAL rows +-- whose completed_at is past the retention, oldest first and a bounded batch at a time. V001's +-- (state, claimed_at) index orders by claim time, not completion time, so without this index every +-- purge batch scans and sorts all finished rows. +-- +-- Partial: IN_PROGRESS rows have no completed_at and are never purged, so they stay out of the +-- index. The predicate repeats the query's state list literally so the planner can match it. +-- +-- A plain CREATE INDEX, not CONCURRENTLY: Flyway runs each migration in a transaction, and the +-- platform is not adopted anywhere yet, so the table is empty when this runs. An adopter that +-- applies it to a large existing ledger should run the CONCURRENTLY form by hand first. +CREATE INDEX ix_grpc_operation_ledger_finished_completed_at + ON grpc_operation_ledger (completed_at) + WHERE state IN ('COMMITTED', 'FAILED_TERMINAL'); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java b/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java index 9b7fcb49..e3aada69 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java @@ -73,6 +73,12 @@ class GrpcOperationLedgerRepositoryTest { "the stale takeover is certified against PostgreSQL by JpaGrpcOperationLedgerContractIT"); } + @Override + public int deleteFinishedBefore(Instant completedBefore, int limit) { + throw new UnsupportedOperationException( + "the bounded purge is certified against PostgreSQL by JpaGrpcOperationLedgerContractIT"); + } + @Override public GrpcOperationLedgerEntity save(GrpcOperationLedgerEntity entity) { rows.put(entity.getStorageKey(), entity); diff --git a/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetention.java b/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetention.java new file mode 100644 index 00000000..ac4e22c0 --- /dev/null +++ b/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetention.java @@ -0,0 +1,80 @@ +package dev.caskeleton.grpc.idempotency; + +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; +import java.time.Duration; +import java.time.Instant; + +/** + * Deletes finished operation-ledger records once they are older than the retention. + * + *

        Without it the ledger keeps every {@code COMMITTED} and {@code FAILED_TERMINAL} row forever. A + * finished row exists only to answer a retry, so once it is older than any retry a caller still + * sends, it is dead weight on the table every keyed call writes to. + * + *

        This class decides what to delete; it does not decide when. Nothing here + * schedules itself: the platform starter does not own a scheduler, does not start the server, and + * cannot know which replica should run the purge, so the adopter calls {@link #purgeExpired} from + * its own scheduler (one replica, or every replica — the bounded delete is safe either way). + */ +public final class GrpcOperationLedgerRetention { + + /** + * Rows deleted per statement. Small enough that one delete holds its row locks briefly on the + * hottest table of the idempotency path, large enough that a day's backlog drains in few calls. + */ + public static final int DEFAULT_BATCH_SIZE = 500; + + private final GrpcOperationLedger ledger; + private final Duration retention; + private final int batchSize; + + /** + * @param retention how long a finished record is kept after it completed. It must exceed the + * longest window in which a caller still retries the same key: a retry after the purge finds + * no record, claims afresh and runs the mutation again. + * @param batchSize the most rows one delete statement removes + */ + public GrpcOperationLedgerRetention( + GrpcOperationLedger ledger, Duration retention, int batchSize) { + if (ledger == null) { + throw new IllegalArgumentException("a ledger retention needs a ledger"); + } + if (retention == null || retention.isZero() || retention.isNegative()) { + throw new IllegalArgumentException("a ledger retention must be present and positive"); + } + if (batchSize < 1) { + throw new IllegalArgumentException("a ledger purge batch size must be positive"); + } + this.ledger = ledger; + this.retention = retention; + this.batchSize = batchSize; + } + + /** How long a finished record is kept. */ + public Duration retention() { + return retention; + } + + /** + * Deletes every finished record that completed more than the retention before {@code now}, in + * bounded batches, and never an {@code IN_PROGRESS} one. + * + *

        The cutoff is fixed at the start, so the loop ends: records finishing while it runs are + * newer than the cutoff and are left for the next call. + * + * @return how many records were deleted + */ + public int purgeExpired(Instant now) { + if (now == null) { + throw new IllegalArgumentException("a purge needs the current moment"); + } + Instant cutoff = now.minus(retention); + int total = 0; + int purged; + do { + purged = ledger.purgeCompletedBefore(cutoff, batchSize); + total += purged; + } while (purged == batchSize); + return total; + } +} diff --git a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetentionTest.java b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetentionTest.java new file mode 100644 index 00000000..fca364a6 --- /dev/null +++ b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetentionTest.java @@ -0,0 +1,83 @@ +package dev.caskeleton.grpc.idempotency; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; +import dev.caskeleton.grpc.api.ledger.InMemoryOperationLedger; +import dev.caskeleton.grpc.core.GrpcMethodName; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class GrpcOperationLedgerRetentionTest { + + private static final GrpcMethodName CREATE = + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); + private static final Instant NOW = Instant.parse("2026-11-01T10:00:00Z"); + private static final Duration RETENTION = Duration.ofHours(24); + private static final String BODY = GrpcRequestFingerprint.of("body"); + + private final InMemoryOperationLedger ledger = new InMemoryOperationLedger(); + + @Test + @DisplayName("보존 기간이 지난 종결 행을 batch 크기와 무관하게 모두 지운다") + void everyFinishedRecordPastTheRetentionIsPurgedAcrossBatches() { + // given + List old = List.of(identity("k1"), identity("k2"), identity("k3")); + old.forEach(identity -> committed(identity, NOW.minus(RETENTION).minusSeconds(60))); + GrpcOperationLedgerRetention retention = new GrpcOperationLedgerRetention(ledger, RETENTION, 2); + + // when + int purged = retention.purgeExpired(NOW); + + // then + assertThat(purged).isEqualTo(3); + assertThat(old).allSatisfy(identity -> assertThat(ledger.find(identity)).isEmpty()); + } + + @Test + @DisplayName("보존 기간 안에 끝난 행과 진행 중인 행은 남긴다") + void recentFinishedRecordsAndInProgressClaimsAreKept() { + // given + GrpcOperationIdentity recent = identity("recent"); + GrpcOperationIdentity running = identity("running"); + committed(recent, NOW.minus(RETENTION).plusSeconds(60)); + ledger.claim(running, BODY, NOW.minus(Duration.ofDays(30))); + GrpcOperationLedgerRetention retention = new GrpcOperationLedgerRetention(ledger, RETENTION, 2); + + // when + int purged = retention.purgeExpired(NOW); + + // then + assertThat(purged).isZero(); + assertThat(ledger.find(recent)).isPresent(); + assertThat(ledger.find(running)).isPresent(); + } + + @Test + @DisplayName("보존 기간이 양수가 아니면 만들 수 없다") + void aNonPositiveRetentionIsRefused() { + // when + Throwable refused = + catchThrowable(() -> new GrpcOperationLedgerRetention(ledger, Duration.ZERO, 2)); + + // then + assertThat(refused) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("retention must be present and positive"); + } + + private static GrpcOperationIdentity identity(String key) { + return new GrpcOperationIdentity( + "tenant-1|actor-1", CREATE, GrpcRequestFingerprint.hashIdempotencyKey(key)); + } + + // Finished at the claim moment; the completion moment is what the retention measures. + private void committed(GrpcOperationIdentity identity, Instant claimedAt) { + ledger.claim(identity, BODY, claimedAt); + ledger.markCommitted(identity, "outcome://document/" + identity.storageKey(), claimedAt); + } +} diff --git a/src/grpc/grpc-spring-boot-starter/build.gradle b/src/grpc/grpc-spring-boot-starter/build.gradle index ad114e67..2a8fbfa8 100644 --- a/src/grpc/grpc-spring-boot-starter/build.gradle +++ b/src/grpc/grpc-spring-boot-starter/build.gradle @@ -18,4 +18,6 @@ dependencies { implementation 'org.springframework.boot:spring-boot-autoconfigure' + // The shared operation-ledger fake stands in for the adopter's ledger bean in context tests. + testImplementation testFixtures(project(':grpc:grpc-core-api')) } diff --git a/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfiguration.java b/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfiguration.java index 85169398..02eddcad 100644 --- a/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfiguration.java +++ b/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfiguration.java @@ -5,15 +5,20 @@ import dev.caskeleton.grpc.admin.GrpcDrainPolicy; import dev.caskeleton.grpc.admin.GrpcHealthPolicy; import dev.caskeleton.grpc.admin.GrpcReflectionPolicy; import dev.caskeleton.grpc.admin.GrpcServiceHealthRegistry; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; import dev.caskeleton.grpc.api.policy.GrpcMethodPolicyCatalog; import dev.caskeleton.grpc.client.GrpcNamedChannelProfile; import dev.caskeleton.grpc.context.GrpcContextBinder; import dev.caskeleton.grpc.context.GrpcContextPropagationPolicy; import dev.caskeleton.grpc.error.GrpcErrorMapper; +import dev.caskeleton.grpc.idempotency.GrpcIdempotencyInterceptor; +import dev.caskeleton.grpc.idempotency.GrpcOperationLedgerRetention; import dev.caskeleton.grpc.security.GrpcTlsProfile; import dev.caskeleton.grpc.server.GrpcAdmissionController; import dev.caskeleton.grpc.server.GrpcExecutorProfile; import dev.caskeleton.grpc.server.GrpcServerProfile; +import java.time.Duration; +import java.util.List; import java.util.UUID; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.SmartInitializingSingleton; @@ -131,6 +136,89 @@ public class GrpcPlatformAutoConfiguration { serverProfile); } + /** + * The keyed-idempotency decision, assembled when {@code operation-ledger-enabled=true}. + * + *

        Built here rather than left to the adopter (review 2026-11-01, 03-11, option (b)): a flag + * that only satisfied the startup check while nothing honoured the key was a promise the platform + * did not keep. The ledger itself stays the deployment's bean — the starter does not depend on + * {@code grpc-operation-ledger-jpa} (11-M9) — and a missing one refuses startup. + * + *

        A duplicate of a running operation is refused rather than told to wait: keyed callers are + * usually user-facing requests that already retry with backoff. There is deliberately no + * {@code @ConditionalOnMissingBean}: a replacement bean would silently ignore {@code + * operation-ledger-claim-ttl}, which is the same false promise this bean exists to remove. + * + *

        The starter does not build a server, so nothing calls this yet: the adopter's {@code + * IDEMPOTENCY} stage interceptor ({@code GrpcServerInterceptorChain}) or service adapter calls + * {@code decide} before the mutation and {@code recordCommit} inside the mutation's transaction. + */ + @Bean + @ConditionalOnProperty( + prefix = "app.grpc.platform", + name = "operation-ledger-enabled", + havingValue = "true") + public GrpcIdempotencyInterceptor grpcIdempotencyInterceptor( + GrpcPlatformProperties properties, + ObjectProvider ledgers, + ObjectProvider catalogs) { + GrpcOperationLedger ledger = requireLedger(ledgers); + try { + return new GrpcIdempotencyInterceptor( + ledger, + catalogs.getIfAvailable(() -> GrpcMethodPolicyCatalog.builder().build()), + Duration.ZERO, + false, + properties.getOperationLedgerClaimTtl()); + } catch (IllegalArgumentException invalidTtl) { + // The ledger and catalog are present and the poll interval is fixed, so the claim TTL is the + // only input left for the constructor to refuse. + throw new GrpcPlatformConfigurationException( + List.of("app.grpc.platform.operation-ledger-claim-ttl: " + invalidTtl.getMessage())); + } + } + + /** + * Retention of finished ledger records, assembled with the interceptor. + * + *

        Only the policy: nothing here schedules it. The starter owns no scheduler and does not know + * which replica should run the purge, so the adopter calls {@code purgeExpired(now)} from its own + * scheduler. A scheduled bean here was rejected because it would force a task scheduler onto + * every deployment and run on every replica whether or not that deployment wants it. + */ + @Bean + @ConditionalOnProperty( + prefix = "app.grpc.platform", + name = "operation-ledger-enabled", + havingValue = "true") + public GrpcOperationLedgerRetention grpcOperationLedgerRetention( + GrpcPlatformProperties properties, ObjectProvider ledgers) { + GrpcOperationLedger ledger = requireLedger(ledgers); + try { + return new GrpcOperationLedgerRetention( + ledger, + properties.getOperationLedgerRetention(), + GrpcOperationLedgerRetention.DEFAULT_BATCH_SIZE); + } catch (IllegalArgumentException invalidRetention) { + throw new GrpcPlatformConfigurationException( + List.of( + "app.grpc.platform.operation-ledger-retention: " + invalidRetention.getMessage())); + } + } + + private static GrpcOperationLedger requireLedger(ObjectProvider ledgers) { + GrpcOperationLedger ledger = ledgers.getIfAvailable(); + if (ledger == null) { + throw new GrpcPlatformConfigurationException( + List.of( + "app.grpc.platform.operation-ledger-enabled=true but there is no GrpcOperationLedger" + + " bean; the starter does not bring one. Add :grpc:grpc-operation-ledger-jpa and" + + " define a JpaGrpcOperationLedger bean (with the db/migration/grpc Flyway" + + " location), or turn the flag off")); + } + return ledger; + } + /** The shared error mapper. Its execution ids are random and carry no derived content. */ @Bean @ConditionalOnMissingBean diff --git a/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformProperties.java b/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformProperties.java index c480573d..3d3a73b6 100644 --- a/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformProperties.java +++ b/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformProperties.java @@ -3,6 +3,7 @@ package dev.caskeleton.grpc.boot; import dev.caskeleton.grpc.admin.GrpcReflectionMode; import dev.caskeleton.grpc.security.GrpcTlsProfile; import dev.caskeleton.grpc.server.GrpcServerTransport; +import java.time.Duration; import org.springframework.boot.context.properties.ConfigurationProperties; /** @@ -49,9 +50,32 @@ public class GrpcPlatformProperties { /** The bounded executor's maximum size. */ private int executorMaxPoolSize = 32; - /** Whether the operation ledger is available, which gates keyed idempotency. */ + /** + * Whether keyed idempotency runs. When true the starter assembles {@code + * GrpcIdempotencyInterceptor} and {@code GrpcOperationLedgerRetention} over the deployment's + * {@code GrpcOperationLedger} bean, and refuses to start without one; the starter never brings a + * ledger implementation itself. When false, a method that requires an idempotency key is refused + * at startup, because the key would be accepted and never honoured. + */ private boolean operationLedgerEnabled; + /** + * How long an {@code IN_PROGRESS} claim is trusted to have a live owner before a retry of the + * same request takes it over. Five minutes: far beyond a unary deadline (the interceptor refuses + * a TTL not longer than every keyed method's deadline), so a slow but live owner is not + * overtaken, and short enough that a key whose owner died unblocks within a client's normal retry + * patience. It is also the value the ledger contract and interceptor tests certify. + */ + private Duration operationLedgerClaimTtl = Duration.ofMinutes(5); + + /** + * How long a finished ({@code COMMITTED} or {@code FAILED_TERMINAL}) ledger record is kept before + * {@code GrpcOperationLedgerRetention} may delete it. A retry of the same key after that is a new + * operation, so this must exceed the callers' retry window. 24 hours, matching the HTTP + * idempotency replay TTL ({@code app.capabilities.idempotency.replay-ttl}). + */ + private Duration operationLedgerRetention = Duration.ofHours(24); + public boolean isEnabled() { return enabled; } @@ -124,6 +148,22 @@ public class GrpcPlatformProperties { this.operationLedgerEnabled = operationLedgerEnabled; } + public Duration getOperationLedgerClaimTtl() { + return operationLedgerClaimTtl; + } + + public void setOperationLedgerClaimTtl(Duration operationLedgerClaimTtl) { + this.operationLedgerClaimTtl = operationLedgerClaimTtl; + } + + public Duration getOperationLedgerRetention() { + return operationLedgerRetention; + } + + public void setOperationLedgerRetention(Duration operationLedgerRetention) { + this.operationLedgerRetention = operationLedgerRetention; + } + /** * The reflection mode this deployment runs, defaulting to the environment's floor, and to * disabled while the environment is unset (the startup check refuses that state). diff --git a/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java b/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java index 1f1a4dec..a2892787 100644 --- a/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java +++ b/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java @@ -151,8 +151,8 @@ public final class GrpcPlatformStartupValidator { violations.add( "method '" + method.canonical() - + "' requires an idempotency key but no operation ledger is enabled; the key would " - + "be accepted and never honoured"); + + "' requires an idempotency key but app.grpc.platform.operation-ledger-enabled is" + + " false; the key would be accepted and never honoured"); } if (!policy.rpcType().stable()) { violations.add( diff --git a/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java b/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java index 6957096b..a07b65b2 100644 --- a/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java +++ b/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java @@ -4,13 +4,41 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile; +import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; +import dev.caskeleton.grpc.api.ledger.InMemoryOperationLedger; +import dev.caskeleton.grpc.api.policy.GrpcMethodPolicy; +import dev.caskeleton.grpc.api.policy.GrpcMethodPolicyCatalog; +import dev.caskeleton.grpc.api.policy.RpcIdempotencyProfile; +import dev.caskeleton.grpc.api.policy.WaitForReadyPolicy; +import dev.caskeleton.grpc.core.GrpcMethodName; +import dev.caskeleton.grpc.core.RpcType; +import dev.caskeleton.grpc.idempotency.GrpcIdempotencyDecision; +import dev.caskeleton.grpc.idempotency.GrpcIdempotencyInterceptor; +import dev.caskeleton.grpc.idempotency.GrpcOperationLedgerRetention; +import dev.caskeleton.grpc.idempotency.GrpcRequestFingerprint; +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import org.springframework.core.env.MapPropertySource; class GrpcPlatformAutoConfigurationContextTest { + private static final GrpcMethodName CREATE = + GrpcMethodName.parse("caskeleton.document.v1.DocumentService/CreateDocument"); + private static final Duration KEYED_DEADLINE = Duration.ofSeconds(10); + private static final String CALLER = "tenant-1|actor-1"; + private static final String KEY = "order-2026-0001"; + private static final Instant NOW = Instant.parse("2026-11-01T10:00:00Z"); + @Test void invalidProductionSecurityFailsDuringActualAutoConfigurationStartup() { assertThatThrownBy( @@ -77,12 +105,169 @@ class GrpcPlatformAutoConfigurationContextTest { } } - private static AnnotationConfigApplicationContext start(Map properties) { + @Test + @DisplayName("ledger 플래그가 켜져 있고 ledger bean이 있으면 멱등성 interceptor가 조립된다") + void anEnabledLedgerWithALedgerBeanAssemblesTheIdempotencyInterceptor() { + // when + try (AnnotationConfigApplicationContext context = + start(ledgerEnabled(Map.of()), KeyedMethodWithLedger.class)) { + + // then + assertThat(context.getBeansOfType(GrpcIdempotencyInterceptor.class)).hasSize(1); + } + } + + @Test + @DisplayName("ledger 플래그가 켜져 있는데 ledger bean이 없으면 기동을 거부한다") + void anEnabledLedgerWithoutALedgerBeanRefusesToStart() { + // when + Throwable failure = catchThrowable(() -> start(ledgerEnabled(Map.of()), KeyedMethod.class)); + + // then + assertThat(failure) + .rootCause() + .isInstanceOf(GrpcPlatformConfigurationException.class) + .hasMessageContaining("app.grpc.platform.operation-ledger-enabled=true") + .hasMessageContaining("no GrpcOperationLedger bean"); + } + + @Test + @DisplayName("ledger 플래그가 꺼져 있으면 멱등성 interceptor와 보존 정리를 만들지 않는다") + void aDisabledLedgerAssemblesNoIdempotencyInterceptorOrRetention() { + // when + try (AnnotationConfigApplicationContext context = + start(localPlatform(Map.of()), LedgerOnly.class)) { + + // then + assertThat(context.getBeansOfType(GrpcIdempotencyInterceptor.class)).isEmpty(); + assertThat(context.getBeansOfType(GrpcOperationLedgerRetention.class)).isEmpty(); + } + } + + @Test + @DisplayName("claim-ttl 설정이 interceptor의 stale claim 판단에 쓰인다") + void theClaimTtlKeyDecidesWhenAnInProgressClaimIsTakenOver() { + // given + try (AnnotationConfigApplicationContext context = + start( + ledgerEnabled(Map.of("app.grpc.platform.operation-ledger-claim-ttl", "1m")), + KeyedMethodWithLedger.class)) { + GrpcIdempotencyInterceptor interceptor = context.getBean(GrpcIdempotencyInterceptor.class); + String body = GrpcRequestFingerprint.of("body"); + interceptor.decide(CREATE, CALLER, KEY, body, NOW); + + // when + GrpcIdempotencyDecision retry = + interceptor.decide(CREATE, CALLER, KEY, body, NOW.plus(Duration.ofSeconds(61))); + + // then + assertThat(retry.outcome()).isEqualTo(GrpcIdempotencyDecision.Outcome.PROCEED); + } + } + + @Test + @DisplayName("claim-ttl이 keyed method의 deadline보다 길지 않으면 기동을 거부한다") + void aClaimTtlWithinAKeyedDeadlineRefusesToStart() { + // when + Throwable failure = + catchThrowable( + () -> + start( + ledgerEnabled(Map.of("app.grpc.platform.operation-ledger-claim-ttl", "10s")), + KeyedMethodWithLedger.class)); + + // then + assertThat(failure) + .rootCause() + .isInstanceOf(GrpcPlatformConfigurationException.class) + .hasMessageContaining("app.grpc.platform.operation-ledger-claim-ttl") + .hasMessageContaining("CreateDocument"); + } + + @Test + @DisplayName("retention 설정이 지난 종결 행을 보존 정리가 지운다") + void theRetentionKeyDecidesWhichFinishedRecordsArePurged() { + // given + try (AnnotationConfigApplicationContext context = + start( + ledgerEnabled(Map.of("app.grpc.platform.operation-ledger-retention", "1h")), + KeyedMethodWithLedger.class)) { + GrpcOperationLedger ledger = context.getBean(GrpcOperationLedger.class); + GrpcOperationIdentity identity = + new GrpcOperationIdentity(CALLER, CREATE, GrpcRequestFingerprint.hashIdempotencyKey(KEY)); + ledger.claim(identity, GrpcRequestFingerprint.of("body"), NOW); + ledger.markCommitted(identity, "outcome://document/42", NOW.plusSeconds(1)); + + // when + int purged = + context + .getBean(GrpcOperationLedgerRetention.class) + .purgeExpired(NOW.plus(Duration.ofHours(2))); + + // then + assertThat(purged).isEqualTo(1); + assertThat(ledger.find(identity)).isEmpty(); + } + } + + private static Map localPlatform(Map extra) { + Map properties = new HashMap<>(); + properties.put("app.grpc.platform.enabled", "true"); + properties.put("app.grpc.platform.environment", "LOCAL"); + properties.put("app.grpc.platform.transport", "NETTY_SHADED"); + properties.putAll(extra); + return properties; + } + + private static Map ledgerEnabled(Map extra) { + Map properties = new HashMap<>(extra); + properties.put("app.grpc.platform.operation-ledger-enabled", "true"); + return localPlatform(properties); + } + + /** One keyed method with a 10-second deadline, the shape the claim TTL is measured against. */ + @Configuration(proxyBeanMethods = false) + static class KeyedMethod { + @Bean + GrpcMethodPolicyCatalog keyedCatalog() { + return GrpcMethodPolicyCatalog.builder() + .register( + new GrpcMethodPolicy( + CREATE, + RpcType.UNARY, + RpcIdempotencyProfile.IDEMPOTENCY_KEY_REQUIRED, + GrpcDeadlineProfile.of(KEYED_DEADLINE), + WaitForReadyPolicy.DISABLED, + true, + 1024, + 1024)) + .build(); + } + } + + /** The adopter's ledger, here the shared in-memory fake. */ + @Configuration(proxyBeanMethods = false) + static class LedgerOnly { + @Bean + GrpcOperationLedger operationLedger() { + return new InMemoryOperationLedger(); + } + } + + @Configuration(proxyBeanMethods = false) + @Import({KeyedMethod.class, LedgerOnly.class}) + static class KeyedMethodWithLedger {} + + private static AnnotationConfigApplicationContext start( + Map properties, Class... adopterConfigurations) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context .getEnvironment() .getPropertySources() .addFirst(new MapPropertySource("grpc-platform-test", properties)); + if (adopterConfigurations.length > 0) { + context.register(adopterConfigurations); + } context.register(GrpcPlatformAutoConfiguration.class); try { context.refresh(); diff --git a/src/messaging/messaging-kafka/build.gradle b/src/messaging/messaging-kafka/build.gradle index 00c9892e..cfa3122a 100644 --- a/src/messaging/messaging-kafka/build.gradle +++ b/src/messaging/messaging-kafka/build.gradle @@ -71,10 +71,10 @@ strictTestLanes { // floating tag would make a red run unattributable and a green one unrepeatable. // `-PmessagingKafkaImage=` overrides for a one-off run against another version. systemProperty 'messaging.kafka.image', - (project.findProperty('messagingKafkaImage') ?: 'apache/kafka:4.1.0').toString() + (project.findProperty('messagingKafkaImage') ?: testContainerImages['kafka']).toString() systemProperty 'messaging.toxiproxy.image', (project.findProperty('messagingToxiproxyImage') - ?: 'ghcr.io/shopify/toxiproxy:2.12.0').toString() + ?: testContainerImages['toxiproxy']).toString() systemProperty 'messaging.certification.manifest', project.layout.buildDirectory .file('messaging-certification/broker-certification-evidence.jsonl') diff --git a/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaAmbiguityChaosIT.java b/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaAmbiguityChaosIT.java index 21b4561b..e2787738 100644 --- a/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaAmbiguityChaosIT.java +++ b/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaAmbiguityChaosIT.java @@ -56,7 +56,9 @@ class KafkaAmbiguityChaosIT { private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z"); - @Container private static final KafkaContainer KAFKA = new KafkaContainer("apache/kafka:4.1.0"); + @Container + private static final KafkaContainer KAFKA = + new KafkaContainer(System.getProperty("ca.test.image.kafka")); static boolean dockerAvailable() { return DockerAvailability.isAvailable(); diff --git a/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaBrokerCertificationIT.java b/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaBrokerCertificationIT.java index 7a1dff71..beec17d2 100644 --- a/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaBrokerCertificationIT.java +++ b/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaBrokerCertificationIT.java @@ -92,10 +92,11 @@ class KafkaBrokerCertificationIT { * latest} resolved to that morning". */ private static final String IMAGE = - System.getProperty("messaging.kafka.image", "apache/kafka:4.1.0"); + System.getProperty("messaging.kafka.image", System.getProperty("ca.test.image.kafka")); private static final String TOXIPROXY_IMAGE = - System.getProperty("messaging.toxiproxy.image", "ghcr.io/shopify/toxiproxy:2.12.0"); + System.getProperty( + "messaging.toxiproxy.image", System.getProperty("ca.test.image.toxiproxy")); /** The in-network listener the proxy forwards to. */ private static final int BROKER_PORT = 19092; diff --git a/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaBrokerIT.java b/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaBrokerIT.java index 89db8a62..ac3cec45 100644 --- a/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaBrokerIT.java +++ b/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaBrokerIT.java @@ -71,7 +71,9 @@ class KafkaBrokerIT { private static final String DEAD_LETTER_TOPIC = "order.events.v1.dlt"; private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z"); - @Container private static final KafkaContainer KAFKA = new KafkaContainer("apache/kafka:4.1.0"); + @Container + private static final KafkaContainer KAFKA = + new KafkaContainer(System.getProperty("ca.test.image.kafka")); private Producer producer; private Consumer consumer; diff --git a/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaContainerFixture.java b/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaContainerFixture.java index 9fb2e018..9d6b1a4c 100644 --- a/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaContainerFixture.java +++ b/src/messaging/messaging-kafka/src/integrationTest/java/dev/caskeleton/messaging/kafka/KafkaContainerFixture.java @@ -35,7 +35,7 @@ import org.testcontainers.kafka.KafkaContainer; */ final class KafkaContainerFixture { - private static final String IMAGE = "apache/kafka:4.1.0"; + private static final String IMAGE = System.getProperty("ca.test.image.kafka"); private static KafkaContainer container; diff --git a/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/inbox/InboxPostgresIT.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/inbox/InboxPostgresIT.java index 899707c0..2ec95ce0 100644 --- a/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/inbox/InboxPostgresIT.java +++ b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/inbox/InboxPostgresIT.java @@ -45,7 +45,7 @@ class InboxPostgresIT { @SuppressWarnings("resource") @Container private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer("postgres:16-alpine") + new PostgreSQLContainer(System.getProperty("ca.test.image.postgres-16")) .withDatabaseName("messaging") .withUsername("messaging") .withPassword("messaging"); diff --git a/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/AdminOperationJournalPostgresIT.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/AdminOperationJournalPostgresIT.java index 7752598e..5af7f49c 100644 --- a/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/AdminOperationJournalPostgresIT.java +++ b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/AdminOperationJournalPostgresIT.java @@ -50,7 +50,7 @@ class AdminOperationJournalPostgresIT { @SuppressWarnings("resource") @Container private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer("postgres:16-alpine") + new PostgreSQLContainer(System.getProperty("ca.test.image.postgres-16")) .withDatabaseName("messaging") .withUsername("messaging") .withPassword("messaging"); diff --git a/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java index 16becff1..388707d5 100644 --- a/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java +++ b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java @@ -51,7 +51,7 @@ class OutboxPostgresIT { @SuppressWarnings("resource") @Container private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer("postgres:16-alpine") + new PostgreSQLContainer(System.getProperty("ca.test.image.postgres-16")) .withDatabaseName("messaging") .withUsername("messaging") .withPassword("messaging"); diff --git a/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingKafkaConsumeQualificationTest.java b/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingKafkaConsumeQualificationTest.java index 7083bc63..13ad8fcb 100644 --- a/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingKafkaConsumeQualificationTest.java +++ b/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingKafkaConsumeQualificationTest.java @@ -97,13 +97,14 @@ class MessagingKafkaConsumeQualificationTest { private static final MessageType CREATED = new MessageType("order.created"); - @Container static final KafkaContainer KAFKA = new KafkaContainer("apache/kafka:4.1.0"); + @Container + static final KafkaContainer KAFKA = new KafkaContainer(System.getProperty("ca.test.image.kafka")); // @Container: the Testcontainers JUnit extension owns this lifecycle. @SuppressWarnings("resource") @Container static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer("postgres:16-alpine") + new PostgreSQLContainer(System.getProperty("ca.test.image.postgres-16")) .withDatabaseName("messaging") .withUsername("messaging") .withPassword("messaging"); diff --git a/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingLiveRoundTripQualificationTest.java b/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingLiveRoundTripQualificationTest.java index 42c1d157..a4d96044 100644 --- a/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingLiveRoundTripQualificationTest.java +++ b/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingLiveRoundTripQualificationTest.java @@ -63,7 +63,8 @@ class MessagingLiveRoundTripQualificationTest { // membership against 3.8.0 proved the membership on a broker two minors below the one the matrix // calls certified, so the one test that decides whether the starter may reach a deployment's // classpath was the only one not run against what a deployment gets. - @Container static final KafkaContainer KAFKA = new KafkaContainer("apache/kafka:4.1.0"); + @Container + static final KafkaContainer KAFKA = new KafkaContainer(System.getProperty("ca.test.image.kafka")); static boolean dockerAvailable() { return DockerClientFactory.instance().isDockerAvailable(); diff --git a/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingSecuredBrokerQualificationTest.java b/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingSecuredBrokerQualificationTest.java index 5e823a32..8a081ccd 100644 --- a/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingSecuredBrokerQualificationTest.java +++ b/src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/autoconfigure/MessagingSecuredBrokerQualificationTest.java @@ -43,7 +43,7 @@ import org.testcontainers.utility.MountableFile; @EnabledIf(value = "dockerAvailable", disabledReason = "Docker not available for the live broker") class MessagingSecuredBrokerQualificationTest { - private static final String IMAGE = "apache/kafka:4.1.0"; + private static final String IMAGE = System.getProperty("ca.test.image.kafka"); private static final String BROKER_USER = "svc-orders"; diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingReliabilityAutoConfiguration.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingReliabilityAutoConfiguration.java index f6e096ac..7696cde5 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingReliabilityAutoConfiguration.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingReliabilityAutoConfiguration.java @@ -1,6 +1,7 @@ package dev.caskeleton.messaging.autoconfigure; import dev.caskeleton.messaging.api.publish.MessagePublisher; +import dev.caskeleton.messaging.inbox.IdempotentConsumer; import dev.caskeleton.messaging.inbox.InboxCleanupJob; import dev.caskeleton.messaging.inbox.InboxRetentionPolicy; import dev.caskeleton.messaging.outbox.OutboxCleanupJob; @@ -180,6 +181,27 @@ public class MessagingReliabilityAutoConfiguration { return new InboxRetentionPolicy(InboxRetentionPolicy.DEFAULT_RETENTION, Duration.ofDays(1)); } + /** + * Returns the inbox runner that {@code INBOX_TRANSACTIONAL} destinations wrap their handlers in + * ({@link MessagingConsumeConfiguration}). + * + *

        Assembled from the two parts the platform cannot supply itself, like every bean here: the + * application's inbox repository and the runner that opens the application's transaction, so the + * reservation and the handler's side effect commit or roll back together. Without both, an {@code + * INBOX_TRANSACTIONAL} destination still refuses to start. + * + * @param inbox the application's inbox repository + * @param transactions runs work in the application's transaction + * @return the idempotent consumer + */ + @Bean + @ConditionalOnBean({InboxRepository.class, IdempotentConsumer.TransactionRunner.class}) + @ConditionalOnMissingBean + public IdempotentConsumer idempotentConsumer( + InboxRepository inbox, IdempotentConsumer.TransactionRunner transactions) { + return new IdempotentConsumer(inbox, transactions); + } + /** * Returns the inbox cleanup job. * diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingShutdownLifecycle.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingShutdownLifecycle.java index 0229f135..7efaa471 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingShutdownLifecycle.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingShutdownLifecycle.java @@ -30,6 +30,13 @@ import org.springframework.context.SmartLifecycle; public final class MessagingShutdownLifecycle implements SmartLifecycle { /** How often the drain is re-checked. Short enough that a fast drain is not padded. */ + /** + * The phase this drain stops in: {@link #getPhase()}. Public so a relay outside the platform — + * the application's own outbox relay, which may not name this type in production code — can be + * held above it by a test that does name it. + */ + public static final int PHASE = Integer.MAX_VALUE - 1024; + private static final Duration POLL = Duration.ofMillis(50); private final MessagingAdmissionController admission; @@ -111,14 +118,18 @@ public final class MessagingShutdownLifecycle implements SmartLifecycle { * *

        {@code SmartLifecycle} stops in descending phase order. A phase above the default puts this * drain ahead of the transports it is draining, because closing a connection first would strand - * the settlements the drain exists to flush. It sits below the outbox relay's phase for the + * the settlements the drain exists to flush. It sits below the outbox relays' phase for the * mirror-image reason: refusing admission while a relay pass is mid-publish turns that pass's - * rows ambiguous, which is the uncertainty the drain exists to avoid. + * rows into refusals. Two relays stand above it: the platform's own ({@code + * MessagingOutboxRelayLifecycle}, built only when a platform outbox repository exists) and the + * application's ({@code composition:outbox-relay} {@code OutboxRelayScheduler}, phase {@code + * Integer.MAX_VALUE}), which finishes the publish it is in and releases its other claims before + * this phase runs. * - * @return the lifecycle phase + * @return the lifecycle phase, {@link #PHASE} */ @Override public int getPhase() { - return Integer.MAX_VALUE - 1024; + return PHASE; } } diff --git a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingInboxAssemblyTest.java b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingInboxAssemblyTest.java new file mode 100644 index 00000000..1bc1271a --- /dev/null +++ b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingInboxAssemblyTest.java @@ -0,0 +1,68 @@ +package dev.caskeleton.messaging.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.messaging.api.MessageId; +import dev.caskeleton.messaging.inbox.IdempotentConsumer; +import dev.caskeleton.messaging.reliability.InboxRepository; +import java.time.Instant; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +/** + * The platform assembles its inbox runner from the two parts only the application can supply + * (review 06-08): nothing assembled it before, so an INBOX_TRANSACTIONAL destination could only + * refuse to start. + */ +class MessagingInboxAssemblyTest { + + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withUserConfiguration(MessagingReliabilityAutoConfiguration.class); + + @Test + @DisplayName("애플리케이션이 inbox 저장소와 트랜잭션 runner를 주면 platform이 IdempotentConsumer를 만든다") + void theApplicationsInboxPartsAssembleTheIdempotentConsumer() { + // when & then + runner + .withBean(InboxRepository.class, NoInbox::new) + .withBean(IdempotentConsumer.TransactionRunner.class, () -> Runner.DIRECT) + .run(context -> assertThat(context).hasSingleBean(IdempotentConsumer.class)); + } + + @Test + @DisplayName("트랜잭션 runner가 없으면 IdempotentConsumer를 만들지 않는다") + void withoutTheApplicationsTransactionNoIdempotentConsumerIsAssembled() { + // when & then + runner + .withBean(InboxRepository.class, NoInbox::new) + .run(context -> assertThat(context).doesNotHaveBean(IdempotentConsumer.class)); + } + + private enum Runner implements IdempotentConsumer.TransactionRunner { + DIRECT; + + @Override + public T inTransaction(java.util.function.Supplier work) { + return work.get(); + } + } + + private static final class NoInbox implements InboxRepository { + @Override + public boolean reserve(MessageId messageId, String consumerId, Instant now) { + return true; + } + + @Override + public boolean isProcessed(MessageId messageId, String consumerId) { + return false; + } + + @Override + public int purgeProcessedBefore(Instant processedBefore, int limit) { + return 0; + } + } +} diff --git a/src/optional-platforms/gradle.properties b/src/optional-platforms/gradle.properties new file mode 100644 index 00000000..0d1f5861 --- /dev/null +++ b/src/optional-platforms/gradle.properties @@ -0,0 +1,9 @@ +# optional-platforms is a build of its own (`./gradlew -p optional-platforms ...`), and Gradle reads +# gradle.properties from the build's root directory only, so src/gradle.properties never reached it: +# the optional build ran serially and without the build cache (review 2026-11-01 08-06). +# The values and their reasons are src/gradle.properties'. settings.gradle fails the build when the +# two files disagree, so this is a copy that cannot drift, not a second source. +org.gradle.workers.max=4 +org.gradle.jvmargs=-Xmx1g -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8 +org.gradle.caching=true +org.gradle.parallel=true diff --git a/src/optional-platforms/settings.gradle b/src/optional-platforms/settings.gradle index cf08c106..a34cfb8d 100644 --- a/src/optional-platforms/settings.gradle +++ b/src/optional-platforms/settings.gradle @@ -19,3 +19,18 @@ dependencyResolutionManagement { } rootProject.name = 'optional-platforms' + +// gradle.properties here must say what src/gradle.properties says (review 2026-11-01 08-06): Gradle +// reads only this build's own file, and a copy that drifted would make the optional build quietly +// slower or differently configured than the main one. +def readBuildProperties = { File file -> + def properties = new Properties() + file.withInputStream { properties.load(it) } + properties +} +def mainBuildProperties = readBuildProperties(new File(settingsDir, '../gradle.properties')) +def ownBuildProperties = readBuildProperties(new File(settingsDir, 'gradle.properties')) +if (mainBuildProperties != ownBuildProperties) { + throw new GradleException("optional-platforms/gradle.properties differs from src/gradle.properties: " + + "${ownBuildProperties} vs ${mainBuildProperties}. Copy the main build's values.") +} diff --git a/src/sample-portfolio/README.md b/src/sample-portfolio/README.md index 84124b88..abb91fae 100644 --- a/src/sample-portfolio/README.md +++ b/src/sample-portfolio/README.md @@ -26,7 +26,7 @@ | GET | /api/worklogs | 목록 (메인) | 없음(공개) | Envelope wrap | | GET | /api/worklogs/{id} | 상세 | 없음(공개) | 도메인 예외→404 envelope | | POST | /api/worklogs | 생성 | `worklog:write` | Bean Validation @GroupSequence (B4), unknown-field 거부 (B1), mapper 실패→MAPPING_FAILED (B3) | -| PATCH | /api/worklogs/{id} | 부분수정 | `worklog:write` | JsonNullable 3-state (B2) | +| PATCH | /api/worklogs/{id} | 부분수정 | `worklog:write` + 소유자 본인 | JsonNullable 3-state (B2), 남의 기록이면 403 `WORKLOG_NOT_OWNER` | | DELETE | /api/worklogs/{id} | 삭제 | `worklog:close` | 204 | | POST | /api/worklogs:batchCreate | 일괄 등록 | `worklog:write` | 동기 = 원자적(한 항목 실패 → 전체 롤백, 단일 4xx) | @@ -39,8 +39,11 @@ | 계정 | 비밀번호 | 역할 | 할 수 있는 것 | | --- | --- | --- | --- | -| `demo-user` | `demo-user` | `user` | 읽기, 생성, 수정. 삭제는 403 | -| `demo-admin` | `demo-admin` | `admin` | 위 전부 + 삭제 | +| `demo-user` | `demo-user` | `user` | 읽기, 생성, 자기 기록 수정. 삭제는 403 | +| `demo-admin` | `demo-admin` | `admin` | 읽기, 생성, 자기 기록 수정, 삭제 | + +수정은 권한(`worklog:write`)과 소유자를 둘 다 봅니다. `demo-admin` 도 `demo-user` 가 만든 기록은 +고칠 수 없습니다(403 `WORKLOG_NOT_OWNER`). 삭제는 관리 작업이라 소유자를 보지 않습니다. 비밀번호가 문서에 적혀 있는 공개 데모 계정입니다. 비밀이 아니며, 실제 서비스는 이 방식을 쓰지 않고 `adapter:inbound:web`의 JWT 체인으로 인증합니다. @@ -71,6 +74,25 @@ curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type }' ``` +## 복제해도 되는 모양 — 새 기능이 따라 할 것 + +이 샘플은 새 기능이 베껴 가는 예시입니다. 아래 다섯은 리뷰(2026-11-01 성숙도 리뷰 09·01·04 영역)에서 +실측으로 문제를 확인하고 고친 모양이라, 그대로 복제해도 안전합니다. 각 항목의 근거는 아래 「설계 결정 +참조」에 있습니다. + +| 할 일 | 이 샘플의 모양 | 피한 함정 | +| --- | --- | --- | +| 목록 조회 | 요약 projection(`WorkLogSummaryQueryPort.findPage`) 한 쿼리 + count | 애그리거트를 통째로 읽으면 항목마다 컬렉션 쿼리 2개(20건에 SQL 42개, 100건에 202개) | +| 수정 저장 | 읽어 둔 관리 엔티티에 바뀐 값만 덮어쓰기(`WorkLogRepositoryAdapter.update`) | 새 엔티티를 merge 하면 제목 하나 고쳐도 자식 테이블 전부 삭제·재삽입 | +| 남의 리소스 수정 | 권한 검사 + 유스케이스 안 소유자 검사(`UpdateWorkLogUseCase`) | 권한만 보면 `worklog:write` 가진 누구나 남의 기록을 고침 | +| 유일해야 하는 값 | DB 유일 인덱스가 규칙을 지키고 위반을 도메인 409 로 변환(생성·수정 둘 다) | 사전 조회만으로는 동시 요청에서 중복 행 | +| 동기 일괄 쓰기 | 건수 상한 + JDBC batch(`application.yml`), 상한·왕복 수를 테스트로 고정 | 행마다 왕복하는 동안 커넥션 하나를 오래 잡음(자식 컬렉션 행은 아직 항목당 왕복 — 아래 BatchCreate 절) | + +이 다섯은 테스트로 고정돼 있습니다: `WorkLogStatementCostSystemTest`(목록 SQL 수가 페이지 크기와 +무관, 제목만 고친 PATCH 의 자식 테이블 쓰기 0), `SampleWorkLogAuthorizationSystemTest`(남의 기록 PATCH +403), `PosterRepositoryAdapterIntegrationTest`(다른 포스터 제목으로 바꾸면 409), +`WorkLogStatementCostSystemTest.batchCreate…`(일괄 생성 JDBC 왕복 수). + ## 계층 (adapter-mirrored) - `domain/worklog` — WorkLog/WorkCategory/Period/RepoStats/WorkLogRepository (POJO) - `application/<기능>` — 기능별 패키지(review S6-#10a): `worklog`(대표 예제), `poster`, @@ -145,12 +167,13 @@ curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type 타입을 일절 참조하지 않습니다. 이것을 발행 가능한 integration 이벤트로 바꾸는 일은 application 경계의 몫입니다(`application.worklog.WorkLogReservedPayload` 와 `application.event.PortfolioEventOutbox` 참고). -### 포트 — WorkLogRepository / WorkLogIdFactory / OutboxEventIdFactory +### 포트 — WorkLogRepository / WorkLogIdFactory (도메인), OutboxEventIdFactory (application) - **WorkLogRepository**: WorkLog 영속 아웃바운드 포트(구현은 adapter-persistence). `findPage` 는 한 페이지 + 전체 개수를 함께 돌려주며, `sortField`/`category` 가 `null` 이면 정렬/필터 없음을 뜻합니다. 전체 개수는 같은 필터 기준으로 세어 `meta.page.total` 이 필터된 결과를 반영하게 합니다. -- **WorkLogIdFactory / OutboxEventIdFactory**: id 를 만들어 주는 도메인 포트. 둘을 **굳이 따로 둔 - 이유**는, 애그리거트 식별자 타입(`WorkLogId`)이 이벤트 id 모양을 묶어버리지 않게 하기 위해서입니다. +- **WorkLogIdFactory / OutboxEventIdFactory**: id 를 만들어 주는 포트. `WorkLogIdFactory`는 도메인 + 포트이고, `OutboxEventIdFactory`는 `application.event`에 있다 — outbox는 도메인 개념이 아니고 + 쓰는 곳이 `PortfolioEventOutbox`뿐이기 때문이다. 둘을 **굳이 따로 둔 이유**는, 애그리거트 식별자 타입(`WorkLogId`)이 이벤트 id 모양을 묶어버리지 않게 하기 위해서입니다. 실제로는 둘 다 UUIDv7 기반이지만(identifier 어댑터가 구현), 도메인은 생성 방식을 모릅니다. outbox 이벤트 id 는 envelope 의 `eventId` 이고, consumer 는 이 값으로 중복을 거릅니다(이벤트 단위 중복 제거). @@ -195,8 +218,34 @@ curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type 처리하므로 한 항목이라도(매핑/검증/영속) 실패하면 배치 전체가 되돌려지고, 엔드포인트는 부분 성공 대신 단일 4xx 를 냅니다. (`BATCH_PARTIAL_FAILURE` 같은 부분 실패 형태는 비동기 폴링 응답용으로 예약돼 있고, 동기 배치에는 쓰지 않습니다.) +- **크기와 트랜잭션.** 상한은 `MAX_BATCH_SIZE`(1000)이고, 1000건도 한 트랜잭션입니다. 트랜잭션을 나누면 + "전부 아니면 전무" 계약이 깨지므로 나누지 않았습니다. 대신 행 단위 왕복을 줄였습니다: 샘플 + `application.yml` 이 `hibernate.jdbc.batch_size=50`·`order_inserts=true` 를 켭니다(2라운드 04 수정 뒤로는 + persistence-jpa 모듈 기본값도 같다). JDBC 왕복으로 세면(`InsertRoundTripCounter`) 100건 = insert 400행이 + 400번 → 8번입니다: 표마다 50행씩(work_log 2 + tech_stack 4 + link 2). 새 엔티티를 merge 가 아니라 + persist 하게 바꾼 뒤(`Persistable`, 리뷰 04-17) `@ElementCollection` 행도 소유 엔티티를 넘어 묶입니다. + 그 전에는 컬렉션 행이 항목마다 따로 가서 202번이었습니다 + (`WorkLogStatementCostSystemTest.batchCreatingAHundredWorkLogsSendsTheWorkLogRowsInJdbcBatches`). +- 실측(2026-11-02, 리뷰 09 문서와 같은 방법: 호스트 `java -jar -Xmx1g`, PostgreSQL 16 컨테이너 + `--cpus 4 --memory 1g`, `work_log` 10,000행): 1000건 요청 시간 batch 끔 0.32~0.61 s → 켬 0.22~0.47 s. + PG 문장 로그는 둘 다 4,004줄입니다 — 서버는 묶음 안의 행도 하나씩 execute 로 기록하기 때문입니다(줄어드는 + 것은 네트워크 왕복: 1000건 4,000번 → 약 2,000번). 로컬 DB 라 왕복 비용이 작아 차이가 작고, 원격 DB(왕복 + 1 ms)라면 1000건 요청이 커넥션을 약 2 s 잡습니다. +- 상한을 바꿀 조건: 1000건 요청이 커넥션을 잡는 시간이 `connection-timeout`(기본 5 s)의 일부를 넘기 시작하면 + (원격 DB, 큰 본문) 상한을 낮추고 그 이상은 비동기 operation(`OperationsController`)으로 보냅니다. -### UpdateWorkLogUseCase — Patch 3-state 적용 +### UpdateWorkLogUseCase — 소유자 검사 + Patch 3-state 적용 +- **소유자만 고칠 수 있습니다.** `@RequiresPermission("worklog:write")` 는 "이 사람이 기록을 고칠 수 + 있는 역할인가"만 답합니다. "이 기록을 고칠 수 있는가"는 저장된 소유자가 있어야 답할 수 있어서, 유스케이스가 + 기록을 읽은 직후 같은 쓰기 트랜잭션 안에서 `WorkLog.isOwnedBy(editor)` 로 확인합니다. 검사와 변경 사이에 + 다른 쓰기가 끼어들 틈이 없습니다. 소유자가 아니면 `WorkLogNotOwnedException` → 403 + `WORKLOG_NOT_OWNER`. 읽기가 공개라 존재 자체는 비밀이 아니므로 404 로 숨기지 않습니다. +- 호출자는 `UpdateWorkLogCommand.editor` 로 들어옵니다(웹 어댑터가 인증 principal 의 subject 를 넣음). + command 가 생성 시점에 null 을 거부하므로, 인증 없이 이 유스케이스에 닿는 경로는 만들 수 없습니다. +- 버린 대안: application-core `ObjectAccessPolicy` 로 묻기 — tenant 가 필수이고 정책 구현이 소유자를 다시 + 읽어야 해서 왕복이 하나 늘고, 검사와 변경이 다른 읽기를 보게 됩니다. 이미 읽은 애그리거트에 묻는 쪽이 + 싸고 원자적입니다. 관리자 예외(관리자는 남의 기록도 수정)는 두지 않았습니다. 필요하면 별도 권한 + (`worklog:moderate` 등)으로 명시해 이 검사 옆에 둡니다. - 각 필드의 `Patch` 상태에 따라 다르게 동작합니다: `hasValue()` 면 교체, `isExplicitNull()` 이면 비움, 둘 다 아니면(없음) 변경하지 않습니다. 상태 전이는 도메인 메서드(`startProgress`/`close`)에 위임하고, OPEN 으로 되돌리는 시도는 잘못된 전이로 막습니다. @@ -208,13 +257,21 @@ curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type 눈에 보이게 만듭니다 — 인증된 `user` 는 여기서 거절되고 `admin` 만 통과합니다. (참고로 생성·수정· 일괄 생성은 `worklog:write` 로 막고, 이 권한은 `user`/`admin` 양쪽에 부여됩니다.) -### 읽기 모델(projection) — ListRecentWorkLogSummariesUseCase / WorkLogSummaryQueryPort / WorkLogSummary -- 이 세 타입은 **CQRS-lite "쿼리 우회(query bypass)"** 예시입니다. 보드/목록 화면처럼 가벼운 읽기는 +### 읽기 모델(projection) — ListWorkLogsUseCase / ListRecentWorkLogSummariesUseCase / WorkLogSummaryQueryPort / WorkLogSummary +- **목록은 모두 이 길로 읽습니다.** `GET /api/worklogs`(`ListWorkLogsUseCase`)가 `WorkLogSummaryQueryPort.findPage` + 를 씁니다. 예전에는 `WorkLogRepository.findPage` 로 애그리거트를 통째로 읽었고, 항목마다 lazy + `@ElementCollection` 두 개를 따로 읽어 SQL 이 페이지 크기에 비례했습니다(실측 20건 42개, 100건 202개 — + 리뷰 09-01). 응답에 쓰지 않는 `content`·`techStack`·`links` 를 읽던 것이라, 그 메서드는 지웠습니다. + 실측(2026-11-02, 리뷰 09 문서와 같은 방법, PG 문장 로그·동시 16·15 s×3 중앙값): 20건 46 → 6문장, + 765 → 2,528 rps / 100건 206 → 6문장, 147 → 703 rps. 6문장은 SHOW·BEGIN·본문·count·COMMIT·검증 1개입니다. + `WorkLogRepository` 는 이제 한 건씩만 다룹니다. 목록 응답에 컬렉션이 필요해지면 projection 에 넣지 말고 + IN 쿼리 하나(또는 `default_batch_fetch_size`)로 따로 읽어 문장 수를 상수로 유지합니다. +- 이 타입들은 **CQRS-lite "쿼리 우회(query bypass)"** 예시입니다. 보드/목록 화면처럼 가벼운 읽기는 WorkLog 애그리거트를 통째로 복원하지 않고, 필요한 컬럼만 뽑은 projection 으로 읽습니다 (`content`/`summary`/`techStack`/`links` 같은 무거운 상태를 빼서, lazy 컬렉션 조인 없는 컬럼-부분 SELECT 가 됩니다). -- **이것은 강제 기본값이 아니라 선택적 최적화**입니다. 애그리거트를 통해 읽는 길 - (`WorkLogRepository`)도 단순한 읽기에서는 똑같이 유효한 기본 경로입니다. +- 단건 읽기(`GET /worklogs/{id}`)는 애그리거트(`WorkLogRepository.findById`)로 읽습니다. 한 건이라 + 컬렉션 쿼리가 2개로 고정이고, 응답이 컬렉션을 씁니다. - projection DTO 의 순수성: projection 은 **application 타입**이어야 합니다 — 도메인 애그리거트도, JPA 엔티티도, 웹 DTO 도 아니어야 합니다. 도메인 *값* 타입(예: `WorkCategory` enum)을 참조하는 것은 허용됩니다(application 은 domain 에 의존 가능). 다만 쿼리 포트의 반환 시그니처에 도메인 애그리거트/ @@ -273,8 +330,8 @@ curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type `MAX_BATCH_SIZE`(1000)로 제한하고, 넘으면 400 입니다. 요청 봉투는 `{ "requests": [ ... ] }` 형태입니다. - **소유자(owner) 스탬프**: 생성되는 WorkLog 에는 인증된 호출자의 IdP subject 를 소유자로 찍습니다. 보안 컨텍스트에서 null 안전하게 읽으며, 이 값은 **가공 전 원시 principal id** 입니다 — - 가명화(pseudonymization)는 별도 프라이버시 계약의 몫이라 여기서 적용하지 않고, 소유자 범위 - 인가(ABAC)는 의도적으로 뒤로 미룬 확장입니다. 유스케이스에 건 `worklog:write` 권한이 생성이 실제 + 가명화(pseudonymization)는 별도 프라이버시 계약의 몫이라 여기서 적용하지 않습니다. 같은 값이 PATCH 의 + `editor` 로 들어가 소유자 검사에 쓰입니다(`UpdateWorkLogUseCase`). 유스케이스에 건 `worklog:write` 권한이 생성이 실제 실행될 시점엔 인증된 principal 이 있음을 보장합니다. - **id 정규화(`toId`)**: 대소문자 무관 canonical UUID 경로 입력을 받아, 도메인 id 를 만들기 전에 표준 36자 소문자 UUID 로 정규화합니다. 여기서 쓰는 `UUID.fromString(...)` 은 (생성기가 아니라) 파서라, @@ -283,7 +340,11 @@ curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type ### OperationsController / SampleOperationStore / WorkLogExportResult — 장기 실행 작업(LRO) 예시 - `POST /worklogs:export` 는 `202 Accepted` + 폴링 경로를 가리키는 `Location` 헤더 + `operationId`/ `statusUrl` 을 담은 봉투를 돌려주고, `GET /operations/{id}` 로 상태를 폴링합니다. 상태는 5값 - `OperationStatus` enum 에서 옵니다. + `OperationStatus` enum 에서 옵니다. 모르는 id 는 404 `OPERATION_NOT_FOUND` 입니다. +- `Operation`·`OperationStatus` 는 **이 샘플 전용 타입**입니다(`adapter.inbound.web.operation`). 예전엔 + shared-contract 에 있었지만 소비자가 샘플뿐이었습니다. 실제 서비스의 LRO 정본은 application-core + `DurableOperation` + web `OperationHttpResponse`(`GET /operations/{operationId}`)이고, 두 컨트롤러는 + 같은 경로를 잡으므로 한 앱에 함께 켜지 않습니다. - **operation id 를 컨트롤러가 아니라 `SampleOperationStore` 에서 만드는 이유**: 컨트롤러/유스케이스는 id 를 직접 생성하면 안 된다는 규칙(`no_uuid_random_in_controller`) 때문입니다. `SampleOperationStore` 는 컨트롤러도 application 서비스도 아닌 웹 인프라 컴포넌트라 여기서 id 를 발급해도 됩니다. @@ -346,8 +407,17 @@ curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type - `WorkLogRepository` 포트 구현체. 감사 메타데이터(생성/수정 시각·주체)를 **여기 영속 어댑터에서** 찍습니다(생성자 주입 Clock + 감사 컨텍스트). 도메인 WorkLog 는 감사 필드를 들고 있지 않습니다. - INSERT(버전 null): 새 애그리거트라 created/updated 둘 다 지금 시각·주체로 초기화합니다. -- UPDATE(버전 non-null): 기존 행의 created 값을 읽어 그대로 이어가고(같은 트랜잭션에서 유스케이스가 - 이미 로드해둔 JPA 1차 캐시에서 served), updated 만 갱신합니다. +- UPDATE(버전 non-null): **새 엔티티를 merge 하지 않고, 유스케이스가 같은 트랜잭션에서 읽어 둔 관리 + 엔티티에 값을 덮어씁니다**(`WorkLogPersistenceMapper.copyState` → `WorkLogEntity.replaceState`, 1차 캐시라 + 추가 왕복 없음). 새 엔티티는 새 `List` 를 들고 오고, Hibernate 는 바뀐 컬렉션을 "전부 지우고 전부 다시 + 넣기"로 처리합니다 — 제목만 고친 PATCH 가 `work_log_tech_stack`·`work_log_link` 를 매번 삭제·재삽입했습니다 + (리뷰 09-06, 실측 13문장). 이제 컬렉션은 내용이 다를 때만 교체하고, 같으면 SQL 이 없습니다. 비교는 복사본으로 + 합니다: Hibernate `PersistentBag.equals` 는 인스턴스 동일성이라 같은 내용이어도 false 입니다. +- created 값은 저장된 그대로 두고 updated 만 갱신합니다. 도메인 객체의 version 이 관리 엔티티와 다르면(다른 + 시점에 읽은 객체) `ObjectOptimisticLockingFailureException` 으로 거절합니다 — merge 가 하던 것과 같은 + 답입니다. 그 사이 다른 트랜잭션의 수정은 `@Version` 조건 UPDATE 가 잡습니다. +- `saveAndFlush` 로 UPDATE 를 그 자리에서 실행해, Hibernate 가 올린 version 이 반환 객체(→ 응답 ETag)에 + 들어갑니다. ### PosterRepositoryAdapter — 중복 규칙은 DB 제약 + 충돌 변환 - 포스터 제목은 대소문자를 무시하고 유일합니다. 이 규칙은 **DB 유일 인덱스가 지킵니다** @@ -359,6 +429,12 @@ curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type 조회와 같은 `PosterTitleAlreadyExistsException`(409 `POSTER_ALREADY_EXISTS`)으로 바꿉니다. flush 를 미루면 위반이 커밋 시점에 일반 `DB_UNIQUE_VIOLATION` 으로 나와 도메인 오류 코드를 잃습니다. - 버린 대안: 비관적 락·`SERIALIZABLE` 격리(더 비싸고 재시도가 필요함), 사전 조회만 유지(동시성에서 깨짐). +- **수정(PATCH)도 같은 규칙입니다.** 다른 포스터가 가진 제목(대소문자 무시)으로 바꾸면 같은 + `PosterTitleAlreadyExistsException` → 409 `POSTER_ALREADY_EXISTS` 입니다. `UpdatePosterUseCase` 는 사전 + 조회를 하지 않습니다: `existsByTitle` 은 자기 자신의 제목도 찾아서, 같은 포스터의 대소문자만 바꾸는 + 수정을 잘못 거절하기 때문입니다. 인덱스만으로 규칙이 지켜지고 동시 수정에서도 같습니다. + 고정 테스트: `PosterRepositoryAdapterIntegrationTest.renamingAPosterToAnotherPostersTitleIs…`, + `…ToItsOwnTitleInAnotherCaseIsAccepted`, `PosterControllerWireTest.patchToATitleAnotherPosterHolds…`. - 인덱스 키가 `upper(title)` 인 이유: 사전 조회(`existsByTitleIgnoreCase`)를 Hibernate 가 `upper(title) = upper(?)` 로 만들기 때문입니다. 같은 식이라 그 조회도 순차 스캔 대신 이 인덱스를 씁니다. 제목 정렬용 `ix_poster_title` 은 그대로 둡니다. @@ -367,9 +443,10 @@ curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type 이미 중복 제목이 있으면 그 제목을 이름으로 대며 멈춥니다. ### WorkLogJpaRepository -- `findByCategory`: 계약이 허용하는 유일한 필터 구문인 **평면 동등 필터**를 데이터 계층 안에 둔 - 파생 쿼리입니다. -- `findRecentSummaryRows`: CQRS-lite projection 읽기. JPQL `SELECT new` 생성자 표현식으로 요약 +- `findSummaryRows` / `findSummaryRowsByCategory`: 목록 projection. 같은 `SUMMARY_SELECT` 에 정렬·페이지는 + `Pageable` 로, 카테고리는 계약이 허용하는 유일한 필터 구문인 **평면 동등 필터**로 붙입니다. count 쿼리를 + 명시해 Spring Data 가 생성자 표현식에서 count 를 추론하지 않게 합니다. +- `findRecentSummaryRows`: 같은 projection, count 없음. CQRS-lite projection 읽기. JPQL `SELECT new` 생성자 표현식으로 요약 컬럼만 골라(`content/summary/techStack/links` 제외) `WorkLogSummaryRow` 로 담는 컬럼-부분 읽기라, 애그리거트 복원과 lazy `@ElementCollection` 조인을 건너뜁니다. 닫힌 인터페이스 projection 대신 `SELECT new`/`JdbcTemplate` 을 택한 이유: 닫힌-projection 의 컬럼 가지치기는 구현체 의존적이고 @@ -405,7 +482,7 @@ curl -X POST localhost:8080/api/worklogs -u demo-user:demo-user -H 'Content-Type ## adapter/identifier — ID 생성 (UUIDv7) ### UuidWorkLogIdFactory / UuidOutboxEventIdFactory -- 도메인 id 포트(`WorkLogIdFactory`, `OutboxEventIdFactory`)의 인프라 구현체입니다. +- id 포트(`WorkLogIdFactory`(도메인), `OutboxEventIdFactory`(application))의 인프라 구현체입니다. - 둘 다 `UuidCreator.getTimeOrderedEpochPlus1()` 을 씁니다 — RFC 9562 UUIDv7(time-ordered)이며 같은 밀리초 안에서도 단조 증가(monotonic)하고 secure random 으로 뒷받침됩니다. - **여기가 샘플에서 `UuidCreator` 호출이 허용되는 유일한 곳**입니다. `no_uuid_random_in_controller` diff --git a/src/sample-portfolio/build.gradle b/src/sample-portfolio/build.gradle index deab916d..4b96569f 100644 --- a/src/sample-portfolio/build.gradle +++ b/src/sample-portfolio/build.gradle @@ -194,7 +194,6 @@ strictTestLanes { systemProperty 'openapi.snapshot.write', project.hasProperty('approveOpenApiChange') ? 'true' : 'false' // Pin UTC like the main test task for host-locale independence. - jvmArgs '-Duser.timezone=UTC' } } @@ -221,7 +220,6 @@ strictTestLanes { 'dev.caskeleton.sample.portfolio.qualification.PosterImageRetirementQualificationTest', 'dev.caskeleton.sample.portfolio.qualification.PosterImageV8MigrationQualificationTest') rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' shouldRunAfter 'test' } lane('messagingSampleContractQualificationTest') { @@ -229,7 +227,6 @@ strictTestLanes { description = 'Runs exact Messaging sample contract qualification tests.' requires('dev.caskeleton.sample.portfolio.application.worklog.WorkLogReservedContractContributionTest') rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' } } diff --git a/src/sample-portfolio/gradle.lockfile b/src/sample-portfolio/gradle.lockfile index 9aafaf59..fb96d48c 100644 --- a/src/sample-portfolio/gradle.lockfile +++ b/src/sample-portfolio/gradle.lockfile @@ -40,15 +40,15 @@ com.google.guava:guava:33.6.0-jre=checkstyle com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,posterImageMigrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,webSystemTestAnnotationProcessor com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,posterImageMigrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,webSystemTestAnnotationProcessor com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,integrationTestAnnotationProcessor,posterImageMigrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,webSystemTestAnnotationProcessor -com.h2database:h2:2.4.240=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +com.h2database:h2:2.4.240=posterImageMigrationTestRuntimeClasspath com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath com.nimbusds:nimbus-jose-jwt:10.4=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.squareup.okhttp3:okhttp-jvm:5.2.1=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath -com.squareup.okhttp3:okhttp:5.2.1=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath -com.squareup.okio:okio-jvm:3.16.1=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath -com.squareup.okio:okio:3.16.1=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +com.squareup.okhttp3:okhttp-jvm:5.2.1=posterImageMigrationTestRuntimeClasspath +com.squareup.okhttp3:okhttp:5.2.1=posterImageMigrationTestRuntimeClasspath +com.squareup.okio:okio-jvm:3.16.1=posterImageMigrationTestRuntimeClasspath +com.squareup.okio:okio:3.16.1=posterImageMigrationTestRuntimeClasspath com.sun.istack:istack-commons-runtime:4.1.2=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath com.tngtech.archunit:archunit-junit5-api:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath com.tngtech.archunit:archunit-junit5-engine-api:1.3.0=integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath @@ -97,7 +97,8 @@ io.opentelemetry:opentelemetry-context:1.55.0=compileClasspath,integrationTestCo io.opentelemetry:opentelemetry-exporter-common:1.55.0=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath io.opentelemetry:opentelemetry-exporter-otlp-common:1.55.0=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath -io.opentelemetry:opentelemetry-exporter-sender-okhttp:1.55.0=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-sender-jdk:1.55.0=integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-sender-okhttp:1.55.0=posterImageMigrationTestRuntimeClasspath io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath io.opentelemetry:opentelemetry-sdk-common:1.55.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.55.0=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath @@ -181,8 +182,7 @@ org.hibernate.orm:hibernate-envers:7.2.24.Final=integrationTestRuntimeClasspath, org.hibernate.validator:hibernate-validator:9.0.1.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle org.jboss.logging:jboss-logging:3.6.3.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib:2.2.21=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath -org.jetbrains:annotations:13.0=productionRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib:2.2.21=posterImageMigrationTestRuntimeClasspath org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestAnnotationProcessor,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestAnnotationProcessor,systemTestCompileClasspath,systemTestRuntimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestAnnotationProcessor,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath 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 43f523bc..fae67951 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 @@ -196,6 +196,42 @@ class PosterRepositoryAdapterIntegrationTest { .hasMessage("Poster title already in use: 여름 세일 BANNER"); } + /** + * PATCH holds the same rule as create, and only the index holds it: the update use case asks no + * question first, because a pre-check would also find the poster's own title. + */ + @Test + void renamingAPosterToAnotherPostersTitleIsRejectedAsATitleConflict() { + // given + saveAndDetach(Poster.create(ID, "여름 세일 Banner", "7월 한정")); + PosterId otherId = PosterId.of("0190bd6e-7c3e-7abc-8def-0123456789ac"); + saveAndDetach(Poster.create(otherId, "가을 세일 배너", null)); + Poster other = adapter.findById(otherId).orElseThrow(); + other.rename("여름 세일 BANNER"); + + // when + Throwable failure = catchThrowable(() -> adapter.save(other)); + + // then + assertThat(failure) + .isInstanceOf(PosterTitleAlreadyExistsException.class) + .hasMessage("Poster title already in use: 여름 세일 BANNER"); + } + + @Test + void renamingAPosterToItsOwnTitleInAnotherCaseIsAccepted() { + // given + saveAndDetach(Poster.create(ID, "여름 세일 Banner", "7월 한정")); + Poster loaded = adapter.findById(ID).orElseThrow(); + loaded.rename("여름 세일 BANNER"); + + // when + saveAndDetach(loaded); + + // then + assertThat(adapter.findById(ID)).get().extracting(Poster::title).isEqualTo("여름 세일 BANNER"); + } + @Test void aPreV8RawKeyRowReadsBackWithoutAnImage() { // given diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterContractTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterContractTest.java index 7250a593..e0c159ea 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterContractTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterContractTest.java @@ -1,6 +1,7 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.config.JpaConfig; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryQueryPort; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; import dev.caskeleton.sample.portfolio.domain.worklog.testkit.WorkLogRepositoryContract; import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; @@ -21,9 +22,9 @@ import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.postgresql.PostgreSQLContainer; /** - * The shipped adapter against real PostgreSQL, held to the same {@link WorkLogRepositoryContract} - * as the in-memory fake. The test-managed transaction is switched off so every contract call - * commits on its own and every read goes back to the database. + * The shipped adapters (repository and summary query) against real PostgreSQL, held to the same + * {@link WorkLogRepositoryContract} as the in-memory fakes. The test-managed transaction is + * switched off so every contract call commits on its own and every read goes back to the database. */ @DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) @@ -32,6 +33,7 @@ import org.testcontainers.postgresql.PostgreSQLContainer; @Import({ JpaConfig.class, WorkLogRepositoryAdapter.class, + WorkLogSummaryQueryAdapter.class, WorkLogRepositoryAdapterIntegrationTest.TestAuditConfig.class }) @TestPropertySource( @@ -46,6 +48,7 @@ class WorkLogRepositoryAdapterContractTest extends WorkLogRepositoryContract { static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); @Autowired private WorkLogRepositoryAdapter adapter; + @Autowired private WorkLogSummaryQueryAdapter summaries; @Autowired private WorkLogJpaRepository jpa; @Autowired private PlatformTransactionManager transactionManager; @@ -63,6 +66,11 @@ class WorkLogRepositoryAdapterContractTest extends WorkLogRepositoryContract { return adapter; } + @Override + protected WorkLogSummaryQueryPort summaries() { + return summaries; + } + @Override protected T inTransaction(Supplier work) { return new TransactionTemplate(transactionManager).execute(status -> work.get()); diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java index bf1dadcc..d31647f0 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.audit.AuditContextPort; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxAggregateSequences; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.UuidPosterIdFactory; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.config.JpaConfig; @@ -134,7 +135,8 @@ class CreatePosterConcurrencyIntegrationTest { } private CreatePosterUseCase useCase() { - FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(); + FakeIntegrationEventEncoder encoder = + new FakeIntegrationEventEncoder(PosterEventContracts.POSTER_CREATED); // The in-memory fakes are single-threaded; the requests reach them one at a time. PortfolioEventOutbox events = new PortfolioEventOutbox( @@ -150,7 +152,8 @@ class CreatePosterConcurrencyIntegrationTest { }, () -> UUID.randomUUID().toString(), Optional::empty, - Clock.systemUTC()); + Clock.systemUTC(), + new InMemoryOutboxAggregateSequences()); return new CreatePosterUseCase( repository, new UuidPosterIdFactory(), diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageRetirementQualificationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageRetirementQualificationTest.java index 5e33ee41..af0e6c10 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageRetirementQualificationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageRetirementQualificationTest.java @@ -21,7 +21,8 @@ import org.testcontainers.postgresql.PostgreSQLContainer; class PosterImageRetirementQualificationTest { @Container - static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:16.4-alpine"); + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer(System.getProperty("ca.test.image.postgres-16-4")); private static final OffsetDateTime NOW = OffsetDateTime.parse("2026-07-29T00:00:00Z"); diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageV8MigrationQualificationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageV8MigrationQualificationTest.java index bebd9e8d..32765388 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageV8MigrationQualificationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageV8MigrationQualificationTest.java @@ -23,7 +23,8 @@ import org.testcontainers.postgresql.PostgreSQLContainer; class PosterImageV8MigrationQualificationTest { @Container - static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:16.4-alpine"); + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer(System.getProperty("ca.test.image.postgres-16-4")); private static final OffsetDateTime NOW = OffsetDateTime.parse("2026-07-29T00:00:00Z"); diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsController.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsController.java index b52dceb4..661dc4a5 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsController.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsController.java @@ -1,9 +1,10 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.controller; import dev.caskeleton.adapter.inbound.web.settings.PresentationSettings; +import dev.caskeleton.sample.portfolio.adapter.inbound.web.operation.Operation; +import dev.caskeleton.sample.portfolio.adapter.inbound.web.operation.SampleOperationNotFoundException; import dev.caskeleton.sample.portfolio.adapter.inbound.web.operation.SampleOperationStore; import dev.caskeleton.sample.portfolio.adapter.inbound.web.operation.WorkLogExportResult; -import dev.caskeleton.shared.operation.Operation; import java.net.URI; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -38,8 +39,6 @@ public class OperationsController { @GetMapping("/operations/{id}") public Operation poll(@PathVariable String id) { - return operations - .find(id) - .orElseThrow(() -> new IllegalArgumentException("unknown operation id: " + id)); + return operations.find(id).orElseThrow(SampleOperationNotFoundException::new); } } 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 6d8ed7c9..d9416379 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 @@ -2,6 +2,7 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.controller; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; +import dev.caskeleton.adapter.inbound.web.http.IdempotencyKeyHeader; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; @@ -53,19 +54,16 @@ public final class PosterImagePublicationController { consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity publish( @PathVariable String id, - @RequestHeader(ApiHeaders.IDEMPOTENCY_KEY) String idempotencyKey, + // Not required here: IdempotencyKeyHeader answers a missing key with its own code. + @RequestHeader(name = ApiHeaders.IDEMPOTENCY_KEY, required = false) + String idempotencyKeyHeader, @RequestParam("expectedVersion") long expectedVersion, @RequestParam("sha256") String sha256, @RequestParam("file") MultipartFile file, @AuthenticationPrincipal AuthenticatedPrincipal principal) { - if (idempotencyKey == null - || idempotencyKey.isBlank() - || idempotencyKey.length() > 256 - || principal == null - || principal.idpUserId() == null - || principal.idpUserId().isBlank()) { - throw new IllegalArgumentException( - "authenticated principal and Idempotency-Key are required"); + IdempotencyKeyHeader idempotencyKey = IdempotencyKeyHeader.parse(idempotencyKeyHeader); + if (principal == null || principal.idpUserId() == null || principal.idpUserId().isBlank()) { + throw new IllegalArgumentException("authenticated principal is required"); } ObjectContentIdentity identity = new ObjectContentIdentity( @@ -79,7 +77,7 @@ public final class PosterImagePublicationController { expectedVersion, null, principal.idpUserId(), - idempotencyKey.trim(), + idempotencyKey.value(), identity, ObjectMediaType.of(contentType), new MultipartObjectContentProducer(file, identity), 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 eb91b7fd..330fcf65 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 @@ -24,10 +24,10 @@ import dev.caskeleton.sample.portfolio.application.worklog.GetWorkLogUseCase; import dev.caskeleton.sample.portfolio.application.worklog.ListWorkLogsQuery; import dev.caskeleton.sample.portfolio.application.worklog.ListWorkLogsUseCase; import dev.caskeleton.sample.portfolio.application.worklog.UpdateWorkLogUseCase; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryPage; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; import dev.caskeleton.shared.response.Envelope; import dev.caskeleton.shared.response.PageMeta; @@ -100,7 +100,7 @@ public class WorkLogController { boolean ascending = WebRequestParams.Sort.ascendingOf(requested); String appliedSort = WebRequestParams.Sort.canonicalOf(requested); - WorkLogPage result = + WorkLogSummaryPage result = list.handle( new ListWorkLogsQuery( pageParams.page(), pageParams.size(), sortField, ascending, category)); @@ -139,7 +139,9 @@ public class WorkLogController { /** * When {@code If-Match} is supplied it must match the current ETag, else 412 (optimistic - * concurrency); an absent {@code If-Match} is allowed. See README. + * concurrency); an absent {@code If-Match} is allowed. Only the work log's owner may edit it (403 + * {@code WORKLOG_NOT_OWNER} otherwise); the caller is handed to the use case, which owns that + * check. See README. */ @PatchMapping("/worklogs/{id}") public ResponseEntity patch( @@ -147,7 +149,9 @@ public class WorkLogController { @RequestHeader(value = ApiHeaders.IF_MATCH, required = false) String ifMatch, @Valid @RequestBody UpdateWorkLogRequest body) { WorkLog updated = - update.handle(WorkLogWebMapper.toUpdateCommand(toId(id), body, expectedVersion(ifMatch))); + update.handle( + WorkLogWebMapper.toUpdateCommand( + toId(id), currentOwnerSubject(), body, expectedVersion(ifMatch))); return ResponseEntity.ok().eTag(etagOf(updated)).body(WorkLogWebMapper.toResponse(updated)); } @@ -214,9 +218,9 @@ public class WorkLogController { } /** - * The owner stamped on a created work log is the authenticated caller's IdP subject, read - * null-safely from the security context. This is the raw principal id (no pseudonymization here). - * See README. + * The owner stamped on a created work log, and the editor an update is checked against, is the + * authenticated caller's IdP subject, read null-safely from the security context. This is the raw + * principal id (no pseudonymization here). See README. */ private static String currentOwnerSubject() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandler.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandler.java index 1c6f6e1b..ffb4f4ce 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandler.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandler.java @@ -5,6 +5,7 @@ import dev.caskeleton.sample.portfolio.application.poster.PosterNotFoundExceptio import dev.caskeleton.sample.portfolio.application.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageAlreadyPublishedException; import dev.caskeleton.sample.portfolio.application.worklog.WorkLogNotFoundException; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogNotOwnedException; import dev.caskeleton.sample.portfolio.application.worklog.WorkLogVersionMismatchException; import dev.caskeleton.sample.portfolio.domain.poster.PosterInvariantException; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException; @@ -31,6 +32,12 @@ public class DomainExceptionHandler { return ErrorResponseFactory.envelope(PortfolioErrorCode.WORKLOG_NOT_FOUND, null); } + /** Allowed to edit work logs, but not this one: it belongs to another account → 403. */ + @ExceptionHandler(WorkLogNotOwnedException.class) + public ResponseEntity> handleWorkLogNotOwned(WorkLogNotOwnedException ex) { + return ErrorResponseFactory.envelope(PortfolioErrorCode.WORKLOG_NOT_OWNER, null); + } + /** A stale {@code If-Match}, found by the update use case inside its transaction → 412. */ @ExceptionHandler(WorkLogVersionMismatchException.class) public ResponseEntity> handleWorkLogVersionMismatch( @@ -38,9 +45,19 @@ public class DomainExceptionHandler { return ErrorResponseFactory.envelope(OperationalError.PRECONDITION_FAILED, null); } + /** + * Maps the invariant's {@code reason()}: a blank title is the client's input (400), a mutation + * the work log's state forbids is a conflict (409). + */ @ExceptionHandler(WorkLogInvariantException.class) public ResponseEntity> handleWorkLogInvariant(WorkLogInvariantException ex) { - return ErrorResponseFactory.envelope(PortfolioErrorCode.WORKLOG_CONFLICT, null); + PortfolioErrorCode code = + switch (ex.reason()) { + case TITLE_BLANK -> PortfolioErrorCode.WORKLOG_INVALID; + case INVALID_STATUS_TRANSITION, CLOSED_WORKLOG_MUTATION -> + PortfolioErrorCode.WORKLOG_CONFLICT; + }; + return ErrorResponseFactory.envelope(code, null); } @ExceptionHandler(PosterNotFoundException.class) @@ -61,7 +78,7 @@ public class DomainExceptionHandler { return ErrorResponseFactory.envelope(PortfolioErrorCode.POSTER_IMAGE_ALREADY_PUBLISHED, null); } - /** Maps the invariant's {@code reason()} to a specific code (finer-grained than WorkLog's). */ + /** Maps the invariant's {@code reason()} to a specific code. */ @ExceptionHandler(PosterInvariantException.class) public ResponseEntity> handlePosterInvariant(PosterInvariantException ex) { PortfolioErrorCode code = diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCode.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCode.java index 744c8600..5cf3deef 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCode.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCode.java @@ -10,11 +10,14 @@ import dev.caskeleton.shared.error.Category; public enum PortfolioErrorCode implements ApiErrorCode { WORKLOG_NOT_FOUND(Category.NOT_FOUND, 404, false), WORKLOG_CONFLICT(Category.CONFLICT, 409, false), + WORKLOG_NOT_OWNER(Category.AUTHZ, 403, false), + WORKLOG_INVALID(Category.VALIDATION, 400, false), POSTER_NOT_FOUND(Category.NOT_FOUND, 404, false), POSTER_ALREADY_EXISTS(Category.CONFLICT, 409, false), POSTER_IMAGE_ALREADY_PUBLISHED(Category.CONFLICT, 409, false), POSTER_INVALID_STATE(Category.VALIDATION, 400, false), - POSTER_IMAGE_REQUIRED(Category.VALIDATION, 400, false); + POSTER_IMAGE_REQUIRED(Category.VALIDATION, 400, false), + OPERATION_NOT_FOUND(Category.NOT_FOUND, 404, false); private final Category category; private final int httpStatus; 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 70ff836f..8efd0e35 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 @@ -7,6 +7,7 @@ import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.WorkLogR import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.WorkLogSummaryResponse; import dev.caskeleton.sample.portfolio.application.worklog.CreateWorkLogCommand; import dev.caskeleton.sample.portfolio.application.worklog.UpdateWorkLogCommand; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummary; import dev.caskeleton.sample.portfolio.domain.worklog.RepoStats; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; @@ -51,9 +52,10 @@ public final class WorkLogWebMapper { // adapter owns all request DTO -> command translation. The WorkLogId is parsed at the // web edge and passed in. See README. public static UpdateWorkLogCommand toUpdateCommand( - WorkLogId id, UpdateWorkLogRequest body, OptionalLong expectedVersion) { + WorkLogId id, String editor, UpdateWorkLogRequest body, OptionalLong expectedVersion) { return new UpdateWorkLogCommand( id, + editor, body.titlePatch(), body.summaryPatch(), body.contentPatch(), @@ -77,9 +79,10 @@ public final class WorkLogWebMapper { w.period().end()); } - public static WorkLogSummaryResponse toSummary(WorkLog w) { + /** A list row from the summary projection; the list never loads the aggregate. */ + public static WorkLogSummaryResponse toSummary(WorkLogSummary s) { return new WorkLogSummaryResponse( - w.id(), w.title(), w.category(), w.status(), w.period().start(), w.period().end()); + WorkLogId.of(s.id()), s.title(), s.category(), s.status(), s.periodStart(), s.periodEnd()); } public static RepoStatsResponse toRepoStatsResponse(RepoStats s) { diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/operation/Operation.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/Operation.java similarity index 96% rename from src/shared-contract/src/main/java/dev/caskeleton/shared/operation/Operation.java rename to src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/Operation.java index c3684a98..f1e90bbc 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/operation/Operation.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/Operation.java @@ -1,4 +1,4 @@ -package dev.caskeleton.shared.operation; +package dev.caskeleton.sample.portfolio.adapter.inbound.web.operation; import dev.caskeleton.shared.response.ApiError; diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/operation/OperationStatus.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/OperationStatus.java similarity index 82% rename from src/shared-contract/src/main/java/dev/caskeleton/shared/operation/OperationStatus.java rename to src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/OperationStatus.java index d9004f08..bcefd50d 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/operation/OperationStatus.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/OperationStatus.java @@ -1,4 +1,4 @@ -package dev.caskeleton.shared.operation; +package dev.caskeleton.sample.portfolio.adapter.inbound.web.operation; /** * Long-running-operation (LRO) lifecycle status surfaced by the polling endpoint {@code GET diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/SampleOperationNotFoundException.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/SampleOperationNotFoundException.java new file mode 100644 index 00000000..8a23dc08 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/SampleOperationNotFoundException.java @@ -0,0 +1,23 @@ +package dev.caskeleton.sample.portfolio.adapter.inbound.web.operation; + +import dev.caskeleton.sample.portfolio.adapter.inbound.web.error.PortfolioErrorCode; +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; + +/** + * An operation id the store never issued: 404, not the 400 an {@code IllegalArgumentException} is. + */ +public final class SampleOperationNotFoundException extends RuntimeException + implements ApiErrorCarrier { + + private static final long serialVersionUID = 1L; + + public SampleOperationNotFoundException() { + super("unknown operation id"); + } + + @Override + public ApiErrorCode errorCode() { + return PortfolioErrorCode.OPERATION_NOT_FOUND; + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/SampleOperationStore.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/SampleOperationStore.java index eb7af812..1d48169b 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/SampleOperationStore.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/SampleOperationStore.java @@ -1,7 +1,6 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.operation; import com.github.f4b6a3.uuid.UuidCreator; -import dev.caskeleton.shared.operation.Operation; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/UuidOutboxEventIdFactory.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/UuidOutboxEventIdFactory.java index 00728e79..f414db73 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/UuidOutboxEventIdFactory.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/UuidOutboxEventIdFactory.java @@ -1,13 +1,13 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.identifier; import com.github.f4b6a3.uuid.UuidCreator; -import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; +import dev.caskeleton.sample.portfolio.application.event.OutboxEventIdFactory; import org.springframework.stereotype.Component; /** - * Infrastructure adapter for the {@link OutboxEventIdFactory} domain port. Uses the same {@code - * UuidCreator.getTimeOrderedEpochPlus1()} mechanism as {@link UuidWorkLogIdFactory}; id generation - * lives here, never in the application layer. See README. + * Infrastructure adapter for the {@link OutboxEventIdFactory} application port. Uses the same + * {@code UuidCreator.getTimeOrderedEpochPlus1()} mechanism as {@link UuidWorkLogIdFactory}; id + * generation lives here, never in the application layer. See README. */ @Component public class UuidOutboxEventIdFactory implements OutboxEventIdFactory { diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntity.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntity.java index 68ff6813..046437fd 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntity.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntity.java @@ -120,6 +120,41 @@ public class WorkLogEntity extends AuditableEntity { this.version = version; } + /** + * Overwrites the mutable state of this managed entity. A collection is replaced only when its + * contents differ: touching an unchanged one would make Hibernate delete and re-insert all of its + * rows. The owner and the id never change after insert. + */ + public void replaceState( + String title, + WorkCategory category, + WorkLogStatus status, + String summary, + String content, + List techStack, + List links, + LocalDate periodStart, + LocalDate periodEnd) { + this.title = title; + this.category = category; + this.status = status; + this.summary = summary; + this.content = content; + replaceIfChanged(this.techStack, techStack); + replaceIfChanged(this.links, links); + this.periodStart = periodStart; + this.periodEnd = periodEnd; + } + + private static void replaceIfChanged(List stored, List wanted) { + // Compared element by element through a plain copy: Hibernate's PersistentBag.equals is + // instance identity, so stored.equals(wanted) is false even for the same contents. + if (!List.copyOf(stored).equals(wanted)) { + stored.clear(); + stored.addAll(wanted); + } + } + public UUID getId() { return id; } 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 6e08f19b..0fd5c7d2 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 @@ -37,6 +37,20 @@ public final class WorkLogPersistenceMapper { w.version()); } + /** Copies the WorkLog's mutable state onto the managed entity it was read from. */ + public static void copyState(WorkLog w, WorkLogEntity managed) { + managed.replaceState( + w.title(), + w.category(), + w.status(), + w.summary(), + w.content(), + w.techStack(), + w.links(), + w.period().start(), + w.period().end()); + } + public static WorkLog toDomain(WorkLogEntity e) { WorkLogId id = WorkLogId.of(e.getId().toString()); return WorkLog.rehydrate( diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogJpaRepository.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogJpaRepository.java index 588738d4..55565783 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogJpaRepository.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogJpaRepository.java @@ -8,19 +8,30 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; public interface WorkLogJpaRepository extends JpaRepository { - // Flat equality filter (the only filter syntax the contract allows), kept in the data layer. - Page findByCategory(WorkCategory category, Pageable pageable); - - long countByCategory(WorkCategory category); - // CQRS-lite projection read: a JPQL SELECT-new selects only the summary columns into - // WorkLogSummaryRow, skipping aggregate hydration and lazy @ElementCollection joins. - // SELECT-new is preferred over a closed interface projection. See README. + // WorkLogSummaryRow, skipping aggregate hydration and the lazy @ElementCollection reads. One + // statement per page (plus Spring Data's count), whatever the page size. SELECT-new is preferred + // over a closed interface projection. See README. + String SUMMARY_SELECT = + "select new dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository" + + ".WorkLogSummaryRow(e.id, e.title, e.category, e.status, e.periodStart, e.periodEnd)" + + " from WorkLogEntity e"; + + @Query(value = SUMMARY_SELECT, countQuery = "select count(e) from WorkLogEntity e") + Page findSummaryRows(Pageable pageable); + + // Flat equality filter (the only filter syntax the contract allows), kept in the data layer. @Query( - "select new dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository.WorkLogSummaryRow(" - + "e.id, e.title, e.category, e.periodStart, e.periodEnd) from WorkLogEntity e") + value = SUMMARY_SELECT + " where e.category = :category", + countQuery = "select count(e) from WorkLogEntity e where e.category = :category") + Page findSummaryRowsByCategory( + @Param("category") WorkCategory category, Pageable pageable); + + // The same projection without a count: the recent-summaries read wants no total. + @Query(SUMMARY_SELECT) List findRecentSummaryRows(Pageable pageable); } 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 2e867330..d83c923a 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 @@ -3,19 +3,14 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; import dev.caskeleton.adapter.outbound.persistence.audit.AuditContextPort; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.entity.WorkLogEntity; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.mapper.WorkLogPersistenceMapper; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; import java.time.Clock; import java.time.Instant; -import java.util.List; +import java.util.Objects; import java.util.Optional; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; +import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.springframework.stereotype.Repository; @Repository @@ -36,25 +31,43 @@ public class WorkLogRepositoryAdapter implements WorkLogRepository { @Override public WorkLog save(WorkLog workLog) { - WorkLogEntity entity = WorkLogPersistenceMapper.toEntity(workLog); Instant now = clock.instant(); String actor = auditContext.currentActor(); if (workLog.version() == null) { // INSERT: created_* and updated_* both take now/actor. + WorkLogEntity entity = WorkLogPersistenceMapper.toEntity(workLog); entity.initializeAudit(now, actor); - } else { - // UPDATE: carry the persisted created_* forward and bump only updated_*. - WorkLogEntity existing = - jpa.findById(entity.getId()) - .orElseThrow( - () -> - new IllegalStateException( - "no persisted work_log row to carry audit creation from: " - + entity.getId())); - entity.carryCreation(existing.getCreatedAt(), existing.getCreatedBy()); - entity.applyModification(now, actor); + return WorkLogPersistenceMapper.toDomain(jpa.save(entity)); } - return WorkLogPersistenceMapper.toDomain(jpa.save(entity)); + return WorkLogPersistenceMapper.toDomain(update(workLog, now, actor)); + } + + /** + * UPDATE: change the managed entity in place rather than merging a new one. + * + *

        A merged copy carries new collection instances, and Hibernate answers a replaced collection + * by deleting every child row and inserting them again, even when only the title changed. Applied + * to the managed entity, an unchanged collection writes nothing; created_* stays as stored. The + * read is the use case's own (same transaction, first-level cache), not a second round trip. + * + *

        The flush puts the version Hibernate assigns into the returned WorkLog, which is the ETag + * the caller hands out next. + */ + private WorkLogEntity update(WorkLog workLog, Instant now, String actor) { + WorkLogEntity managed = + jpa.findById(WorkLogPersistenceMapper.toUuid(workLog.id())) + .orElseThrow( + () -> + new IllegalStateException( + "no persisted work_log row to update: " + workLog.id().value())); + if (!Objects.equals(managed.getVersion(), workLog.version())) { + // The caller changed a WorkLog read at another version; applying it would overwrite the + // change in between. A merge used to fail here the same way. + throw new ObjectOptimisticLockingFailureException(WorkLogEntity.class, managed.getId()); + } + WorkLogPersistenceMapper.copyState(workLog, managed); + managed.applyModification(now, actor); + return jpa.saveAndFlush(managed); } @Override @@ -63,24 +76,6 @@ public class WorkLogRepositoryAdapter implements WorkLogRepository { .map(WorkLogPersistenceMapper::toDomain); } - @Override - public WorkLogPage findPage( - int page, int size, WorkLogSortField sortField, boolean ascending, WorkCategory category) { - int safeSize = size <= 0 ? 20 : size; - int safePage = Math.max(0, page); - Sort sort = - sortField == null - ? Sort.unsorted() - : 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); - List items = result.map(WorkLogPersistenceMapper::toDomain).getContent(); - return new WorkLogPage(items, result.getTotalElements()); - } - @Override public boolean existsById(WorkLogId id) { return jpa.existsById(WorkLogPersistenceMapper.toUuid(id)); diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapter.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapter.java index 8dd7938e..ff682bfe 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapter.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapter.java @@ -1,27 +1,55 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; +import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.mapper.WorkLogPersistenceMapper; import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummary; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryPage; import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryQueryPort; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; import java.util.List; +import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Repository; /** - * Persistence adapter for the WorkLog summary projection read. Implements {@link - * WorkLogSummaryQueryPort} via the JPQL {@code SELECT new} query and maps the storage-native {@link - * WorkLogSummaryRow} (UUID id) to {@link WorkLogSummary} (canonical UUID string id). The + * Persistence adapter for the WorkLog summary projection reads. Implements {@link + * WorkLogSummaryQueryPort} via the JPQL {@code SELECT new} queries and maps the storage-native + * {@link WorkLogSummaryRow} (UUID id) to {@link WorkLogSummary} (canonical UUID string id). The * storage-native {@code UUID} never escapes this adapter. See README. */ @Repository public class WorkLogSummaryQueryAdapter implements WorkLogSummaryQueryPort { + private static final int DEFAULT_PAGE_SIZE = 20; + private final WorkLogJpaRepository jpa; public WorkLogSummaryQueryAdapter(WorkLogJpaRepository jpa) { this.jpa = jpa; } + @Override + public WorkLogSummaryPage findPage( + int page, int size, WorkLogSortField sortField, boolean ascending, WorkCategory category) { + int safeSize = size <= 0 ? DEFAULT_PAGE_SIZE : size; + int safePage = Math.max(0, page); + Sort sort = + sortField == null + ? Sort.unsorted() + : Sort.by( + ascending ? Sort.Direction.ASC : Sort.Direction.DESC, + WorkLogPersistenceMapper.sortProperty(sortField)); + PageRequest pageRequest = PageRequest.of(safePage, safeSize, sort); + Page rows = + category == null + ? jpa.findSummaryRows(pageRequest) + : jpa.findSummaryRowsByCategory(category, pageRequest); + return new WorkLogSummaryPage( + rows.getContent().stream().map(WorkLogSummaryQueryAdapter::toSummary).toList(), + rows.getTotalElements()); + } + @Override public List findRecentSummaries(int limit) { int safeLimit = limit <= 0 ? 1 : limit; @@ -34,6 +62,11 @@ public class WorkLogSummaryQueryAdapter implements WorkLogSummaryQueryPort { private static WorkLogSummary toSummary(WorkLogSummaryRow row) { return new WorkLogSummary( - row.id().toString(), row.title(), row.category(), row.periodStart(), row.periodEnd()); + row.id().toString(), + row.title(), + row.category(), + row.status(), + row.periodStart(), + row.periodEnd()); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryRow.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryRow.java index 335ecbc2..0a9c96da 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryRow.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryRow.java @@ -1,14 +1,20 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus; import java.time.LocalDate; import java.util.UUID; /** - * Persistence-side read row for the WorkLog summary projection: the target of a JPQL {@code SELECT - * new} in {@link WorkLogJpaRepository#findRecentSummaryRows}, mirroring the storage shape (native - * {@code UUID} id). Kept inside the persistence package so the storage-native {@code UUID} never - * escapes the adapter. See README. + * Persistence-side read row for the WorkLog summary projection: the target of the JPQL {@code + * SELECT new} in {@link WorkLogJpaRepository}, mirroring the storage shape (native {@code UUID} + * id). Kept inside the persistence package so the storage-native {@code UUID} never escapes the + * adapter. See README. */ public record WorkLogSummaryRow( - UUID id, String title, WorkCategory category, LocalDate periodStart, LocalDate periodEnd) {} + UUID id, + String title, + WorkCategory category, + WorkLogStatus status, + LocalDate periodStart, + LocalDate periodEnd) {} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/OutboxEventIdFactory.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/OutboxEventIdFactory.java new file mode 100644 index 00000000..1b8ca67a --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/OutboxEventIdFactory.java @@ -0,0 +1,17 @@ +package dev.caskeleton.sample.portfolio.application.event; + +/** + * Application port that mints opaque string identifiers for outbox events. The outbox is not a + * domain concept and only {@link PortfolioEventOutbox} uses this, so it lives beside it rather than + * in the domain. Kept distinct from {@code WorkLogIdFactory} so the aggregate id type does not + * constrain the event id shape. See README. + */ +public interface OutboxEventIdFactory { + + /** + * Mints a new, globally unique event identifier. + * + * @return a non-null, non-blank string suitable for use as a UUIDv7 event id + */ + String newEventId(); +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java index c964db2a..5e439c7e 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java @@ -5,59 +5,58 @@ import dev.caskeleton.application.messaging.contract.IntegrationPayload; import dev.caskeleton.application.messaging.event.AggregateIdentity; import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.EventId; -import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.IntegrationEventDrafts; import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; import dev.caskeleton.application.observability.CorrelationIdPort; +import dev.caskeleton.application.outbox.OutboxAggregateSequencePort; import dev.caskeleton.application.outbox.OutboxAppendPort; -import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; import java.time.Clock; import java.time.Instant; import java.util.Objects; -import java.util.Optional; -import java.util.regex.Pattern; /** * Appends one portfolio integration event to the transactional outbox: build the draft, encode it, * append it. MUST be called from within a use case's {@code TransactionPort.inWrite(...)} block, so * the append joins the business write (no dual write). * - *

        What the draft needs and a domain event does not carry is decided here, once: + *

        The rules every feature shares — correlation fallback, single-tenant scope, contract fields — + * are application-core's {@link IntegrationEventDrafts}. What this class adds is the sample's own + * choice: * *

          *
        • The event id is a UUIDv7 from {@link OutboxEventIdFactory}; consumers deduplicate on it. - *
        • The correlation id is the request's, through {@link CorrelationIdPort}, when it fits the - * canonical identity grammar; otherwise — off-HTTP, or a caller-supplied header that does not - * fit — the event id. An unusable header must not fail the business write. - *
        • The aggregate order is the occurrence time in microseconds. The sample's aggregates keep no - * event counter, and time order is the order the pre-canonical outbox released them in; a - * service whose aggregate has a version column should use that instead. + *
        • The aggregate order comes from {@link OutboxAggregateSequencePort}, in the same transaction + * as the append, so it follows commit order. It used to be the occurrence time in + * microseconds, which two instances with different clocks, an NTP step back, or two events in + * one microsecond turn into an order that is not the commit order (review 06-07). A service + * whose aggregate has a version column may use that instead. *
        */ public final class PortfolioEventOutbox { /** The tenant every sample aggregate belongs to; the sample is single-tenant. */ - static final String TENANT_SCOPE = "portfolio"; - - private static final Pattern CORRELATION_GRAMMAR = - Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,95}"); + static final String TENANT_SCOPE = IntegrationEventDrafts.SINGLE_TENANT_SCOPE; private final OutboxAppendPort outbox; private final IntegrationEventEncoderPort encoder; private final OutboxEventIdFactory eventIds; private final CorrelationIdPort correlations; private final Clock clock; + private final OutboxAggregateSequencePort sequences; public PortfolioEventOutbox( OutboxAppendPort outbox, IntegrationEventEncoderPort encoder, OutboxEventIdFactory eventIds, CorrelationIdPort correlations, - Clock clock) { + Clock clock, + OutboxAggregateSequencePort sequences) { this.outbox = Objects.requireNonNull(outbox, "outbox"); this.encoder = Objects.requireNonNull(encoder, "encoder"); this.eventIds = Objects.requireNonNull(eventIds, "eventIds"); this.correlations = Objects.requireNonNull(correlations, "correlations"); this.clock = Objects.requireNonNull(clock, "clock"); + this.sequences = Objects.requireNonNull(sequences, "sequences"); } /** @@ -74,34 +73,18 @@ public final class PortfolioEventOutbox { String aggregateType, String aggregateId, P payload) { - String eventId = eventIds.newEventId(); + EventId eventId = new EventId(eventIds.newEventId()); Instant occurredAt = clock.instant(); - String correlationId = - correlations - .currentCorrelationId() - .filter(value -> CORRELATION_GRAMMAR.matcher(value).matches()) - .orElse(eventId); + AggregateIdentity aggregate = new AggregateIdentity(TENANT_SCOPE, aggregateType, aggregateId); outbox.append( encoder.encode( - new IntegrationEventDraft<>( - new EventId(eventId), - contract.contractId(), - contract.payloadVersion(), - contract.descriptor().logicalDestination(), - new AggregateIdentity(TENANT_SCOPE, aggregateType, aggregateId), - new AggregateOrder(sequenceOf(occurredAt), 0), + IntegrationEventDrafts.draft( + contract, + eventId, + aggregate, + new AggregateOrder(sequences.nextSequence(aggregate), 0), occurredAt, - correlationId, - Optional.empty(), + correlations.currentCorrelationId(), payload))); } - - /** Microseconds since the epoch, increasing with time; at least 1, as an aggregate order is. */ - static long sequenceOf(Instant occurredAt) { - return Math.max( - 1L, - Math.addExact( - Math.multiplyExact(occurredAt.getEpochSecond(), 1_000_000L), - occurredAt.getNano() / 1_000L)); - } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/UpdatePosterUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/UpdatePosterUseCase.java index 3f7a3e84..d2bf7cba 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/UpdatePosterUseCase.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/UpdatePosterUseCase.java @@ -13,6 +13,12 @@ import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; /** * Partial update of a poster's title/caption using {@code Patch} 3-state semantics. Mirrors {@code * UpdateWorkLogUseCase}. + * + *

        Title contract: renaming onto a title another poster holds (ignoring case) fails with {@link + * PosterTitleAlreadyExistsException} → 409 {@code POSTER_ALREADY_EXISTS}, the same answer create + * gives. Unlike create there is no {@code existsByTitle} question first: it would also find this + * poster's own title and refuse a case-only rename. {@link PosterRepository#save} reports the + * unique-index violation, so the rule holds under concurrent renames too. */ @RequiresPermission("poster:write") @UseCaseCapability( diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/ListWorkLogsUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/ListWorkLogsUseCase.java index f75bf19a..7d334171 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/ListWorkLogsUseCase.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/ListWorkLogsUseCase.java @@ -6,26 +6,28 @@ import dev.caskeleton.application.capability.UseCaseCapability; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.QueryUseCase; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; +/** + * The board's paged list. It reads the summary projection, not the aggregate: the list shows six + * columns, and loading each listed WorkLog would read its two collections per item. See README. + */ @UseCaseCapability( transactionMode = TransactionMode.READ_ONLY, idempotency = Idempotency.IDEMPOTENT, repositoryAccess = RepositoryAccess.READ_REPOSITORY) -public class ListWorkLogsUseCase implements QueryUseCase { +public class ListWorkLogsUseCase implements QueryUseCase { - private final WorkLogRepository repository; + private final WorkLogSummaryQueryPort queries; private final TransactionPort tx; - public ListWorkLogsUseCase(WorkLogRepository repository, TransactionPort tx) { - this.repository = repository; + public ListWorkLogsUseCase(WorkLogSummaryQueryPort queries, TransactionPort tx) { + this.queries = queries; this.tx = tx; } @Override - public WorkLogPage handle(ListWorkLogsQuery q) { + public WorkLogSummaryPage handle(ListWorkLogsQuery q) { return tx.inRead( - () -> repository.findPage(q.page(), q.size(), q.sortField(), q.ascending(), q.category())); + () -> queries.findPage(q.page(), q.size(), q.sortField(), q.ascending(), q.category())); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/UpdateWorkLogCommand.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/UpdateWorkLogCommand.java index 52f2e42d..97e0782a 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/UpdateWorkLogCommand.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/UpdateWorkLogCommand.java @@ -11,12 +11,14 @@ import java.util.OptionalLong; /** * A partial update. * + * @param editor the authenticated caller's subject; only the work log's owner may edit it * @param expectedVersion the version the caller last read; empty sets no precondition. Compared by * the use case inside its write transaction, so no other write can land between the check and * the update. */ public record UpdateWorkLogCommand( WorkLogId id, + String editor, Patch title, Patch summary, Patch content, @@ -29,6 +31,7 @@ public record UpdateWorkLogCommand( // fast at construction; use Patch.absent() for "no change", never null. See README. public UpdateWorkLogCommand { Objects.requireNonNull(id, "id"); + Objects.requireNonNull(editor, "editor"); Objects.requireNonNull(title, "title"); Objects.requireNonNull(summary, "summary"); Objects.requireNonNull(content, "content"); diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/UpdateWorkLogUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/UpdateWorkLogUseCase.java index 70a0c961..81c8492c 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/UpdateWorkLogUseCase.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/UpdateWorkLogUseCase.java @@ -9,9 +9,20 @@ import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.CommandUseCase; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogOwner; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus; +/** + * Applies a partial update — only for the work log's owner. + * + *

        Two checks, and they answer different questions. {@code @RequiresPermission} asks whether the + * caller may edit work logs at all (role → permission, before the use case runs). The owner check + * asks whether this caller may edit this work log; it needs the stored owner, so it runs here, + * after the read and inside the same write transaction as the change, where no other write can slip + * between the check and the update. A copy of this use case that drops the owner check lets every + * holder of {@code worklog:write} edit everyone's records. See README. + */ @RequiresPermission("worklog:write") @UseCaseCapability( transactionMode = TransactionMode.WRITE, @@ -35,6 +46,9 @@ public class UpdateWorkLogUseCase implements CommandUseCase new WorkLogNotFoundException(cmd.id())); + if (!w.isOwnedBy(WorkLogOwner.of(cmd.editor()))) { + throw new WorkLogNotOwnedException(cmd.id()); + } long current = w.version() == null ? 0L : w.version(); if (cmd.expectedVersion().isPresent() && cmd.expectedVersion().getAsLong() != current) { throw new WorkLogVersionMismatchException(cmd.id()); diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogNotOwnedException.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogNotOwnedException.java new file mode 100644 index 00000000..4e035fb0 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogNotOwnedException.java @@ -0,0 +1,17 @@ +package dev.caskeleton.sample.portfolio.application.worklog; + +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; + +/** + * The caller holds the permission to edit work logs but is not this work log's owner. Answered with + * 403 {@code WORKLOG_NOT_OWNER}, not 404: anyone may read a work log, so its existence is not a + * secret worth hiding. + */ +public class WorkLogNotOwnedException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public WorkLogNotOwnedException(WorkLogId id) { + super("WorkLog is owned by someone else: " + id.value()); + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedContractContribution.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedContractContribution.java index b6241aa6..fda778f6 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedContractContribution.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedContractContribution.java @@ -25,7 +25,7 @@ public final class WorkLogReservedContractContribution new ContractDescriptor( "sample-portfolio", new LogicalDestinationId("portfolio-domain-events"), - "json-schema-envelope-v1", + "json-envelope-v1", true, 64 * 1024, 128 * 1024, diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummary.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummary.java index 4f294260..0024142d 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummary.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummary.java @@ -1,6 +1,7 @@ package dev.caskeleton.sample.portfolio.application.worklog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus; import java.time.LocalDate; /** @@ -11,4 +12,9 @@ import java.time.LocalDate; * from the storage-native {@code UUID} inside the adapter. See README. */ public record WorkLogSummary( - String id, String title, WorkCategory category, LocalDate periodStart, LocalDate periodEnd) {} + String id, + String title, + WorkCategory category, + WorkLogStatus status, + LocalDate periodStart, + LocalDate periodEnd) {} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummaryPage.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummaryPage.java new file mode 100644 index 00000000..81e8abf2 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummaryPage.java @@ -0,0 +1,14 @@ +package dev.caskeleton.sample.portfolio.application.worklog; + +import java.util.List; + +/** + * One page of WorkLog summaries plus the total element count across all pages. {@code total} feeds + * the response {@code meta.page.total}; {@code items} is never {@code null}. + */ +public record WorkLogSummaryPage(List items, long total) { + + public WorkLogSummaryPage { + items = items == null ? List.of() : List.copyOf(items); + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummaryQueryPort.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummaryQueryPort.java index da6da49c..1de745d0 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummaryQueryPort.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogSummaryQueryPort.java @@ -1,15 +1,29 @@ package dev.caskeleton.sample.portfolio.application.worklog; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; import java.util.List; /** * Application read/query port for WorkLog projections. By convention a read port returning a * projection (not an aggregate) ends with {@code QueryPort}, and an ArchUnit rule keeps such a port - * from leaking domain aggregate / JPA / web types. The read-model bypass is an opt-in optimisation, - * not a forced default. See README. + * from leaking domain aggregate / JPA / web types. + * + *

        Every list of WorkLogs reads through here, never through {@code WorkLogRepository}: a list + * shows summary columns, and rebuilding each listed aggregate would load its tech-stack and link + * collections one row at a time (two extra statements per listed item). See README. */ public interface WorkLogSummaryQueryPort { + /** + * Returns one page of summaries plus the total count, in a constant number of statements however + * large the page. {@code sortField} / {@code category} may be {@code null} (unsorted / + * unfiltered); the total is computed against the same filter. A negative page reads as the first + * page and a non-positive size as pages of twenty. + */ + WorkLogSummaryPage findPage( + int page, int size, WorkLogSortField sortField, boolean ascending, WorkCategory category); + /** Returns the most recent WorkLog summaries (newest period first), at most {@code limit}. */ List findRecentSummaries(int limit); } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java index e5d61d29..6d16531a 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java @@ -2,8 +2,10 @@ package dev.caskeleton.sample.portfolio.bootstrap.application; import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; import dev.caskeleton.application.observability.CorrelationIdPort; +import dev.caskeleton.application.outbox.OutboxAggregateSequencePort; import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.sample.portfolio.application.event.OutboxEventIdFactory; import dev.caskeleton.sample.portfolio.application.event.PortfolioEventContract; import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; import dev.caskeleton.sample.portfolio.application.poster.ArchivePosterUseCase; @@ -35,7 +37,6 @@ import dev.caskeleton.sample.portfolio.application.worklog.WorkLogReservedContra import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryQueryPort; import dev.caskeleton.sample.portfolio.domain.poster.PosterIdFactory; import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; -import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogIdFactory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; import java.time.Clock; @@ -99,8 +100,9 @@ public class SampleApplicationUseCaseConfig { IntegrationEventEncoderPort encoder, OutboxEventIdFactory eventIds, CorrelationIdPort correlations, - Clock clock) { - return new PortfolioEventOutbox(outbox, encoder, eventIds, correlations, clock); + Clock clock, + OutboxAggregateSequencePort sequences) { + return new PortfolioEventOutbox(outbox, encoder, eventIds, correlations, clock, sequences); } @Bean @@ -199,8 +201,8 @@ public class SampleApplicationUseCaseConfig { @Bean ListWorkLogsUseCase listWorkLogsUseCase( - WorkLogRepository repository, TransactionPort transactions) { - return new ListWorkLogsUseCase(repository, transactions); + WorkLogSummaryQueryPort queries, TransactionPort transactions) { + return new ListWorkLogsUseCase(queries, transactions); } @Bean diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/OutboxEventIdFactory.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/OutboxEventIdFactory.java deleted file mode 100644 index 12e74e97..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/OutboxEventIdFactory.java +++ /dev/null @@ -1,16 +0,0 @@ -package dev.caskeleton.sample.portfolio.domain.worklog; - -/** - * Domain port that mints opaque string identifiers for outbox events. Kept distinct from {@link - * WorkLogIdFactory} so the aggregate id type does not constrain the event id shape; the returned - * value is used as both {@code eventId} and {@code idempotencyKey}. See README. - */ -public interface OutboxEventIdFactory { - - /** - * Mints a new, globally unique event identifier. - * - * @return a non-null, non-blank string suitable for use as a UUIDv7 event id - */ - String newEventId(); -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLog.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLog.java index a5cd5860..c3fa7313 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLog.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLog.java @@ -197,6 +197,11 @@ public class WorkLog { } } + /** Whether {@code candidate} is the owner this work log was created for. */ + public boolean isOwnedBy(WorkLogOwner candidate) { + return owner.equals(candidate); + } + public WorkLogId id() { return id; } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogPage.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogPage.java deleted file mode 100644 index ec592dff..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogPage.java +++ /dev/null @@ -1,14 +0,0 @@ -package dev.caskeleton.sample.portfolio.domain.worklog; - -import java.util.List; - -/** - * One page of WorkLogs plus the total element count across all pages. {@code total} feeds the - * response {@code meta.page.total}; {@code items} is never {@code null}. - */ -public record WorkLogPage(List items, long total) { - - public WorkLogPage { - items = items == null ? List.of() : List.copyOf(items); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogRepository.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogRepository.java index 4c0c8084..4ae6dbfb 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogRepository.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogRepository.java @@ -2,20 +2,16 @@ package dev.caskeleton.sample.portfolio.domain.worklog; import java.util.Optional; -/** Outbound port for WorkLog persistence. Implemented in adapter-persistence. */ +/** + * Outbound port for WorkLog persistence, one aggregate at a time. Implemented in + * adapter-persistence. Lists read the summary projection ({@code WorkLogSummaryQueryPort}), not + * this port. See README. + */ public interface WorkLogRepository { WorkLog save(WorkLog workLog); Optional findById(WorkLogId id); - /** - * Returns one page of WorkLogs plus the total count. {@code sortField} / {@code category} may be - * {@code null} (unsorted / unfiltered); the total is computed against the same filter. See - * README. - */ - WorkLogPage findPage( - int page, int size, WorkLogSortField sortField, boolean ascending, WorkCategory category); - boolean existsById(WorkLogId id); void deleteById(WorkLogId id); diff --git a/src/sample-portfolio/src/main/resources/application.yml b/src/sample-portfolio/src/main/resources/application.yml index 8b3404e7..7c5ec9fe 100644 --- a/src/sample-portfolio/src/main/resources/application.yml +++ b/src/sample-portfolio/src/main/resources/application.yml @@ -1,7 +1,10 @@ # ============================================================================= # sample-portfolio standalone application configuration. -# Mirrors app-bootstrap/application.yml for the settings that scanned beans require. -# Values are driven by env vars so the same src/.env file used by app-bootstrap works here. +# Only the settings this composition's beans read. A runtime value the default composition +# (app-bootstrap) also sets keeps the same default here, so a number measured on the sample says +# something about the default composition (09-08); a module's own defaults +# (config/module-defaults/*.yml) are not restated. Where the sample differs on purpose, the reason +# sits next to the key. Values are driven by env vars so the same src/.env works for both. # ============================================================================= spring: @@ -33,7 +36,6 @@ spring: hikari: maximum-pool-size: ${APP_DATASOURCE_POOL_MAX_SIZE:10} minimum-idle: ${APP_DATASOURCE_POOL_MIN_IDLE:2} - connection-timeout: ${APP_DATASOURCE_CONNECTION_TIMEOUT:30000} idle-timeout: ${APP_DATASOURCE_POOL_IDLE_TIMEOUT:600000} max-lifetime: ${APP_DATASOURCE_POOL_MAX_LIFETIME:1800000} keepalive-time: 120000 @@ -56,19 +58,28 @@ spring: properties: hibernate: format_sql: ${APP_DATASOURCE_FORMAT_SQL:false} + # POST /api/worklogs:batchCreate writes up to MAX_BATCH_SIZE work logs, each with its + # tech-stack and link rows, in one transaction. Without JDBC batching every row is its own + # round trip while the request holds a pool connection; with it the work_log rows go 50 per + # round trip, grouped by table (order_inserts). Element-collection rows batch across work logs too + # (new entities are persisted, not merged — review 04-17): 100 items = 400 -> 8 round trips, pinned by + # WorkLogStatementCostSystemTest. Same env keys as the persistence-jpa + # module defaults, which leave batching off; this service turns it on because it has a + # bulk write. Measured numbers: README "BatchCreateWorkLogsUseCase". + jdbc: + batch_size: ${APP_JPA_HIBERNATE_BATCH_SIZE:50} + order_inserts: ${APP_JPA_HIBERNATE_ORDER_INSERTS:true} # spring.security.oauth2.resourceserver.jwt is intentionally absent. - # The custom JwtDecoderConfig (adapter-web) builds its JwtDecoder from - # app.security.issuer-uri via SecuritySettings — not from Spring Boot's - # OAuth2ResourceServer auto-config. Declaring issuer-uri here would activate - # OAuth2SecurityFilterChainConfiguration, which requires HttpSecurity and therefore - # SecurityAutoConfiguration — breaking narrow @WebMvcTest slices that exclude Security. + # No issuer or audience anywhere in this file: the sample authenticates its demo accounts + # (SampleDemoSecurityConfig) and excludes the web leaf's JWT chain, so nothing would read them. main: banner-mode: ${SPRING_BANNER_MODE:off} lazy-initialization: ${SPRING_MAIN_LAZY_INITIALIZATION:false} log-startup-info: ${SPRING_MAIN_LOG_STARTUP_INFO:true} threads: virtual: - enabled: ${SPRING_THREADS_VIRTUAL_ENABLED:false} + # Same default as app-bootstrap: request handling on virtual threads. + enabled: ${SPRING_THREADS_VIRTUAL_ENABLED:true} jackson: deserialization: fail-on-unknown-properties: ${SPRING_JACKSON_DESER_FAIL_ON_UNKNOWN_PROPERTIES:true} @@ -136,7 +147,7 @@ server: logging: level: root: ${APP_LOG_LEVEL_ROOT:INFO} - dev.caskeleton: ${APP_LOG_LEVEL_APP:DEBUG} + dev.caskeleton: ${APP_LOG_LEVEL_APP:INFO} org.springframework: ${APP_LOG_LEVEL_SPRING:INFO} org.springframework.web: ${APP_LOG_LEVEL_WEB:INFO} org.hibernate.SQL: ${APP_LOG_LEVEL_SQL:WARN} @@ -147,40 +158,11 @@ logging: # --------------------------------------------------------------------------- app: capabilities: - cache: - bindings: - default: ${APP_CACHE_CANONICAL_DEFAULT_PROVIDER:disabled} - regions: - default: - key-hmac-secret-reference: secret://environment/APP_CACHE_REDIS_KEY_HMAC_SECRET - namespace-application: ${APP_NAME:sample-portfolio} - namespace-environment: ${APP_CACHE_REDIS_NAMESPACE_ENVIRONMENT:local} - semantic-region: ${APP_CACHE_REDIS_SEMANTIC_REGION:default} - hash-key-version: 1 - key-version: 1 - policy-revision: canonical-default-r1 - positive-soft-ttl: ${APP_CACHE_REDIS_POSITIVE_SOFT_TTL:240s} - positive-hard-ttl: ${APP_CACHE_DEFAULT_TTL:300s} - negative-ttl: ${APP_CACHE_NEGATIVE_TTL:60s} - ttl-jitter: ${APP_CACHE_REDIS_TTL_JITTER:0.10} - maximum-value-bytes: 61440 - l1: - enabled: ${APP_CACHE_REDIS_L1_ENABLED:false} - maximum-entries: ${APP_CACHE_REDIS_L1_MAXIMUM_ENTRIES:10000} - maximum-weight-bytes: ${APP_CACHE_REDIS_L1_MAXIMUM_WEIGHT_BYTES:67108864} - maximum-entry-weight-bytes: ${APP_CACHE_REDIS_L1_MAXIMUM_ENTRY_WEIGHT_BYTES:1048576} - time-to-live: ${APP_CACHE_REDIS_L1_TTL:30s} - generation-recheck-interval: ${APP_CACHE_REDIS_L1_GENERATION_RECHECK_INTERVAL:5s} - invalidation-queue-capacity: ${APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY:1024} # The only IdempotencyStorePort this composition can produce is persistence-jpa's PostgreSQL # store, which applies its own migration stream when selected. composition:idempotency builds # the executor over it (the same module app-bootstrap uses); `disabled` builds neither. idempotency: provider: ${APP_IDEMPOTENCY_PROVIDER:postgresql} - bootstrap: - app-name: ${APP_NAME:sample-portfolio} - runtime: - multi-instance-enabled: ${APP_MULTI_INSTANCE_ENABLED:false} lock: wait-time: 3s lease-ttl: 30s @@ -191,38 +173,12 @@ app: default-policy-id: ${APP_RATE_LIMIT_DEFAULT_POLICY_ID:api-default} hash-key-version: ${APP_RATE_LIMIT_HASH_KEY_VERSION:1} caller-deadline-budget: 2s - security: - issuer-uri: ${APP_SECURITY_JWT_ISSUER:http://localhost:8080/auth/realms/sample} - audience: ${APP_SECURITY_JWT_AUDIENCE:} - public-paths: ${SECURITY_PUBLIC_PATHS:/api/healthcheck} + # Read by method security (WebMethodSecurityAutoConfiguration), which the sample keeps. The JWT + # chain's own settings (app.security.*, app.cors.*) are absent: that chain is excluded. authz: role-permissions: user: worklog:read,worklog:write,poster:write admin: worklog:read,worklog:write,worklog:close,poster:write,poster:close - cors: - enabled: ${APP_SECURITY_CORS_ENABLED:true} - allowed-origins: ${APP_SECURITY_CORS_ORIGINS:http://localhost:3000} - allowed-methods: ${APP_SECURITY_CORS_ALLOWED_METHODS:} - allowed-headers: ${APP_SECURITY_CORS_ALLOWED_HEADERS:*} - allow-credentials: ${APP_SECURITY_CORS_ALLOW_CREDENTIALS:true} - max-age-seconds: ${APP_SECURITY_CORS_MAX_AGE:3600} - logging: - file: - enabled: ${APP_LOG_FILE_ENABLED:false} - path: ${APP_LOG_FILE_PATH:logs/sample-portfolio.json} - max-size: ${APP_LOG_FILE_MAX_SIZE:100MB} - max-history: ${APP_LOG_FILE_MAX_HISTORY:14} - total-size-cap: ${APP_LOG_FILE_TOTAL_SIZE_CAP:3GB} - async: - enabled: ${APP_LOG_ASYNC_ENABLED:true} - queue-size: ${APP_LOG_ASYNC_QUEUE_SIZE:512} - discarding-threshold: ${APP_LOG_ASYNC_DISCARDING_THRESHOLD:20} - json: - timezone: ${APP_LOG_JSON_TIMEZONE:UTC} - timestamp-pattern: ${APP_LOG_JSON_TIMESTAMP_PATTERN:"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"} - include-caller-data: ${APP_LOG_JSON_INCLUDE_CALLER_DATA:false} - logger-name-length: ${APP_LOG_JSON_LOGGER_NAME_LENGTH:0} - sampling-rate: ${APP_LOG_SAMPLING_RATE:1.0} privacy: pseudonymization-salt: ${APP_PRIVACY_PSEUDONYMIZATION_SALT:} tracing: @@ -251,31 +207,6 @@ app: enabled: false publication: enabled: false - cache: - redis: - enabled: ${APP_CACHE_REDIS_ENABLED:false} - client-mode: ${APP_CACHE_REDIS_CLIENT_MODE:managed} - host: ${APP_CACHE_REDIS_HOST:} - port: ${APP_CACHE_REDIS_PORT:6379} - password: ${APP_CACHE_REDIS_PASSWORD:} - key-hmac-secret: ${APP_CACHE_REDIS_KEY_HMAC_SECRET:} - command-timeout: ${APP_CACHE_REDIS_COMMAND_TIMEOUT:2s} - maximum-queued-commands: ${APP_CACHE_REDIS_MAXIMUM_QUEUED_COMMANDS:8} - maximum-in-flight-bytes: ${APP_CACHE_REDIS_MAXIMUM_IN_FLIGHT_BYTES:16777216} - positive-ttl: ${APP_CACHE_DEFAULT_TTL:300s} - negative-ttl: ${APP_CACHE_NEGATIVE_TTL:60s} - namespace-application: ${APP_NAME:ca-skeleton} - namespace-environment: ${APP_CACHE_REDIS_NAMESPACE_ENVIRONMENT:local} - semantic-region: ${APP_CACHE_REDIS_SEMANTIC_REGION:default} - maximum-value-bytes: ${APP_CACHE_REDIS_MAXIMUM_VALUE_BYTES:1048576} - l1: - enabled: ${APP_CACHE_REDIS_L1_ENABLED:false} - maximum-entries: ${APP_CACHE_REDIS_L1_MAXIMUM_ENTRIES:10000} - maximum-weight-bytes: ${APP_CACHE_REDIS_L1_MAXIMUM_WEIGHT_BYTES:67108864} - maximum-entry-weight-bytes: ${APP_CACHE_REDIS_L1_MAXIMUM_ENTRY_WEIGHT_BYTES:1048576} - time-to-live: ${APP_CACHE_REDIS_L1_TTL:30s} - generation-recheck-interval: ${APP_CACHE_REDIS_L1_GENERATION_RECHECK_INTERVAL:5s} - invalidation-queue-capacity: ${APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY:1024} messaging: broker: ${APP_MESSAGING_BROKER:} notification: diff --git a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/SampleApiDocsSystemTest.java b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/SampleApiDocsSystemTest.java new file mode 100644 index 00000000..ad11eb0f --- /dev/null +++ b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/SampleApiDocsSystemTest.java @@ -0,0 +1,57 @@ +package dev.caskeleton.sample.portfolio.adapter.inbound.web; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.sample.portfolio.SamplePortfolioApplication; +import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.test.context.ActiveProfiles; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * The OpenAPI document is served by the whole sample composition, not only by the slice the drift + * gate boots. + * + *

        The drift gate ({@code OpenApiDriftContractTest}) leaves the web adapter's response advice + * out, so it could not see that the advice wrapped springdoc's already-serialized document in an + * envelope and failed every {@code /api/v3/api-docs} request of a running sample with 500. + */ +@SpringBootTest( + classes = SamplePortfolioApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +@Testcontainers(disabledWithoutDocker = true) +class SampleApiDocsSystemTest { + + @Container @ServiceConnection + static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); + + @LocalServerPort int port; + + @Test + void theRunningSampleServesItsOpenApiDocumentUnwrapped() throws Exception { + // when + HttpResponse response = + HttpClient.newHttpClient() + .send( + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/api/v3/api-docs")) + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()); + + // then: the document itself, not an envelope around it + assertThat(List.of(response.statusCode(), response.body().startsWith("{\"openapi\":\"3."))) + .as(response.body()) + .containsExactly(200, true); + } +} diff --git a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/InsertRoundTripCounter.java b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/InsertRoundTripCounter.java new file mode 100644 index 00000000..8fc17286 --- /dev/null +++ b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/InsertRoundTripCounter.java @@ -0,0 +1,119 @@ +package dev.caskeleton.sample.portfolio.adapter.outbound.persistence; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicLong; +import javax.sql.DataSource; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.jdbc.datasource.DelegatingDataSource; + +/** + * Counts the JDBC calls that send work-log inserts to the database: each {@code executeBatch()} is + * one round trip however many rows it carries, each {@code executeUpdate()} one round trip for one + * row. + * + *

        Counted at the JDBC layer because nothing above it can tell: Hibernate's statement inspector + * sees the insert SQL once per collection action whether or not the rows travel in one batch, and + * PostgreSQL's statement log records every row of a batch as its own execute. + */ +public final class InsertRoundTripCounter { + + private static final AtomicLong ROUND_TRIPS = new AtomicLong(); + + private InsertRoundTripCounter() {} + + /** Forgets every call counted so far. */ + public static void clear() { + ROUND_TRIPS.set(0L); + } + + /** Round trips that carried inserts into a work-log table since the last {@link #clear()}. */ + public static long roundTrips() { + return ROUND_TRIPS.get(); + } + + /** Wraps the application's data source so its insert statements are counted. */ + @TestConfiguration(proxyBeanMethods = false) + public static class Config { + + @Bean + static BeanPostProcessor countingDataSource() { + return new BeanPostProcessor() { + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) { + return bean instanceof DataSource dataSource && !(bean instanceof CountingDataSource) + ? new CountingDataSource(dataSource) + : bean; + } + }; + } + } + + private static final class CountingDataSource extends DelegatingDataSource { + + CountingDataSource(DataSource target) { + super(target); + } + + @Override + public Connection getConnection() throws SQLException { + return counting(super.getConnection()); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return counting(super.getConnection(username, password)); + } + } + + private static Connection counting(Connection connection) { + return proxy( + Connection.class, + connection, + (target, method, args) -> { + Object result = invoke(target, method, args); + if (method.getName().equals("prepareStatement") + && args != null + && args[0] instanceof String sql + && sql.toLowerCase(Locale.ROOT).startsWith("insert into work_log")) { + return proxy(PreparedStatement.class, result, InsertRoundTripCounter::countExecution); + } + return result; + }); + } + + private static Object countExecution(Object target, Method method, Object[] args) + throws Throwable { + if (method.getName().equals("executeBatch") || method.getName().equals("executeUpdate")) { + ROUND_TRIPS.incrementAndGet(); + } + return invoke(target, method, args); + } + + private interface Handler { + Object handle(Object target, Method method, Object[] args) throws Throwable; + } + + private static T proxy(Class type, Object target, Handler handler) { + InvocationHandler invocation = (p, method, args) -> handler.handle(target, method, args); + return type.cast( + Proxy.newProxyInstance( + InsertRoundTripCounter.class.getClassLoader(), new Class[] {type}, invocation)); + } + + private static Object invoke(Object target, Method method, Object[] args) throws Throwable { + try { + return method.invoke(target, args); + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + } +} diff --git a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/RecordingStatementInspector.java b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/RecordingStatementInspector.java new file mode 100644 index 00000000..a9673f31 --- /dev/null +++ b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/RecordingStatementInspector.java @@ -0,0 +1,36 @@ +package dev.caskeleton.sample.portfolio.adapter.outbound.persistence; + +import java.util.List; +import java.util.Locale; +import java.util.concurrent.CopyOnWriteArrayList; +import org.hibernate.resource.jdbc.spi.StatementInspector; + +/** + * Records every SQL statement Hibernate prepares, so a test can count what one HTTP request cost. + * + *

        Hibernate builds the inspector from its class name ({@code + * hibernate.session_factory.statement_inspector}), so the record is static. Background jobs of the + * running sample (idempotency reaper, outbox reaper) prepare statements too; a test therefore reads + * only the statements that touch the tables it is about, never the raw total. + */ +public final class RecordingStatementInspector implements StatementInspector { + + private static final List STATEMENTS = new CopyOnWriteArrayList<>(); + + @Override + public String inspect(String sql) { + STATEMENTS.add(sql.toLowerCase(Locale.ROOT)); + return sql; + } + + /** Forgets everything recorded so far. */ + public static void clear() { + STATEMENTS.clear(); + } + + /** The recorded statements that name {@code table}, in the order they were prepared. */ + public static List touching(String table) { + String name = table.toLowerCase(Locale.ROOT); + return STATEMENTS.stream().filter(sql -> sql.contains(name)).toList(); + } +} diff --git a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/WorkLogStatementCostSystemTest.java b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/WorkLogStatementCostSystemTest.java new file mode 100644 index 00000000..043c66da --- /dev/null +++ b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/WorkLogStatementCostSystemTest.java @@ -0,0 +1,200 @@ +package dev.caskeleton.sample.portfolio.adapter.outbound.persistence; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.sample.portfolio.SamplePortfolioApplication; +import dev.caskeleton.sample.portfolio.domain.worklog.Period; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +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.WorkLogRepository; +import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ActiveProfiles; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * What one work-log request costs in SQL, counted on the running sample over a real PostgreSQL. + * + *

        The sample is the pattern new features copy, so a request whose statement count grows with the + * page size, or an edit that rewrites rows it did not change, is copied with it. Hibernate hands + * every statement to {@link RecordingStatementInspector}; each test counts only the statements that + * touch the work-log tables, so the sample's background jobs cannot move the number. Insert round + * trips are counted below Hibernate by {@link InsertRoundTripCounter}. + */ +@SpringBootTest( + classes = SamplePortfolioApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = + "spring.jpa.properties.hibernate.session_factory.statement_inspector=" + + "dev.caskeleton.sample.portfolio.adapter.outbound.persistence.RecordingStatementInspector") +@Import(InsertRoundTripCounter.Config.class) +@ActiveProfiles("test") +@Testcontainers(disabledWithoutDocker = true) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class WorkLogStatementCostSystemTest { + + @Container @ServiceConnection + static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); + + private static final String OWNER = "demo-user"; + + private final HttpClient http = HttpClient.newHttpClient(); + + @LocalServerPort int port; + + @Autowired WorkLogRepository repository; + + @Autowired TransactionPort transactions; + + /** A full page at both sizes, each row with two tech-stack rows and one link row. */ + @BeforeAll + void storeOneHundredWorkLogs() { + transactions.inWrite( + () -> { + IntStream.rangeClosed(1, 100).forEach(n -> repository.save(workLog("stored-" + n))); + return null; + }); + } + + @Test + void listingAPageCostsTheSameStatementsAtTwentyAndAtAHundredItems() throws Exception { + // given + int twenty = statementsFor(get("/api/worklogs?size=20")); + + // when + int hundred = statementsFor(get("/api/worklogs?size=100")); + + // then: one page read and one count, never a read per listed item + assertThat(List.of(twenty, hundred)).containsExactly(2, 2); + } + + @Test + void patchingOnlyTheTitleLeavesTheTechStackAndLinkRowsUntouched() throws Exception { + // given + WorkLogId id = WorkLogId.of(UUID.randomUUID().toString()); + transactions.inWrite(() -> repository.save(workLog(id, "before"))); + RecordingStatementInspector.clear(); + + // when + HttpResponse response = send(patchTitle(id, "after"), OWNER); + + // then + assertThat(List.of(response.statusCode(), collectionWrites())).containsExactly(200, List.of()); + } + + /** + * One hundred work logs carry four hundred rows (work_log, two tech-stack rows, one link row). + * Row by row that is four hundred round trips on one pooled connection. With JDBC batching (50) + * and insert ordering, every table travels fifty rows per round trip: work_log 2 + tech-stack 4 + + * link 2 = 8. The element-collection rows batch across owners because the work logs are new + * entities persisted, not merged ({@code Persistable}, review 04-17); before that each owner's + * collection rows went alone and the count was 202. The number pins the whole shape: a + * regression to per-owner collection inserts shows as 202, to row-by-row as 400. + */ + @Test + void batchCreatingAHundredWorkLogsSendsTheWorkLogRowsInJdbcBatches() throws Exception { + // given + InsertRoundTripCounter.clear(); + + // when + HttpResponse response = send(batchCreate(100), OWNER); + + // then + assertThat(List.of(response.statusCode(), InsertRoundTripCounter.roundTrips())) + .containsExactly(200, 8L); + } + + private HttpRequest.Builder batchCreate(int items) { + String item = + "{\"title\":\"batch\",\"category\":\"BACKEND\",\"techStack\":[\"java\",\"jpa\"]," + + "\"links\":[\"https://example.test/a\"],\"periodStart\":\"2025-01-01\"}"; + String body = "{\"requests\":[" + String.join(",", Collections.nCopies(items, item)) + "]}"; + return HttpRequest.newBuilder(uri("/api/worklogs:batchCreate")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body)); + } + + private int statementsFor(HttpRequest.Builder request) throws Exception { + RecordingStatementInspector.clear(); + HttpResponse response = send(request, null); + assertThat(response.statusCode()).as(response.body()).isEqualTo(200); + return RecordingStatementInspector.touching("work_log").size(); + } + + private static List collectionWrites() { + return Stream.concat( + RecordingStatementInspector.touching("work_log_tech_stack").stream(), + RecordingStatementInspector.touching("work_log_link").stream()) + .filter(sql -> !sql.startsWith("select")) + .toList(); + } + + private static WorkLog workLog(String title) { + return workLog(WorkLogId.of(UUID.randomUUID().toString()), title); + } + + private static WorkLog workLog(WorkLogId id, String title) { + return WorkLog.create( + id, + WorkLogOwner.of(OWNER), + title, + WorkCategory.DATABASE, + "summary", + "content", + List.of("postgresql", "jpa"), + List.of("https://example.test/" + title), + new Period(LocalDate.of(2025, 1, 1), null)); + } + + private HttpRequest.Builder get(String path) { + return HttpRequest.newBuilder(uri(path)).GET(); + } + + private HttpRequest.Builder patchTitle(WorkLogId id, String title) { + return HttpRequest.newBuilder(uri("/api/worklogs/" + id.value())) + .header("Content-Type", "application/json") + .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"title\":\"" + title + "\"}")); + } + + private HttpResponse send(HttpRequest.Builder request, String demoAccount) + throws IOException, InterruptedException { + if (demoAccount != null) { + // The demo accounts publish their own name as the password; see SampleDemoSecurityConfig. + String credentials = demoAccount + ":" + demoAccount; + request.header( + "Authorization", + "Basic " + + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8))); + } + return http.send(request.build(), HttpResponse.BodyHandlers.ofString()); + } + + private URI uri(String path) { + return URI.create("http://localhost:" + port + path); + } +} diff --git a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java index 3cfc6904..d5f6c7d7 100644 --- a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java +++ b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java @@ -8,6 +8,7 @@ import dev.caskeleton.sample.portfolio.domain.worklog.Period; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; 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.WorkLogRepository; import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; import java.io.IOException; @@ -115,13 +116,46 @@ class SampleWorkLogAuthorizationSystemTest { assertThat(response.statusCode()).isEqualTo(401); } + @Test + void updateByTheOwnerAppliesTheChange() throws Exception { + // given + WorkLogId id = storedWorkLog("demo-user"); + + // when + HttpResponse response = send(renameTo(id, "renamed by owner"), "demo-user"); + + // then + assertThat(List.of(response.statusCode(), title(id))).containsExactly(200, "renamed by owner"); + } + + /** + * {@code demo-admin} holds {@code worklog:write}, so the permission check lets it through; the + * record belongs to {@code demo-user}, so the owner check must not. + */ + @Test + void updateByAnAccountThatDoesNotOwnTheRecordIsForbiddenAndKeepsTheRecord() throws Exception { + // given + WorkLogId id = storedWorkLog("demo-user"); + + // when + HttpResponse response = send(renameTo(id, "renamed by someone else"), "demo-admin"); + + // then + assertThat(List.of(response.statusCode(), title(id))).containsExactly(403, "stored"); + } + private WorkLogId storedWorkLog() { + return storedWorkLog("sample-owner"); + } + + private WorkLogId storedWorkLog(String owner) { WorkLogId id = WorkLogId.of(UUID.randomUUID().toString()); transactions.inWrite( () -> repository.save( WorkLog.create( id, + WorkLogOwner.of(owner), "stored", WorkCategory.DATABASE, "summary", @@ -136,6 +170,16 @@ class SampleWorkLogAuthorizationSystemTest { return transactions.inRead(() -> repository.existsById(id)); } + private String title(WorkLogId id) { + return transactions.inRead(() -> repository.findById(id).orElseThrow().title()); + } + + private HttpRequest.Builder renameTo(WorkLogId id, String title) { + return HttpRequest.newBuilder(uri("/api/worklogs/" + id.value())) + .header("Content-Type", "application/json") + .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"title\":\"" + title + "\"}")); + } + private HttpRequest.Builder delete(WorkLogId id) { return HttpRequest.newBuilder(uri("/api/worklogs/" + id.value())).DELETE(); } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsControllerWireTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsControllerWireTest.java index d05390c8..e6973af5 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsControllerWireTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsControllerWireTest.java @@ -83,4 +83,16 @@ class OperationsControllerWireTest { .andExpect(jsonPath("$.data.status").value("SUCCEEDED")) .andExpect(jsonPath("$.data.result.exportedCount").value(0)); } + + /** An id the store never issued is a missing resource, not a malformed request. */ + @Test + void pollingAnUnknownOperationIsA404() throws Exception { + // when + ResultActions result = mvc.perform(get("/operations/no-such-operation")); + + // then + result + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error.code").value("OPERATION_NOT_FOUND")); + } } 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 aaa57ccd..cc319c83 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 @@ -21,6 +21,7 @@ import dev.caskeleton.sample.portfolio.application.poster.GetPosterQuery; import dev.caskeleton.sample.portfolio.application.poster.GetPosterUseCase; import dev.caskeleton.sample.portfolio.application.poster.ListPostersUseCase; import dev.caskeleton.sample.portfolio.application.poster.PosterNotFoundException; +import dev.caskeleton.sample.portfolio.application.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.application.poster.PublishPosterUseCase; import dev.caskeleton.sample.portfolio.application.poster.UpdatePosterUseCase; import dev.caskeleton.sample.portfolio.domain.poster.Poster; @@ -260,6 +261,26 @@ class PosterControllerWireTest { // then result.andExpect(status().isOk()).andExpect(jsonPath("$.data.title").value("새 제목")); } + + /** Renaming onto another poster's title breaks the same rule creating it would: 409. */ + @Test + void patchToATitleAnotherPosterHoldsReturns409PosterAlreadyExists() throws Exception { + // given + when(updateUseCase.handle(any())) + .thenThrow(new PosterTitleAlreadyExistsException("여름 세일 배너")); + + // when + ResultActions result = + mvc.perform( + patch("/posters/" + ID) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"title\":\"여름 세일 배너\"}")); + + // then + result + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error.code").value("POSTER_ALREADY_EXISTS")); + } } /** The object-storage domain invariant: a poster cannot be published without an image. */ diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationControllerWireTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationControllerWireTest.java index 2247f383..9af8d90d 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationControllerWireTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationControllerWireTest.java @@ -21,10 +21,15 @@ import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUpload import dev.caskeleton.sample.portfolio.application.posterimage.PublishPosterImageUseCase; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterImageReference; +import dev.caskeleton.shared.error.ApiErrorCarrier; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Set; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.mock.web.MockMultipartFile; @@ -111,24 +116,48 @@ class PosterImagePublicationControllerWireTest { .doesNotContain("s3://", "file://", "bucket", "presigned", "providerVersion"); } - @Test - void blankIdempotencyKeyIsRejectedBeforeCallingPublishUseCase() { + @ParameterizedTest(name = "[{index}] key=<{0}>") + @NullSource + @ValueSource(strings = {" ", "key with space", "키"}) + @DisplayName("헤더가 없거나 형식이 틀린 Idempotency-Key는 use case를 부르기 전에 IDEMPOTENCY_KEY_INVALID로 거부된다") + void aMissingOrMalformedIdempotencyKeyIsRejectedBeforeCallingPublishUseCase(String key) { // when Throwable thrown = catchThrowable( () -> controller.publish( POSTER.value(), - " ", + key, 0, ObjectDigest.sha256(new byte[] {1}).base64Value(), new MockMultipartFile("file", "x.png", "image/png", new byte[] {1}), - new AuthenticatedPrincipal("principal-a", null, Set.of()))); + PRINCIPAL)); + + // then + assertThat(thrown).isInstanceOf(ApiErrorCarrier.class); + assertThat(((ApiErrorCarrier) thrown).errorCode().code()).isEqualTo("IDEMPOTENCY_KEY_INVALID"); + verifyNoInteractions(publish); + } + + @Test + @DisplayName("인증 주체가 없으면 use case를 부르기 전에 거부된다") + void aMissingPrincipalIsRejectedBeforeCallingPublishUseCase() { + // when + Throwable thrown = + catchThrowable( + () -> + controller.publish( + POSTER.value(), + "client-key", + 0, + ObjectDigest.sha256(new byte[] {1}).base64Value(), + new MockMultipartFile("file", "x.png", "image/png", new byte[] {1}), + null)); // then assertThat(thrown) .isInstanceOf(IllegalArgumentException.class) - .hasMessage("authenticated principal and Idempotency-Key are required"); + .hasMessage("authenticated principal is required"); verifyNoInteractions(publish); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogControllerWireTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogControllerWireTest.java index 7b95bf75..b7d2a18b 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogControllerWireTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogControllerWireTest.java @@ -32,6 +32,9 @@ import dev.caskeleton.sample.portfolio.application.worklog.ListWorkLogsUseCase; import dev.caskeleton.sample.portfolio.application.worklog.UpdateWorkLogCommand; import dev.caskeleton.sample.portfolio.application.worklog.UpdateWorkLogUseCase; import dev.caskeleton.sample.portfolio.application.worklog.WorkLogNotFoundException; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogNotOwnedException; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummary; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryPage; import dev.caskeleton.sample.portfolio.application.worklog.WorkLogVersionMismatchException; import dev.caskeleton.sample.portfolio.domain.worklog.Period; import dev.caskeleton.sample.portfolio.domain.worklog.RepoStats; @@ -39,7 +42,7 @@ import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus; import dev.caskeleton.shared.request.Patch; import java.time.LocalDate; import java.util.List; @@ -49,6 +52,7 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -92,6 +96,10 @@ import org.springframework.test.web.servlet.ResultActions; class WorkLogControllerWireTest { private static final String ID = "0190bd6e-7c3e-7abc-8def-0123456789ab"; // D19 fixture + + /** The authenticated caller every PATCH in {@link PatchWorkLog} is sent as. */ + private static final String EDITOR = "sub-7"; + private static final String VALID_CREATE_BODY = "{\"title\":\"t\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}"; @@ -123,9 +131,16 @@ class WorkLogControllerWireTest { 0L); } + /** A list row as the summary projection reads it. */ + private static WorkLogSummary summary(String title) { + return new WorkLogSummary( + ID, title, WorkCategory.DATABASE, WorkLogStatus.OPEN, LocalDate.of(2025, 1, 1), null); + } + private static UpdateWorkLogCommand patchOf(Patch title, Patch summary) { return new UpdateWorkLogCommand( WorkLogId.of(ID), + EDITOR, title, summary, Patch.absent(), @@ -141,7 +156,8 @@ class WorkLogControllerWireTest { @Test void listIsWrappedInEnvelopeWithPageMeta() throws Exception { // given - when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(sample("DB 튜닝")), 1)); + when(listUseCase.handle(any())) + .thenReturn(new WorkLogSummaryPage(List.of(summary("DB 튜닝")), 1)); // when ResultActions result = mvc.perform(get("/worklogs")); @@ -160,7 +176,7 @@ class WorkLogControllerWireTest { @Test void emptyListIsDataArrayNotNullWithZeroTotal() throws Exception { // given - when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(), 0)); + when(listUseCase.handle(any())).thenReturn(new WorkLogSummaryPage(List.of(), 0)); // when ResultActions result = mvc.perform(get("/worklogs")); @@ -189,7 +205,7 @@ class WorkLogControllerWireTest { @Test void nativeSortSyntaxIsAcceptedAndEchoedInMeta() throws Exception { // given - when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(sample("a")), 1)); + when(listUseCase.handle(any())).thenReturn(new WorkLogSummaryPage(List.of(summary("a")), 1)); // when ResultActions result = mvc.perform(get("/worklogs").param("sort", "title,desc")); @@ -214,7 +230,7 @@ class WorkLogControllerWireTest { // given // only the category-filtered query is answered, so a 200 proves the filter reached it when(listUseCase.handle(new ListWorkLogsQuery(0, 20, null, true, WorkCategory.DATABASE))) - .thenReturn(new WorkLogPage(List.of(sample("a")), 1)); + .thenReturn(new WorkLogSummaryPage(List.of(summary("a")), 1)); // when ResultActions result = mvc.perform(get("/worklogs").param("category", "DATABASE")); @@ -227,7 +243,7 @@ class WorkLogControllerWireTest { @Test void filterDslIsIgnoredNotParsed() throws Exception { // given - when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(sample("a")), 1)); + when(listUseCase.handle(any())).thenReturn(new WorkLogSummaryPage(List.of(summary("a")), 1)); // when ResultActions result = mvc.perform(get("/worklogs").param("filter", "status==OPEN")); @@ -425,6 +441,50 @@ class WorkLogControllerWireTest { @Nested class PatchWorkLog { + @BeforeEach + void authenticateTheEditor() { + TestingAuthenticationToken token = + new TestingAuthenticationToken( + new AuthenticatedPrincipal(EDITOR, "u@example.com", Set.of("user")), "n/a"); + token.setAuthenticated(true); + SecurityContextHolder.getContext().setAuthentication(token); + } + + @Test + void patchHandsTheAuthenticatedCallerToTheUpdateUseCaseAsTheEditor() throws Exception { + // given + ArgumentCaptor command = + ArgumentCaptor.forClass(UpdateWorkLogCommand.class); + when(updateUseCase.handle(command.capture())).thenReturn(sample("new title")); + + // when + mvc.perform( + patch("/worklogs/" + ID) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"title\":\"new title\"}")); + + // then + assertThat(command.getValue().editor()).isEqualTo(EDITOR); + } + + @Test + void patchByAnAccountThatDoesNotOwnTheWorkLogReturns403() throws Exception { + // given + when(updateUseCase.handle(any())).thenThrow(new WorkLogNotOwnedException(WorkLogId.of(ID))); + + // when + ResultActions result = + mvc.perform( + patch("/worklogs/" + ID) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"title\":\"x\"}")); + + // then + result + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.error.code").value("WORKLOG_NOT_OWNER")); + } + @Test void patchWithStaleIfMatchReturns412() throws Exception { // given: the update use case finds version 0 stored where 99 was expected diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java index 35074ca8..718181fc 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java @@ -66,6 +66,34 @@ class DomainExceptionHandlerTest { .doesNotContain("CLOSED_WORKLOG_MUTATION"); } + /** A blank title is the client's input, not a conflict with the stored state. */ + @Test + void aBlankWorkLogTitleIsA400ValidationErrorNotAConflict() { + // when + ResponseEntity> response = + handler.handleWorkLogInvariant( + new WorkLogInvariantException(WorkLogInvariantException.Reason.TITLE_BLANK)); + + // then + assertThat(response) + .extracting(ResponseEntity::getStatusCode, r -> r.getBody().error().code()) + .containsExactly(HttpStatus.BAD_REQUEST, "WORKLOG_INVALID"); + } + + @Test + void aClosedWorkLogMutationStaysA409Conflict() { + // when + ResponseEntity> response = + handler.handleWorkLogInvariant( + new WorkLogInvariantException( + WorkLogInvariantException.Reason.CLOSED_WORKLOG_MUTATION)); + + // then + assertThat(response) + .extracting(ResponseEntity::getStatusCode, r -> r.getBody().error().code()) + .containsExactly(HttpStatus.CONFLICT, "WORKLOG_CONFLICT"); + } + @Test void posterInvariantUsesAFixedMessageWithoutTheReason() { // when diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/operation/OperationTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/OperationTest.java similarity index 95% rename from src/shared-contract/src/test/java/dev/caskeleton/shared/operation/OperationTest.java rename to src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/OperationTest.java index ab3a66bb..910cf9ce 100644 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/operation/OperationTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/operation/OperationTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.shared.operation; +package dev.caskeleton.sample.portfolio.adapter.inbound.web.operation; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterTest.java index cf8b63ce..271ec214 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterTest.java @@ -1,8 +1,8 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -14,8 +14,6 @@ import dev.caskeleton.sample.portfolio.domain.worklog.Period; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; import java.time.Clock; import java.time.Instant; import java.time.LocalDate; @@ -25,10 +23,7 @@ import java.util.Optional; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; +import org.springframework.orm.ObjectOptimisticLockingFailureException; /** * Adapter logic over a mocked Spring Data repository; real PostgreSQL runs in the integrationTest @@ -126,13 +121,13 @@ class WorkLogRepositoryAdapterTest { WorkLogEntity existing = WorkLogPersistenceMapper.toEntity(persisted(1L)); existing.initializeAudit(EARLIER, "alice"); when(jpa.findById(WorkLogPersistenceMapper.toUuid(ID))).thenReturn(Optional.of(existing)); - when(jpa.save(any(WorkLogEntity.class))).thenAnswer(inv -> inv.getArgument(0)); + when(jpa.saveAndFlush(any(WorkLogEntity.class))).thenAnswer(inv -> inv.getArgument(0)); // when adapter.save(persisted(1L)); // then - assertThat(savedEntity()) + assertThat(existing) .extracting( WorkLogEntity::getCreatedAt, WorkLogEntity::getCreatedBy, @@ -155,57 +150,43 @@ class WorkLogRepositoryAdapterTest { assertThat(found).get().usingRecursiveComparison().isEqualTo(workLog); } + /** The update writes onto the entity the read returned; a new copy would rewrite its lists. */ @Test - void findPageMapsTheItemsAndTheTotal() { + void savingAPersistedWorkLogChangesTheEntityThatWasReadInsteadOfANewCopy() { // given - stubFindAll(); + WorkLogEntity existing = WorkLogPersistenceMapper.toEntity(persisted(1L)); + existing.initializeAudit(EARLIER, "alice"); + when(jpa.findById(WorkLogPersistenceMapper.toUuid(ID))).thenReturn(Optional.of(existing)); + when(jpa.saveAndFlush(any(WorkLogEntity.class))).thenAnswer(inv -> inv.getArgument(0)); + WorkLog renamed = persisted(1L); + renamed.rename("renamed"); // when - WorkLogPage result = adapter.findPage(2, 5, WorkLogSortField.TITLE, false, null); + adapter.save(renamed); // then - assertThat(result) - .extracting(p -> p.items().stream().map(WorkLog::id).toList(), WorkLogPage::total) - .containsExactly(List.of(ID), 11L); + assertThat(List.of(savedAndFlushedEntity() == existing, existing.getTitle())) + .containsExactly(true, "renamed"); } @Test - void findPagePassesPageSizeAndSortDirectionToSpringData() { + void savingAWorkLogReadAtAnotherVersionIsRefusedAsAnOptimisticLockFailure() { // given - stubFindAll(); + WorkLogEntity existing = WorkLogPersistenceMapper.toEntity(persisted(2L)); + existing.initializeAudit(EARLIER, "alice"); + when(jpa.findById(WorkLogPersistenceMapper.toUuid(ID))).thenReturn(Optional.of(existing)); // when - adapter.findPage(2, 5, WorkLogSortField.TITLE, false, null); + Throwable thrown = catchThrowable(() -> adapter.save(persisted(1L))); // then - ArgumentCaptor pageable = ArgumentCaptor.forClass(Pageable.class); - verify(jpa).findAll(pageable.capture()); - assertThat(pageable.getValue()) - .extracting( - Pageable::getPageNumber, - Pageable::getPageSize, - p -> p.getSort().getOrderFor("title").getDirection()) - .containsExactly(2, 5, Sort.Direction.DESC); + assertThat(thrown).isInstanceOf(ObjectOptimisticLockingFailureException.class); } - @Test - void findPageWithACategoryQueriesByThatCategory() { - // given - when(jpa.findByCategory(eq(WorkCategory.DATABASE), any(Pageable.class))) - .thenReturn(new PageImpl<>(List.of(WorkLogPersistenceMapper.toEntity(sample())))); - - // when - WorkLogPage result = adapter.findPage(0, 20, null, true, WorkCategory.DATABASE); - - // then - assertThat(result.items()).extracting(WorkLog::id).containsExactly(ID); - } - - private void stubFindAll() { - when(jpa.findAll(any(Pageable.class))) - .thenReturn( - new PageImpl<>( - List.of(WorkLogPersistenceMapper.toEntity(sample())), PageRequest.of(2, 5), 11)); + private WorkLogEntity savedAndFlushedEntity() { + ArgumentCaptor saved = ArgumentCaptor.forClass(WorkLogEntity.class); + verify(jpa).saveAndFlush(saved.capture()); + return saved.getValue(); } private WorkLogEntity savedEntity() { diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapterTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapterTest.java index 39fa99b5..48cf7e6d 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapterTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapterTest.java @@ -2,17 +2,22 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummary; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryPage; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus; import java.time.LocalDate; import java.util.List; import java.util.UUID; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -35,6 +40,7 @@ class WorkLogSummaryQueryAdapterTest { ROW_UUID, "Tuned Hikari pool", WorkCategory.DATABASE, + WorkLogStatus.OPEN, LocalDate.of(2025, 1, 1), null))); @@ -45,7 +51,69 @@ class WorkLogSummaryQueryAdapterTest { assertThat(result) .containsExactly( new WorkLogSummary( - ID, "Tuned Hikari pool", WorkCategory.DATABASE, LocalDate.of(2025, 1, 1), null)); + ID, + "Tuned Hikari pool", + WorkCategory.DATABASE, + WorkLogStatus.OPEN, + LocalDate.of(2025, 1, 1), + null)); + } + + @Test + void findPageMapsTheRowsAndTheTotal() { + // given + stubSummaryRows(); + + // when + WorkLogSummaryPage result = adapter.findPage(2, 5, WorkLogSortField.TITLE, false, null); + + // then + assertThat(result) + .extracting( + p -> p.items().stream().map(WorkLogSummary::id).toList(), WorkLogSummaryPage::total) + .containsExactly(List.of(ID), 11L); + } + + @Test + void findPagePassesPageSizeAndSortDirectionToSpringData() { + // given + stubSummaryRows(); + + // when + adapter.findPage(2, 5, WorkLogSortField.TITLE, false, null); + + // then + ArgumentCaptor pageable = ArgumentCaptor.forClass(Pageable.class); + verify(jpa).findSummaryRows(pageable.capture()); + assertThat(pageable.getValue()) + .extracting( + Pageable::getPageNumber, + Pageable::getPageSize, + p -> p.getSort().getOrderFor("title").getDirection()) + .containsExactly(2, 5, Sort.Direction.DESC); + } + + @Test + void findPageWithACategoryQueriesByThatCategory() { + // given + when(jpa.findSummaryRowsByCategory(eq(WorkCategory.DATABASE), any(Pageable.class))) + .thenReturn(new PageImpl<>(List.of(row()))); + + // when + WorkLogSummaryPage result = adapter.findPage(0, 20, null, true, WorkCategory.DATABASE); + + // then + assertThat(result.items()).extracting(WorkLogSummary::id).containsExactly(ID); + } + + private void stubSummaryRows() { + when(jpa.findSummaryRows(any(Pageable.class))) + .thenReturn(new PageImpl<>(List.of(row()), PageRequest.of(2, 5), 11)); + } + + private static WorkLogSummaryRow row() { + return new WorkLogSummaryRow( + ROW_UUID, "t", WorkCategory.DATABASE, WorkLogStatus.OPEN, LocalDate.of(2025, 1, 1), null); } @Test diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/CommandSelfValidationTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/CommandSelfValidationTest.java index 7f1404d1..dc62e456 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/CommandSelfValidationTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/CommandSelfValidationTest.java @@ -50,8 +50,9 @@ class CommandSelfValidationTest { "create without periodStart", () -> create("t", WorkCategory.DATABASE, null), "periodStart"), - missing("update without id", () -> update(null, Patch.absent()), "id"), - missing("update without title patch", () -> update(ID, null), "title"), + missing("update without id", () -> update(null, "o", Patch.absent()), "id"), + missing("update without editor", () -> update(ID, null, Patch.absent()), "editor"), + missing("update without title patch", () -> update(ID, "o", null), "title"), missing("delete without id", () -> new DeleteWorkLogCommand(null), "id"), missing("get without id", () -> new GetWorkLogQuery(null), "id"), missing("repo stats without repoUrl", () -> new GetRepoStatsQuery(null), "repoUrl")); @@ -80,9 +81,10 @@ class CommandSelfValidationTest { "o", title, category, "s", "c", List.of(), List.of(), periodStart, null); } - private static UpdateWorkLogCommand update(WorkLogId id, Patch title) { + private static UpdateWorkLogCommand update(WorkLogId id, String editor, Patch title) { return new UpdateWorkLogCommand( id, + editor, title, Patch.absent(), Patch.absent(), diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutboxTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutboxTest.java index 3195252b..ea2f267e 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutboxTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutboxTest.java @@ -7,6 +7,7 @@ import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.IntegrationEventDraft; import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.observability.CorrelationIdPort; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxAggregateSequences; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.sample.portfolio.application.poster.PosterEventContracts; import dev.caskeleton.sample.portfolio.application.poster.PosterIdPayload; @@ -14,6 +15,8 @@ import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullSource; @@ -24,7 +27,8 @@ class PortfolioEventOutboxTest { private static final String EVENT_ID = "0190bd6e-7c3e-7abc-8def-0123456789ff"; private static final Instant NOW = Instant.parse("2025-06-01T10:00:00.123456Z"); - private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(); + private final FakeIntegrationEventEncoder encoder = + new FakeIntegrationEventEncoder(PosterEventContracts.POSTER_PUBLISHED); @Test void usesTheCurrentCorrelationIdWhenItFitsTheCanonicalGrammar() { @@ -57,8 +61,9 @@ class PortfolioEventOutboxTest { .isEqualTo(EVENT_ID); } + /** The sample is single-tenant, and says so with the scope every single-tenant feature uses. */ @Test - void theEventBelongsToThePortfolioTenantAndIsOrderedByItsOccurrenceMicrosecond() { + void theEventBelongsToTheSharedSingleTenantScopeAndIsTheAggregatesFirstInOrder() { // when append(Optional::empty); @@ -67,8 +72,44 @@ class PortfolioEventOutboxTest { .singleElement() .extracting(IntegrationEventDraft::aggregate, IntegrationEventDraft::order) .containsExactly( - new AggregateIdentity("portfolio", "poster", "poster-1"), - new AggregateOrder(1_748_772_000_123_456L, 0)); + new AggregateIdentity("global", "poster", "poster-1"), new AggregateOrder(1, 0)); + } + + /** + * The order used to be the occurrence time in microseconds: two writes in one microsecond, or on + * two instances whose clocks differ, were not ordered by commit (review 06-07). With the clock + * frozen the two events below share their occurrence time and still get consecutive numbers. + */ + @Test + @DisplayName("같은 aggregate의 연속 변경은 같은 시각에 일어나도 순서 번호가 하나씩 커진다") + void consecutiveEventsOfOneAggregateGetIncreasingNumbersEvenAtTheSameInstant() { + // given + AtomicInteger ids = new AtomicInteger(); + PortfolioEventOutbox outbox = + new PortfolioEventOutbox( + new InMemoryOutboxStore(), + encoder, + () -> "0190bd6e-7c3e-7abc-8def-00000000000" + ids.incrementAndGet(), + Optional::empty, + Clock.fixed(NOW, ZoneOffset.UTC), + new InMemoryOutboxAggregateSequences()); + outbox.append( + PosterEventContracts.POSTER_PUBLISHED, + "poster", + "poster-1", + new PosterIdPayload("poster-1")); + + // when + outbox.append( + PosterEventContracts.POSTER_PUBLISHED, + "poster", + "poster-1", + new PosterIdPayload("poster-1")); + + // then + assertThat(encoder.drafts()) + .extracting(draft -> draft.order().sequence()) + .containsExactly(1L, 2L); } private void append(CorrelationIdPort correlations) { @@ -77,7 +118,8 @@ class PortfolioEventOutboxTest { encoder, () -> EVENT_ID, correlations, - Clock.fixed(NOW, ZoneOffset.UTC)) + Clock.fixed(NOW, ZoneOffset.UTC), + new InMemoryOutboxAggregateSequences()) .append( PosterEventContracts.POSTER_PUBLISHED, "poster", diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterEventPublisherTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterEventPublisherTest.java index 573053a0..32faec65 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterEventPublisherTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterEventPublisherTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.messaging.event.IntegrationEventDraft; import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxAggregateSequences; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; import dev.caskeleton.sample.portfolio.domain.poster.PosterCreated; @@ -23,10 +24,21 @@ class PosterEventPublisherTest { Clock.fixed(Instant.parse("2025-06-01T10:00:00Z"), ZoneOffset.UTC); private final InMemoryOutboxStore outbox = new InMemoryOutboxStore(); - private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(); + private final FakeIntegrationEventEncoder encoder = + new FakeIntegrationEventEncoder( + PosterEventContracts.POSTER_CREATED, + PosterEventContracts.POSTER_PUBLISHED, + PosterEventContracts.POSTER_ARCHIVED, + PosterEventContracts.POSTER_DELETED); private final PosterEventPublisher publisher = new PosterEventPublisher( - new PortfolioEventOutbox(outbox, encoder, () -> EVENT_ID, Optional::empty, CLOCK)); + new PortfolioEventOutbox( + outbox, + encoder, + () -> EVENT_ID, + Optional::empty, + CLOCK, + new InMemoryOutboxAggregateSequences())); @Test void aCreatedPosterIsAnnouncedAsPosterCreatedAboutThatPoster() { diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAbortReconcileRaceTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAbortReconcileRaceTest.java index 962d2ec8..9817493d 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAbortReconcileRaceTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAbortReconcileRaceTest.java @@ -35,6 +35,7 @@ import dev.caskeleton.application.objectstorage.request.ObjectHandoffRenewReques import dev.caskeleton.application.objectstorage.request.ObjectStageRequest; import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; import dev.caskeleton.application.outbound.CallBudget; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxAggregateSequences; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; import dev.caskeleton.sample.portfolio.application.posterimage.testkit.InMemoryPosterImageRetirementIntentStore; @@ -207,10 +208,13 @@ class PosterImageAbortReconcileRaceTest { new PosterImagePublicationEventPublisher( new PortfolioEventOutbox( event -> {}, - new FakeIntegrationEventEncoder(), + new FakeIntegrationEventEncoder( + PosterImageEventContracts.POSTER_IMAGE_ATTACHMENT_PREPARED, + PosterImageEventContracts.POSTER_IMAGE_ATTACHMENT_READY), () -> "0190bd6e-7c3e-7abc-8def-0123456789ff", Optional::empty, - CLOCK)), + CLOCK, + new InMemoryOutboxAggregateSequences())), transactions, publications, handoffs, diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImagePublicationWorkflowTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImagePublicationWorkflowTest.java index 51a80ee0..4882e9ee 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImagePublicationWorkflowTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImagePublicationWorkflowTest.java @@ -30,6 +30,7 @@ import dev.caskeleton.application.objectstorage.request.ObjectHandoffClaimReques import dev.caskeleton.application.objectstorage.request.ObjectStageRequest; import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; import dev.caskeleton.application.outbound.CallBudget; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxAggregateSequences; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.HmacPosterImageIdempotencyScopeDigester; @@ -218,10 +219,13 @@ class PosterImagePublicationWorkflowTest { event -> appendedInsideTransaction.add( Map.entry(event.contractId().value(), transactions.active())), - new FakeIntegrationEventEncoder(), + new FakeIntegrationEventEncoder( + PosterImageEventContracts.POSTER_IMAGE_ATTACHMENT_PREPARED, + PosterImageEventContracts.POSTER_IMAGE_ATTACHMENT_READY), () -> "0190bd6e-7c3e-7abc-8def-0123456789ff", Optional::empty, - CLOCK)), + CLOCK, + new InMemoryOutboxAggregateSequences())), new PosterImagePublicationPolicy(1024), new PosterImagePublicationParameters( ObjectDestinationId.of("poster"), diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java index d8977097..271fd4fc 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java @@ -6,6 +6,7 @@ import dev.caskeleton.application.messaging.event.IntegrationEventDraft; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.outbox.OutboxAppendPort; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxAggregateSequences; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; @@ -33,7 +34,8 @@ class CreateWorkLogOutboxTest { private static final Instant NOW = Instant.parse("2025-06-01T10:00:00Z"); private final DirectTransactionPort tx = new DirectTransactionPort(); - private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(); + private final FakeIntegrationEventEncoder encoder = + new FakeIntegrationEventEncoder(new WorkLogReservedContractContribution()); private final List appended = new ArrayList<>(); private final List appendedInsideTransaction = new ArrayList<>(); @@ -101,7 +103,8 @@ class CreateWorkLogOutboxTest { encoder, () -> FIXED_EVENT_ID, Optional::empty, - Clock.fixed(NOW, ZoneOffset.UTC)), + Clock.fixed(NOW, ZoneOffset.UTC), + new InMemoryOutboxAggregateSequences()), tx) .handle( new CreateWorkLogCommand( diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/ListRecentWorkLogSummariesUseCaseTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/ListRecentWorkLogSummariesUseCaseTest.java index 6132f0f1..4ad898d7 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/ListRecentWorkLogSummariesUseCaseTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/ListRecentWorkLogSummariesUseCaseTest.java @@ -4,38 +4,57 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; +import dev.caskeleton.sample.portfolio.application.worklog.testkit.InMemoryWorkLogSummaryQuery; +import dev.caskeleton.sample.portfolio.domain.worklog.Period; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +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.WorkLogStatus; +import dev.caskeleton.sample.portfolio.domain.worklog.testkit.InMemoryWorkLogRepository; import java.time.LocalDate; -import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ListRecentWorkLogSummariesUseCaseTest { - private static final WorkLogSummary SUMMARY = - new WorkLogSummary( - "0190bd6e-7c3e-7abc-8def-0123456789ab", - "Tuned Hikari pool", - WorkCategory.DATABASE, - LocalDate.of(2025, 1, 1), - null); - private final DirectTransactionPort tx = new DirectTransactionPort(); - // WorkLogSummaryQueryPort has no other test double; this recording lambda is its only fake. - private final List requestedLimits = new ArrayList<>(); - private final List readInsideTransaction = new ArrayList<>(); + private final InMemoryWorkLogRepository store = new InMemoryWorkLogRepository(); private final ListRecentWorkLogSummariesUseCase useCase = - new ListRecentWorkLogSummariesUseCase( - limit -> { - requestedLimits.add(limit); - readInsideTransaction.add(tx.active()); - return List.of(SUMMARY); - }, - tx); + new ListRecentWorkLogSummariesUseCase(new InMemoryWorkLogSummaryQuery(store), tx); + + @BeforeEach + void storeThreeMonths() { + store.save(workLog(1, "january")); + store.save(workLog(2, "february")); + store.save(workLog(3, "march")); + } @Test - void returnsTheSummariesTheQueryPortReads() { - assertThat(useCase.handle(new ListRecentWorkLogSummariesQuery(10))).containsExactly(SUMMARY); + void returnsTheSummaryColumnsOfTheNewestWorkLog() { + // when + List recent = useCase.handle(new ListRecentWorkLogSummariesQuery(1)); + + // then + assertThat(recent) + .containsExactly( + new WorkLogSummary( + id(3).value(), + "march", + WorkCategory.DATABASE, + WorkLogStatus.OPEN, + LocalDate.of(2025, 3, 1), + null)); + } + + @Test + void returnsAtMostTheRequestedNumberNewestFirst() { + // when + List recent = useCase.handle(new ListRecentWorkLogSummariesQuery(2)); + + // then + assertThat(recent).extracting(WorkLogSummary::title).containsExactly("march", "february"); } @Test @@ -44,18 +63,23 @@ class ListRecentWorkLogSummariesUseCaseTest { useCase.handle(new ListRecentWorkLogSummariesQuery(10)); // then - assertThat(readInsideTransaction) - .as("projection read must run inside TransactionPort.inRead (D4 default)") - .containsExactly(true); assertThat(tx.committed()).containsExactly(Boundary.READ); } - @Test - void forwardsTheRequestedLimitToThePort() { - // when - useCase.handle(new ListRecentWorkLogSummariesQuery(7)); + private static WorkLog workLog(int month, String title) { + return WorkLog.create( + id(month), + WorkLogOwner.of("owner-1"), + title, + WorkCategory.DATABASE, + "s", + "c", + List.of("postgres"), + List.of(), + new Period(LocalDate.of(2025, month, 1), null)); + } - // then - assertThat(requestedLimits).containsExactly(7); + private static WorkLogId id(int n) { + return WorkLogId.of("0190bd6e-7c3e-7abc-8def-%012d".formatted(n)); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedContractContributionTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedContractContributionTest.java index 71b3a00b..f0374e62 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedContractContributionTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedContractContributionTest.java @@ -122,7 +122,7 @@ class WorkLogReservedContractContributionTest { new ContractDescriptor( "sample-portfolio", new LogicalDestinationId("portfolio-domain-events"), - "json-schema-envelope-v1", + "json-envelope-v1", true, 64 * 1024, 128 * 1024, diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java index 7b79e2a6..42e9167e 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java @@ -10,16 +10,17 @@ import com.github.f4b6a3.uuid.UuidCreator; import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.observability.CorrelationIdPort; import dev.caskeleton.application.outbox.OutboxAppendPort; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxAggregateSequences; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; +import dev.caskeleton.sample.portfolio.application.worklog.testkit.InMemoryWorkLogSummaryQuery; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogIdFactory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException.Reason; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus; import dev.caskeleton.sample.portfolio.domain.worklog.testkit.InMemoryWorkLogRepository; import dev.caskeleton.shared.request.Patch; @@ -40,6 +41,9 @@ class WorkLogUseCasesTest { private static final WorkLogIdFactory IDS = () -> WorkLogId.of(UuidCreator.getTimeOrderedEpochPlus1().toString()); + /** The owner every work log in these tests is created for, and the editor of every update. */ + private static final String OWNER = "sample-owner"; + private static final OutboxAppendPort NO_OP_OUTBOX = event -> {}; private static final CorrelationIdPort NO_CORRELATION = Optional::empty; @@ -51,10 +55,11 @@ class WorkLogUseCasesTest { IDS, new PortfolioEventOutbox( NO_OP_OUTBOX, - new FakeIntegrationEventEncoder(), + new FakeIntegrationEventEncoder(new WorkLogReservedContractContribution()), () -> "01FAKEEVENTIDTSV4RRFFQ6900", NO_CORRELATION, - Clock.systemUTC()), + Clock.systemUTC(), + new InMemoryOutboxAggregateSequences()), tx); private final UpdateWorkLogUseCase update = new UpdateWorkLogUseCase(repository, tx); @@ -113,6 +118,7 @@ class WorkLogUseCasesTest { update.handle( new UpdateWorkLogCommand( created.id(), + OWNER, Patch.of("new title"), Patch.absent(), Patch.of("new content"), @@ -126,6 +132,31 @@ class WorkLogUseCasesTest { .containsExactly("new title", "s", "new content"); } + @Test + void refusesAnEditByAnyoneOtherThanTheOwnerAndKeepsTheRecord() { + // given + WorkLogId id = aCreatedWorkLog("owned").id(); + + // when + Throwable thrown = + catchThrowable( + () -> + update.handle( + new UpdateWorkLogCommand( + id, + "someone-else", + Patch.of("taken over"), + Patch.absent(), + Patch.absent(), + Patch.absent(), + Patch.absent(), + OptionalLong.empty()))); + + // then + assertThat(List.of(thrown.getClass(), repository.findById(id).orElseThrow().title())) + .containsExactly(WorkLogNotOwnedException.class, "owned"); + } + @Test void staleExpectedVersionIsRefusedInsideTheUpdate() { // given: created at version 0, then edited to version 1 @@ -163,6 +194,7 @@ class WorkLogUseCasesTest { update.handle( new UpdateWorkLogCommand( created.id(), + OWNER, Patch.absent(), Patch.ofNull(), Patch.absent(), @@ -201,6 +233,7 @@ class WorkLogUseCasesTest { update.handle( new UpdateWorkLogCommand( id, + OWNER, Patch.of("late edit"), Patch.absent(), Patch.absent(), @@ -242,14 +275,15 @@ class WorkLogUseCasesTest { aCreatedWorkLog("b"); // when - WorkLogPage page = - new ListWorkLogsUseCase(repository, tx) + WorkLogSummaryPage page = + new ListWorkLogsUseCase(new InMemoryWorkLogSummaryQuery(repository), tx) .handle(new ListWorkLogsQuery(0, 10, null, true, null)); // then assertThat(page) .extracting( - p -> p.items().stream().map(WorkLog::title).sorted().toList(), WorkLogPage::total) + p -> p.items().stream().map(WorkLogSummary::title).sorted().toList(), + WorkLogSummaryPage::total) .containsExactly(List.of("a", "b"), 2L); } } @@ -277,7 +311,7 @@ class WorkLogUseCasesTest { batchCreate.handle(oneAndTwo); // then - assertThat(repository.findPage(0, 20, null, true, null).items()) + assertThat(repository.stored()) .extracting(WorkLog::title) .containsExactlyInAnyOrder("one", "two"); } @@ -315,7 +349,7 @@ class WorkLogUseCasesTest { } private static CreateWorkLogCommand createCmd(String title) { - return createCmd("sample-owner", title); + return createCmd(OWNER, title); } private static CreateWorkLogCommand createCmd(String owner, String title) { @@ -334,6 +368,7 @@ class WorkLogUseCasesTest { private static UpdateWorkLogCommand statusChange(WorkLogId id, WorkLogStatus status) { return new UpdateWorkLogCommand( id, + OWNER, Patch.absent(), Patch.absent(), Patch.absent(), @@ -345,6 +380,7 @@ class WorkLogUseCasesTest { private static UpdateWorkLogCommand renameExpecting(WorkLogId id, long expectedVersion) { return new UpdateWorkLogCommand( id, + OWNER, Patch.of("renamed"), Patch.absent(), Patch.absent(), diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java index 9739b5f5..4a66ed6f 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java @@ -12,14 +12,16 @@ import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry; import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.observability.CorrelationIdPort; import dev.caskeleton.application.outbox.OutboxAppendPort; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxAggregateSequences; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.sample.portfolio.application.event.OutboxEventIdFactory; import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; import dev.caskeleton.sample.portfolio.application.worklog.CreateWorkLogCommand; import dev.caskeleton.sample.portfolio.application.worklog.CreateWorkLogUseCase; import dev.caskeleton.sample.portfolio.application.worklog.DeleteWorkLogCommand; import dev.caskeleton.sample.portfolio.application.worklog.DeleteWorkLogUseCase; -import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogReservedContractContribution; import dev.caskeleton.sample.portfolio.domain.worklog.Period; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; @@ -249,10 +251,11 @@ class WorkLogAuthorizationContractTest { idFactory, new PortfolioEventOutbox( outboxAppendPort, - new FakeIntegrationEventEncoder(), + new FakeIntegrationEventEncoder(new WorkLogReservedContractContribution()), eventIdFactory, correlationIdPort, - clock), + clock, + new InMemoryOutboxAggregateSequences()), tx); } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepositoryContractTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepositoryContractTest.java index 3c17d403..669eb3bb 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepositoryContractTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepositoryContractTest.java @@ -1,17 +1,25 @@ package dev.caskeleton.sample.portfolio.domain.worklog.testkit; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryQueryPort; +import dev.caskeleton.sample.portfolio.application.worklog.testkit.InMemoryWorkLogSummaryQuery; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; import java.util.function.Supplier; class InMemoryWorkLogRepositoryContractTest extends WorkLogRepositoryContract { private final InMemoryWorkLogRepository repository = new InMemoryWorkLogRepository(); + private final InMemoryWorkLogSummaryQuery summaries = new InMemoryWorkLogSummaryQuery(repository); @Override protected WorkLogRepository repository() { return repository; } + @Override + protected WorkLogSummaryQueryPort summaries() { + return summaries; + } + @Override protected T inTransaction(Supplier work) { return work.get(); diff --git a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/application/worklog/testkit/InMemoryWorkLogSummaryQuery.java b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/application/worklog/testkit/InMemoryWorkLogSummaryQuery.java new file mode 100644 index 00000000..1b2e8a12 --- /dev/null +++ b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/application/worklog/testkit/InMemoryWorkLogSummaryQuery.java @@ -0,0 +1,72 @@ +package dev.caskeleton.sample.portfolio.application.worklog.testkit; + +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummary; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryPage; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryQueryPort; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; +import dev.caskeleton.sample.portfolio.domain.worklog.testkit.InMemoryWorkLogRepository; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Stream; + +/** + * In-memory {@link WorkLogSummaryQueryPort} over what an {@link InMemoryWorkLogRepository} stored, + * held to the adapter's semantics by {@code WorkLogRepositoryContract}: {@code findPage} sorts, + * filters and clamps page/size the way {@code WorkLogSummaryQueryAdapter} does. + */ +public final class InMemoryWorkLogSummaryQuery implements WorkLogSummaryQueryPort { + + private static final int DEFAULT_PAGE_SIZE = 20; + + private final InMemoryWorkLogRepository store; + + public InMemoryWorkLogSummaryQuery(InMemoryWorkLogRepository store) { + this.store = Objects.requireNonNull(store, "store"); + } + + @Override + public WorkLogSummaryPage findPage( + int page, int size, WorkLogSortField sortField, boolean ascending, WorkCategory category) { + int safeSize = size <= 0 ? DEFAULT_PAGE_SIZE : size; + int safePage = Math.max(0, page); + List matching = + store.stored().stream().filter(w -> category == null || w.category() == category).toList(); + Stream ordered = matching.stream(); + if (sortField != null) { + Comparator order = comparator(sortField); + ordered = ordered.sorted(ascending ? order : order.reversed()); + } + List items = + ordered + .skip((long) safePage * safeSize) + .limit(safeSize) + .map(InMemoryWorkLogSummaryQuery::toSummary) + .toList(); + return new WorkLogSummaryPage(items, matching.size()); + } + + @Override + public List findRecentSummaries(int limit) { + int safeLimit = limit <= 0 ? 1 : limit; + return store.stored().stream() + .sorted(comparator(WorkLogSortField.PERIOD_START).reversed()) + .limit(safeLimit) + .map(InMemoryWorkLogSummaryQuery::toSummary) + .toList(); + } + + private static Comparator comparator(WorkLogSortField field) { + return switch (field) { + case TITLE -> Comparator.comparing(WorkLog::title); + case PERIOD_START -> Comparator.comparing(w -> w.period().start()); + }; + } + + private static WorkLogSummary toSummary(WorkLog w) { + return new WorkLogSummary( + w.id().value(), w.title(), w.category(), w.status(), w.period().start(), w.period().end()); + } +} diff --git a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepository.java b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepository.java index 0e2254ef..10c1c2de 100644 --- a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepository.java +++ b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepository.java @@ -1,30 +1,23 @@ package dev.caskeleton.sample.portfolio.domain.worklog.testkit; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; -import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Stream; /** * In-memory {@link WorkLogRepository} with the semantics of {@code WorkLogRepositoryAdapter}, held * to them by {@link WorkLogRepositoryContract}: it stores snapshots (a caller's later mutation is - * not saved), a new WorkLog is saved at version 0 and an update increments it, and {@code findPage} - * sorts, filters, and clamps page/size the way the adapter does. + * not saved), and a new WorkLog is saved at version 0 and an update increments it. Lists are read + * through {@code InMemoryWorkLogSummaryQuery}, which reads what this fake stored. * *

        It does not model optimistic-lock conflicts on a stale version. */ public final class InMemoryWorkLogRepository implements WorkLogRepository { - private static final int DEFAULT_PAGE_SIZE = 20; - private final Map rows = new LinkedHashMap<>(); @Override @@ -50,25 +43,9 @@ public final class InMemoryWorkLogRepository implements WorkLogRepository { return Optional.ofNullable(rows.get(id)).map(w -> copy(w, w.version())); } - @Override - public WorkLogPage findPage( - int page, int size, WorkLogSortField sortField, boolean ascending, WorkCategory category) { - int safeSize = size <= 0 ? DEFAULT_PAGE_SIZE : size; - int safePage = Math.max(0, page); - List matching = - rows.values().stream().filter(w -> category == null || w.category() == category).toList(); - Stream ordered = matching.stream(); - if (sortField != null) { - Comparator order = comparator(sortField); - ordered = ordered.sorted(ascending ? order : order.reversed()); - } - List items = - ordered - .skip((long) safePage * safeSize) - .limit(safeSize) - .map(w -> copy(w, w.version())) - .toList(); - return new WorkLogPage(items, matching.size()); + /** Every stored WorkLog, as copies, in insertion order. Read by the summary-query fake. */ + public List stored() { + return rows.values().stream().map(w -> copy(w, w.version())).toList(); } @Override @@ -81,13 +58,6 @@ public final class InMemoryWorkLogRepository implements WorkLogRepository { rows.remove(id); } - private static Comparator comparator(WorkLogSortField field) { - return switch (field) { - case TITLE -> Comparator.comparing(WorkLog::title); - case PERIOD_START -> Comparator.comparing(w -> w.period().start()); - }; - } - private static WorkLog copy(WorkLog w, Long version) { return WorkLog.rehydrate( w.id(), diff --git a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/WorkLogRepositoryContract.java b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/WorkLogRepositoryContract.java index 712e4587..2c2d2761 100644 --- a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/WorkLogRepositoryContract.java +++ b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/WorkLogRepositoryContract.java @@ -2,12 +2,14 @@ package dev.caskeleton.sample.portfolio.domain.worklog.testkit; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummary; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryPage; +import dev.caskeleton.sample.portfolio.application.worklog.WorkLogSummaryQueryPort; import dev.caskeleton.sample.portfolio.domain.worklog.Period; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; 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.WorkLogPage; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus; @@ -22,8 +24,11 @@ import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; /** - * What every {@link WorkLogRepository} promises, run against {@link InMemoryWorkLogRepository} and - * the PostgreSQL {@code WorkLogRepositoryAdapter} alike. + * What every {@link WorkLogRepository} promises, together with the {@link WorkLogSummaryQueryPort} + * that lists what it stored, run against {@link InMemoryWorkLogRepository} (with {@code + * InMemoryWorkLogSummaryQuery}) and the PostgreSQL {@code WorkLogRepositoryAdapter} (with {@code + * WorkLogSummaryQueryAdapter}) alike. The two ports share one store, so their promises are tested + * together: a list shows what a save kept. * *

        Every call goes through {@link #inTransaction}, so each one commits before the next reads it: * a read sees what the store kept, not the caller's object. @@ -38,6 +43,9 @@ public abstract class WorkLogRepositoryContract { /** The repository under test, empty at the start of each test. */ protected abstract WorkLogRepository repository(); + /** The list reader over the same store as {@link #repository()}. */ + protected abstract WorkLogSummaryQueryPort summaries(); + /** Runs {@code work} in one committed transaction of the repository under test. */ protected abstract T inTransaction(Supplier work); @@ -141,9 +149,7 @@ public abstract class WorkLogRepositoryContract { }); // then - assertThat(page(0, 20, WorkLogSortField.TITLE, true, null)) - .extracting(WorkLog::id) - .containsExactly(ALPHA, CHARLIE); + assertThat(page(0, 20, WorkLogSortField.TITLE, true, null)).containsExactly(ALPHA, CHARLIE); } @Test @@ -160,7 +166,6 @@ public abstract class WorkLogRepositoryContract { // then assertThat(page(0, 20, WorkLogSortField.TITLE, true, null)) - .extracting(WorkLog::id) .containsExactly(ALPHA, BRAVO, CHARLIE); } @@ -177,26 +182,47 @@ public abstract class WorkLogRepositoryContract { saveAll(); // when - WorkLogPage found = inTransaction(() -> repository().findPage(0, 20, field, ascending, null)); + WorkLogSummaryPage found = + inTransaction(() -> summaries().findPage(0, 20, field, ascending, null)); // then assertThat(found.items()) - .extracting(WorkLog::title) + .extracting(WorkLogSummary::title) .containsExactly(expectedTitles.split("\\|")); } + @Test + void findPageListsTheSummaryColumnsOfWhatWasSaved() { + // given + WorkLog saved = save(alpha()); + saved.startProgress(); + save(saved); + + // when + WorkLogSummaryPage found = inTransaction(() -> summaries().findPage(0, 20, null, true, null)); + + // then + assertThat(found.items()) + .containsExactly( + new WorkLogSummary( + ALPHA.value(), + "alpha", + WorkCategory.DATABASE, + WorkLogStatus.IN_PROGRESS, + LocalDate.of(2025, 3, 1), + LocalDate.of(2025, 3, 28))); + } + @Test void findPageWithoutASortFieldReturnsEveryWorkLog() { // given saveAll(); // when - WorkLogPage found = inTransaction(() -> repository().findPage(0, 20, null, true, null)); + WorkLogSummaryPage found = inTransaction(() -> summaries().findPage(0, 20, null, true, null)); // then - assertThat(found.items()) - .extracting(WorkLog::id) - .containsExactlyInAnyOrder(ALPHA, BRAVO, CHARLIE); + assertThat(ids(found)).containsExactlyInAnyOrder(ALPHA, BRAVO, CHARLIE); } @Test @@ -205,14 +231,13 @@ public abstract class WorkLogRepositoryContract { saveAll(); // when - WorkLogPage found = + WorkLogSummaryPage found = inTransaction( - () -> - repository().findPage(0, 20, WorkLogSortField.TITLE, true, WorkCategory.DATABASE)); + () -> summaries().findPage(0, 20, WorkLogSortField.TITLE, true, WorkCategory.DATABASE)); // then assertThat(found) - .extracting(WorkLogRepositoryContract::ids, WorkLogPage::total) + .extracting(WorkLogRepositoryContract::ids, WorkLogSummaryPage::total) .containsExactly(List.of(ALPHA, CHARLIE), 2L); } @@ -222,12 +247,12 @@ public abstract class WorkLogRepositoryContract { saveAll(); // when - WorkLogPage found = - inTransaction(() -> repository().findPage(1, 2, WorkLogSortField.TITLE, true, null)); + WorkLogSummaryPage found = + inTransaction(() -> summaries().findPage(1, 2, WorkLogSortField.TITLE, true, null)); // then assertThat(found) - .extracting(WorkLogRepositoryContract::ids, WorkLogPage::total) + .extracting(WorkLogRepositoryContract::ids, WorkLogSummaryPage::total) .containsExactly(List.of(CHARLIE), 3L); } @@ -237,11 +262,11 @@ public abstract class WorkLogRepositoryContract { saveAll(); // when - WorkLogPage found = - inTransaction(() -> repository().findPage(-1, 2, WorkLogSortField.TITLE, true, null)); + WorkLogSummaryPage found = + inTransaction(() -> summaries().findPage(-1, 2, WorkLogSortField.TITLE, true, null)); // then - assertThat(found.items()).extracting(WorkLog::id).containsExactly(ALPHA, BRAVO); + assertThat(ids(found)).containsExactly(ALPHA, BRAVO); } @ParameterizedTest @@ -252,12 +277,12 @@ public abstract class WorkLogRepositoryContract { .forEach(n -> save(workLog(id(n), "title-%02d".formatted(n), WorkCategory.BACKEND, 1))); // when - WorkLogPage found = - inTransaction(() -> repository().findPage(0, size, WorkLogSortField.TITLE, true, null)); + WorkLogSummaryPage found = + inTransaction(() -> summaries().findPage(0, size, WorkLogSortField.TITLE, true, null)); // then assertThat(found) - .extracting(p -> p.items().size(), WorkLogPage::total) + .extracting(p -> p.items().size(), WorkLogSummaryPage::total) .containsExactly(20, 21L); } @@ -269,10 +294,9 @@ public abstract class WorkLogRepositoryContract { return inTransaction(() -> repository().findById(id)); } - private List page( + private List page( int page, int size, WorkLogSortField field, boolean ascending, WorkCategory category) { - return inTransaction(() -> repository().findPage(page, size, field, ascending, category)) - .items(); + return ids(inTransaction(() -> summaries().findPage(page, size, field, ascending, category))); } /** Titles and period starts sort in different orders, so each sort field is observable. */ @@ -299,8 +323,8 @@ public abstract class WorkLogRepositoryContract { new Period(LocalDate.of(2025, month, 1), LocalDate.of(2025, month, 28))); } - private static List ids(WorkLogPage page) { - return page.items().stream().map(WorkLog::id).toList(); + private static List ids(WorkLogSummaryPage page) { + return page.items().stream().map(summary -> WorkLogId.of(summary.id())).toList(); } private static WorkLogId id(int n) { diff --git a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/testinfra/PostgreSqlTestContainer.java b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/testinfra/PostgreSqlTestContainer.java index 536fd198..e859179d 100644 --- a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/testinfra/PostgreSqlTestContainer.java +++ b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/testinfra/PostgreSqlTestContainer.java @@ -5,7 +5,7 @@ import org.testcontainers.postgresql.PostgreSQLContainer; /** Creates sample integration-test databases with reuse off unless local opt-in is explicit. */ public final class PostgreSqlTestContainer { - public static final String IMAGE = "postgres:16-alpine"; + public static final String IMAGE = System.getProperty("ca.test.image.postgres-16"); private static final String REUSE_ENV = "TESTCONTAINERS_REUSE_ENABLE"; private PostgreSqlTestContainer() {} diff --git a/src/shared-contract/CLAUDE.md b/src/shared-contract/CLAUDE.md index da28e91b..6d8b23aa 100644 --- a/src/shared-contract/CLAUDE.md +++ b/src/shared-contract/CLAUDE.md @@ -28,7 +28,12 @@ envelope shape, metric cardinality bounds, tracing seam, domain-context propagat SHA-256 digest value and the one `MessageDigest.getInstance("SHA-256")`), `digest/HmacSha256` (sign and constant-time verify), `retry/Backoff` (capped exponential ceiling; "full jitter" means `U[0, ceiling]` and nothing else). Vendored `messaging:*` and the optional gRPC build do not depend - on this module and keep their own copies. + on this module and keep their own copies. A leaf that has the `shared-contract` edge uses these and + does not copy them (application-fileserver `SafeFileFingerprint` and cache-redis `RedisKeys` were + the last two). Template leaves that still copy because the registry gives them no edge — + identifier, persistence-mongo, application-objectstorage, redis-sdk — are an open decision: add the + edge (recommended for template leaves) or keep the copy and say so in that leaf's CLAUDE.md + (review 2026-11-01 01-11). - `observability/MdcKeys`: the snake_case MDC key names (registry `docs/registries/mdc-keys.yaml`) every transport puts a request's correlation under — web, GraphQL, STOMP and gRPC alike. - Registry-rule mirrors read only by contract tests live in `testFixtures`, not `main`: diff --git a/src/shared-contract/README.md b/src/shared-contract/README.md index 32855e7f..d3b2e6bb 100644 --- a/src/shared-contract/README.md +++ b/src/shared-contract/README.md @@ -295,23 +295,13 @@ Spring/Lettuce 타입을 노출하지 않는다. --- -## operation — 장기 실행 작업(LRO) 계약 +## operation — 없음 (sample로 옮김) -### Operation -- **장기 실행 작업(long-running-operation) 폴링 본문**. - `GET /v1/operations/{id}` 가 `Envelope` 의 `data` 로 반환한다. -- 필드: `operationId`(opaque server id, 202 응답 `Location` 헤더의 마지막 segment 이기도 함, - never null), `status`(`OperationStatus`, terminal 까지 클라이언트가 polling), `statusUrl`(self - link), `result`(`SUCCEEDED` 일 때만, AIP151-C3), `error`(`FAILED` 일 때만, AIP151-C5, 스켈레톤 - `ApiError` 모양 재사용). -- 프레임워크 중립. id 발급과 202/Location 배선은 web 어댑터가 한다. - -### OperationStatus -- **LRO lifecycle status**(D17). -- **프로젝트 선택:** 이 5-value 어휘는 Google AIP-151 의 `done`/`response`/`error` - 이진 모델(AIP151-C4/C3/C5)을 프로젝트 내부용으로 투영한 것이다 — AIP-151 자체에는 enum 이 없다. - 매핑: `PENDING`=접수됐으나 미시작, `RUNNING`=`done=false` 진행 중, `SUCCEEDED`=`done=true`+ - `response`, `FAILED`=`done=true`+`error`, `CANCELLED`=`done=true`+취소. +장기 실행 작업(LRO)의 정본 공개 계약은 application-core `DurableOperation` + web +`OperationHttpResponse`(`GET /operations/{operationId}`, 소유자 결정 15·26)다. 이 모듈에 있던 +`Operation`·`OperationStatus`(`status` 필드, `CANCELLED` 철자)는 production 소비자가 sample뿐이라 +`sample-portfolio`의 `adapter.inbound.web.operation`으로 옮겼다(리뷰 2026-11-01 01-08). 같은 개념의 +두 번째 응답 모양을 "skeleton-wide 계약"으로 두면 파생 서비스가 틀린 쪽을 고르기 쉽다. --- diff --git a/src/shared-contract/build.gradle b/src/shared-contract/build.gradle index 7c82217b..fb4bd46b 100644 --- a/src/shared-contract/build.gradle +++ b/src/shared-contract/build.gradle @@ -16,6 +16,5 @@ strictTestLanes { description = 'Runs exact Messaging shared schema qualification tests.' requires 'dev.caskeleton.shared.contract.messaging.MessagingEnvelopeSchemaResourceTest' rejectSkipped = true - jvmArgs '-Duser.timezone=UTC' } } diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/annotation/.gitkeep b/src/shared-contract/src/main/java/dev/caskeleton/shared/annotation/.gitkeep deleted file mode 100644 index 8b137891..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/annotation/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/headers/.gitkeep b/src/shared-contract/src/main/java/dev/caskeleton/shared/headers/.gitkeep deleted file mode 100644 index 8b137891..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/headers/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/registry/.gitkeep b/src/shared-contract/src/main/java/dev/caskeleton/shared/registry/.gitkeep deleted file mode 100644 index 8b137891..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/registry/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - From 5786126cfa515cca04fc8ce53854c250d76be214 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 19:52:06 +0900 Subject: [PATCH 03/17] =?UTF-8?q?fix!:=20=EB=82=A8=EC=9D=80=20=EB=A6=AC?= =?UTF-8?q?=EB=B7=B0=20=ED=95=AD=EB=AA=A9=EA=B3=BC=20=ED=95=A9=EC=B9=9C=20?= =?UTF-8?q?=EB=92=A4=20=EB=93=9C=EB=9F=AC=EB=82=9C=20=EA=B2=B0=ED=95=A8?= =?UTF-8?q?=EC=9D=84=20=EA=B3=A0=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 앞 커밋 뒤에도 알림·파일 서버 묶음이 합쳐지지 않았고, 포트 다수에 fake와 실제 구현이 함께 통과하는 공유 계약이 없었고, SpotBugs가 신뢰도 HIGH만 봤고, application-core에 관계없는 클래스 묶음 패키지(outbound)가 있었다. 묶음을 합치자 lane·검사가 새로 드러낸 결함도 있었다(JpaOutbox Store가 읽기 전용 트랜잭션에서 이벤트를 조용히 잃음, gRPC admission controller가 public synchronized라 외부 lock에 막힘, 소비자 decode 타입 등록 경로 없음, compose Redis 익명 접근, local-fileserver lane DB 없음). 방법: 리뷰 README 15절에 남은 결정을 모두 적고 그대로 고쳤다. 트랜잭션· 멱등성·발행·notification 포트에 testFixtures 계약 키트를 두고 fake와 PG·Redis 구현이 상속한다(fake 변이로 계약이 잡는지 확인). SpotBugs는 MEDIUM으로 내리고 진짜 결함은 고치고 오탐은 위치·패턴별 이유를 단 제외로 처리했다. 업무 기능 패키지 규칙을 application-core/CLAUDE.md에 정본으로 두고 ArchUnit 2개와 생성 명령이 강제한다. compose Redis는 infra/redis-sdk ACL로 뜬다. 묶음별 결과는 리뷰 README 16절에 있다. 위험·한계: APP_FLYWAY_ENABLED가 dev·prod에도 적용된다. app.security 오타 키가 이제 기동을 막는다. SES 콜백 replay 창 기본값이 1시간이다. 템플릿 패키지 목록은 CLAUDE.md 표와 TemplatePackageOwnership 두 곳에 있고 일치 검사는 없다. 실제 CI runner 실행은 확인하지 못했다. 검증: ci, mainCheck, integrationCheck, -p optional-platforms ci integrationCheck, performanceCheck, releaseCheck(-PgitRevision), verify-compose-profile-contracts(18 lane) 통과. compose lane 실제 기동: local-fileserver, notification ingest·serving·handoff, local-redis, all-adapters(smoke 3개 포함). Refs: docs/reviews/2026-11-01-maturity-review/README.md 15·16절 BREAKING CHANGE: APP_FLYWAY_ENABLED가 dev·prod 프로필에도 적용되고, app.security의 모르는 키는 기동을 거부한다. MessageHandler에 schemaVersions()가 생겨 decode 목록을 handler 선언에서 만든다. --- AGENTS.md | 3 + docker-compose.infra.yml | 47 +- docker-compose.yml | 22 +- docs/capability-status.md | 2 +- docs/fileserver/configuration.md | 31 +- docs/fileserver/storage-certification.md | 13 +- docs/httpclient/configuration-reference.md | 17 +- docs/manual/01-generator.md | 3 +- docs/manual/03-placement.md | 11 +- docs/manual/09-outbox-events.md | 75 ++- docs/manual/10-capabilities.md | 2 +- docs/manual/11-checklist.md | 2 +- docs/messaging/outbox-inbox.md | 5 + docs/notification/api-surface-snapshot.txt | 4 +- docs/notification/configuration-reference.md | 19 +- docs/notification/evidence-manifest.json | 22 +- docs/notification/module-mapping.md | 4 +- docs/registries/env-keys.yaml | 60 +- .../2026-11-01-maturity-review/README.md | 142 +++++ docs/runbooks/migration-failed.md | 2 + docs/runbooks/outbox-dead-letter.md | 82 +++ docs/testing/TESTING_STRATEGY.md | 145 +++++ .../compose/docker-compose.fileserver.yml | 58 ++ infra/postgres/apply-capability-streams.sh | 21 +- infra/redis-sdk/acl/README.md | 16 + scripts/new-feature.sh | 48 +- scripts/run-compose-runtime-smoke.sh | 2 +- scripts/verify-compose-profile-contracts.sh | 84 ++- scripts/verify-feature-scaffold.sh | 21 + src/.env.example | 14 +- src/Dockerfile | 14 +- src/adapter/inbound/messaging/CLAUDE.md | 10 +- src/adapter/inbound/messaging/README.md | 50 +- src/adapter/inbound/messaging/build.gradle | 68 ++ src/adapter/inbound/messaging/gradle.lockfile | 274 ++++---- .../InboxRedeliveryIntegrationTest.java | 463 ++++++++++++++ .../MessagingInboxAutoConfiguration.java | 19 + .../messaging/MessagingInboxSchemaStream.java | 93 +++ .../MessagingInboxAutoConfigurationTest.java | 43 +- .../patch/JsonMergePatchDocument.java | 16 + .../patch/JsonMergePatchDocumentTest.java | 48 ++ .../web/fileserver/tus/TusController.java | 18 +- .../InMemoryUploadApplicationService.java | 7 +- .../tus/TusProtocolContractTest.java | 57 ++ .../CallbackIngressUnavailableException.java | 24 + .../NotificationCallbackMvcController.java | 31 +- .../callback/ProviderCallbackIngress.java | 11 +- .../NotificationSubmissionController.java | 2 +- .../NotificationTemplateController.java | 2 +- ...NotificationCallbackMvcControllerTest.java | 21 + src/adapter/inbound/web/CLAUDE.md | 6 +- src/adapter/inbound/web/README.md | 5 + src/adapter/inbound/web/build.gradle | 6 + .../web/envelope/EnvelopeBodyAdvice.java | 2 +- .../web/error/GlobalExceptionHandler.java | 29 +- .../WebSecurityAutoConfiguration.java | 5 +- .../operation/DurableOperationController.java | 2 +- .../web/settings/SecuritySettings.java | 24 +- .../web/settings/SecuritySettingsConfig.java | 28 + .../CorsSecurityFilterIntegrationTest.java | 6 +- .../JwtJwksSecurityFilterIntegrationTest.java | 6 +- .../web/auth/RedisSessionWebConfigTest.java | 6 +- .../web/auth/SecurityModeWebContractTest.java | 6 +- .../AuthorizationAdapterContractTest.java | 30 + ...cCorrelationIdPortAdapterContractTest.java | 26 + .../web/settings/SecuritySettingsTest.java | 54 +- .../outbound/SerializedOutboundWriter.java | 19 +- .../servlet/PlatformWebSocketHandler.java | 2 +- .../stomp/LiveEventStompBroadcaster.java | 2 +- ...SocketInboundAuthorizationInterceptor.java | 13 +- src/adapter/outbound/cache-redis/CLAUDE.md | 10 +- src/adapter/outbound/cache-redis/README.md | 6 + src/adapter/outbound/cache-redis/build.gradle | 40 +- .../outbound/cache-redis/gradle.lockfile | 12 +- .../redis/capability/RedisCacheConfig.java | 2 +- .../capability/RedisCapabilityConfig.java | 2 +- .../cache/redis/capability/RedisKeys.java | 4 +- .../cache/redis/LiveRedisRuntime.java | 22 +- .../redis/LiveRedisSemanticPortsTest.java | 2 +- .../cache/redis/RedisTestContainer.java | 92 +++ .../RedisCapabilityActivationTest.java | 2 +- .../RedisCapabilityCompositionTest.java | 2 +- ...LiveRedisIdempotencyStoreContractTest.java | 67 ++ src/adapter/outbound/fileserver/README.md | 7 +- src/adapter/outbound/fileserver/build.gradle | 4 + .../FileserverPlatformSettings.java | 42 +- ...FileserverStorageGatewayConfiguration.java | 5 +- .../local/LocalBlockingContentStore.java | 3 +- .../platform/local/LocalUploadContent.java | 46 +- .../FileserverSecuritySettingsTest.java | 32 + .../local/LocalUploadStorageContractTest.java | 28 + src/adapter/outbound/httpclient/CLAUDE.md | 7 + .../HttpClientActuatorEndpoint.java | 2 +- ...ClientAuthenticationAutoConfiguration.java | 4 +- .../HttpClientPlatformSettingsBinder.java | 14 +- .../HttpClientProfileAutoConfiguration.java | 26 +- .../HttpClientStartupValidator.java | 14 +- .../autoconfigure/ListElementKeyGuard.java | 111 ---- .../httpclient/jdk/JdkFailureClassifier.java | 6 +- .../httpclient/profile/TlsSettings.java | 6 +- .../HttpClientJitterRandomTest.java | 28 + .../HttpClientStartupValidatorTest.java | 82 +++ .../AllStableTransportsContractTest.java | 100 --- .../ScriptedTransportContractTest.java | 73 +++ .../StableTransportProviderContractTest.java | 56 ++ .../testkit/BlockingTransportContract.java | 109 ---- .../BlockingTransportProviderContract.java | 303 +++++++++ .../httpclient/testkit/ScriptedTransport.java | 54 +- src/adapter/outbound/identifier/CLAUDE.md | 3 + src/adapter/outbound/identifier/build.gradle | 2 + .../HmacUserPrincipalPseudonymizer.java | 25 +- ...cUserPrincipalPseudonymizerVectorTest.java | 32 + .../outbound/messaging-kafka/build.gradle | 8 +- .../ApplicationRelayKafkaIntegrationTest.java | 4 +- src/adapter/outbound/messaging/build.gradle | 3 + .../OutboxMessagePublishAdapterTest.java | 110 +--- ...ormIntegrationEventPublishAdapterTest.java | 44 +- .../outbound/notification/build.gradle | 15 + .../outbound/notification/gradle.lockfile | 208 +++---- .../NotificationCallbackProviderConfig.java | 21 +- .../NotificationHealthEndpoint.java | 2 +- ...tificationPlatformObservabilityConfig.java | 6 +- .../NotificationPlatformSettings.java | 8 +- .../NotificationProviderAssembly.java | 46 +- ...lbackVerificationUnavailableException.java | 39 ++ .../callback/ProviderCallbackAdapter.java | 8 + .../dispatch/ProviderRuntimeRegistry.java | 15 + .../provider/ses/SesCallbackAdapter.java | 25 +- .../ses/SesNotificationProviderAdapter.java | 21 +- .../provider/ses/SesRequestMapper.java | 3 +- .../provider/ses/SnsCertificateProvider.java | 12 +- .../provider/ses/SnsSignatureVerifier.java | 11 +- .../smtp/JavaMailSenderSmtpDispatch.java | 112 +++- .../provider/smtp/SmtpDispatchException.java | 2 +- .../NotificationEvidenceVerifier.java | 89 ++- .../NotificationEvidenceVerifierTest.java | 84 ++- .../NotificationHealthWiringTest.java | 91 +++ .../NotificationProviderAssemblyTest.java | 63 +- .../SnsCertificateCacheTest.java | 25 + .../provider/SubmissionCompatibilityTest.java | 2 +- .../provider/ses/SesCallbackAdapterTest.java | 66 ++ .../provider/ses/SesCallbackContractTest.java | 106 ++++ .../SesNotificationProviderAdapterTest.java | 29 +- .../smtp/JavaMailSenderSmtpDispatchTest.java | 243 ++++++++ .../provider/smtp/SmtpAttachmentBodyTest.java | 2 +- .../SmtpNotificationProviderAdapterTest.java | 2 +- .../platform/testkit/ContractAdapters.java | 2 + .../CrossProviderContractSuiteTest.java | 2 + .../NotificationChaosSecurityTest.java | 2 + .../callback}/testkit/CallbackContract.java | 14 +- src/adapter/outbound/objectstorage/README.md | 11 + .../outbound/objectstorage/build.gradle | 13 + .../outbound/objectstorage/gradle.lockfile | 172 ++--- .../config/ObjectStorageCapabilityConfig.java | 2 +- .../ObjectStorageDestinationSettings.java | 19 +- .../filesystem/LocalObjectStreamTransfer.java | 2 +- .../provider/ObjectStorageProvider.java | 2 +- .../ObjectStorageProviderOperation.java | 2 +- .../S3ObjectStorageProviderContribution.java | 2 +- .../ObjectStorageCapabilityConfigTest.java | 2 +- .../ObjectStorageDestinationSettingsTest.java | 38 ++ .../StagedObjectPublicationLifecycleTest.java | 2 +- .../RoutingObjectStorageAdapterTest.java | 2 +- .../s3/S3AsyncRequestBodyBridgeTest.java | 3 +- .../s3/S3AsyncResponseBodyBridgeTest.java | 2 +- .../s3/S3ManagedObjectProviderTest.java | 2 +- .../s3/S3ProviderCompositionTest.java | 2 +- .../ObjectStorageProviderContract.java | 246 +++++--- .../outbound/persistence-fileserver/CLAUDE.md | 20 +- .../persistence/fileserver/JpaFileQuota.java | 5 + .../FileserverPersistenceActivationTest.java | 79 +++ .../FileserverStoreCallerTransactionTest.java | 127 ++++ .../repository/CleanupClaimSqlTest.java | 51 ++ .../outbound/persistence-jpa/CLAUDE.md | 5 +- .../outbound/persistence-jpa/README.md | 6 + .../outbound/persistence-jpa/build.gradle | 13 + .../PersistenceExceptionTranslator.java | 2 +- .../IdempotencyTransitionGateway.java | 2 +- .../PostgreSqlIdempotencyStore.java | 18 +- .../liveevent/JpaLiveEventReplay.java | 2 +- .../outbox/jpa/JpaOutboxStore.java | 6 +- .../startup/JpaPlatformEndpoint.java | 2 +- .../PersistenceVendorProdSafetyValidator.java | 4 +- .../transaction/SpringTransaction.java | 2 +- .../module-defaults/persistence-jpa.yml | 9 +- ...ostgreSqlIdempotencyStoreContractTest.java | 106 ++++ .../JpaLiveEventReplayContractTest.java | 147 +++++ .../AdminOperationClaimContractTest.java | 196 ------ .../LateEventBindingContractTest.java | 201 ------ .../notification/NotificationFixtures.java | 3 +- .../notification/NotificationJpaStack.java | 21 + .../notification/NotificationTestCodecs.java | 116 ++++ ...greSqlAdminOperationStoreContractTest.java | 95 +++ ...stgreSqlContactPointStoreContractTest.java | 49 ++ ...tgreSqlDeduplicationStoreContractTest.java | 60 ++ ...qlDeliveryAttemptResolverContractTest.java | 103 +++ ...reSqlDeliveryAttemptStoreContractTest.java | 100 +++ ...qlDeliveryProjectionStoreContractTest.java | 143 +++++ ...lNotificationRequestStoreContractTest.java | 61 ++ ...SqlNotificationSideEffectContractTest.java | 66 ++ ...PostgreSqlPreferenceStoreContractTest.java | 2 +- ...greSqlProviderEventLedgerContractTest.java | 114 ++++ ...SqlRecipientDeliveryStoreContractTest.java | 74 +++ ...greSqlRecipientLeaseStoreContractTest.java | 125 ++++ ...SqlReconciliationJobStoreContractTest.java | 74 +++ ...ostgreSqlSuppressionStoreContractTest.java | 2 +- ...ostgreSqlTemplateRegistryContractTest.java | 62 ++ .../ProjectionFactDurabilityContractTest.java | 271 -------- .../RecipientClaimContractTest.java | 320 ---------- .../ReconciliationJobClaimContractTest.java | 257 -------- .../WorkerCrashRecoveryContractTest.java | 28 +- .../InboxBulkReadVersionContractTest.java | 3 +- .../RecipientExpiryVersionContractTest.java | 3 +- ...ileserverMetadataStoreIntegrationTest.java | 20 + .../PostgreSqlIdempotencyIntegrationTest.java | 12 +- .../PostgreSqlInboxCutoffIntegrationTest.java | 2 +- ...ficationBackgroundPassIntegrationTest.java | 111 ++-- ...icationPersistenceUnitIntegrationTest.java | 2 +- .../PostgreSqlOptionalStreamLifecycle.java | 4 +- ...boxAppendTransactionalIntegrationTest.java | 57 +- ...lOutboxOrderKeyRunbookIntegrationTest.java | 276 ++++++++ .../readiness/PostgreSqlReadinessSupport.java | 22 + ...lRecipientLeaseFencingIntegrationTest.java | 2 +- .../SpringTransactionContractTest.java | 100 +++ .../AppliedMigrationImmutabilityTest.java | 10 +- .../resources/db/applied-migrations.sha256 | 7 + .../outbound/persistence-mongo/CLAUDE.md | 7 +- .../outbound/persistence-mongo/build.gradle | 3 + .../tenancy/shared/MongoTenantContext.java | 14 +- ...rofileClientSettingsAutoConfiguration.java | 2 +- .../pagination/MongoKeysetCursorCodec.java | 20 +- .../security/MongoCredentialReference.java | 13 +- .../security/admin/MongoAdminCommand.java | 13 +- ...leClientSettingsAutoConfigurationTest.java | 2 +- .../mongo/digest/MongoDigestOutputTest.java | 90 +++ .../persistence-notification/CLAUDE.md | 19 +- .../NotificationJpaPersistenceFacade.java | 37 +- .../InboxCommitEventPublisher.java | 2 +- .../{inbox => }/InboxOutboxRecordFactory.java | 2 +- .../platform/JpaAdminOperationStore.java | 1 + .../platform/JpaContactPointStore.java | 2 + .../platform/JpaDeliveryAttemptStore.java | 3 + .../{inbox => }/JpaNotificationInbox.java | 4 +- .../platform/JpaNotificationRequestStore.java | 8 + .../platform/JpaPolicyStores.java | 5 + .../platform/JpaProviderEventLedger.java | 2 + .../platform/JpaRecipientDeliveryStore.java | 2 + .../platform/JpaRecipientLeaseStore.java | 1 + .../platform/JpaSuppressionStore.java | 2 + .../platform/JpaTemplateRegistry.java | 2 + .../platform/NotificationRecordMapper.java | 9 +- .../{ => entity}/AdminAuditEntity.java | 12 +- .../platform/{ => entity}/ConsentEntity.java | 20 +- .../{ => entity}/ContactPointEntity.java | 47 +- .../DeduplicationClaimEntity.java | 6 +- .../{ => entity}/DeliveryAttemptEntity.java | 92 +-- .../{inbox => entity}/InboxItemEntity.java | 34 +- .../NotificationRequestEntity.java | 58 +- .../{ => entity}/PreferenceEntity.java | 18 +- .../{ => entity}/ProviderEventEntity.java | 42 +- .../{ => entity}/RecipientDeliveryEntity.java | 52 +- .../{ => entity}/SuppressionEntity.java | 26 +- .../{ => entity}/TemplateVersionEntity.java | 24 +- .../AdminAuditJpaRepository.java | 3 +- .../ConsentJpaRepository.java | 3 +- .../ContactPointJpaRepository.java | 3 +- .../DeduplicationClaimJpaRepository.java | 3 +- .../DeliveryAttemptJpaRepository.java | 3 +- .../InboxItemJpaRepository.java | 3 +- .../NotificationRequestJpaRepository.java | 14 +- .../PreferenceJpaRepository.java | 3 +- .../ProviderEventJpaRepository.java | 3 +- .../{ => repository}/RecipientClaimSql.java | 8 +- .../RecipientDeliveryJpaRepository.java | 3 +- .../SuppressionJpaRepository.java | 3 +- .../TemplateVersionJpaRepository.java | 3 +- .../TenantBoundRepositoryGuard.java | 2 +- .../V13__notification_request_acceptance.sql | 21 + .../InboxItemEntityTest.java | 2 +- .../NotificationRepositoryDiscoveryTest.java | 2 +- .../NotificationRepositorySurfaceTest.java | 3 +- .../RecipientClaimSqlTest.java | 2 +- src/adapter/outbound/redis-sdk/README.md | 4 +- src/adapter/outbound/redis-sdk/build.gradle | 2 + .../ConfiguredRedisPolicyAuthority.java | 37 +- .../RedisPermitSignatureVectorTest.java | 33 + src/adapter/outbound/support/CLAUDE.md | 5 + .../support/EnvironmentSecretSource.java | 2 +- .../support/StrictSettingsBinder.java | 157 ++++- .../EnvironmentSecretSourceContractTest.java | 21 + .../support/EnvironmentSecretSourceTest.java | 2 +- .../support/StrictSettingsBinderTest.java | 155 +++++ src/app-bootstrap/README.md | 4 +- .../AdapterBoundaryArchitectureTest.java | 41 +- .../ArchRuleDiscoveryContractTest.java | 2 + .../architecture/NamingConventionTest.java | 56 +- .../TemplatePackageOwnership.java | 129 ++++ .../TemplatePackageOwnershipRuleTest.java | 128 ++++ .../invoice/LockInvoiceForPayment.java | 7 + .../application/lock/LockHandle.java | 4 + .../application/lock/LockerRental.java | 17 + .../domain/invoice/Invoice.java | 4 + .../domain/locker/Locker.java | 4 + .../domain/operation/Operation.java | 7 + .../packageownership/package-info.java | 7 + ...jectStorageCompositionIntegrationTest.java | 2 +- .../bootstrap/runtime/SecretSourceConfig.java | 2 +- .../runtime/SecretSourceFactory.java | 2 +- .../runtime/SecretSourceValidator.java | 4 +- .../runtime/StartupSafetyValidator.java | 2 +- .../AuthenticationModeCompositionConfig.java | 57 +- .../security/AuthenticationModeSettings.java | 68 -- .../src/main/resources/application-dev.yml | 33 +- .../src/main/resources/application-local.yml | 33 +- .../src/main/resources/application-prod.yml | 28 +- .../CapabilityStorageOverlayContractTest.java | 198 ++++++ .../ProfileSeparationContractTest.java | 234 ++++++- .../bootstrap/runtime/SecretSourceTest.java | 2 +- ...thenticationModeCompositionConfigTest.java | 127 ++-- .../BootstrapRolePermissionOwnershipTest.java | 61 ++ src/application-core/CLAUDE.md | 62 +- src/application-core/README.md | 12 + .../PublishPendingOutboxEventsUseCase.java | 2 +- .../{outbound => secret}/SecretReference.java | 2 +- .../SecretSourcePort.java | 2 +- ...IntegrationEventPublisherContractTest.java | 26 + .../FixedCorrelationIdContractTest.java | 12 + .../SubmitDurableOperationUseCaseTest.java | 118 +--- .../outbox/OutcomeAwareRelayTest.java | 91 +-- ...PublishPendingOutboxEventsUseCaseTest.java | 115 ++-- .../StoppingRelayReleasesItsClaimsTest.java | 14 +- .../TransientPublishFailureRelayTest.java | 85 +-- ...akeOutboxMessagePublisherContractTest.java | 76 +++ ...InMemoryOutboxStoreAppendContractTest.java | 27 + .../InMemoryLiveEventReplayContractTest.java | 27 + .../SecretReferenceTest.java | 2 +- .../InMemorySecretSourceContractTest.java | 13 + .../InMemoryAuthorizationContractTest.java | 15 + .../transaction/TransactionPortTest.java | 79 ++- .../DirectTransactionPortContractTest.java | 47 ++ .../testkit/IdempotencyStoreContract.java | 187 +++++- .../messaging/event/testkit/BrokerAnswer.java | 23 + .../FakeIntegrationEventPublisher.java | 60 ++ .../IntegrationEventPublishContract.java | 118 ++++ .../testkit/CorrelationIdContract.java | 64 ++ .../testkit/FixedCorrelationId.java | 38 ++ .../InMemoryDurableOperationStore.java | 62 +- .../testkit/FakeOutboxMessagePublisher.java | 137 ++++ .../outbox/testkit/InMemoryOutboxStore.java | 29 + .../outbox/testkit/OutboxAppendContract.java | 182 ++++-- .../testkit/OutboxMessagePublishContract.java | 132 ++++ .../testkit/InMemoryLiveEventReplay.java | 103 +++ .../testkit/LiveEventReplayContract.java | 213 +++++++ .../secret/testkit/InMemorySecretSource.java | 28 + .../secret/testkit/SecretSourceContract.java | 68 ++ .../testkit/AuthorizationContract.java | 123 ++++ .../testkit/InMemoryAuthorization.java | 39 ++ .../testkit/DirectTransactionPort.java | 106 +++- .../testkit/TransactionPortContract.java | 311 +++++++++ .../transaction/testkit/TransactionProbe.java | 27 + src/application-fileserver/build.gradle | 14 +- .../api/content/CreateContentCommand.java | 5 +- .../api/metadata/FileQuotaPort.java | 8 + .../lifecycle/CopyFileApplicationUseCase.java | 35 +- .../lifecycle/MoveFileApplicationUseCase.java | 6 +- .../lifecycle/TargetNamespacePolicy.java | 44 ++ .../fileserver/quota/NamespaceQuota.java | 60 ++ .../AppendUploadApplicationUseCase.java | 6 +- .../fileserver/upload/AppendUploadResult.java | 22 +- .../CreateUploadApplicationUseCase.java | 1 + .../FinalizeUploadApplicationUseCase.java | 41 +- .../fileserver/upload/UploadContentPort.java | 4 - .../fileserver/upload/UploadPolicy.java | 22 +- .../fileserver/upload/UploadSessions.java | 8 +- .../download/DownloadUseCasesTest.java | 19 + .../lifecycle/FileLifecycleUseCasesTest.java | 152 ++++- .../FakeUploadStorageGatewayContractTest.java | 14 + .../FinalizeUploadApplicationUseCaseTest.java | 77 ++- .../upload/ResumableUploadUseCasesTest.java | 24 + .../UploadFileApplicationUseCaseTest.java | 9 +- .../testkit/DirectTransactions.java | 40 +- .../fileserver/testkit/FakeAdminPorts.java | 0 .../testkit/FakeCleanupContentGateway.java | 0 .../testkit/FakeCopyContentGateway.java | 0 .../testkit/FakeDownloadContentGateway.java | 0 .../testkit/FakeFileAccessPolicy.java | 0 .../testkit/FakeFileQuotaService.java | 39 +- .../testkit/FakeQuotaCommitGateway.java | 0 .../FakeReconciliationContentProbe.java | 0 .../testkit/FakeUploadContentGateway.java | 12 - .../testkit/FakeUploadStorageGateway.java | 15 + .../testkit/FileserverFixtures.java | 10 +- .../testkit/InMemoryRecoveryQueue.java | 0 .../testkit/InMemoryUploadSessionStore.java | 3 +- .../fileserver/testkit/ReadyFileFixture.java | 0 .../testkit/RecordingQuotaReclaimGateway.java | 0 .../SequentialUploadIdentifierFactory.java | 0 .../testkit/UploadStoragePortContract.java | 180 ++++++ src/application-notification/build.gradle | 6 + .../dispatch/NotificationDispatchService.java | 38 +- .../dispatch/NotificationRequestRecord.java | 102 ++- .../NotificationSubmissionService.java | 22 +- .../dispatch/SuppressionSideEffect.java} | 45 +- .../admin/AdminOperationExecutorTest.java | 165 ++--- ...tificationAdminApplicationServiceTest.java | 32 +- .../InMemoryAdminOperationStoreTest.java | 26 + .../CallbackIngestionAtomicityTest.java | 101 +-- .../callback/ProviderEventLateMatchTest.java | 304 +++------ .../InMemoryDeliveryAttemptResolverTest.java | 53 ++ .../InMemoryDeliveryProjectionStoreTest.java | 53 ++ .../InMemoryProviderEventLedgerTest.java | 55 ++ ...eptNotificationApplicationUseCaseTest.java | 57 +- .../platform/dispatch/AttemptSnapshots.java | 102 +++ .../dispatch/DispatchOutcomeRecorderTest.java | 589 +++++------------- .../dispatch/DispatchPipelineTest.java | 60 +- .../dispatch/LeaseRecoveryServiceTest.java | 256 +++----- .../NotificationApplicationUseCasesTest.java | 31 +- .../NotificationDispatchServiceTest.java | 326 +++++----- .../dispatch/NotificationPlatformNoops.java | 215 ------- .../NotificationSubmissionServiceTest.java | 45 +- .../dispatch/PlatformCollaborators.java | 125 ++++ .../platform/dispatch/PlatformFakes.java | 331 +--------- ...icationTemplateApplicationUseCaseTest.java | 8 +- .../dispatch/ReconciliationServiceTest.java | 67 +- .../dispatch/SuppressionSideEffectTest.java | 38 ++ .../InMemoryContactPointStoreTest.java | 20 + .../InMemoryDeliveryAttemptStoreTest.java | 44 ++ .../InMemoryNotificationRequestStoreTest.java | 26 + .../InMemoryRecipientQueueDeliveryTest.java | 33 + .../InMemoryRecipientQueueLeaseTest.java | 33 + .../InMemoryReconciliationJobStoreTest.java | 29 + .../policy/DeduplicationAndCollapseTest.java | 28 +- .../InMemoryDeduplicationStoreTest.java | 26 + .../TemplateRegistryContractTest.java | 74 --- .../template/TemplateSelectionTest.java | 15 + .../testkit/InMemoryTemplateRegistryTest.java | 26 + .../testkit/AdminOperationStoreContract.java | 206 ++++++ .../testkit/InMemoryAdminOperationStore.java | 84 +++ .../DeliveryAttemptResolverContract.java | 116 ++++ .../DeliveryProjectionStoreContract.java | 170 +++++ .../testkit/InMemoryProviderEventLedger.java | 257 ++++++++ .../NotificationSideEffectContract.java | 186 ++++++ .../testkit/ProviderEventLedgerContract.java | 279 +++++++++ .../dispatch/testkit/AttemptStoreFixture.java | 126 ++++ .../testkit/ContactPointStoreContract.java | 189 ++++++ .../dispatch/testkit/ContractClock.java | 51 ++ .../testkit/DeliveryAttemptStoreContract.java | 187 ++++++ .../testkit/InMemoryContactPointStore.java | 128 ++++ .../testkit/InMemoryDeliveryAttemptStore.java | 393 ++++++++++++ .../InMemoryNotificationRequestStore.java | 138 ++++ .../testkit/InMemoryRecipientQueue.java | 377 +++++++++++ .../InMemoryReconciliationJobStore.java | 161 +++++ .../NotificationRequestStoreContract.java | 205 ++++++ .../dispatch/testkit/NotificationRows.java | 193 ++++++ .../RecipientDeliveryStoreContract.java | 293 +++++++++ .../testkit/RecipientLeaseStoreContract.java | 336 ++++++++++ .../ReconciliationJobStoreContract.java | 227 +++++++ .../Sha256ProviderRequestIdHasher.java | 32 + .../testkit/DeduplicationStoreContract.java | 125 ++++ .../testkit/InMemoryDeduplicationStore.java | 37 ++ .../policy/testkit/OverlappingWrites.java | 7 +- .../testkit/ProviderAdapterContract.java | 2 +- .../testkit/ProviderFaultHarness.java | 2 +- .../provider}/testkit/ProviderFixtures.java | 2 +- .../testkit}/InMemoryTemplateRegistry.java | 21 +- .../testkit/TemplateRegistryContract.java | 157 +++++ src/application-objectstorage/build.gradle | 2 + .../objectstorage/content}/CallBudget.java | 7 +- .../ObjectContentProductionContext.java | 1 - .../content/ObjectContentReadContext.java | 1 - .../identity/ObjectIdentitySupport.java | 11 +- .../objectstorage/model/ObjectDigest.java | 13 +- .../request/ObjectAbortRequest.java | 2 +- .../request/ObjectFinalizeRequest.java | 2 +- .../request/ObjectHandoffClaimRequest.java | 2 +- .../request/ObjectHandoffReleaseRequest.java | 2 +- .../request/ObjectHandoffRenewRequest.java | 2 +- .../request/ObjectPublishRequest.java | 2 +- .../request/ObjectReadRequest.java | 2 +- .../request/ObjectRetireRequest.java | 2 +- .../request/ObjectScanReadRequest.java | 2 +- .../request/ObjectStageRequest.java | 2 +- .../request/ObjectVerifyRequest.java | 2 +- .../ObjectContentContractTest.java | 2 +- .../content}/CallBudgetTest.java | 2 +- .../ObjectIdentityDigestOutputTest.java | 54 ++ .../quality/QualityConventionsPlugin.java | 53 +- src/composition/fileserver-platform/README.md | 19 + .../fileserver-platform/build.gradle | 2 + .../FileserverCleanupConfiguration.java | 9 +- ...ileserverCleanupDisabledConfiguration.java | 41 ++ .../fileserver/FileserverCleanupWorker.java | 2 +- .../FileserverCorePolicyConfiguration.java | 21 +- .../FileserverFileUseCaseConfiguration.java | 7 +- .../FileserverPlatformAutoConfiguration.java | 1 + .../FileserverUploadUseCaseConfiguration.java | 2 + .../config/module-defaults/fileserver.yml | 8 +- .../fileserver/FileserverAssemblyFixture.java | 23 +- .../FileserverModuleDefaultsTest.java | 26 + .../FileserverPlatformEnvRoundTripTest.java | 51 +- .../FileserverRuntimeAssemblyTest.java | 30 +- .../idempotency/IdempotencySettings.java | 2 +- .../NotificationDeliveryConfiguration.java | 18 + .../ProviderCallbackIngressBridge.java | 20 +- .../config/module-defaults/notification.yml | 13 +- .../NotificationModuleDefaultsTest.java | 72 +++ .../ProviderCallbackIngressBridgeTest.java | 36 ++ src/config/architecture/modules.json | 17 +- .../runtime/compose-profile-contracts.json | 70 ++- src/config/spotbugs/exclude.xml | 364 +++++++++++ .../testing/container-images.properties | 2 + src/grpc-advanced/CLAUDE.md | 6 + src/grpc/CLAUDE.md | 9 + .../grpc/server/GrpcAdmissionController.java | 79 ++- .../server/GrpcAdmissionControllerTest.java | 22 + src/messaging/CLAUDE.md | 10 + .../api/delivery/MessageHandler.java | 22 + .../messaging/inbox/InboxMessageHandler.java | 7 + .../autoconfigure/MessageContracts.java | 53 +- .../MessagingConfigurationCompiler.java | 18 +- .../autoconfigure/MessagingEndpoint.java | 2 +- .../MessagingPublishConfiguration.java | 14 +- .../MessagingConsumeConfigurationTest.java | 126 ++++ src/sample-portfolio/README.md | 5 + src/sample-portfolio/build.gradle | 3 + .../PosterImagePublicationController.java | 2 +- .../persistence/entity/WorkLogEntity.java | 7 +- .../AbortPosterImageUploadCommand.java | 2 +- .../PublishPosterImageCommand.java | 2 +- ...ReconcilePosterImageRetirementCommand.java | 2 +- .../ReconcilePosterImageUploadCommand.java | 2 +- .../PosterImageRetirementJob.java | 2 +- .../SampleDemoAccountsProductionGuard.java | 52 ++ .../security/SampleDemoSecurityConfig.java | 18 + .../portfolio/domain/poster/Poster.java | 2 +- .../portfolio/domain/worklog/WorkLog.java | 2 +- .../WorkLogStatementCostSystemTest.java | 4 +- .../MultipartObjectContentProducerTest.java | 2 +- .../persistence/entity/WorkLogEntityTest.java | 47 ++ .../PosterImageAbortReconcileRaceTest.java | 2 +- .../PosterImagePublicationWorkflowTest.java | 2 +- .../PosterImageRetirementCrashMatrixTest.java | 2 +- .../architecture/SampleArchitectureTest.java | 2 + ...SampleDemoAccountsProductionGuardTest.java | 78 +++ src/shared-contract/CLAUDE.md | 11 +- 545 files changed, 20138 insertions(+), 5870 deletions(-) create mode 100644 infra/fileserver/compose/docker-compose.fileserver.yml create mode 100644 src/adapter/inbound/messaging/src/integrationTest/java/dev/caskeleton/adapter/inbound/messaging/InboxRedeliveryIntegrationTest.java create mode 100644 src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxSchemaStream.java create mode 100644 src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocumentTest.java create mode 100644 src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackIngressUnavailableException.java create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsConfig.java create mode 100644 src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/authz/AuthorizationAdapterContractTest.java create mode 100644 src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapterContractTest.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/LiveRedisIdempotencyStoreContractTest.java create mode 100644 src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverSecuritySettingsTest.java create mode 100644 src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorageContractTest.java delete mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/ListElementKeyGuard.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientJitterRandomTest.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientStartupValidatorTest.java delete mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/AllStableTransportsContractTest.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/ScriptedTransportContractTest.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/StableTransportProviderContractTest.java delete mode 100644 src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/BlockingTransportContract.java create mode 100644 src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/BlockingTransportProviderContract.java create mode 100644 src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizerVectorTest.java create mode 100644 src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/CallbackVerificationUnavailableException.java create mode 100644 src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationHealthWiringTest.java create mode 100644 src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackContractTest.java create mode 100644 src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatchTest.java rename src/adapter/outbound/notification/src/{test/java/dev/caskeleton/adapter/outbound/notification/platform => testFixtures/java/dev/caskeleton/adapter/outbound/notification/platform/callback}/testkit/CallbackContract.java (80%) create mode 100644 src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageDestinationSettingsTest.java rename src/adapter/outbound/objectstorage/src/{test => testFixtures}/java/dev/caskeleton/adapter/outbound/objectstorage/contract/ObjectStorageProviderContract.java (52%) create mode 100644 src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverPersistenceActivationTest.java create mode 100644 src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverStoreCallerTransactionTest.java create mode 100644 src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSqlTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayContractTest.java delete mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/AdminOperationClaimContractTest.java delete mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/LateEventBindingContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationTestCodecs.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlAdminOperationStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlContactPointStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeduplicationStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryAttemptResolverContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryAttemptStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryProjectionStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlNotificationRequestStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlNotificationSideEffectContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlProviderEventLedgerContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientDeliveryStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientLeaseStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlReconciliationJobStoreContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlTemplateRegistryContractTest.java delete mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ProjectionFactDurabilityContractTest.java delete mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/RecipientClaimContractTest.java delete mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ReconciliationJobClaimContractTest.java rename src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{inbox => repository}/InboxBulkReadVersionContractTest.java (96%) rename src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/RecipientExpiryVersionContractTest.java (96%) create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java create mode 100644 src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/digest/MongoDigestOutputTest.java rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{inbox => }/InboxCommitEventPublisher.java (99%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{inbox => }/InboxOutboxRecordFactory.java (98%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{inbox => }/JpaNotificationInbox.java (97%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => entity}/AdminAuditEntity.java (93%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => entity}/ConsentEntity.java (88%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => entity}/ContactPointEntity.java (84%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => entity}/DeduplicationClaimEntity.java (95%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => entity}/DeliveryAttemptEntity.java (88%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{inbox => entity}/InboxItemEntity.java (89%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => entity}/NotificationRequestEntity.java (82%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => entity}/PreferenceEntity.java (88%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => entity}/ProviderEventEntity.java (88%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => entity}/RecipientDeliveryEntity.java (88%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => entity}/SuppressionEntity.java (85%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => entity}/TemplateVersionEntity.java (90%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/AdminAuditJpaRepository.java (97%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/ConsentJpaRepository.java (90%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/ContactPointJpaRepository.java (86%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/DeduplicationClaimJpaRepository.java (95%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/DeliveryAttemptJpaRepository.java (91%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{inbox => repository}/InboxItemJpaRepository.java (97%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/NotificationRequestJpaRepository.java (85%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/PreferenceJpaRepository.java (95%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/ProviderEventJpaRepository.java (98%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/RecipientClaimSql.java (91%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/RecipientDeliveryJpaRepository.java (98%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/SuppressionJpaRepository.java (96%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/TemplateVersionJpaRepository.java (95%) rename src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/TenantBoundRepositoryGuard.java (98%) create mode 100644 src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V13__notification_request_acceptance.sql rename src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{inbox => entity}/InboxItemEntityTest.java (99%) rename src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/NotificationRepositoryDiscoveryTest.java (99%) rename src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/NotificationRepositorySurfaceTest.java (96%) rename src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/{ => repository}/RecipientClaimSqlTest.java (94%) create mode 100644 src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitSignatureVectorTest.java create mode 100644 src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSourceContractTest.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnership.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipRuleTest.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/invoice/LockInvoiceForPayment.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/lock/LockHandle.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/lock/LockerRental.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/invoice/Invoice.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/locker/Locker.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/operation/Operation.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/package-info.java delete mode 100644 src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeSettings.java create mode 100644 src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStorageOverlayContractTest.java create mode 100644 src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/BootstrapRolePermissionOwnershipTest.java rename src/application-core/src/main/java/dev/caskeleton/application/{outbound => secret}/SecretReference.java (97%) rename src/application-core/src/main/java/dev/caskeleton/application/{outbound => secret}/SecretSourcePort.java (93%) create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisherContractTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/observability/testkit/FixedCorrelationIdContractTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisherContractTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreAppendContractTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/realtime/testkit/InMemoryLiveEventReplayContractTest.java rename src/application-core/src/test/java/dev/caskeleton/application/{outbound => secret}/SecretReferenceTest.java (97%) create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/secret/testkit/InMemorySecretSourceContractTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/security/testkit/InMemoryAuthorizationContractTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPortContractTest.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/BrokerAnswer.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisher.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventPublishContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/observability/testkit/CorrelationIdContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/observability/testkit/FixedCorrelationId.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisher.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxMessagePublishContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/realtime/testkit/InMemoryLiveEventReplay.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/realtime/testkit/LiveEventReplayContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/secret/testkit/InMemorySecretSource.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/secret/testkit/SecretSourceContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/security/testkit/AuthorizationContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/security/testkit/InMemoryAuthorization.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionPortContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionProbe.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/TargetNamespacePolicy.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/NamespaceQuota.java create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGatewayContractTest.java rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/DirectTransactions.java (51%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/FakeAdminPorts.java (100%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/FakeCleanupContentGateway.java (100%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/FakeCopyContentGateway.java (100%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/FakeDownloadContentGateway.java (100%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java (100%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java (52%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/FakeQuotaCommitGateway.java (100%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/FakeReconciliationContentProbe.java (100%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/FakeUploadContentGateway.java (87%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGateway.java (84%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/FileserverFixtures.java (87%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueue.java (100%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java (98%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/ReadyFileFixture.java (100%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/RecordingQuotaReclaimGateway.java (100%) rename src/application-fileserver/src/{test => testFixtures}/java/dev/caskeleton/application/fileserver/testkit/SequentialUploadIdentifierFactory.java (100%) create mode 100644 src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/UploadStoragePortContract.java rename src/{adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffect.java => application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/SuppressionSideEffect.java} (63%) create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/testkit/InMemoryAdminOperationStoreTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryDeliveryAttemptResolverTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryDeliveryProjectionStoreTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryProviderEventLedgerTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AttemptSnapshots.java delete mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformCollaborators.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/SuppressionSideEffectTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryContactPointStoreTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryDeliveryAttemptStoreTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStoreTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueueDeliveryTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueueLeaseTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStoreTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryDeduplicationStoreTest.java delete mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/TemplateRegistryContractTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/TemplateSelectionTest.java create mode 100644 src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/testkit/InMemoryTemplateRegistryTest.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/AdminOperationStoreContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/InMemoryAdminOperationStore.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/DeliveryAttemptResolverContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/DeliveryProjectionStoreContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryProviderEventLedger.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/NotificationSideEffectContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/ProviderEventLedgerContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/AttemptStoreFixture.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ContactPointStoreContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ContractClock.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/DeliveryAttemptStoreContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryContactPointStore.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryDeliveryAttemptStore.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueue.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStore.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRequestStoreContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRows.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/RecipientDeliveryStoreContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/RecipientLeaseStoreContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ReconciliationJobStoreContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/Sha256ProviderRequestIdHasher.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/DeduplicationStoreContract.java create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryDeduplicationStore.java rename src/{adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform => application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider}/testkit/ProviderAdapterContract.java (98%) rename src/{adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform => application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider}/testkit/ProviderFaultHarness.java (98%) rename src/{adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform => application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider}/testkit/ProviderFixtures.java (98%) rename src/application-notification/src/{test/java/dev/caskeleton/application/notification/platform/template => testFixtures/java/dev/caskeleton/application/notification/platform/template/testkit}/InMemoryTemplateRegistry.java (78%) create mode 100644 src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/template/testkit/TemplateRegistryContract.java rename src/{application-core/src/main/java/dev/caskeleton/application/outbound => application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content}/CallBudget.java (83%) rename src/{application-core/src/test/java/dev/caskeleton/application/outbound => application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/content}/CallBudgetTest.java (96%) create mode 100644 src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/identity/ObjectIdentityDigestOutputTest.java create mode 100644 src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupDisabledConfiguration.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java create mode 100644 src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntityTest.java create mode 100644 src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuardTest.java diff --git a/AGENTS.md b/AGENTS.md index f86cf3cd..27b27f35 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -234,6 +234,9 @@ capability 모듈 완료 기준 (7개 모두 충족해야 "포장 완료"): 자체를 두지 않는다. 4. 설정 prefix는 하나만 쓴다. 바인딩은 `StrictSettingsBinder`, 값 검증은 설정 record의 compact constructor에서 한다. + 예외(리뷰 05-18): Redis는 `app.redis.*`(redis-runtime, setter+`validate()`)·`app.capabilities.*`· + `app.rate-limit.*` 세 트리를 유지한다. 키를 바꾸면 운영 env가 깨진다. 새 Redis 설정은 이 셋 중 + 하나에 넣고 네 번째 트리는 만들지 않는다. 이유는 `src/adapter/outbound/cache-redis/CLAUDE.md`. 5. 포트 소유 모듈 testFixtures의 포트 계약 테스트(추상 클래스)를 fake와 실제 어댑터가 모두 통과한다. 실제 벤더(Testcontainers)로 도는 테스트가 1개 이상 있다. 6. 모듈 README에 세 가지를 적는다: 제공하는 것, 추가할 한 줄, 필요한 env 키. diff --git a/docker-compose.infra.yml b/docker-compose.infra.yml index 7f0b49c5..93de6c85 100644 --- a/docker-compose.infra.yml +++ b/docker-compose.infra.yml @@ -30,6 +30,7 @@ services: profiles: - local-jpa - local-messaging-outbox + - local-fileserver - local-notification-ingest - local-notification-serving - local-notification-handoff @@ -136,16 +137,44 @@ services: start_period: 30s # ---- Redis — local compose contract for the shipped Redis runtime ---------------- + # Authenticated, with the accounts a deployment loads: infra/redis-sdk/acl/all-accounts.acl, the + # same file the Redis topology lanes use, mounted as it is rather than copied. Its first line turns + # the passwordless `default` user off, so the application connects as the named accounts the lane + # contract gives it (compose-profile-contracts.json, $redisComment). + # + # This Redis was open and the lanes declared app.redis.authentication.anonymous-access-accepted. + # The application then logged that trade, and the missing advanced account, as two startup + # warnings — correctly, because in production both are risks — and every Redis lane failed its + # "startup is silent" check. Quieting the warning would hide the same trade in production; the + # lane now authenticates the way a deployment does instead. + # + # The passwords are the file's fixture values (infra/redis-sdk/acl/README.md); this container is + # on the lane's internal network only and publishes no port. redis: profiles: - local-redis - all-adapters image: redis:7.4 - command: ["redis-server", "--appendonly", "no", "--save", ""] + command: + - redis-server + - --appendonly + - "no" + - --save + - "" + - --aclfile + - /etc/redis/acl/all-accounts.acl + volumes: + - type: bind + source: ./infra/redis-sdk/acl + target: /etc/redis/acl + read_only: true networks: - caskeleton-infra healthcheck: - test: ["CMD", "redis-cli", "ping"] + # As the application account: with `default` off, an unauthenticated PING answers NOAUTH. + test: + - "CMD-SHELL" + - "[ \"$$(redis-cli --user ca-skeleton-application --pass fixture-application --no-auth-warning ping)\" = PONG ]" interval: 5s timeout: 3s retries: 12 @@ -301,6 +330,7 @@ services: - local-notification-ingest - local-notification-serving - local-notification-handoff + - local-fileserver - all-adapters image: flyway/flyway:11.1.0 depends_on: @@ -326,6 +356,18 @@ services: source: ./src/adapter/outbound/persistence-jpa/src/main/resources/db/migration target: /flyway/sql read_only: true + # Each capability stream from the leaf that owns it, beside rather than inside /flyway/sql: a + # bind mount nested in that read-only one would need its mount point created in the source + # tree. They moved out of persistence-jpa with their capabilities, and the mount above stopped + # reaching them — the script then refused with "no such stream". + - type: bind + source: ./src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform + target: /flyway/streams/notification-platform + read_only: true + - type: bind + source: ./src/adapter/outbound/persistence-fileserver/src/main/resources/db/migration/jpa/fileserver + target: /flyway/streams/fileserver + read_only: true networks: - caskeleton-infra restart: "no" @@ -335,6 +377,7 @@ services: - local-notification-ingest - local-notification-serving - local-notification-handoff + - local-fileserver - all-adapters image: postgres:16-alpine depends_on: diff --git a/docker-compose.yml b/docker-compose.yml index b63042d3..39d0562f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -75,20 +75,9 @@ services: tmpfs: - /tmp:mode=1777,size=128m - /var/tmp/heap:mode=1777,size=512m - # ---- Fileserver storage volume ------------------------------------------ - # A named volume, not a tmpfs and not the read-only root. The Fileserver platform's default - # storage root is /var/lib/backend/files, and with a read-only root and no mount there was - # nowhere on the image it could legally write: enabling the capability failed on its first - # upload rather than at startup. The volume is declared unconditionally because a volume - # nobody writes to costs nothing, while a missing one costs an outage. - # - # Ownership: the image runs as uid/gid 1000 (see src/Dockerfile). Docker initialises a fresh - # named volume from the image path's ownership, so the directory is created in the image with - # that owner; a pre-existing volume or a host bind mount must be chowned to 1000:1000 by the - # operator, or every write is refused with a permission error the application reports as - # STORAGE_UNAVAILABLE. - volumes: - - fileserver-data:/var/lib/backend/files + # No volume: the shipped composition keeps nothing on disk. A capability that does brings its + # mount in its own overlay file under infra//compose/, added with -f when the + # capability is selected, so this file never names one (07-08). # ---- Memory limit (D4) -------------------------------------------------- # Must be set so -XX:MaxRAMPercentage=75 can compute a meaningful heap bound. mem_limit: 512m @@ -116,8 +105,3 @@ services: start_period: 60s retries: 3 restart: unless-stopped - -volumes: - # Survives container replacement, which is the point: published content outlives the process - # that wrote it. Back this with real storage in any deployment that keeps files. - fileserver-data: diff --git a/docs/capability-status.md b/docs/capability-status.md index 1ad7bc5f..ab9f8972 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -30,7 +30,7 @@ lanes and CI; it is not a deployment artifact. | Relational persistence (JPA/PostgreSQL) | `ca-skeleton.persistence-jpa.enabled` / `APP_PERSISTENCE_JPA_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-jpa')`) | yes | Not in the default composition. The one line brings everything — its own `AutoConfiguration.imports` (`PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig`, `JpaStartupAutoConfiguration`), its environment handling (`JpaActivationEnvironmentPostProcessor`, `spring.factories`: readiness `db` while on; with `false` it also excludes Boot's JDBC, Hibernate, Spring Data JPA and Flyway auto-configuration, so no DataSource is bound), the startup guards (Flyway strategy, datasource/OSIV/DDL/pool/TLS/vendor checks, exit codes unchanged) and its settings (`config/module-defaults/persistence-jpa.yml`). `persistence-jpa:PersistenceJpaCapabilityAssemblyTest` proves the module assembles on its own; the `postgresql*IntegrationTest` readiness lanes, run by `integration-main.yml` → `integration-check` (`:integrationCheck`), qualify it against PostgreSQL. `sample-portfolio` selects it by its build dependency and the module's auto-configuration (no broad scan of the persistence package). `bootRunH2` adds the module to its own classpath only. | | Document persistence (MongoDB) | `ca-skeleton.persistence-mongo.enabled` / `APP_PERSISTENCE_MONGO_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-mongo')`) | yes | On when present; `false` also excludes Boot's Mongo auto-configuration (`MongoCapabilityActivationTest`). The connection-source rule (`SPRING_MONGODB_URI` or the selected profile's `uri-secret`) is checked by the module's own `MongoDefaultsEnvironmentPostProcessor`. Six container lanes (`mongoReplicaSetTest`, `mongoFailoverTest`, …), run by `integration-main.yml` → `integration-check` (`:integrationCheck`) | | Messaging (Kafka) | `app.messaging.enabled` / `APP_MESSAGING_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:messaging-kafka')`, which brings the application bridge, the legacy `KafkaSender` seam and the vendored platform with its Kafka transport) | Kafka only | On when present (`KafkaCapabilityActivationTest`). `messaging-kafka:messagingCertificationTest` behind `verifyMessagingCertificationEvidence`, run by `messaging-certification.yml`; the starter's `integrationTest` is the live Kafka round trip. Kafka is the only registered broker; the RabbitMQ broker keys were removed (no transport). | -| Redis capabilities (cache / rate-limit / lease / idempotency) | `app.redis.enabled` / `APP_REDIS_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:cache-redis')`, which brings `redis-runtime`) | yes | `cache-redis:redisTopologyTest`, run by `redis-sdk-topology.yml`. Not in the default composition. On when present; `false` contributes no Redis bean — no settings, client, connection, thread or health contributor. The module owns its readiness contribution (`RedisReadinessGroupPostProcessor`, `spring.factories`) and its settings (`config/module-defaults/cache-redis.yml`: `app.redis.enabled`, `app.rate-limit.*`, the Redis `ca-skeleton.capabilities.*`). No `app-bootstrap` main source names a Redis type. | +| Redis capabilities (cache / rate-limit / lease / idempotency) | `app.redis.enabled` / `APP_REDIS_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:cache-redis')`, which brings `redis-runtime`) | yes | `cache-redis:redisContainerContractTest` (Testcontainers Redis, `integrationCheck` and `mainCheck`); `cache-redis:redisTopologyTest`, run by `redis-sdk-topology.yml`. Not in the default composition. On when present; `false` contributes no Redis bean — no settings, client, connection, thread or health contributor. The module owns its readiness contribution (`RedisReadinessGroupPostProcessor`, `spring.factories`) and its settings (`config/module-defaults/cache-redis.yml`: `app.redis.enabled`, `app.rate-limit.*`, the Redis `ca-skeleton.capabilities.*`). No `app-bootstrap` main source names a Redis type. | | Request idempotency | `APP_IDEMPOTENCY_PROVIDER` (`disabled` \| `redis` \| `postgresql`; a selector, not an on/off key) | yes | yes | Redis only | One generation: the application `IdempotencyExecutor`, built once by `app-bootstrap` `IdempotencyProviderSelectionConfig` over the one store the selected provider contributes (`cache-redis` or `persistence-jpa`); startup is refused unless exactly one store exists. `sample-portfolio` cannot depend on `app-bootstrap`, so its own `SampleIdempotencyConfig` builds its one executor from the same keys. Redis is covered by the row above. PostgreSQL has `persistence-jpa:postgresqlIdempotencyIntegrationTest`, but no workflow runs it. The `postgresql` provider refuses a non-PostgreSQL data source, so `bootRunH2` uses `disabled` or `redis`.. The executor stays in the composition root on purpose — it needs only application-core and its settings — while each store comes with its module: `postgresql` needs the persistence-jpa line, `redis` the cache-redis one. | | Transactional outbox relay | `ca-skeleton.outbox.enabled` / `APP_OUTBOX_ENABLED`, `false` (+ `APP_OUTBOX_RELAY_ENABLED`, `false`; persistence-jpa settings) | yes | yes (with the persistence-jpa line; the scheduler also needs the messaging-kafka line) | yes | The store and its settings are persistence-jpa's; the relay (`OutboxConfig`) is application composition in `app-bootstrap` because a driven adapter must not build or call a use case. It turns on only when an `OutboxStorePort` bean exists, and the scheduler only when an `OutboxMessagePublishPort` does (the messaging bridge), each ordered after its contributor by `afterName` — so an environment with no publisher keeps its PENDING rows. The bridge registers no stand-in publisher: a present-and-enabled bridge with a blank broker and no canonical transport is refused at startup. `postgresqlLegacyOutboxConcurrentRelayIntegrationTest` qualifies claim/fencing against PostgreSQL. | | Notification platform | `ca-skeleton.notification.platform.enabled` / `APP_NOTIFICATION_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:notification-platform')`, plus the persistence-jpa line) | claim-scoped | Not in the default composition. The one line brings the use-case assembly, `adapter:outbound:notification`, the HTTP surface `adapter:inbound:web-notification` and its own settings (`config/module-defaults/notification.yml`), each registered through the module's own `AutoConfiguration.imports`; `adapter:inbound:web` no longer depends on `application-notification`. `verifyNotificationEvidence` refuses a grade in `docs/notification/support-matrix.md` that no proven claim backs; run by `notification-platform.yml`. There is no real-SMTP lane, and the matrix says so rather than implying one. | diff --git a/docs/fileserver/configuration.md b/docs/fileserver/configuration.md index 72bed55b..2cd42562 100644 --- a/docs/fileserver/configuration.md +++ b/docs/fileserver/configuration.md @@ -7,8 +7,8 @@ While `app.fileserver-platform.enabled` is false none of these keys is bound at auto-configuration that binds them is not processed — so a malformed value in a block nobody enabled cannot fail a startup. Once enabled, binding is strict: an unknown key under the prefix is refused rather than ignored. The defaults are the conservative ones: the -capability is off, the admin plane is off, background reclamation is off, and there is no permissive -authorization fallback. Turning the capability on is a deliberate act, and so is every surface it +admin plane is off, background reclamation is on (leaving it off is what fills the volume), copies +and moves may only target the default namespace, and there is no permissive authorization fallback. Turning the capability on is a deliberate act, and so is every surface it exposes. ## Minimum to start @@ -127,7 +127,13 @@ Set `inline-safe-profile: true` only when downloads are never served inline from | `scope-upload-permits` | `4` | concurrent uploads one caller (principal) admits; over it is a retryable `429` | | `direct-download-permits` | `64` | concurrent non-delegated downloads | | `soft-high-water` | `0.70` | storage fraction at which pressure is reported | -| `hard-high-water` | `0.85` | storage fraction at which uploads are refused | +| `hard-high-water` | `0.85` | storage fraction at which uploads and copies are refused | +| `namespace-limit` | unset (unlimited) | most bytes one namespace may hold, live reservations plus committed usage; a create or copy that would pass it is refused with `QUOTA_EXCEEDED` (413) before any record or byte exists | + +`namespace-limit` is checked against the usage the quota ledger reports and then reserved, in one +transaction but without a per-namespace lock: reservations admitted at the same moment can overshoot +the limit by at most their own size, and the next one is refused. A service that needs an exact cap +adds that lock in its persistence adapter. When the storage fraction cannot be read, admission treats it as unknown and does not apply the high-water rule — a synthetic `0` would silently disable the guard, and a synthetic `1` would take @@ -137,14 +143,19 @@ the capability down over a failed syscall. | Key | Default | Meaning | | --- | --- | --- | -| `enabled` | `false` | run the cleanup worker on this node | +| `enabled` | `true` | run the cleanup worker on this node; `false` logs a startup warning | | `interval` | `60s` | fixed delay between batches, not fixed rate | | `max-items` | `100` | items one batch may claim | | `max-bytes` | `1GB` | bytes one batch may reclaim | | `retry-backoff` | `5m` | how long a failed item waits before it is due again | -The worker deletes physical objects, so it is off until a deployment decides otherwise. A node -without it still queues cleanup items; another node or an operator reclaims them. An item that fails +The worker is on by default: it deletes only what the cleanup queue names, and without it cancelled +and expired staging, rejected and deleted content stay on the volume until the hard high-water mark +stops every upload. A node may turn it off — for instance when another node runs it — and startup +then logs a `WARN` naming `app.fileserver-platform.cleanup.enabled=false`. A node without it still +queues cleanup items; another node or an operator reclaims them. (A required "reason" key was +considered instead of the warning and rejected: it would be a setting whose only effect is to +silence startup, carried by every non-worker node.) An item that fails eight times is abandoned rather than retried forever — it stays visible to an operator, parked rather than discarded. @@ -153,6 +164,14 @@ staged bytes are queued), purges orphans the admin plane retired to quarantine, reconciliation over stale `UPLOADED`/`VERIFYING`/`FAILED` records, so an ambiguous publish settles without an operator. +## Copy and move targets + +`app.fileserver-platform.target-namespaces` (`APP_FILESERVER_PLATFORM_TARGET_NAMESPACES`, a comma +list, empty by default) names the namespaces copy and move may write into besides +`default-namespace`, which is always allowed. The target namespace of a copy or a move comes from the request body, and a namespace is also the +quota grouping. Any other target is refused with `ACCESS_DENIED` before a byte moves or a +reservation is taken. + ## Management plane — `admin` | Key | Default | Meaning | diff --git a/docs/fileserver/storage-certification.md b/docs/fileserver/storage-certification.md index 73d14953..b6788738 100644 --- a/docs/fileserver/storage-certification.md +++ b/docs/fileserver/storage-certification.md @@ -61,6 +61,13 @@ fails closed rather than degrading silently. ## Adding a new store -Extend `ContentStoreContract` and pass it. A prose claim of compatibility is not accepted; the -contract is executable precisely so a future object-storage adapter has to demonstrate the same -offset, digest, and create-only behaviour the local store does. +Pass two executable contracts. A prose claim of compatibility is not accepted. + +- `UploadStoragePortContract` — the application port's contract, in `application-fileserver` + testFixtures (`testImplementation testFixtures(project(':application-fileserver'))`). The + application's `FakeUploadStorageGateway` extends it too, so use case tests and the real store obey + the same offset, chunk-checksum and size-ceiling rules (a declared 0-byte upload refuses its first + byte). +- `ContentStoreContract` — the local adapter's internal `BlockingContentStore` SPI, in this + adapter's tests. That SPI stays in the adapter by design (review S1-#12: the application never + calls it), so its contract stays with it; a store that reuses the SPI extends it as well. diff --git a/docs/httpclient/configuration-reference.md b/docs/httpclient/configuration-reference.md index 6feb9cc8..d4ff4823 100644 --- a/docs/httpclient/configuration-reference.md +++ b/docs/httpclient/configuration-reference.md @@ -107,7 +107,8 @@ instead, so a long download is not cut at an arbitrary total (design §15.3). ### Removed settings Six keys were removed because they were bound and reached no transport (review 2026-11-01 05-15). -Setting one now fails startup with `HTTPCLIENT_UNKNOWN_SETTING` naming the key, instead of being +Setting one now fails startup with a bind error naming the key (`The elements +[app.httpclient.clients[0].timeout.request-write-idle] were left unbound.`), instead of being accepted and ignored. | Removed key | Why | @@ -225,13 +226,15 @@ the profile, not to a runtime generation, so a certificate rotation keeps its st `TLS_PROTOCOL_SET_REQUIRED`, `RETRY_POLICY_CONTRADICTS_ATTEMPTS`, `FULL_URL_RECORDING_FORBIDDEN`, `BODY_LOGGING_FORBIDDEN`, `DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED`, `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED`, -`TIMEOUT_NOT_POSITIVE`, `RETRY_MAX_ATTEMPTS_EXCEEDED`, `CIRCUIT_BREAKER_SETTING_INVALID`, -`HTTPCLIENT_UNKNOWN_SETTING`. +`TIMEOUT_NOT_POSITIVE`, `RETRY_MAX_ATTEMPTS_EXCEEDED`, `CIRCUIT_BREAKER_SETTING_INVALID`. -`HTTPCLIENT_UNKNOWN_SETTING` covers a gap in the shared strict binder: Spring's unbound-key check -stops at the first level under a list element, so `clients[0].timeout.` used to bind nothing -and fail nothing. The platform now checks every key under `clients[N]` and `dynamic-targets[N]` -against the settings records. +A key that names no setting is not a violation code: the shared strict binder +(`adapter:outbound:support` `StrictSettingsBinder`) refuses it while binding, at any depth. Spring's +own unbound-key check stops at the first level under a list element, so `clients[0].timeout.` +used to bind nothing and fail nothing; the binder now refuses a key under `clients[N]` or +`dynamic-targets[N]` that bound nothing, for every capability rather than for this platform alone +(review 2026-11-01 05-15). The platform's own guard for it, and its `HTTPCLIENT_UNKNOWN_SETTING` +code, were removed with that change. `DNS_TIMEOUT_UNSUPPORTED`, `PROXY_CREDENTIAL_UNSUPPORTED` and `PROXY_AMBIENT_NO_PROXY_UNSUPPORTED` name settings the platform binds but cannot yet honour. Neither the Apache classic client nor the JDK client exposes a DNS-resolution timeout, and no proxy-credential path exists, so diff --git a/docs/manual/01-generator.md b/docs/manual/01-generator.md index 79bebae6..fe9a0c8e 100644 --- a/docs/manual/01-generator.md +++ b/docs/manual/01-generator.md @@ -30,7 +30,7 @@ scripts/new-feature.sh Invoice --no-format # Gradle 없이 파일만 (뒤에 | 입력 | 규칙 | 어디서 막나 | | --- | --- | --- | | 이름 | PascalCase, 영숫자 | 스크립트 | -| 패키지 이름 | 이름을 소문자로(`purchaseorder`). Java 예약어·플랫폼 패키지(`operation`, `lock`, `cache`…)와 겹치면 거절 | 스크립트 | +| 패키지 이름 | 이름을 소문자로(`purchaseorder`). Java 예약어이거나, 다섯 루트 중 어디든(어느 leaf든) 이미 있는 패키지 이름이면 거절 — 템플릿 패키지(`operation`, `lock`, `cache`…)가 모두 여기 걸린다. 목록은 `src/application-core/CLAUDE.md` 「Package ownership」 | 스크립트, `NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES` | | HTTP 경로 | lowerCamel 복수형. AIP-122 모양 | 스크립트, `ForbiddenApiArchitectureTest.CONTROLLER_REQUEST_MAPPINGS_FOLLOW_AIP122` | | 이미 있는 파일·패키지 | 덮어쓰지 않고 멈춘다 | 스크립트 | @@ -61,6 +61,7 @@ cd src ```text verify-feature-scaffold.sh -> 작업 트리를 임시 디렉터리로 복사(추적 + 무시되지 않은 새 파일), git init + -> new-feature.sh Operation / Notification / Common (템플릿 패키지 이름: 거절되고 아무것도 안 씀) -> new-feature.sh Invoice, new-feature.sh PurchaseOrder (한 단어 / 여러 단어) -> 생성 파일이 있는지 확인 -> ./gradlew 5 leaf check + architectureCheck diff --git a/docs/manual/03-placement.md b/docs/manual/03-placement.md index 448d13fc..01ecf57a 100644 --- a/docs/manual/03-placement.md +++ b/docs/manual/03-placement.md @@ -56,10 +56,13 @@ | inbound | `dev.caskeleton.adapter.inbound.web.` | | | bootstrap | `dev.caskeleton.bootstrap.autoconfigure.` | `@AutoConfiguration`만(`BOOTSTRAP_AUTOCONFIGURE_STEREOTYPES_ARE_AUTO_CONFIGURATIONS`) | -- ``는 템플릿 플랫폼 패키지(`operation`, `outbox`, `lock`, `cache`, `idempotency`, `security`, - `tenant`, `transaction`…)와 겹치지 않는다. 생성 명령이 막는다. 겹치면 upstream 템플릿을 받을 때 같은 - 패키지 트리에서 병합 충돌이 난다. -- 이름 규칙은 `src/application-core/CLAUDE.md` 「Naming convention」이 정본이다. +- ``는 템플릿 패키지 이름(`operation`, `outbox`, `lock`, `cache`, `secret`, `notification`…)과 + 겹치지 않는다. 겹치면 upstream 템플릿을 받을 때 같은 패키지 트리에서 병합 충돌이 난다. 업무 코드를 + 이름이 맞아 보이는 템플릿 패키지에 넣지도 않는다. +- **어느 패키지가 템플릿 소유인지와 이 규칙의 정본은 `src/application-core/CLAUDE.md` + 「Package ownership」이다.** 매뉴얼은 목록을 다시 적지 않는다. 생성 명령이 이름을 거절하고, 생성 + 뒤에는 ArchUnit(`NamingConventionTest`의 package ownership 규칙 두 개)이 다시 막는다. +- 이름 규칙은 같은 파일 「Naming convention」이 정본이다. ## 저장 adapter는 어디에 diff --git a/docs/manual/09-outbox-events.md b/docs/manual/09-outbox-events.md index 780d20cc..1c6f7999 100644 --- a/docs/manual/09-outbox-events.md +++ b/docs/manual/09-outbox-events.md @@ -53,7 +53,9 @@ DB 저장과 broker 발행을 따로 하면(dual write) 둘 중 하나만 성공 operation) 작업 id에서 파생한다. - correlation: 요청의 correlation id가 문법에 맞으면 그것, 아니면 event id. 문법 밖 헤더가 업무 쓰기를 실패시키면 안 된다. -- aggregate 순서: aggregate에 version 열이 있으면 그것, 없으면 발생 시각(µs). +- aggregate 순서: `OutboxAggregateSequencePort.nextSequence(aggregate)`로 같은 `tx.inWrite` 안에서 + 받는다(V21 카운터, 커밋 순서를 따른다). 이벤트가 하나뿐인 aggregate는 `AggregateOrder.first()`. 발생 + 시각(벽시계)은 쓰지 않는다 — 서버 시계가 어긋나면 순서가 뒤집힌다(리뷰 06-07). - 이 규칙은 아직 기능마다 다시 쓴다(sample `PortfolioEventOutbox`). application-core 헬퍼로 올리는 일은 리뷰 01-09 후속이다. 그 전까지는 위 세 규칙을 지킨다. @@ -66,8 +68,77 @@ DB 저장과 broker 발행을 따로 하면(dual write) 둘 중 하나만 성공 - 발행 응답을 못 받으면 결과 불명(`OutboxPublishAmbiguousException`) — 05장 규칙과 같다. - 운영: `docs/runbooks/outbox-dead-letter.md`, `docs/runbooks/outbox-publish-failed.md`. +## 소비 — 이벤트를 받는 쪽 + +같은 메시지는 두 번 이상 올 수 있다. 소비 쪽은 **inbox 예약과 업무 쓰기를 한 트랜잭션**에 묶어 효과를 +한 번으로 만든다. + +```text +Kafka ─▶ platform consumer ─▶ (INBOX_TRANSACTIONAL이면) InboxMessageHandler + └─ 한 트랜잭션: messaging_inbox 예약 + handler ─▶ use case 쓰기 + 성공 → 커밋 → offset 커밋 + 예외·Retry → 예약과 쓰기가 함께 롤백 → 같은 메시지 재전달 → 다시 처리 + 이미 예약된 메시지 → handler를 부르지 않고 성공으로 넘김 +``` + +### 순서 + +1. 조립에 한 줄 추가: `runtimeOnly project(':adapter:inbound:messaging')`(app-bootstrap). Kafka + capability(`adapter:outbound:messaging-kafka`)와 persistence-jpa가 함께 있어야 한다. 이 leaf가 inbox + 저장소와 트랜잭션 runner를 서비스의 DataSource·트랜잭션 위에 조립한다. +2. inbox 테이블은 따로 만들지 않는다: 1번 줄의 leaf가 기동 중에 platform의 + `db/migration/messaging/V1101__messaging_inbox.sql`을 자기 history 표(`flyway_messaging_inbox_history`)로 + 적용한다. `app.runtime.migration-on-startup=false`로 마이그레이션을 밖에서 돌리는 배포만 이 파일을 직접 + 적용한다. +3. destination을 선언한다: `guarantees.external-side-effect: INBOX_TRANSACTIONAL`, `consumer.group`, + `retry.mode`·`retry.max-attempts`, `dlq.destination`. 예: `src/adapter/inbound/messaging/README.md`. +4. handler(`MessageHandler`)를 `adapter:inbound:messaging`에 둔다. delivery 하나를 use case 호출 + 하나로 바꾸고 업무 규칙은 use case에 둔다. use case는 평소처럼 `tx.inWrite`로 쓴다. 바깥 inbox + 트랜잭션에 합류한다. +5. payload 타입을 정한다. 템플릿 relay가 보낸 메시지의 payload는 canonical envelope JSON 전체다 + (`eventId`, `payload` 등). handler의 record는 그 모양이다. 등록 코드는 쓰지 않는다: handler의 + `destination()`(계약 id, record class)과 `schemaVersions()`(읽는 payloadVersion, 기본 v1)가 decode + 목록이 된다. 발행 쪽이 v2를 보내기 시작하면 handler가 `schemaVersions()`에 v2를 더한다 — 선언하지 않은 + 버전은 `SCHEMA_VERSION_NOT_REGISTERED`로 DLQ에 간다. +6. 테스트 본보기: `InboxRedeliveryIntegrationTest`(lane `messagingInboxRedeliveryIntegrationTest`, 실제 + Kafka + PostgreSQL). offset을 되감아 다시 전달해도, 처리 중 예외 뒤 재전달돼도 효과와 inbox 행이 + 하나인지 본다. + +### 판단 지점 + +#### 멱등 키 + +- **기본값**: inbox가 message id(발행 쪽 event id)와 `consumer.group`으로 거른다. handler가 따로 할 + 일은 없다. +- `consumer.group`은 바꾸지 않는다. 이름이 바뀌면 이미 처리한 메시지도 처음 보는 것으로 본다. +- **예외**: 발행 쪽이 재시도마다 다른 event id를 낸다면 inbox가 못 거른다. 그때는 use case가 업무 + 키(주문 id + 상태 등)로 멱등하게 쓴다. +- 쓰기는 handler를 부른 스레드에서 끝낸다. 다른 스레드로 넘긴 쓰기는 inbox 트랜잭션 밖이다. +- 메일·외부 API 같은 DB 밖 부작용은 롤백되지 않는다. handler 안에서는 DB 쓰기와 outbox append만 하고, + 외부 호출은 그 이벤트를 받는 별도 소비자가 한다. + +#### inbox 보존 기간 + +- inbox 행은 broker가 같은 메시지를 다시 줄 수 있는 기간보다 오래 남아야 한다. 먼저 지우면 늦게 온 + 재전달이 효과를 한 번 더 낸다. +- **기본값**: `InboxRetentionPolicy` — 보존 7일, 재전달 창 1일. topic 보존 기간이나 offset을 되감는 운영 + 범위가 1일보다 길면 이 bean을 덮어쓴다. 너무 짧은 조합은 기동 때 `INBOX_RETENTION_TOO_SHORT`로 거부된다. +- 정리 job(`InboxCleanupJob`)은 bean만 있다. 어느 replica에서 언제 돌릴지는 서비스가 스케줄한다. + +#### 실패 시 재처리 + +- handler가 예외를 던지거나 `Retry`로 답하면 예약과 쓰기가 함께 롤백되고, platform이 같은 메시지를 + 다시 준다. 다시 처리될 때 효과는 한 번이다. +- **기본값**: destination retry는 `NONE`(시도 1회)이라 실패하면 바로 DLQ로 간다. 일시 장애가 있는 + 소비자는 `retry.mode: PAUSE_PARTITION`과 `max-attempts`를 정한다. partition 순서는 유지된다. +- 다시 해도 소용없는 입력(검증 실패)은 예외 대신 `Reject`·`DeadLetter`로 답한다. 예외는 시도를 다 쓴 + 뒤에야 DLQ로 간다. +- DLQ가 없는 destination은 실패한 메시지 뒤에서 partition이 멈춘다. 운영 소비자는 DLQ를 둔다. +- offset을 되감아 다시 읽혀도 보존 기간 안의 메시지는 inbox가 건너뛴다. + ## 지금 이해하면 되는 것 - 저장과 append는 같은 `tx.inWrite` 안. - 계약(id·버전·schema·해시)을 먼저 정하고 계약 bean을 등록한다. -- 전달은 적어도 한 번. 소비자는 event id로 중복을 거른다. +- 전달은 적어도 한 번. 소비자는 inbox(`INBOX_TRANSACTIONAL`)로 예약과 업무 쓰기를 한 트랜잭션에 묶는다. +- 실패한 처리는 예약까지 롤백되어 재전달에서 다시 처리된다. inbox 보존 기간은 재전달 창보다 길게. diff --git a/docs/manual/10-capabilities.md b/docs/manual/10-capabilities.md index 880a5a1e..e5c20061 100644 --- a/docs/manual/10-capabilities.md +++ b/docs/manual/10-capabilities.md @@ -49,7 +49,7 @@ app-bootstrap/build.gradle | 1 | 서비스는 포트만 호출 | `runtimeOnly`로 컴파일되는가 | | 2 | 자기 `AutoConfiguration.imports`, 필요하면 `enabled` 스위치, 순서는 `afterName` | 모듈 자동 설정 테스트 | | 3 | 켜면 완전히 동작. 동작하지 않는 설정 키는 두지 않는다 | 설정 바인딩 테스트 | -| 4 | 설정 prefix 하나(`app.<모듈>`), `StrictSettingsBinder`, 검증은 record compact constructor | | +| 4 | 설정 prefix 하나(`app.<모듈>`), `StrictSettingsBinder`, 검증은 record compact constructor | Redis만 예외(AGENTS.md 기준 4) | | 5 | 포트 계약 테스트를 fake와 실제 adapter가 모두 통과, 실 벤더(Testcontainers) 1개 이상 | strict lane(08장) | | 6 | README: 제공하는 것, 추가할 한 줄, env 키 | | | 7 | 이 모듈을 아는 곳은 모듈 자신뿐. bootstrap scan·스위치 목록에 등록하지 않는다 | 줄을 지우면 기능이 완전히 사라지는가 | diff --git a/docs/manual/11-checklist.md b/docs/manual/11-checklist.md index 53cfc670..70c210d2 100644 --- a/docs/manual/11-checklist.md +++ b/docs/manual/11-checklist.md @@ -5,7 +5,7 @@ ## 배치·이름 - [ ] 배치를 03장 기준표로 정했다(기본: 계층 leaf 안 `` 패키지). -- [ ] 패키지 이름이 템플릿 플랫폼 패키지와 겹치지 않는다. +- [ ] 패키지 이름이 템플릿 패키지(`src/application-core/CLAUDE.md` 「Package ownership」)와 겹치지 않고, 업무 코드를 템플릿 패키지에 넣지 않았다. - [ ] 이름이 `src/application-core/CLAUDE.md` 「Naming convention」을 따른다. ## domain diff --git a/docs/messaging/outbox-inbox.md b/docs/messaging/outbox-inbox.md index 7167b1e6..6ec2d046 100644 --- a/docs/messaging/outbox-inbox.md +++ b/docs/messaging/outbox-inbox.md @@ -4,6 +4,8 @@ > DataSource 위 `JdbcInboxRepository`, `PlatformTransactionManager` 위 `TransactionRunner`)은 > `adapter:inbound:messaging`(`src/adapter/inbound/messaging/README.md`)이 둔다. platform starter는 두 > bean이 있을 때 `IdempotentConsumer`를 만들어 `INBOX_TRANSACTIONAL` destination의 handler를 감싼다. +> 그 leaf는 inbox 마이그레이션(`V1101`)만 자기 history 표로 적용하므로, 아래 "location 추가"는 platform +> outbox를 쓰는 배포의 이야기다. payload decode 목록은 handler bean의 선언으로 만든다. ## 두 패턴이 각각 무엇을 해결하는가 @@ -130,6 +132,9 @@ consume 계약은 `MessageHandler` 하나다. handler를 bean으로 등록하 - `Reject`는 at-most-once destination에서만 버리고, 그 밖에서는 dead letter로 보낸다. 실제 왕복·중복 제거·DLQ는 `MessagingKafkaConsumeQualificationTest`(Kafka + PostgreSQL Testcontainers)가 확인한다. +애플리케이션 경로(앱 outbox relay가 발행 → `adapter:inbound:messaging`이 조립한 inbox와 JPA 트랜잭션 → +handler)의 중복 전달·실패 재처리는 `InboxRedeliveryIntegrationTest`(lane +`messagingInboxRedeliveryIntegrationTest`)가 확인한다. ### 복합 키 diff --git a/docs/notification/api-surface-snapshot.txt b/docs/notification/api-surface-snapshot.txt index 99474fda..691f0444 100644 --- a/docs/notification/api-surface-snapshot.txt +++ b/docs/notification/api-surface-snapshot.txt @@ -2,7 +2,7 @@ # Every top-level public type under the platform packages. Growth is a reviewed change. # Update only after review with: # ./gradlew :adapter:outbound:notification:updateNotificationApiSurface -PapproveNotificationApiSurfaceChange -# types: 362 +# types: 364 dev.caskeleton.adapter.outbound.notification.NotificationConfig dev.caskeleton.adapter.outbound.notification.NotificationRoutesSettings dev.caskeleton.adapter.outbound.notification.core.FailOpenNotificationProvider @@ -24,6 +24,7 @@ dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.ProviderType dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.SmtpProviderRuntimeAssembler dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackLimits dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationResult +dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationUnavailableException dev.caskeleton.adapter.outbound.notification.platform.callback.MapProviderCallbackAdapterRegistry dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapter dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapterRegistry @@ -256,6 +257,7 @@ dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStore dev.caskeleton.application.notification.platform.dispatch.ReconciliationService dev.caskeleton.application.notification.platform.dispatch.ScheduleNotificationApplicationUseCase dev.caskeleton.application.notification.platform.dispatch.SubmitNotificationApplicationUseCase +dev.caskeleton.application.notification.platform.dispatch.SuppressionSideEffect dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint dev.caskeleton.application.notification.platform.dispatch.TenantContextPort dev.caskeleton.application.notification.platform.inbox.CreateInboxItemCommand diff --git a/docs/notification/configuration-reference.md b/docs/notification/configuration-reference.md index 230377c6..f7a6fc7b 100644 --- a/docs/notification/configuration-reference.md +++ b/docs/notification/configuration-reference.md @@ -20,7 +20,7 @@ variable names from Boot's relaxed binding. `NotificationEnvironmentRegistryTest | Property | Environment variable | Default | Meaning | |---|---|---|---| | `enabled` | `APP_NOTIFICATION_PLATFORM_ENABLED` | `true` | On while the module is present. `false` binds nothing at all: no runtime, no schema check, no scheduler thread, no secret required | -| `mode` | `APP_NOTIFICATION_PLATFORM_MODE` | `SERVING` | `SERVING` refuses to start without a working provider; `INGEST_ONLY` stores requests and does not dispatch | +| `mode` | `APP_NOTIFICATION_PLATFORM_MODE` | `SERVING` | `SERVING` refuses to start without a working provider; `INGEST_ONLY` stores requests and does not dispatch: it builds no provider runtime but records each enabled profile's route, so a request accepted now is delivered later on that route by a `SERVING` deployment (handoff) | ## Dispatch @@ -44,18 +44,25 @@ still waiting on gets claimed by a second worker, and the recipient receives the | Property | Environment variable | Default | Bound | |---|---|---|---| | `callbacks.enabled` | `APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED` | `false` | boolean | -| `callbacks.max-body-bytes` | `APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES` | `65508` | 1..65508 | -| `callbacks.replay-skew` | `APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW` | `5m` | positive; SNS messages whose `Timestamp` is further than this from receipt, either way, are rejected | +| `callbacks.max-body-bytes` | `APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES` | `65251` | 1..65251 | +| `callbacks.replay-skew` | `APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW` | `1h` | positive; SNS messages whose `Timestamp` is further than this from receipt, either way, are rejected. The default is SNS's longest HTTP/S retry period (3,600 s), so a bounce or complaint SNS redelivers after an outage is still accepted; a replay inside the window is a duplicate in the provider event ledger, not a second event (review 05-20) | | `callbacks.trusted-proxies` | `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES` | *(empty)* | CSV of peer addresses | +콜백 응답: 기록(중복 포함) `204`, 거절 `400`(서명·topic·시각·형식), 본문 초과 `413`. SNS 서명 인증서를 가져오지 못하면 거절하지 않고 `503`+`Retry-After`로 답한다 — SNS는 4xx를 처리 완료로 보고 재전송을 멈추지만 5xx는 다시 보낸다(review 05-20). + 여러 provider가 요청 URL에 서명하므로, 그 URL을 잘못 재구성하면 정상 webhook이 전부 서명 실패가 된다. `trusted-proxies`가 비어 있으면 forwarded 헤더를 **믿지 않고** 컨테이너가 관측한 값을 쓴다. 무조건 믿으면 아무 호출자나 자기 서명이 검증될 URL을 고를 수 있어 서명 자체가 무의미해진다. 로드밸런서 뒤에 있는 배포는 그 peer를 명시한다. -65508 is not a round number by accident: it is the ciphertext column's 65536 bytes minus the AES-GCM -nonce and tag. A larger configured value would pass every check above the database and fail the -`CHECK` constraint after the callback had already been acknowledged to the provider. +65251 is not a round number by accident: it is the ciphertext column's 65536 bytes minus the largest +envelope the protector writes — a version byte, a key-id length byte, a key id of up to 255 bytes, the +AES-GCM nonce and tag. A larger configured value is refused when the settings bind, so the capability +does not start; before that check existed it passed every layer above the database and failed the +`CHECK` constraint after the callback had already been acknowledged to the provider. The shipped +default was 65508 (nonce and tag only) for a while after the envelope gained its key id, and every +deployment that turned the platform on failed to start until it was corrected (review 2026-11-01 +r3-i, found by booting the compose lanes). ## Provider profiles diff --git a/docs/notification/evidence-manifest.json b/docs/notification/evidence-manifest.json index 3fe4076c..752a4402 100644 --- a/docs/notification/evidence-manifest.json +++ b/docs/notification/evidence-manifest.json @@ -7,7 +7,11 @@ "continue-on-error. So the strongest claim in the document rested on the weakest evidence in", "the pipeline, and nothing connected the two.", "NotificationEvidenceVerifierTest reads this file, checks that every claim marked satisfied names", - "test classes that exist, and refuses a grade whose claims are not all satisfied." + "test classes that exist, and refuses a grade whose claims are not all satisfied.", + "A PostgreSql*ContractTest runs a shared port contract (application-notification testFixtures)", + "against the JPA store; its cases are the contract's, and the verifier follows the superclass to", + "find them. Those contracts replaced RecipientClaimContractTest, ProjectionFactDurabilityContractTest", + "and LateEventBindingContractTest, which ran the adapter's SQL over a bare connection (r3-J)." ], "claims": { "durable": { @@ -15,8 +19,9 @@ "status": "satisfied", "lane": ":adapter:outbound:persistence-jpa:jpaPlatformContractTest", "evidence": [ - "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/RecipientClaimContractTest.java", - "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ProjectionFactDurabilityContractTest.java", + "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientDeliveryStoreContractTest.java", + "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientLeaseStoreContractTest.java", + "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryProjectionStoreContractTest.java", "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ServingStateContractTest.java" ] }, @@ -25,7 +30,8 @@ "status": "satisfied", "lane": ":adapter:outbound:persistence-jpa:jpaPlatformContractTest", "evidence": [ - "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/RecipientClaimContractTest.java", + "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientLeaseStoreContractTest.java", + "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientDeliveryStoreContractTest.java", "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecipientLeaseFencingIntegrationTest.java" ] }, @@ -34,11 +40,13 @@ "status": "satisfied", "lanes": [ ":adapter:outbound:persistence-jpa:jpaPlatformContractTest", - ":application-notification:test" + ":application-notification:test", + ":adapter:outbound:notification:test" ], "evidence": [ - "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/LateEventBindingContractTest.java", - "application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/CallbackIngestionAtomicityTest.java" + "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlProviderEventLedgerContractTest.java", + "application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/CallbackIngestionAtomicityTest.java", + "adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackContractTest.java" ] }, "recoverable": { diff --git a/docs/notification/module-mapping.md b/docs/notification/module-mapping.md index b6276e46..ba7edb5e 100644 --- a/docs/notification/module-mapping.md +++ b/docs/notification/module-mapping.md @@ -42,8 +42,8 @@ that owns its responsibility. No public contract, evidence rule, or reliability | `notification-observability` (Micrometer impl) | `adapter:outbound:notification` | `…platform.observation` | | `notification-admin-runtime` | `adapter:outbound:notification` | `…platform.admin` | | `notification-spring-boot-starter` | `adapter:outbound:notification` | `…platform.autoconfigure` | -| `notification-persistence-jpa` | `adapter:outbound:persistence-notification` | `dev.caskeleton.adapter.outbound.persistence.notification.platform` | -| `notification-inbox-jpa` | `adapter:outbound:persistence-notification` | `…persistence.notification.platform.inbox` | +| `notification-persistence-jpa` | `adapter:outbound:persistence-notification` | `dev.caskeleton.adapter.outbound.persistence.notification.platform` (store adapters), `….platform.entity` (JPA rows), `….platform.repository` (Spring Data interfaces and SQL text) | +| `notification-inbox-jpa` | `adapter:outbound:persistence-notification` | `…persistence.notification.platform` (`JpaNotificationInbox`, `InboxCommitEventPublisher`, `InboxOutboxRecordFactory`); row and repository in `….platform.entity` / `….platform.repository` | | `notification-callback-mvc` | `adapter:inbound:web-notification` | `dev.caskeleton.adapter.inbound.web.notification.platform.callback` | | `notification-submission-mvc` | `adapter:inbound:web-notification` | `dev.caskeleton.adapter.inbound.web.notification.platform.submission` | | application composition (use cases, callback bridge, `config/module-defaults/notification.yml`) | `composition:notification-platform` | `dev.caskeleton.composition.notification` | diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 8f06cee0..c59640f4 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -380,8 +380,9 @@ env_keys: - name: APP_FLYWAY_ENABLED # source: local PostgreSQL parity / explicit H2 developer lane. - # Local PostgreSQL runs migrations by default; bootRunH2 disables them because the migration - # tree is PostgreSQL-specific. + # Every profile runs migrations by default — the persistence-jpa module default reads this key + # (07-08; dev/prod no longer pin a literal over it); bootRunH2 disables them because the + # migration tree is PostgreSQL-specific. property: spring.flyway.enabled type: boolean default: true @@ -1995,6 +1996,11 @@ env_keys: # APP_REDIS_ENABLED is true, and deliberately absent from application.yml and .env. - name: APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE + # Pointer to the account registered scripts run as, in the same + # secret://@/ form as the application reference. Unset, scripts run + # as the application account and startup logs a warning saying so. The Compose Redis lanes use + # secret://ca-skeleton-application-advanced@environment/REDIS_LANE_ADVANCED_PASSWORD, a fixture + # account of infra/redis-sdk/acl/all-accounts.acl. property: app.redis.authentication.advanced-credential-reference owner_module: adapter-outbound-cache-redis type: string @@ -2017,6 +2023,8 @@ env_keys: # cannot run a single command on any deployment which disabled the `default` ACL user — the # failure moves from startup to the first request, where it reads as an outage rather than a # missing setting. Setting this to true keeps the deployment running and logs the trade. + # No Compose lane sets it: the Redis lanes authenticate with the fixture accounts instead, because + # the warning this logs is the one their "startup is silent" check exists to catch. type: boolean default: false allowed_values: [true, false] @@ -2031,6 +2039,11 @@ env_keys: - name: APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE # Pointer to the application ACL account credential. The value lives in the secret manager. + # Form: secret://@/; the environment source reads the variable + # . Without the account part the client authenticates as `default`, which a hardened + # Redis turns off. The Compose Redis lanes use + # secret://ca-skeleton-application@environment/REDIS_LANE_APPLICATION_PASSWORD, a fixture + # account of infra/redis-sdk/acl/all-accounts.acl. property: app.redis.authentication.credential-reference owner_module: adapter-outbound-cache-redis type: string @@ -2995,6 +3008,20 @@ env_keys: compatibility_impact: additive required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip + - name: APP_FILESERVER_PLATFORM_TARGET_NAMESPACES + # Namespaces copy and move may write into besides the default namespace, which is always + # allowed. Empty means the default namespace only; any other target is ACCESS_DENIED. + type: csv_list + default: null + allowed_values: null + classification: public-config + required: false + reload_policy: restart-only + owner_branch: fileserver-http-platform-activation-boundary + validation: storage_namespace_list + compatibility_impact: additive + required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip + - name: APP_FILESERVER_PLATFORM_STORAGE_ROOT # Absolute path on its own volume. A relative root resolves against the process working # directory, which differs between a container and a test, so it is refused. @@ -3445,6 +3472,20 @@ env_keys: compatibility_impact: additive required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip + - name: APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT + # Most bytes one namespace may hold, live reservations plus committed usage. Empty means + # unlimited; a reservation past a set limit is refused with QUOTA_EXCEEDED (413). + type: data_size + default: null + allowed_values: null + classification: public-config + required: false + reload_policy: restart-only + owner_branch: fileserver-http-platform-activation-boundary + validation: positive_data_size_when_set + compatibility_impact: additive + required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip + - name: APP_FILESERVER_PLATFORM_ADMIN_ENABLED # Management plane, a separate decision from the data plane. Requires APP_FILESERVER_PLATFORM_ENABLED too: # enabling it alone now does nothing instead of half-building a bean graph. @@ -3474,9 +3515,11 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_CLEANUP_ENABLED - # Background reclamation. Off by default because the worker deletes physical objects. + # Background reclamation. On by default: without it cancelled/expired staging and rejected or + # deleted content stay on the volume until the hard high-water mark stops uploads. Turning it + # off logs a startup warning (another node or the admin plane must reclaim instead). type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -5177,22 +5220,23 @@ env_keys: required_test: adapter-contract:notification-callback-ingestion - name: APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES - # source: NTF-025 — ceiling is 65508 = ciphertext column minus AES-GCM nonce and tag; larger is refused at binding + # source: NTF-025 — ceiling is 65251 = ciphertext column minus the largest envelope (version, key-id length, 255-byte key id, AES-GCM nonce and tag); larger is refused at binding type: integer - default: 65508 + default: 65251 allowed_values: null classification: public-config required: false reload_policy: restart-only owner_branch: worktree-notification-platform - validation: integer_1_to_65508 + validation: integer_1_to_65251 compatibility_impact: behavior-change required_test: adapter-contract:notification-callback-body-bound - 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 + # review 05-20 — 1h covers SNS's whole HTTP/S retry period (capped at 3,600 s); a replay inside it is a ledger duplicate type: duration - default: 5m + default: 1h allowed_values: null classification: security-relevant required: false diff --git a/docs/reviews/2026-11-01-maturity-review/README.md b/docs/reviews/2026-11-01-maturity-review/README.md index 72b44439..a35d064a 100644 --- a/docs/reviews/2026-11-01-maturity-review/README.md +++ b/docs/reviews/2026-11-01-maturity-review/README.md @@ -464,3 +464,145 @@ r2-05a를 뺀 10개 묶음을 합친 메인 작업 트리에서 오케스트레 **검증하지 않은 것** — 2라운드 뒤 `releaseCheck`·`performanceCheck`, GitHub Actions 실제 실행. **커밋** — 하지 않았다(`human-only`). 1·2라운드 변경이 main 작업 트리에 미커밋으로 있다. + +## 15. 결정 기록 (2026-11-03) + +사용자가 "결정이 필요한 부분은 지금 바로 결정하고 남은 부분 전부 진행"을 지시했다. 13.2·14절·14.3의 결정 칸을 아래처럼 정했다. "유지"는 묶음이 고른 기본값을 그대로 확정한다는 뜻이다. "추가 작업"은 3라운드에서 코드로 반영한다. + +| 항목 | 결정 | 이유 | +|---|---|---| +| JWT audience 필수, 자기 client role만 (02-03) | 유지 | 기본값이 닫힌 쪽이어야 한다. 기존 배포는 env 하나를 채우면 된다. 실패 메시지가 키 이름을 알려 준다 | +| 처리 중 409 `retryable=true`+`Retry-After: 2`, Envelope null 생략 (02-01·02-02) | 유지 | 소유자 결정(11-01). 짝 프론트 변경은 프론트 세션에 넘긴다(아래) | +| JSON 아닌 본문 상한 (02-09) | 유지 — 엔드포인트가 직접 둔다 | raw 업로드 경로가 모든 content type을 받아 전역 제외 목록은 경로 단위가 되고, 하나 빠지면 업로드가 깨진다. 문서와 필터 Javadoc에 이미 적었다 | +| 새 오류 코드(`REQUEST_TIMEOUT`, `IDEMPOTENCY_KEY_INVALID`, web-advanced 10종)를 leaf enum으로 (02) | 유지 | 코드를 쓰는 leaf가 소유한다. 계약은 `docs/web/http-contract.md` §4 | +| correlation ID 규칙 밖이면 서버가 새 값으로 교체 (02-11) | 유지 | 요청 ID와 같은 규칙이 로그 주입을 막는다 | +| GraphQL 크기 미선언 list = 20, `first`·`last` 둘 다면 큰 쪽 (03-01), per-parent 경고 임계 10 (03-03) | 유지 | 기본 페이지 크기와 같다. 깊은 쿼리가 거부되면 필드에 `estimatedListSize`를 선언한다 | +| gRPC 서버 기본값(스레드 32·큐 256·동시 100·deadline 10s·drain 2s), `ServerCallExecutorSupplier`(ExperimentalApi) 사용 (03-09) | 유지 | 플랫폼 값과 같다. 실험 API는 넘친 호출을 즉시 닫는 유일한 경로다. grpc 버전 올릴 때 확인 대상으로 README에 적혀 있다 | +| ledger `claimTtl` 5m·보존 24h·purge 스케줄은 서비스 몫 (03-10·03-11) | 유지 | starter는 어느 replica가 돌릴지 모른다 | +| WebSocket `max-connections` 1000, 초과 시 연결 후 1013 (03-06) | 유지 | handshake에서 세면 자리를 돌려줄 곳이 없다 | +| 트랜잭션 제한 30초, JDBC batch 50 기본, H2 운영 jar 제거, 격리 수준 Hikari 고정, upsert `DO NOTHING` 후 갱신 (04) | 유지 | 30초는 Hikari 누수 경고·`inNew`와 맞췄다. batch는 샘플에서 왕복 400→8을 확인했다 | +| 포트 시그니처 변경(04-02 `claimDue` lease·`claimFence`, fileserver `claimDue`·`markAbandoned`·`claimToken`) | 유지 | 소유권을 DB lease로 옮기는 데 필요하다 | +| 마이그레이션 번호: postgresql V20·V21, notification V11·V12, sample V8_1, grpc-ledger V002. r2-05a의 notification V12는 **V13**으로 | 유지/변경 | 스트림별 순번. 샘플은 운영 스트림과 합쳐 도는 테스트가 있어 V8_1 | +| V21 유일 인덱스는 기존 중복이 있으면 마이그레이션 실패 | 유지 | 중복은 순서 보장 위반이라 조용히 넘기면 안 된다. runbook에 확인 쿼리를 둔다(추가 작업) | +| relay: 재시도 가능 거부는 무한 재시도(5분 간격), 예산 설정 키 없음 (06-01·06-03) | 유지 | 일시 실패가 예산을 쓰지 않는다. 진짜 인증 오류는 경보로 잡는다(runbook) | +| 새 leaf `composition:durable-operation`, `adapter:inbound:messaging` 등록 | 승인 | 조립 책임을 bootstrap에서 떼는 기존 방향(capability 기준 7)과 같다 | +| logback이 `app.logging.*`을 읽음, `APP_CACHE_REDIS_TTL_JITTER` deprecated (07) | 유지 | 로그 설정을 한 곳에서 읽는다 | +| sample 이벤트 tenant 범위 `global`, `WORKLOG_INVALID`·`OPERATION_NOT_FOUND` (01) | 유지 | 샘플은 tenant 개념이 없다 | +| notification `TenantId` 통합 시점 (01-03) | 통합하지 않음 — 닫음 | 저장된 행을 읽으려고 느슨하게 둔 P19-new-1 결정이 유효하다. 차이와 이유는 그 타입 Javadoc에 있다 | +| registry edge가 없어 복사본이 남은 leaf 4개 (01-11) | 템플릿 leaf는 `shared-contract` edge 추가 후 정본 사용, vendored(`messaging:*`·`grpc:*`)는 복사본 유지 + leaf CLAUDE.md에 이유 | vendored는 다른 제품이라 의존하면 안 된다(messaging 리뷰 MSG-023) — 추가 작업 | +| 샘플 데모 계정(비밀번호=계정 이름, README 공개), 익명 쓰기 401 (07-03) | 유지 + **prod 프로필에서는 기동 거부** | 샘플을 복제해 운영에 올리는 위험을 코드로 막는다 — 추가 작업 | +| 관리자도 남의 work log 수정 불가, `batchCreate` 상한 1000·한 트랜잭션 (09) | 유지 | 왕복이 8로 줄어 상한을 낮출 이유가 없어졌다 | +| 생성 명령은 JPA adapter를 만들지 않음, 생성된 쓰기 API는 역할 매핑 전 403 (r2-10) | 유지 | 서비스 전용 persistence leaf가 기본이다. 닫힌 쪽이 안전하다 | +| Redis 설정 prefix 예외 (05-18) | AGENTS.md capability 기준 4에 예외 한 줄 | 키를 바꾸면 운영 env가 깨진다 — 추가 작업 | +| objectstorage provider type 하나 추가 (05-16) | 유지 | | +| 파일 서버 쿼터: 상한 미설정=무제한, 동시 예약은 상한을 넘을 수 있음, 정리 worker 기본 켜짐 (r2-05a) | 유지 | 넘는 폭은 동시 업로드 수로 제한된다. 엄격 상한이 필요하면 DB 원자 갱신으로 바꾼다(문서화) | +| MinIO 대체 이미지 `pgsty/minio` digest (05-09) | 유지 | 두 후보 실측 결과가 같았고 Chainguard는 태그·사용자·mc 문제 | +| Jackson 2가 기본 jar에 남음 (09-11) | 유지 — 닫음 | logstash encoder와 springdoc이 요구한다 | +| SpotBugs 신뢰도 (08-07) | **MEDIUM으로 내린다** | 298건을 분류해 진짜 결함은 고치고, 패턴 단위 제외는 이유를 단다 — 추가 작업 | +| `@DisplayName` 언어 | 한국어(소유자 결정 5, AGENTS.md 반영됨) | | +| 커밋 | 하지 않음 | 저장소 정책 `human-only`. 커밋 단위 계획만 만든다 | +| 짝 프론트 계약 반영 | 프론트 세션에 넘긴다 | 다른 repo이고 그 세션이 작업 중이다 | + +| 메시지 소비자의 decode 타입 등록 경로 (06-08 후속) | 핸들러 bean이 선언한 타입으로 decode 목록을 만든다. 서비스가 별도 등록 코드를 쓰지 않는다 | 등록을 빠뜨리면 메시지가 조용히 버려진다 — 위험을 코드로 막는다 | +| `APP_FLYWAY_ENABLED`가 dev·prod에도 적용 (r3-F) | 유지 | profile 파일이 env 값을 덮어쓰던 것이 결함이었다 | + +| notification INGEST_ONLY와 handoff (r3-I 발견) | INGEST_ONLY도 runtime 없이 route 이름을 accept 때 기록한다 | handoff는 accept 때 고정한 route로 나중에 배달된다는 계약이다. 지금은 둘이 모순이라 handoff lane이 기동하지 못한다 | +| 선택 숫자 설정의 빈 env 값 (r3-I 발견) | 빈 값은 "미설정". 오타·모르는 키 거부는 그대로 | `.env.example`이 빈 값을 싣고 있어 그대로 쓰면 기동이 실패한다 | +| notification `ConsentStorePort`·`NotificationInbox` 계약 (04-14) | 보류 — 닫음 | 이 fake를 쓰는 유스케이스 테스트가 없다. 소비자 없는 fake는 두 번째 복사본이 된다. inbox `@Version`은 실 PG 테스트가 본다 | + +| compose `all-adapters`·`local-redis` lane의 Redis 익명 접근 경고 (r3-J 발견) | lane Redis에 ACL 계정을 주고 앱이 그 계정으로 붙는다(`infra/redis-sdk/acl` 재사용). "기동 WARN 없음" 검사는 그대로 둔다 | 경고 로그 수준을 낮추면 운영에서도 같은 위험이 가려진다. 개발 lane이 운영과 같은 인증 모양이어야 한다 | + +### 15.1 3라운드 범위 + +| 묶음 | 내용 | +|---|---| +| r3-A 알림·파일 서버 | r2-05a 패치를 최신 main 위로 다시 올림(V13), 05-11 GREEN, 05-19, 05-20, 05-16 notification, 04-14 notification 포트 계약 10개, 04-16 notification 패키지 분할, 04-04 후반 persistence-fileserver 테스트 | +| r3-B core 계약 | 01-05 트랜잭션·멱등성 포트 계약 키트(PG·Redis store 상속), 01-11 결정 반영, TEST-F-1 application-core 포트 공유 계약 | +| r3-C outbound | 05-15 support binder 2단계 키, 05-16 Redis·HTTP 계약 상속(Testcontainers Redis lane), objectstorage 계약 testFixtures 이동 | +| r3-D messaging | 06-08 실 Kafka+PG 중복 전달 lane, V21 중복 확인 쿼리 runbook | +| r3-E build | 08-07 SpotBugs MEDIUM, AGENTS.md 기준 4 Redis 예외 | +| r3-F bootstrap·sample | 07-08 fileserver 볼륨, 데모 계정 prod 기동 거부, 04-03 sample DisplayName | +| r3-H 정리 | 3라운드에서 새로 나온 후속: 소비자 decode 타입 등록, inbox 마이그레이션 스트림 연결, inbox lane 변이 확인, web `SecuritySettings` strict 바인딩, `local-fileserver` compose lane DB, `ObjectStorageProviderContract` given/when/then | +| r3-J 마지막 정리 | notification 포트 계약 나머지(lease·delivery·attempt·resolver 묶음·contact point), INGEST_ONLY route 기록, 빈 env 값, compose 4 lane 기동 | +| r3-G (마지막, 단독) | 01-10 application-core 패키지 정리 — 전 leaf import를 바꾸므로 나머지를 합친 뒤 | +| 마무리 | 전체 게이트(ci·mainCheck·integrationCheck·optional·performanceCheck·releaseCheck), 커밋 단위 계획, 프론트 인계 | + +## 16. 3라운드 조치 현황 (2026-11-03) + +15절 결정에 따라 남은 항목을 끝냈다. 묶음마다 그 시점의 메인 작업 트리를 담은 임시 클론(baseline3~7)에서 RED→GREEN으로 고치고 오케스트레이터가 합쳤다. 하위 에이전트는 쓰지 않았다(지난 라운드 사용량 한도). 커밋 없음. + +| 묶음 | 상태 | 검증 (에이전트 클론) | 처리 내용 | 결정·합칠 때 조치·남은 것 | +|---|---|---|---|---| +| r3-c | 완료 | support·httpclient·cache-redis·objectstorage check, binder 사용 14 leaf test, 실 Redis lane 38, MinIO 14+1, Toxiproxy 4, architectureCheck, verifyDependencyLocks, verifyEnvKeys, verifyStrictLaneStages | 05-15 StrictSettingsBinder list 원소 하위 키 검사(httpclient 전용 guard 삭제), 05-16 Redis Testcontainers lane redisContainerContractTest, 05-16 HTTP BlockingTransportProviderContract(가짜·실엔진 상속), ObjectStorageProviderContract testFixtures 이동 | 남음: 옮긴 계약 클래스 given/when/then 미적용 | +| r3-e | 완료 | qualityCheck(MEDIUM)·architectureCheck·고친 leaf 16 check 통과(sample spotless 1건 — 오케스트레이터가 1라운드 이후 직접 고친 WorkLogStatementCostSystemTest 형식, spotlessApply로 해결) | 08-07: 307건 중 46건 코드 수정(방어 복사 4곳 RED 5, final 21개, nullable getter 등), 261건 위치·패턴별 이유 단 제외. 05-18 AGENTS.md 기준 4 Redis 예외 | 결정: EI 제외는 필드 타입 기준(컬렉션·배열 등은 계속 검사), DTO는 복사 안 함 | +| r3-f | 완료(AuthenticationModeSettings strict 못함) | sample test 324·systemTest 14·webSystemTest 5, app-bootstrap test 217·repositoryContract 68·documentContract 60·systemTest 11·architectureTest 185, persistence-jpa 558, verifyEnvKeys, architectureCheck, verifyDependencyLocks, compose 18 lane 일치, 실제 docker build·compose healthy·볼륨 소유권 확인 | 07-08 fileserver 볼륨 overlay 분리(one-shot chown), 데모 계정 prod 기동 거부(StartupRule), sample DisplayName, dev/prod JPA 키 정리(APP_FLYWAY_ENABLED가 dev·prod에도 적용 — 동작 변경), smoke 래퍼의 낡은 gRPC 끄기 키 수정 | 못 함: AuthenticationModeSettings strict(web SecuritySettings 쪽에서 해야), 발견: local-fileserver lane이 DB 없이 기동 실패(이전부터 있던 결함) | +| r3-d | 완료(결정·후속 2건) | inbound messaging·messaging-kafka·persistence-jpa 558 check, 새 inbox 재전달 lane 2, Kafka relay 2, aggregate-sequence PG 4, runbook PG 5, architectureCheck, verifyDependencyLocks, documentContractTest, verifyStrictLaneStages | 06-08 실 Kafka+PG 중복 전달 lane(재전달 1회 처리, 실패 후 재처리) — 발견·수정: inbound/outbound messaging leaf가 같은 Gradle 좌표라 bridge가 빠지던 결함. V21 중복 확인 runbook + 쿼리를 runbook에서 읽어 실행하는 PG lane. 매뉴얼 소비자 절 | 후속: handler decode 타입 등록 경로 없음(결정 필요), inbox 마이그레이션 V1101이 서비스 스트림에 미연결, 변이 확인 미실행 | +| r3-b | 완료(TEST-F-1 포트 2개 남음) | leaf check 9, architectureCheck, verifyDependencyLocks, verifyStrictLaneStages, 실 PG jpaPlatformContractTest 277·멱등성·outbox·트랜잭션 lane, 실 Redis standalone·cluster, fake 변이 6개 모두 계약이 잡음 | 01-05 트랜잭션 계약 13건(fake RED 6), 멱등성 계약에 renew 시간 케이스(PG RED 3), PG·Redis 상속. TEST-F-1 계약 5개 추가, 전수 표 docs/testing/TESTING_STRATEGY.md 9절. 발견·수정: JpaOutboxStore.append가 읽기 전용 트랜잭션에서 이벤트를 조용히 잃음. 01-11 템플릿 leaf 4개 shared-contract edge + 정본 헬퍼(출력 동일 고정), vendored 이유 family CLAUDE.md | 결정: PG 멱등성 이전 revision 응답 NOT_OWNER로 통일, CLAIMED 상태 renew 거부. 남음: OutboxMessagePublishPort·IntegrationEventPublishPort 계약(messaging), notification·fileserver 테스트 TransactionPort 구현 6개(r3-A 영역). 합칠 때 cache-redis build.gradle 주석 1곳 충돌(r3-C) 수동 반영 | +| r3-h | 완료(후속 2건) | 건드린 10 leaf check, inbox lane 3, Kafka relay 2, MinIO 19, starter Kafka 6, app-bootstrap architecture·repositoryContract·documentContract·systemTest, sample test 325, architectureCheck, verifyEnvKeys 352, verifyDependencyLocks, verifyStrictLaneStages, compose 정적 18 lane·local-fileserver 실제 기동 healthy | 1 decode 목록을 handler 선언에서(RED: handler 0회), 2 inbox 마이그레이션 스트림(MessagingInboxSchemaStream), 3 변이 확인(중복 검사 제거 시 실패), 4 web SecuritySettings strict(AuthenticationModeSettings 삭제), 5 local-fileserver lane DB, 6 ObjectStorageProviderContract GWT, 7 발행 포트 2개 공유 계약 | 결정: web→support edge(ArchUnit 예외 StrictSettingsBinder 1개), decode·발행 codec 공유, messaging 마이그레이션 트리 전체 고정 목록. 남음: notification compose lane·all-adapters 실제 기동 미실행, relay 테스트의 직접 만든 publish fake 미교체. 합칠 때 TESTING_STRATEGY 9절 표를 오케스트레이터가 갱신 | +| r3-a | 부분(04-14·04-16·04-04 후반 미착수) | notification·fileserver 10 leaf check, architectureCheck, verifyEnvKeys 354, verifyDependencyLocks, verifyStrictLaneStages, 실 PG jpaPlatformContract 245·Migration 45·fileserver 6/21/21·notification schema 8 | r2-05a 이식(V12→V13, 중복 fake 제거, angus-mail lock·스트림 버전 목록 결함 수정), 05-11 SMTP 분류(RED 5/6→GREEN), 05-19 모듈 기본값 고정 테스트, 05-20 SES replay 창 1h·인증서 실패 503+Retry-After(RED 4), 05-16 notification 계약 testFixtures 이동(콜백 계약은 이제 SES가 실행), TransactionPort 손구현 → DirectTransactionPort | 결정: replay 창 1h(SNS 재시도 상한 3600s), Retry-After 30, 인증서 실패는 로그만. 못 함: 04-14·04-16·04-04 후반(시간) | +| r3-g | 완료 | ci(spotbugs 1건 제외 통과 — 원래 있던 결함), sample check, verifyFeatureScaffold(거절 3·생성 2), documentContractTest 60, API surface 5, verifyDependencyLocks | 01-10: SecretSourcePort·SecretReference → application.secret, CallBudget → application-objectstorage objectstorage.content, outbound 패키지 삭제. application-core/CLAUDE.md Package ownership 절(정본) + ArchUnit 2개(템플릿 이름 재사용 금지, 템플릿→기능 import 금지). new-feature.sh가 이미 있는 패키지 이름 거절 | 합친 뒤 오케스트레이터가 고침: JavaMailSenderSmtpDispatch BC_IMPOSSIBLE_INSTANCEOF 2건(r3-A SMTP 수정 + r3-E MEDIUM이 만나 생김 — Angus 예외 3종이 형제 타입이라 부정 조건이 불가능, 동작 같음). 한계: 템플릿 패키지 목록이 CLAUDE.md 표와 TemplatePackageOwnership 두 곳(권위는 클래스로 명시, 일치 검사 없음 — repo가 문서 대조 parser를 없앤 방침) | +| r3-i | 대부분 완료(04-14 부분, compose 2 lane 실패) | leaf check 8, 실 PG jpaPlatformContract 303·fileserver 48·notification schema 8, architectureCheck, verifyEnvKeys, verifyDependencyLocks, verifyStrictLaneStages, 변이 6건 모두 걸림, compose ingest·serving 기동 | 04-14 notification 포트 5개 계약, 04-16 persistence-notification 패키지 분할, 04-04 후반 persistence-fileserver 테스트 3→34, relay 테스트 fake 교체, compose 기동으로 결함 3건 찾아 수정(콜백 본문 상한, SMTP lane timeout env, health가 꺼진 profile 감시) | 남음: 포트 계약 나머지, handoff lane(INGEST_ONLY route 모순), all-adapters lane(빈 namespace-limit) | +| r3-j | 완료(all-adapters lane만 남음) | 건드린 leaf check 8, architectureCheck, verifyEnvKeys, verifyDependencyLocks, verifyStrictLaneStages, jpaPlatformContractTest 333, 변이 13건 모두 걸림, compose ingest·serving·handoff 기동 | 04-14 notification 포트 8개 계약+fake, side effect 규칙을 application으로, INGEST_ONLY route 기록(RED 3), 빈 env 값=미설정(RED 4), 발견·수정: httpclient 기본 난수 생성기가 slim JRE에 없어 기동 실패, 비운영 환경 평문 HTTP 프로필이 기동 검증에 막힘 | 남음: all-adapters lane '기동 WARN 없음' 검사가 Redis 익명 접근 경고 2줄로 실패(local-redis lane도 같은 설정) | +| r3-k | 완료 | compose 정적 검사 18 lane(망가뜨린 6가지 모두 잡음), local-redis·all-adapters 실제 기동(healthy, WARN 0, smoke auth·graphql·notification), ACL 직접 확인, repositoryContractTest 68, documentContractTest 60, verifyEnvKeys | compose redis가 infra/redis-sdk ACL을 마운트해 --aclfile로 기동, healthcheck 인증, 계약 json·검사기 7번 규칙 | 결정: lane namespace prod(fixture 계정이 ~prod:* 만 허용), 비밀번호 env는 REDIS_LANE_*(APP_ 아님 — 코드가 읽지 않는 키) | +| r3-l | 완료 | ci·mainCheck·-p optional-platforms ci 성공(에이전트) | httpclient PREDICTABLE_RANDOM 제외(retry jitter), gRPC USO 6건 진짜 결함 → private lock(RED: 외부 lock으로 tryAdmit 막힘), REDOS 4·CT·COMMAND_INJECTION·UNSAFE_HASH_EQUALS 위치별 제외(근거 실측·상한), notification evidence verifier가 상속 계약 테스트를 근거로 인정하게 수정 + manifest 근거 교체(내린 claim 없음) | | + +### 16.1 합칠 때 오케스트레이터가 직접 고친 것 + +- `JavaMailSenderSmtpDispatch`의 `BC_IMPOSSIBLE_INSTANCEOF` 2건: r3-A(05-11 SMTP 분류)와 r3-E(SpotBugs MEDIUM)가 처음 한 트리에 만나 드러났다. Angus의 SMTP 예외 3종이 형제 타입이라 부정 조건이 항상 참이었다. 지우고 동작은 같다. notification check·spotbugsMain 통과. +- r3-B의 cache-redis `build.gradle` 주석 1곳, r3-F의 `WorkLogStatementCostSystemTest`(같은 Spotless 수정이 이미 있음), r3-H 뒤 `TESTING_STRATEGY.md` 9절 표(발행 포트 2개 이동). +- 그 밖의 패치는 그대로 붙었다. 2라운드(14.1절)보다 충돌이 적었던 것은 묶음마다 직전 메인 상태로 기준 클론을 새로 만들었기 때문이다. + +### 16.2 최종 게이트 + +3라운드 묶음을 모두 합친 메인 작업 트리에서 오케스트레이터가 실행했다(2026-11-03 10:34~10:50, 공유 잠금). + +중간 실행(09:50)에서 실패 3종이 나와 r3-L로 고쳤다: httpclient `PREDICTABLE_RANDOM`(r3-J 코드가 MEDIUM 기준을 만남), optional-platforms gRPC SpotBugs 13건(r3-E가 main 빌드만 판정 — `USO` 6건은 진짜 결함이라 private lock으로 고침), notification evidence manifest가 r3-J가 옮긴 PG 테스트를 가리킴. + +| 게이트 | 결과 | 시간 | 실행 직전 부하 | +|---|---|---|---| +| `ci` | rc=0 | 51초 | load 8.02 | +| `mainCheck` (`verifyFeatureScaffold` 왕복 포함) | rc=0 | 129초 | load 10.26 | +| `:integrationCheck` (컨테이너 lane 전부, MinIO·Kafka inbox·Redis 컨테이너 lane 포함) | rc=0 | 768초 | load 4.18 | +| `-p optional-platforms ci integrationCheck` | rc=0 | 11초(build cache) | load 2.43 | +| `:performanceCheck` | rc=0 | 21초 | load 2.60 | +| `:releaseCheck -PgitRevision=` | rc=0 | 3초 | load 2.35 | +| `scripts/verify-compose-profile-contracts.sh` | rc=0, 18 lane 일치 | — | — | + +compose 실제 기동은 묶음 에이전트가 lane별로 확인했다: local-fileserver(r3-H), notification ingest·serving·handoff(r3-J), local-redis·all-adapters(r3-K, smoke auth·graphql·notification 포함). + +`ci` 시간이 첫 리뷰 때 434초에서 51초로 줄었다. 08-02(strict lane build cache)와 같은 입력의 캐시 재사용 덕이다. 캐시 없이 처음 도는 시간은 재지 않았다. + +### 16.3 남은 것 + +- **결정으로 닫은 것** (15절): notification `TenantId` 통합(01-03), JSON 아닌 본문 전역 상한(02-09), Jackson 2 제거(09-11), notification `ConsentStorePort`·`NotificationInbox` 계약(04-14 일부). +- **검사로 막지 못하는 것**: 템플릿 패키지 목록이 `application-core/CLAUDE.md` 표와 `TemplatePackageOwnership` 두 곳에 있다(정본은 클래스, 일치 검사 없음). 템플릿이 새 패키지를 만들고 목록에 넣는 것을 잊어도 테스트가 잡지 못한다. +- **이 환경에서 확인할 수 없는 것**: 실제 CI runner(원격 `git.learn.hyeonworks.com`)에서의 workflow 실행. +- **커밋**: 하지 않았다(`human-only`). 커밋 단위 계획은 17절. +- **짝 프론트**: 계약 변경 인계 문서를 프론트 세션 scratchpad `backend-contract-handoff.md`에 두었다. + + + +## 17. 커밋 단위 계획 + +저장소 정책이 `human-only`라 커밋하지 않았다. 사람이 그대로 쓸 수 있는 커밋 자료를 +`../clean-architecture-backend-template-commit-kit/`(repo 밖, 같은 상위 폴더)에 두었다. + +### 17.1 고른 단위와 이유 + +세 커밋으로 나눈다. 각 커밋의 트리는 이 리뷰 중에 실제로 존재했고 게이트를 돌린 상태다. + +| 커밋 | 트리 | 그 트리에서 돌린 게이트 | +|---|---|---| +| 1. 리뷰 High·P1 결함 19건 | 1라운드를 합친 상태(13절) | `ci` 통과, `mainCheck`·`integrationCheck`는 MinIO 2 lane만 실패(이미지 소멸 — 2번 커밋에서 해결), optional·`performanceCheck`·`releaseCheck` 통과 | +| 2. 남은 발견, 개발 매뉴얼, 기능 생성 명령 | 2라운드를 합친 상태(14절) | `ci`·`mainCheck`·`integrationCheck`·optional 통과 | +| 3. 마지막 항목과 합친 뒤 드러난 결함 | 지금 상태(15·16절) | 16.2절 전부 통과 | + +- 커밋 규칙(`design-docs/conventions/commit-and-pr.md`)은 "커밋 하나 = 논리적 변경 하나"와 PR 1,000줄 안팎을 권한다. 세 커밋은 각각 수만 줄이라 이 권고와 어긋난다. +- 발견 하나씩 커밋하려면 라운드 사이에 손으로 합친 충돌(14.1·16.1절)을 커밋마다 다시 풀고 중간 트리마다 게이트를 다시 돌려야 한다. 그 중간 트리는 검증된 적이 없다. 검증된 경계에서만 나누는 쪽을 골랐다. +- 리뷰어는 커밋 diff 대신 이 README의 13·14·16절 표(발견별 RED·GREEN·결정)를 따라가며 본다. + +### 17.2 쓰는 법 + +`../clean-architecture-backend-template-commit-kit/README.md`를 본다. 요약: 스크립트가 별도 worktree에 +새 브랜치를 만들고 패치 세 개를 차례로 적용해 커밋한다. 메인 작업 트리는 건드리지 않는다. 마지막에 +브랜치 트리가 메인 작업 트리와 같은지 비교한다. diff --git a/docs/runbooks/migration-failed.md b/docs/runbooks/migration-failed.md index 9eaa81b7..540c6ef2 100644 --- a/docs/runbooks/migration-failed.md +++ b/docs/runbooks/migration-failed.md @@ -42,6 +42,8 @@ status: active 5. Classify the failure: - lock/statement timeout: remove the blocker or reduce rollout concurrency, then rerun; - SQL/data precondition: create a new forward migration that makes the precondition explicit; + a duplicate outbox order key stopping V21 (`ux_outbox_event_aggregate_order`) is the known + case — clean it up with `outbox-dead-letter.md` §8 and rerun, the migration stays as it is; - checksum mismatch: compare the deployed artifact with the already applied script before considering repair; - connection/TLS failure: fix transport or credentials without changing Flyway history. diff --git a/docs/runbooks/outbox-dead-letter.md b/docs/runbooks/outbox-dead-letter.md index 44dbaecd..e926abea 100644 --- a/docs/runbooks/outbox-dead-letter.md +++ b/docs/runbooks/outbox-dead-letter.md @@ -71,6 +71,88 @@ status: stub - 관련 runbook: [[outbox-publish-failed]] - 관련 branch: [[feature-domain-event-outbox-contract]], [[feature-background-job-async-contract]] (max attempts/DLQ vocabulary SSOT) +## 8. 배포 전 확인 — V21 순서 키 중복 + +V21(`V21__outbox_aggregate_sequence.sql`)은 `outbox_event`의 순서 키 +`(tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index)`에 유일 인덱스 +`ux_outbox_event_aggregate_order`를 만든다. 같은 키를 가진 행이 이미 둘 이상 있으면 인덱스 생성이 +실패하고 기동이 멈춘다(`MIGRATION_FAILED`, exit 70). 이 실패는 의도한 동작이다(리뷰 2026-11-01 +README 15절 결정). 같은 키의 행들은 claim gate가 순서를 정하지 못한 행이다. 그냥 넘기면 순서 위반이 +숨는다. V21은 transaction 하나로 적용되므로, 실패하면 V21 전체가 롤백되고 V20 상태로 남는다. + +V20 이하 DB를 V21 이상으로 올리는 배포 전에 아래 순서로 확인한다. + +**Step 1 — 중복 확인 (읽기 전용)** + + +```sql +SELECT tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index, + count(*) AS row_count, + count(*) FILTER (WHERE status <> 'PUBLISHED') AS unpublished_count, + string_agg(event_id || ':' || status, ', ' ORDER BY occurred_at, event_id) AS events +FROM outbox_event +WHERE tenant_scope IS NOT NULL + AND aggregate_type IS NOT NULL + AND aggregate_sequence IS NOT NULL + AND event_index IS NOT NULL +GROUP BY tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index +HAVING count(*) > 1 +ORDER BY tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index; +``` + +- 결과가 0행이면 그대로 배포한다. +- 1행 이상이면 Step 2로 간다. 결과 한 행이 순서 키 하나이고, `events`가 그 키를 쓰는 행들이다. +- `IS NOT NULL` 조건이 있는 이유: 유일 인덱스는 다섯 열 중 하나라도 NULL인 행을 비교하지 않는다 + (PostgreSQL 기본 동작). 순서 열이 비어 있는 옛 행은 V21을 막지 않는다. + +**Step 2 — 미발행 행이 빠질 때까지 기다린다** + +`unpublished_count`가 0이 아닌 키는 아직 지우지 않는다. 같은 키의 행끼리는 서로를 막지 않으므로 +지금 배포된 relay가 계속 발행한다. `DEAD` 행은 §4의 처분(재발행 또는 skip)을 먼저 한다. Step 1을 +다시 돌려 모든 키의 `unpublished_count`가 0이 되면 Step 3으로 간다. + +**Step 3 — 이미 발행된 중복을 정리한다** + +모든 행이 `PUBLISHED`인 키에서 가장 먼저 생긴 행(`occurred_at`, `event_id` 순) 하나만 남기고 나머지를 +지운다. 이 행들은 이미 broker로 나갔고 다시 나가지 않는다. 보존 기간이 지나면 reaper가 어차피 지운다. +지우기 전에 `outbox_event_v21_duplicates` 테이블로 복사해 증거를 남긴다. 미발행 행이 하나라도 있는 +키는 이 SQL이 건드리지 않는다. + + +```sql +BEGIN; +CREATE TABLE outbox_event_v21_duplicates AS +SELECT o.* +FROM outbox_event o +JOIN (SELECT event_id, + row_number() OVER same_key AS copy_no, + bool_and(status = 'PUBLISHED') OVER same_key AS all_published + FROM outbox_event + WHERE tenant_scope IS NOT NULL + AND aggregate_type IS NOT NULL + AND aggregate_sequence IS NOT NULL + AND event_index IS NOT NULL + WINDOW same_key AS ( + PARTITION BY tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index + ORDER BY occurred_at, event_id + ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) d + ON d.event_id = o.event_id +WHERE d.copy_no > 1 + AND d.all_published; +DELETE FROM outbox_event o +USING outbox_event_v21_duplicates d +WHERE o.event_id = d.event_id; +COMMIT; +``` + +Step 1을 다시 돌려 0행이면 배포한다. 정리와 배포 사이에 옛 버전이 새 중복을 만들 수 있다(벽시계로 +순서 번호를 만든 샘플 코드가 그 원인이었다). 그래도 V21은 실패하고 롤백될 뿐이니 Step 1부터 다시 한다. +`outbox_event_v21_duplicates`는 확인이 끝나면 지운다. + +확인 쿼리와 정리 SQL은 이 문서에서 그대로 읽어 실제 PostgreSQL에서 실행하는 테스트가 있다 +(`PostgreSqlOutboxOrderKeyRunbookIntegrationTest`, lane `postgresqlOutboxOrderKeyRunbookIntegrationTest`). +두 SQL 블록을 고치면 그 lane을 다시 돌린다. + --- > **Stub 상태 안내**: 이 runbook은 skeleton 단계의 stub. 실제 broker·DLQ 토픽·승인 체계 확정 시 보강 필요. diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index 50a4f770..09723148 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -177,3 +177,148 @@ scheduled workflow가 실행한다. 문서와 build.gradle의 전체 현재 상태를 다시 파싱해 서로 맞는지 검사하는 별도 verifier는 두지 않는다. 불변조건은 코드와 convention plugin이 강제하고, 이 문서는 분류 기준과 의도를 설명한다. + +## 9. application-core 포트의 공유 계약 현황 (review 2026-11-01 01-05·TEST-F-1) + +규칙(`AGENTS.md` 테스트 규칙): 포트마다 fake 하나를 포트 소유 leaf의 `testFixtures`에 두고, fake와 +모든 adapter가 같은 추상 계약 테스트(`*Contract`)를 상속한다. 실제 adapter의 계약 테스트는 그 +adapter leaf의 실 DB·Redis lane에서 돈다. fake가 실제와 다르게 동작하면 유스케이스 테스트가 거짓 +녹색이 되기 때문이다. + +아래는 application-core가 소유한 `*Port` 전부(2026-11-03 기준, `application-core/src/main`의 +`public interface *Port`)와, `application-notification`이 소유하고 `persistence-notification`이 구현하는 +저장소 포트 전부다(review 04-14, 표에 `(notification)`으로 표시). notification 포트의 계약은 +`application-notification` testFixtures에 있고, 실제 구현 쪽은 persistence-jpa의 `postgresqlIntegrationTest` +source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌린다. fileserver 포트는 +`application-fileserver` testFixtures의 `*PortContract`가 맡고 `persistence-fileserver/CLAUDE.md`에 적혀 있다. + +### 9.1 계약이 있는 포트 + +| 포트 | 계약(`application-core` testFixtures) | fake | 상속하는 실제 구현 테스트 (lane) | +| --- | --- | --- | --- | +| `TransactionPort` | `transaction.testkit.TransactionPortContract` + `TransactionProbe` | `DirectTransactionPort` | `SpringTransactionContractTest` — persistence-jpa, `JpaTransactionManager`, 실 PostgreSQL (`jpaPlatformContractTest`, 태그 `jpa-contract`) | +| `IdempotencyStorePort` | `idempotency.testkit.IdempotencyStoreContract` | `InMemoryIdempotencyStore` | `RedisIdempotencyStoreContractTest`(command fake, `test`) · `LiveRedisIdempotencyStoreContractTest`(실 Redis, `redisTopologyTest` standalone·cluster) · `PostgreSqlIdempotencyStoreContractTest`(실 PostgreSQL, `jpaPlatformContractTest`) | +| `SecretSourcePort` | `secret.testkit.SecretSourceContract` | `InMemorySecretSource` | `EnvironmentSecretSourceContractTest` — support (`test`) | +| `OutboxAppendPort` | `outbox.testkit.OutboxAppendContract` | `InMemoryOutboxStore(DirectTransactionPort)` | `PostgreSqlOutboxAppendTransactionalIntegrationTest` (`postgresqlOutboxAppendTransactionalIntegrationTest`) | +| `LiveEventReplayPort` | `realtime.testkit.LiveEventReplayContract` | `InMemoryLiveEventReplay` | `JpaLiveEventReplayContractTest` (`jpaPlatformContractTest`) | +| `AuthorizationPort` | `security.testkit.AuthorizationContract` | `InMemoryAuthorization` | `AuthorizationAdapterContractTest` — web (`test`) | +| `CorrelationIdPort` | `observability.testkit.CorrelationIdContract` | `FixedCorrelationId` | `MdcCorrelationIdPortAdapterContractTest` — web (`test`) | +| `CacheRegionPort` | `cache.testkit.CacheRegionContract` | `InMemoryCacheRegion` | `RedisCacheRegionContractTest`(`test`) · `LiveRedisCacheRegionContractTest`(`redisTopologyTest`) | +| `DistributedLeasePort` | `lease.testkit.DistributedLeaseContract` | `InMemoryDistributedLease` | `RedisDistributedLeaseContractTest` · `LiveRedisDistributedLeaseContractTest` | +| `DistributedLockPort` | `lock.testkit.DistributedLockContract` | `InMemoryDistributedLock` | `PostgreSqlDistributedLockIntegrationTest` (`postgresqlDistributedLockIntegrationTest`) | +| `DurableOperationStorePort` | `operation.testkit.DurableOperationStoreContract` | `InMemoryDurableOperationStore` | `JpaDurableOperationStoreContractTest` (`jpaPlatformContractTest`) | +| `IntegrationEventEncoderPort` | `messaging.event.testkit.IntegrationEventEncoderContract` | `FakeIntegrationEventEncoder` | `JsonIntegrationEventEncoderContractTest` — support (`test`) | +| `OutboxStorePort` (lease fencing) | `outbox.testkit.OutboxLeaseFencingContract` | `InMemoryOutboxStore` | `PostgreSqlOutboxConcurrentRelayIntegrationTest` | +| `OutboxAggregateSequencePort` | `outbox.testkit.OutboxAggregateSequenceContract` | `InMemoryOutboxAggregateSequences` | `PostgreSqlOutboxAggregateSequenceIntegrationTest` | +| `OutboxMessagePublishPort` | `outbox.testkit.OutboxMessagePublishContract` | `FakeOutboxMessagePublisher` (relay 테스트 4개도 이 fake를 쓴다) | `OutboxMessagePublishAdapterTest` — messaging (`test`) | +| `IntegrationEventPublishPort` | `messaging.event.testkit.IntegrationEventPublishContract` | `FakeIntegrationEventPublisher` | `PlatformIntegrationEventPublishAdapterTest` — messaging (`test`) | +| `PreferenceStorePort` (notification) | `policy.testkit.PreferenceStoreContract` | `InMemoryPreferenceStore` | `PostgreSqlPreferenceStoreContractTest` (`jpaPlatformContractTest`) | +| `SuppressionStorePort` (notification) | `policy.testkit.SuppressionStoreContract` | `InMemorySuppressionStore` | `PostgreSqlSuppressionStoreContractTest` (`jpaPlatformContractTest`) | +| `DeduplicationStorePort` (notification) | `policy.testkit.DeduplicationStoreContract` | `InMemoryDeduplicationStore` | `PostgreSqlDeduplicationStoreContractTest` (`jpaPlatformContractTest`) | +| `NotificationRequestStorePort` (notification) | `dispatch.testkit.NotificationRequestStoreContract` | `InMemoryNotificationRequestStore` | `PostgreSqlNotificationRequestStoreContractTest` (`jpaPlatformContractTest`) | +| `ReconciliationJobStorePort` (notification) | `dispatch.testkit.ReconciliationJobStoreContract` | `InMemoryReconciliationJobStore` | `PostgreSqlReconciliationJobStoreContractTest` (`jpaPlatformContractTest`) | +| `AdminOperationStorePort` (notification) | `admin.testkit.AdminOperationStoreContract` | `InMemoryAdminOperationStore` | `PostgreSqlAdminOperationStoreContractTest` (`jpaPlatformContractTest`) | +| `TemplateRegistry` (notification) | `template.testkit.TemplateRegistryContract` | `InMemoryTemplateRegistry` | `PostgreSqlTemplateRegistryContractTest` (`jpaPlatformContractTest`) | +| `RecipientLeaseStorePort` (notification) | `dispatch.testkit.RecipientLeaseStoreContract` | `InMemoryRecipientQueue` | `PostgreSqlRecipientLeaseStoreContractTest` (`jpaPlatformContractTest`, JPA `@Version` 경우만 PG 전용) | +| `RecipientDeliveryStorePort` (notification) | `dispatch.testkit.RecipientDeliveryStoreContract` | `InMemoryRecipientQueue` (lease 포트와 같은 fake — 같은 행) | `PostgreSqlRecipientDeliveryStoreContractTest` (`jpaPlatformContractTest`) | +| `DeliveryAttemptStorePort` (notification) | `dispatch.testkit.DeliveryAttemptStoreContract` | `InMemoryDeliveryAttemptStore` | `PostgreSqlDeliveryAttemptStoreContractTest` (`jpaPlatformContractTest`) | +| `DeliveryAttemptResolverPort` (notification) | `callback.testkit.DeliveryAttemptResolverContract` | `InMemoryDeliveryAttemptStore` (JPA처럼 attempt store가 구현) | `PostgreSqlDeliveryAttemptResolverContractTest` (`jpaPlatformContractTest`) | +| `DeliveryProjectionStorePort` (notification) | `callback.testkit.DeliveryProjectionStoreContract` | `InMemoryDeliveryAttemptStore` | `PostgreSqlDeliveryProjectionStoreContractTest` (`jpaPlatformContractTest`, `projection_version` 경우만 PG 전용) | +| `ProviderEventLedger` (notification) | `callback.testkit.ProviderEventLedgerContract` | `InMemoryProviderEventLedger` | `PostgreSqlProviderEventLedgerContractTest` (`jpaPlatformContractTest`) | +| `NotificationSideEffectPort` (notification) | `callback.testkit.NotificationSideEffectContract` | 없음 — 구현 `SuppressionSideEffect`가 application 규칙이라 fake 대신 그대로 쓴다 | `SuppressionSideEffectTest`(store fake 위) · `PostgreSqlNotificationSideEffectContractTest`(JPA store 위, `jpaPlatformContractTest`) | +| `ContactPointStorePort` (notification) | `dispatch.testkit.ContactPointStoreContract` | `InMemoryContactPointStore` | `PostgreSqlContactPointStoreContractTest` (`jpaPlatformContractTest`) | + +계약을 실제 구현에 처음 적용할 때 드러난 차이와 처리: + +- `DirectTransactionPort`는 예외가 나도 쓰기를 되돌리지 않았고, 참여한 안쪽 경계가 실패해도 바깥 + 커밋이 성공했고, `inRead` 안의 쓰기를 막지 않았다. 실 PostgreSQL의 `SpringTransaction`은 셋 다 + 반대다. fake가 롤백(`onRollback`), 참여 실패 시 바깥 커밋 실패, 읽기 전용 표시(`readOnly()`)를 + 갖게 고쳤다. `committed()`는 이제 실제로 커밋된 경계만 담는다(바깥이 롤백되면 안쪽도 빠진다). +- PostgreSQL 멱등성 store는 (1) 이전 revision의 핸들을 `OPERATION_CONFLICT`로, Redis·fake는 + `NOT_OWNER`로 답했다. 핸들의 owner 튜플에는 revision이 들어가므로 `NOT_OWNER`로 맞췄다. + `OPERATION_CONFLICT`는 "같은 operation id가 다른 인자로 이미 적용됨" 한 뜻만 남는다. (2) 실행 + 전(CLAIMED) claim의 renew를 받아 줬고 Redis·fake는 거부했다. renew는 실행 중인 작업의 lease만 + 늘리도록 PostgreSQL을 맞췄다(호출자 없음 — 템플릿 안 동작 변화 없음). (3) release 뒤의 다음 + claim을 `TakenOverClaimed`(attempt 2)로, Redis는 `Acquired`로 답한다. executor는 둘을 같게 + 처리하므로 계약은 "다음 claim이 scope를 가진다"만 요구한다. +- `OutboxAppendContract`는 static helper 두 개였고 JPA readiness 테스트만 불렀다. 추상 계약으로 바꿔 + readiness 테스트가 상속한다(같은 두 케이스 + 트랜잭션 밖·읽기 전용·중복 eventId). 실 PostgreSQL에서 + `inRead` 안의 append가 예외 없이 사라지는 것을 찾았다(실측: 예외 없음, 행 없음) — JPA 트랜잭션 + 매니저가 읽기 전용 세션을 flush하지 않아 저장 자체가 일어나지 않는다. `JpaOutboxStore.append`가 읽기·쓰기 트랜잭션을 요구하게 + 고쳤다. in-memory store는 `DirectTransactionPort`를 받으면 같은 규칙(트랜잭션 밖·읽기 전용 거부, + 롤백 시 취소)으로 동작한다. 인자 없이 만들면 지금처럼 바로 쓴다(relay 테스트가 행을 미리 심는 용도). +- `IdempotencyStoreContract`의 시간 케이스(renew가 lease를 실제로 늘린다, review 05-02)는 시계를 + 가진 store(실 Redis, PostgreSQL)에서만 의미가 있다. in-memory fake는 만료가 없어 `elapse`가 + no-op이다. PostgreSQL에서 renew가 lease를 늘리지 않게 바꾼 변이로 이 케이스가 실패함을 확인했다. + +notification 계약 다섯 개(deduplication·request·reconciliation job·admin operation·template, 2026-11-03)는 +PostgreSQL 쪽에만 있던 테스트를 계약으로 옮긴 것이다. `ReconciliationJobClaimContractTest`(8건)와 +`AdminOperationClaimContractTest`(6건)는 지웠고 같은 경우가 포트 단위로 계약에 들어갔다 — 앞의 것은 SQL을 +직접 돌렸고, 계약은 store를 거친다. 스키마 CHECK 제약 하나(`phase`)는 벤더 동작이라 +`PostgreSqlAdminOperationStoreContractTest`에만 남겼다. 처음 적용할 때 fake와 실제가 다르게 답한 경우는 +없었다. 유스케이스 테스트의 대역은 `PlatformFakes.RequestStore`·deduplication 람다· +`AdminOperationExecutorTest.FakeStore`를 이 fake들로 바꿨다. 아직 테스트 안에 남은 대역: admin +`NotificationAdminApplicationServiceTest.RecordingOperations`·`UnusedSuppressionStore`, reconciliation job +`ReconciliationJobWorkerTest`(notification adapter)의 stub — 호출 횟수를 세거나 "부르지 않는다"를 확인하는 +용도라 fake로 바꾸면 단언을 다시 써야 한다. + +notification 계약 여덟 개(recipient lease·recipient delivery·attempt·resolver·projection·ledger·side +effect·contact point, 2026-11-03 r3-J)로 9.2의 "다음 단계"가 끝났다. fake는 JPA 구현의 묶음을 따른다: +`InMemoryRecipientQueue` 하나가 lease·delivery 두 포트를 구현하고 행을 `InMemoryNotificationRequestStore`와 +나눈다(claim이 lease·fence를 쓰고 fenced 쓰기가 그 값을 읽는다). `InMemoryDeliveryAttemptStore` 하나가 attempt· +resolver·projection 세 포트를 구현한다(`JpaDeliveryAttemptStore`와 같다). PG 쪽에서 SQL을 따로 돌리던 +`RecipientClaimContractTest`·`LateEventBindingContractTest`·`ProjectionFactDurabilityContractTest`는 지웠고 +같은 경우가 store를 거치는 계약으로 들어갔다. 벤더 동작 두 개(claim이 JPA `@Version`을 올림, projection +저장이 `projection_version`을 올림)는 PG 하위 클래스에만 남겼다. `EvidenceCertaintyContractTest`의 DB CHECK +경우와 `WorkerCrashRecoveryContractTest`의 여러 store 시나리오는 그대로 둔다. + +처음 적용할 때 새 fake와 JPA store가 다르게 답한 경우는 없었다. 다르게 답한 것은 지운 대역들이었다: +`PlatformFakes.RecipientStore`는 `save`가 lease까지 덮어썼고(JPA는 lease를 쓰지 않는다) "superseded"를 테스트가 +채운 집합으로 정했다. `PlatformFakes.AttemptStore`는 provider 요청 id를 평문으로 돌려줬고 snapshot을 행과 무관한 +map에서 꺼냈다. 연락처 람다는 지문 조회에서 테넌트를 보지 않았다. 원장·resolver·projection stub은 저장한 +이벤트를 하나도 보여 주지 않았다. 이 대역들(`PlatformFakes.RecipientStore`·`AttemptStore`, +`NotificationDispatchServiceTest`·`LeaseRecoveryServiceTest`·`DispatchOutcomeRecorderTest`의 기록용 store, +`ProviderEventLateMatchTest`·`CallbackIngestionAtomicityTest`의 원장 stub, 연락처 대역 4곳, 테스트 조립 도우미의 +no-op 원장·resolver·projection)은 모두 위 fake로 바꿨다. 조립 도우미는 이제 no-op이 아니라서 +`NotificationPlatformNoops`를 `PlatformCollaborators`로 이름을 바꿨다. + +`NotificationSideEffectPort`의 유일한 구현 `JpaNotificationSideEffect`는 표를 하나도 쓰지 않는 규칙(hard +bounce→INVALID, complaint→SUPPRESSED, 사유별 억제)이었다. persistence에 두면 유스케이스 테스트는 no-op이나 규칙의 +두 번째 복사본만 쓸 수 있어서 application의 `dispatch.SuppressionSideEffect`로 옮겼고(`callback`은 `dispatch`에 의존할 수 없어 연락처 포트를 가진 쪽에 둔다) 조립은 +`composition:notification-platform`이 한다. 계약은 같은 클래스를 store fake 위와 JPA store 위에서 돌린다. + +계약이 실제로 결함을 잡는지는 변이로 확인했다. fake마다 결함 하나를 넣으면 해당 계약이 실패한다: +`DirectTransactionPort`가 중첩 `inRootWrite`를 거부하지 않음(3건 실패), `InMemoryAuthorization`이 권한 +없는 호출을 통과시킴(3건), `InMemoryLiveEventReplay`가 만료 이벤트를 걸러내지 않음(1건), +`InMemoryOutboxStore`가 롤백 때 append를 취소하지 않음(1건), `InMemorySecretSource`가 공백 값을 돌려줌 +(1건), PostgreSQL 멱등성 store의 renew가 lease를 늘리지 않음(시간 케이스 1건). notification: +reconciliation job fake가 fence를 보지 않음(2건), admin operation fake가 다른 명령을 충돌로 보지 않음(1건), +deduplication fake가 window를 무시함(1건), request fake가 `findById`에서 테넌트를 보지 않음(1건), +r3-J: queue가 fence를 보지 않음(같은 worker 이름 재claim 1건), queue가 만료된 작업을 claim함(1건), queue의 +`save`가 lease를 덮어씀(2건), attempt store가 완료 attempt의 요청 id를 평문으로 남김(1건), resolver가 profile을 +보지 않음(1건), projection이 나중 저장에서 읽음 사실을 지움(1건), 원장이 이미 묶인 이벤트를 다시 묶음(1건), +원장이 PENDING이 아닌 상태를 다시 바꿈(1건), 연락처 fake가 지문 조회에서 테넌트를 보지 않음(1건), +`SuppressionSideEffect`가 complaint를 INVALID로 기록함(1건). relay +use case가 결과 조회 대신 예외만 보는 `publish`를 부르게 바꾸면 relay 테스트 7건이 실패한다. + +### 9.2 계약이 없는 포트 (의도) + +| 포트 | 실제 구현 | fake | 계약이 없는 이유 | 다음 단계 | +| --- | --- | --- | --- | --- | +| `UserPrincipalPseudonymizerPort` | identifier `HmacUserPrincipalPseudonymizer` | 없음 — 의도 | 결정적 순수 함수라 테스트가 실제 구현을 그대로 쓴다. fake는 두 번째 복사본이 된다. 출력은 `HmacUserPrincipalPseudonymizerVectorTest`가 고정한다 | 해당 없음 | +| `OutboxRelayFailureReportPort` | messaging `Slf4jOutboxRelayFailureReportAdapter` | 테스트마다 기록용 | 진단 출력 포트라 호출자가 기대는 동작이 "던지지 않는다" 하나뿐이다 | 해당 없음 | +| `NotificationServingStatePort` (notification) | `JdbcNotificationServingState` | 없음 — 의도 | 여러 표에 걸친 집계 읽기다. `FILTER`·`EXTRACT(EPOCH …)`·lease 조건이 답이라 fake는 쿼리를 다시 쓰는 복사본이 된다. `ServingStateContractTest`가 실 PostgreSQL에서 고정한다 | 해당 없음 | +| `ConsentStorePort`·`NotificationInbox` (notification) | `JpaPolicyStores.Consents`·`JpaNotificationInbox` | 없음 — 의도 | 이 포트를 fake로 쓰는 유스케이스 테스트가 없다. 소비자 없는 fake는 두 번째 복사본이 된다(결정 2026-11-03, README 15절). inbox의 `@Version` 동작은 `InboxBulkReadVersionContractTest`가 실 PG에서 본다 | 해당 없음 — fake가 필요한 소비자 테스트가 생기면 계약과 함께 만든다 | + +application-core 안에서 `TransactionPort`를 구현하는 것은 이제 `DirectTransactionPort` 하나다(테스트 +전용 구현 5개를 바꿨다). 롤백을 흉내 내던 `SubmitDurableOperationUseCaseTest.RollbackAwareTransactions` +대신 `InMemoryDurableOperationStore`·`InMemoryOutboxStore`가 `DirectTransactionPort`를 받아 롤백 때 자기 +쓰기를 되돌린다. application-notification 테스트도 `DirectTransactionPort`를 쓴다. 아직 따로 있는 것: +application-fileserver testFixtures의 `DirectTransactions`(composition fileserver +`FileserverAssemblyFixture`가 쓴다). + +relay 테스트(`PublishPendingOutboxEventsUseCaseTest`·`OutcomeAwareRelayTest`·`TransientPublishFailureRelayTest`· +`StoppingRelayReleasesItsClaimsTest`)는 각자 만든 publish 대역 대신 `FakeOutboxMessagePublisher`를 쓴다. +fake는 event별 답(`answering(eventId, outcome)`), 예외(`throwing`), 발행 중 일어나는 일(`whenPublishing` — +시계 이동, 정지 요청)을 받는다. `OutboxPublishOutcomeTest`의 람다 하나는 대역이 아니라 포트의 default +메서드 자체가 시험 대상이라 남겼다. diff --git a/infra/fileserver/compose/docker-compose.fileserver.yml b/infra/fileserver/compose/docker-compose.fileserver.yml new file mode 100644 index 00000000..726c3288 --- /dev/null +++ b/infra/fileserver/compose/docker-compose.fileserver.yml @@ -0,0 +1,58 @@ +# ============================================================================= +# Fileserver capability overlay — the storage volume, added only when the capability is selected. +# +# Usage, on top of a stack whose image carries the fileserver module (a service that selected +# `:composition:fileserver-platform`, or COMPOSITION=qualification): +# docker compose -f docker-compose.yml -f docker-compose.local.yml \ +# -f infra/fileserver/compose/docker-compose.fileserver.yml up +# +# Why a file of its own (review 2026-11-01 07-08, capability criterion 7): the default image and +# docker-compose.yml carry no fileserver, so they no longer carry its volume either. Before, every +# container — default composition included — mounted a volume for a module it did not have, and the +# image declared it a VOLUME. It sits with the rest of the capability's infrastructure +# (infra/fileserver), so removing the capability removes it with that directory. +# +# The volume is a named volume, not a tmpfs and not the read-only root: published content must +# outlive the container that wrote it. Back it with real storage in any deployment that keeps files. +# Kubernetes does the same job with a PersistentVolumeClaim and the pod's fsGroup +# (infra/fileserver/kubernetes/pvc-certification-job.yaml). +# +# Ownership. The application runs as the image's non-root `app` account (src/Dockerfile). Docker +# seeds a fresh named volume's owner from the image directory at the mount point, and the image has +# no such directory any more; a reused volume or a host bind mount keeps whatever owner it had. +# Left like that, the volume is root's, every write is refused, and the module's storage probe stops +# startup with "storage root is not writable". fileserver-storage-init fixes the owner each time +# before the application starts: it runs once, as root, in the application's own image, and chowns +# to the `app` account by name, so the owner follows the image rather than a uid written here. +# ============================================================================= + +services: + fileserver-storage-init: + # The image the app service builds and tags. Never pulled: Compose builds it for `app` first, + # and a registry has no image by this local tag. + image: caskeleton:${BUILD_VERSION:-0.0.1_local_0000000}-${COMPOSITION:-default} + pull_policy: never + user: "0:0" + entrypoint: + - "sh" + - "-c" + - "chown app:app /var/lib/backend/files && chmod 0750 /var/lib/backend/files" + read_only: true + network_mode: none + volumes: + - fileserver-data:/var/lib/backend/files + restart: "no" + + app: + depends_on: + fileserver-storage-init: + condition: service_completed_successfully + environment: + # The mount and the root the module writes to must name one path. This is also the module's + # default (config/module-defaults/fileserver.yml), stated so that moving one moves the other. + APP_FILESERVER_PLATFORM_STORAGE_ROOT: "/var/lib/backend/files" + volumes: + - fileserver-data:/var/lib/backend/files + +volumes: + fileserver-data: diff --git a/infra/postgres/apply-capability-streams.sh b/infra/postgres/apply-capability-streams.sh index d8e1fca9..79acdbdc 100755 --- a/infra/postgres/apply-capability-streams.sh +++ b/infra/postgres/apply-capability-streams.sh @@ -25,7 +25,9 @@ # two with even if that were wanted. infra/postgres/promote-capability-streams.sh is the operator # half, and NotificationSchemaActivation refusing startup until it has run is the fail-closed third. # -# CAPABILITY_STREAMS is a space-separated list of directory names under db/migration/jpa. +# CAPABILITY_STREAMS is a space-separated list of stream names (the directory names under +# db/migration/jpa). A stream is read from /flyway/streams/ when its owning leaf's directory is +# mounted there, and from the persistence-jpa tree under /flyway/sql/jpa otherwise (core, idempotency). # ============================================================================= set -eu @@ -35,21 +37,22 @@ set -eu : "${CAPABILITY_STREAMS:=}" MIGRATIONS=/flyway/sql +STREAMS=/flyway/streams JDBC="jdbc:postgresql://${PGHOST}:${PGPORT:-5432}/${PGDATABASE}" run_flyway() { - location="$1" + directory="$1" history="$2" baseline="$3" - [ -d "${MIGRATIONS}/${location}" ] || { - echo "capability-streams: no such stream 'db/migration/${location}'" >&2 + [ -d "${directory}" ] || { + echo "capability-streams: no such stream '${directory}'" >&2 exit 1 } - echo "capability-streams: applying ${location} into ${history}" + echo "capability-streams: applying ${directory} into ${history}" # shellcheck disable=SC2086 flyway \ -url="${JDBC}" -user="${PGUSER}" -password="${PGPASSWORD:-}" \ - -locations="filesystem:${MIGRATIONS}/${location}" \ + -locations="filesystem:${directory}" \ -table="${history}" \ ${baseline} \ migrate @@ -59,11 +62,13 @@ apply_stream() { stream="$1" # Capability streams baseline at 0 because each is installed into a database the core stream has # already put tables in; the application's own stream must not, for the reason above. - run_flyway "jpa/${stream}" "flyway_jpa_$(echo "${stream}" | tr '-' '_')_history" \ + directory="${STREAMS}/${stream}" + [ -d "${directory}" ] || directory="${MIGRATIONS}/jpa/${stream}" + run_flyway "${directory}" "flyway_jpa_$(echo "${stream}" | tr '-' '_')_history" \ "-baselineOnMigrate=true -baselineVersion=0" } -run_flyway postgresql flyway_schema_history "" +run_flyway "${MIGRATIONS}/postgresql" flyway_schema_history "" apply_stream core for stream in ${CAPABILITY_STREAMS}; do apply_stream "${stream}" diff --git a/infra/redis-sdk/acl/README.md b/infra/redis-sdk/acl/README.md index 49452bb2..d561a860 100644 --- a/infra/redis-sdk/acl/README.md +++ b/infra/redis-sdk/acl/README.md @@ -22,3 +22,19 @@ loads, had been fixed; a fork that copied one of them got an open account and a | `raw-gateway.acl` | `RAW_GATEWAY` | exactly the commands the catalog classifies `RAW_ONLY`, and nothing else | | `all-accounts.acl` | – | the four accounts concatenated; Redis takes one `aclfile`, so this is what a deployment loads | | `admin-readonly.acl` | `ADMIN_READONLY` | read-only diagnostics. Every destructive counterpart is denied here and blocked in the command policy catalog — two independent controls for the same rule | + +## Who loads `all-accounts.acl` + +The Redis topology lanes (`../standalone`, `../sentinel`, `../cluster`, `../tls`) and the +application's Compose lanes that switch Redis on (`local-redis`, `all-adapters` in +`src/config/runtime/compose-profile-contracts.json`). Both mount this directory read-only; neither +keeps a copy, because a second copy of these lines is a second place for a password or a key +pattern to drift. + +The Compose lanes connect the application as `ca-skeleton-application` and +`ca-skeleton-application-advanced`, through `secret://@environment/` references +whose variables carry the fixture passwords above. They run with the Redis namespace environment +`prod`, because every account here is fenced to `~prod:*`. `scripts/verify-compose-profile-contracts.sh` +compares each Redis lane's references, passwords and namespace with the account lines in this file, +so changing a password or a key pattern here without the lanes fails that check rather than the +lane's first command. diff --git a/scripts/new-feature.sh b/scripts/new-feature.sh index c5655cff..4be0a6de 100755 --- a/scripts/new-feature.sh +++ b/scripts/new-feature.sh @@ -68,18 +68,39 @@ if ! [[ "$path_segment" =~ ^[a-z][a-zA-Z0-9]*$ ]]; then exit 2 fi -# Java 예약어와 플랫폼 패키지 이름은 패키지로 쓸 수 없거나 템플릿 코드와 섞인다. -reserved=" abstract assert boolean break byte case catch char class const continue default do +# Java 예약어는 패키지 이름으로 쓸 수 없다. +java_keywords=" abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while record sealed permits - var yield - capability command query usecase transaction security tenant operation outbox idempotency lease - lock cache messaging observability outbound realtime identifier stereotype notification - fileserver objectstorage auth authz error envelope mvc " -reserved=" $(printf '%s' "$reserved" | tr -s ' \n' ' ') " -if [[ "$reserved" == *" $package_name "* ]]; then - echo "'$package_name'는 Java 예약어이거나 템플릿 플랫폼 패키지 이름이다. 다른 이름을 고른다." >&2 + var yield " +java_keywords=" $(printf '%s' "$java_keywords" | tr -s ' \n' ' ') " +if [[ "$java_keywords" == *" $package_name "* ]]; then + echo "'$package_name'는 Java 예약어다. 다른 이름을 고른다." >&2 + exit 2 +fi + +# 기능 패키지는 다섯 루트 바로 아래에 생긴다. 어느 leaf에든 그 이름의 패키지가 이미 있으면 거절한다. +# 템플릿 패키지(operation, lock, cache, secret, notification…)는 모두 여기 걸린다. 이름 목록을 따로 +# 두지 않는 이유: 목록은 템플릿이 패키지를 더하거나 옮길 때 갈라진다(예전 목록에는 사라진 +# `outbound`가 남고 새 `secret`이 없었다). 템플릿 소유 목록의 정본은 src/application-core/CLAUDE.md +# 「Package ownership」이고, 생성 뒤에는 NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES가 +# 같은 규칙을 다시 건다. +feature_roots=(domain application adapter/inbound/web adapter/outbound/identifier bootstrap/autoconfigure) +existing="" +for root in "${feature_roots[@]}"; do + # `| head`를 쓰지 않는다: pipefail 아래에서 find가 SIGPIPE로 끝나면 이 줄에서 스크립트가 멈춘다. + found="$(cd "$repo_root" && find src -path '*/build' -prune -o -type d \ + -path "*/src/main/java/dev/caskeleton/$root/$package_name" -print)" + if [ -n "$found" ]; then + existing="${found%%$'\n'*}" + break + fi +done +if [ -n "$existing" ]; then + echo "'$package_name' 패키지가 이미 있다: $existing" >&2 + echo "템플릿 패키지와 같은 이름의 업무 기능은 upstream 템플릿을 받을 때 같은 패키지 트리에 섞인다." >&2 + echo "다른 이름을 고른다(템플릿 패키지 목록: src/application-core/CLAUDE.md 「Package ownership」)." >&2 exit 2 fi @@ -106,15 +127,6 @@ for source in "${sources[@]}"; do fi targets+=("$target") done -for package_dir in \ - "src/domain-core/src/main/java/dev/caskeleton/domain/$package_name" \ - "src/application-core/src/main/java/dev/caskeleton/application/$package_name" \ - "src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/$package_name"; do - if [ -d "$repo_root/$package_dir" ]; then - echo "패키지가 이미 있다: $package_dir" >&2 - exit 1 - fi -done imports="$repo_root/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports" config_class="dev.caskeleton.bootstrap.autoconfigure.$package_name.${name}Config" diff --git a/scripts/run-compose-runtime-smoke.sh b/scripts/run-compose-runtime-smoke.sh index 3b32fdcc..770b7a97 100755 --- a/scripts/run-compose-runtime-smoke.sh +++ b/scripts/run-compose-runtime-smoke.sh @@ -47,7 +47,7 @@ CAPABILITIES_OFF='{ "APP_HTTPCLIENT_ENABLED": "false", "APP_OBJECTSTORAGE_ENABLED": "false", "APP_WEBSOCKET_ENABLED": "false", - "CASKELETON_GRPC_ENABLED": "false", + "APP_GRPC_SERVER_ENABLED": "false", "APP_FILESERVER_PLATFORM_ENABLED": "false", "APP_NOTIFICATION_PLATFORM_ENABLED": "false" }' diff --git a/scripts/verify-compose-profile-contracts.sh b/scripts/verify-compose-profile-contracts.sh index 7eac5c3d..c12bb386 100755 --- a/scripts/verify-compose-profile-contracts.sh +++ b/scripts/verify-compose-profile-contracts.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # The static half of the Compose contract: every lane renders, and renders exactly what it claims. # -# Six things are checked, and each exists because assuming it cost something: +# Seven things are checked, and each exists because assuming it cost something: # # 1. the Compose version, because `!override` is what stops the dev overlay's tmpfs merging with # the base's and colliding with a bind mount, and it needs 2.24.4; @@ -17,7 +17,11 @@ # lane for its full timeout on a container that was built to exit; # 6. the expected application report (expectedCapabilitiesOn, expectedPersistenceVendor) names # only catalogued capabilities and a vendor that agrees with persistence-jpa, because an -# expectation the application cannot report fails every run of the lane. +# expectation the application cannot report fails every run of the lane; +# 7. a lane that switches Redis on authenticates as an account its Redis provisions, because the +# lanes ran Redis open and the application anonymous, and the two startup warnings that trade +# prints failed the "startup is silent" check of every such lane (r3-J). Lowering that warning +# would hide the same trade in production; the lane has to look like a deployment instead. # # Static only. Nothing starts here; scripts/run-compose-runtime-smoke.sh owns that. set -euo pipefail @@ -28,6 +32,73 @@ FAILURES=0 fail() { echo " FAIL: $*" >&2; FAILURES=$((FAILURES + 1)); } +# Prints one line for each way a Redis lane falls short of authenticating as an account its own +# Redis provisions; prints nothing when it does not. $1 is the lane, $2 its rendered model. +# +# Read against the rendered model rather than the source files, so the ACL file checked is the one +# the container actually mounts. The account line is compared with what the lane supplies — user, +# password and key pattern — because each of the three fails differently and only at runtime: an +# unknown user or a wrong password is WRONGPASS at the first connection, and a key pattern that +# does not cover the lane's namespace is NOPERM on the first key a capability writes, long after +# startup reported healthy. +CREDENTIAL_REFERENCE_FORM='^secret://([A-Za-z0-9_.-]+)@environment/([A-Za-z_][A-Za-z0-9_]*)$' +redis_authentication_problems() { + local lane="$1" model="$2" + local env namespace + env="$(jq -c '.activationEnv // {}' <<<"${lane}")" + if [[ "$(jq -r '.APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED // empty' <<<"${env}")" == "true" ]]; then + echo "accepts anonymous Redis access; the lane's Redis turns the default user off, so the application has to name an account" + fi + namespace="$(jq -r '.APP_REDIS_NAMESPACE_ENVIRONMENT // empty' <<<"${env}")" + [[ -n "${namespace}" ]] \ + || echo "sets no APP_REDIS_NAMESPACE_ENVIRONMENT, so nothing says the account's key pattern covers the keys the lane writes" + + local acl_path acl_file acl_label + acl_path="$(jq -r '.services.redis.command // [] | . as $c | (index("--aclfile") // empty) as $i | $c[$i + 1] // empty' <<<"${model}")" + if [[ -z "${acl_path}" ]]; then + echo "starts Redis without --aclfile, so the default user is open and nothing authenticates" + return 0 + fi + acl_file="$(jq -r --arg p "${acl_path}" ' + [.services.redis.volumes // [] | .[] | select(.type == "bind" and .read_only == true) + | . as $v | select($p | startswith($v.target + "/")) | $v.source + ($p | ltrimstr($v.target))] + | first // empty' <<<"${model}")" + if [[ -z "${acl_file}" || ! -r "${acl_file}" ]]; then + echo "starts Redis with --aclfile ${acl_path}, which no read-only bind mount of a repository file provides" + return 0 + fi + acl_label="${acl_file#"${REPO_ROOT}/"}" + grep -qx 'user default off' "${acl_file}" \ + || echo "${acl_label} leaves the default user on, which makes every account restriction optional" + [[ "$(jq -r '.services.redis.healthcheck.test // [] | join(" ")' <<<"${model}")" == *"--user "* ]] \ + || echo "the Redis healthcheck does not authenticate as a named account, so it cannot pass with the default user off" + + local setting reference user name value account + for setting in APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE; do + reference="$(jq -r --arg k "${setting}" '.[$k] // empty' <<<"${env}")" + if [[ ! "${reference}" =~ ${CREDENTIAL_REFERENCE_FORM} ]]; then + echo "${setting} is '${reference}', not secret://@environment/" + continue + fi + user="${BASH_REMATCH[1]}" + name="${BASH_REMATCH[2]}" + value="$(jq -r --arg k "${name}" '.[$k] // empty' <<<"${env}")" + if [[ -z "${value}" ]]; then + echo "${setting} reads ${name}, which the lane does not supply" + continue + fi + account="$(grep -E "^user ${user} on( |$)" "${acl_file}" || true)" + if [[ -z "${account}" ]]; then + echo "${setting} names ${user}, which ${acl_label} does not enable" + continue + fi + [[ " ${account} " == *" >${value} "* ]] \ + || echo "${name} is not the password ${acl_label} gives ${user}" + [[ -z "${namespace}" || " ${account} " == *" ~${namespace}:* "* ]] \ + || echo "${user} may not touch ${namespace}:*, the namespace this lane writes" + done +} + command -v jq >/dev/null 2>&1 || { echo "jq is required" >&2; exit 78; } command -v docker >/dev/null 2>&1 || { echo "docker is required" >&2; exit 78; } [[ -r "${CONTRACTS}" ]] || { echo "missing ${CONTRACTS}" >&2; exit 78; } @@ -145,10 +216,17 @@ for index in $(seq 0 $((lane_count - 1))); do | join(" ")' "${CONTRACTS}")" [[ -n "${expectation}" ]] && fail "${id}: the expected application report is unreachable — ${expectation}" + # 7. a lane that switches Redis on authenticates as an account its Redis provisions. + if [[ "$(jq -r '.activationEnv.APP_REDIS_ENABLED // empty' <<<"${lane}")" == "true" ]]; then + while read -r problem; do + [[ -n "${problem}" ]] && fail "${id}: ${problem}" + done < <(redis_authentication_problems "${lane}" "${model}") + fi + [[ ${FAILURES} -eq 0 ]] && echo "${id}: ${expected} @ ${runtime}" done -# 7. the Keycloak realm artifact deserializes into Keycloak's own representation. +# 8. the Keycloak realm artifact deserializes into Keycloak's own representation. # # Keycloak rejects unknown fields rather than ignoring them, so one annotation key anywhere in the # tree fails the whole import, the container exits 1, and every lane that needs an identity provider diff --git a/scripts/verify-feature-scaffold.sh b/scripts/verify-feature-scaffold.sh index 9d33fe97..4bcfa754 100755 --- a/scripts/verify-feature-scaffold.sh +++ b/scripts/verify-feature-scaffold.sh @@ -9,6 +9,8 @@ # # 기본 이름 두 개: 한 단어(Invoice)와 여러 단어(PurchaseOrder). 여러 단어 이름은 패키지·경로· # 오류 코드·권한 이름이 서로 다른 모양으로 갈리고 Javadoc 줄바꿈이 달라지는 경우다. +# 그 전에 템플릿 패키지 이름(Operation, Notification, Common)을 넣어 거절되는지와 아무것도 쓰지 +# 않는지 확인한다. # # 루트 Gradle 태스크 `verifyFeatureScaffold`가 이 스크립트를 부르고 mainCheck에 들어 있다. set -euo pipefail @@ -45,6 +47,25 @@ trap cleanup EXIT git commit -q -m "feature scaffold round trip baseline" ) +# 템플릿 패키지 이름은 거절하고 아무것도 쓰지 않는다(review 2026-11-01 01-10). application-core 패키지, +# 다른 leaf가 같은 루트에 둔 패키지, bootstrap autoconfigure 패키지를 하나씩. `Common`은 예전 이름 +# 목록이 놓쳐서 템플릿의 autoconfigure.common 패키지에 기능을 만들던 이름이다. +for rejected in Operation Notification Common; do + status=0 + output="$("$copy/scripts/new-feature.sh" "$rejected" --no-format 2>&1)" || status=$? + if [ "$status" -ne 2 ]; then + echo "템플릿 패키지 이름을 거절하지 않았다(종료 코드 $status): $rejected" >&2 + printf '%s\n' "$output" >&2 + exit 1 + fi + if [ -n "$(cd "$copy" && git status --porcelain)" ]; then + echo "거절했는데 파일을 바꿨다: $rejected" >&2 + (cd "$copy" && git status --porcelain) >&2 + exit 1 + fi + echo "거절: $rejected" +done + for name in "${names[@]}"; do "$copy/scripts/new-feature.sh" "$name" > "$copy/new-feature-$name.log" echo "생성: $name" diff --git a/src/.env.example b/src/.env.example index f7210dde..895cc69d 100644 --- a/src/.env.example +++ b/src/.env.example @@ -147,6 +147,12 @@ APP_REDIS_NODES=localhost:6379 APP_REDIS_TIMEOUT_BATCH=2s APP_REDIS_TIMEOUT_FAST=500ms APP_REDIS_TIMEOUT_SCRIPT=1s +# Redis authentication takes references, never values: secret://@environment/ +# reads the password from and authenticates as . With the application +# reference empty and anonymous access not accepted, the application refuses to start while Redis +# is on; with the advanced one empty, scripts run as the application account and startup warns. The +# Compose Redis lanes connect as the fixture accounts of infra/redis-sdk/acl/all-accounts.acl (the +# Redis comment in src/config/runtime/compose-profile-contracts.json). APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE= APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=false APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE= @@ -205,6 +211,7 @@ APP_HTTPCLIENT_ROTATION_DRAIN_TIMEOUT=30s APP_FILESERVER_PLATFORM_ENABLED=true APP_FILESERVER_PLATFORM_INSTANCE_ID=local-node APP_FILESERVER_PLATFORM_DEFAULT_NAMESPACE=default +APP_FILESERVER_PLATFORM_TARGET_NAMESPACES= APP_FILESERVER_PLATFORM_STORAGE_ROOT=/var/lib/backend/files APP_FILESERVER_PLATFORM_STORAGE_PUBLISH_MODE=atomic-move-preferred APP_FILESERVER_PLATFORM_STORAGE_BUFFER_SIZE=128KB @@ -239,9 +246,10 @@ APP_FILESERVER_PLATFORM_QUOTA_SCOPE_UPLOAD_PERMITS=4 APP_FILESERVER_PLATFORM_QUOTA_DIRECT_DOWNLOAD_PERMITS=64 APP_FILESERVER_PLATFORM_QUOTA_SOFT_HIGH_WATER=0.70 APP_FILESERVER_PLATFORM_QUOTA_HARD_HIGH_WATER=0.85 +APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT= APP_FILESERVER_PLATFORM_ADMIN_ENABLED=false APP_FILESERVER_PLATFORM_ADMIN_ORPHAN_MINIMUM_AGE=1h -APP_FILESERVER_PLATFORM_CLEANUP_ENABLED=false +APP_FILESERVER_PLATFORM_CLEANUP_ENABLED=true APP_FILESERVER_PLATFORM_CLEANUP_INTERVAL=60s APP_FILESERVER_PLATFORM_CLEANUP_MAX_ITEMS=100 APP_FILESERVER_PLATFORM_CLEANUP_MAX_BYTES=1GB @@ -359,8 +367,8 @@ APP_NOTIFICATION_PLATFORM_MAX_FAILED_PROJECTIONS=1000 APP_NOTIFICATION_PLATFORM_MAX_OLDEST_PENDING_PROJECTION_AGE=15m 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 +APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES=65251 +APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW=1h # ---- Secrets — supply out of band; never commit a value here ------------------ APP_DATASOURCE_PASSWORD= diff --git a/src/Dockerfile b/src/Dockerfile index a2e9df3a..f7705495 100644 --- a/src/Dockerfile +++ b/src/Dockerfile @@ -155,16 +155,10 @@ RUN mkdir -p /var/tmp/heap && chmod 1777 /var/tmp/heap RUN groupadd --system --gid 1000 app \ && useradd --system --uid 1000 --gid app --no-create-home --shell /usr/sbin/nologin app -# ---- Fileserver storage root ------------------------------------------------ -# Created in the image with the runtime user's ownership and 0750, so a fresh named volume -# mounted here inherits both. Without it the Fileserver platform's default root does not exist -# on a read-only root filesystem, and the capability fails on its first upload rather than at -# startup. This directory is a mount point, not a place to keep data in the image: an unmounted -# container writes into the container layer and loses everything on replacement. -RUN mkdir -p /var/lib/backend/files \ - && chown app:app /var/lib/backend/files \ - && chmod 0750 /var/lib/backend/files -VOLUME ["/var/lib/backend/files"] +# No data directory and no VOLUME. The image is the shipped composition, which keeps nothing on +# disk; a selected capability that does brings its mount and that mount's ownership in its own +# Compose overlay, or its orchestrator's volume settings (07-08). A VOLUME here made every +# container, default composition included, create an anonymous volume nobody wrote to. WORKDIR /app diff --git a/src/adapter/inbound/messaging/CLAUDE.md b/src/adapter/inbound/messaging/CLAUDE.md index ff67113d..44f14572 100644 --- a/src/adapter/inbound/messaging/CLAUDE.md +++ b/src/adapter/inbound/messaging/CLAUDE.md @@ -4,9 +4,15 @@ `src/config/architecture/modules.json`. - Responsibility: the application's consume side of the vendored messaging platform — the inbox parts the platform needs from the application (`JdbcInboxRepository` over the application - DataSource, a `TransactionRunner` over its `PlatformTransactionManager`) and the application's - `MessageHandler` implementations, each turning a delivery into one use case call. + DataSource, a `TransactionRunner` over its `PlatformTransactionManager`, the inbox migration as + its own Flyway stream `MessagingInboxSchemaStream`) and the application's `MessageHandler` + implementations, each turning a delivery into one use case call. A handler registers nothing + else: the platform decodes what its `destination()` and `schemaVersions()` declare. - Boundaries: no business rule in a handler (HARD-STOP 4); no persistence entity or repository; no broker SDK type. Allowed edges come only from the registry entry. - Tests: focused auto-configuration and inbox behavior tests; `./gradlew :adapter:inbound:messaging:check`. + The real Kafka + PostgreSQL redelivery lane is `messagingInboxRedeliveryIntegrationTest` + (`:integrationCheck`). +- Coordinates: group `dev.caskeleton.adapter.inbound`, jar `adapter-inbound-messaging`. Do not drop them — + with the default group this project and `:adapter:outbound:messaging` are one module to Gradle. - Design and rejected alternatives: `README.md`. diff --git a/src/adapter/inbound/messaging/README.md b/src/adapter/inbound/messaging/README.md index e9b2dc66..042b5d84 100644 --- a/src/adapter/inbound/messaging/README.md +++ b/src/adapter/inbound/messaging/README.md @@ -4,6 +4,8 @@ - Gradle path: `:adapter:inbound:messaging` - Package: `dev.caskeleton.adapter.inbound.messaging` - 테스트: `./gradlew :adapter:inbound:messaging:test --console=plain` +- 실제 Kafka + PostgreSQL lane: `./gradlew :adapter:inbound:messaging:messagingInboxRedeliveryIntegrationTest --console=plain` + (`:integrationCheck`에 포함, Docker 필요) ## 제공하는 것 @@ -38,9 +40,28 @@ runtimeOnly project(':adapter:inbound:messaging') // 이벤트 소비 + inbox ``` `adapter:outbound:messaging-kafka` 줄(broker·platform)과 persistence-jpa(DataSource·트랜잭션)가 함께 -있어야 한다. inbox 테이블(`messaging_inbox`)은 platform의 -`messaging-reliability-jdbc-postgresql` `db/migration/messaging/V1101__messaging_inbox.sql`이 만든다. -그 위치를 애플리케이션 Flyway location에 넣는 일은 이번 변경에 포함되지 않았다(아래 "남은 것"). +있어야 한다. registry의 app-bootstrap 간선에 이 leaf(`adapter-inbound-messaging`)가 있어서 이 줄은 방향 +gate를 통과한다. + +이 leaf의 Gradle 좌표는 `dev.caskeleton.adapter.inbound:adapter-inbound-messaging`이다. 프로젝트 이름이 +발행 bridge(`:adapter:outbound:messaging`)와 같아서, 기본 group이면 두 프로젝트가 같은 모듈로 취급돼 +Gradle이 하나를 조용히 뺐다(relay가 발행 포트를 잃었다). `build.gradle`이 group과 jar 이름을 따로 둔다. + +서비스가 따로 쓰는 코드는 handler뿐이다. 아래 둘은 이 줄을 넣으면 따라온다. + +- **payload decode 등록**: platform consumer는 (메시지 타입, schema version) → payload class 목록에 있는 + 것만 decode한다. 그 목록을 handler bean의 선언으로 만든다 — `destination()`의 메시지 타입·payload class와 + `schemaVersions()`(기본 v1). starter의 `MessageContracts`에 소비 타입을 등록하는 코드는 쓰지 않는다. + 등록을 빠뜨린 handler는 메시지를 `PAYLOAD_UNDECODABLE`로 DLQ에 보내 효과 없이 끝났다. 같은 (타입, 버전)에 + 발행 등록(`MessageContracts`)과 다른 class를 선언하면 기동이 `MESSAGING_CONTRACT_CONFLICT`로 실패한다. +- **inbox 테이블**: `messaging_inbox`는 platform의 `messaging-reliability-jdbc-postgresql` + `db/migration/messaging/V1101__messaging_inbox.sql`이 만든다. `MessagingInboxSchemaStream`이 기동 중 + (모든 singleton 생성 뒤, consumer 시작 전) 이 마이그레이션을 history 표 `flyway_messaging_inbox_history`로 + 적용한다. 같은 위치의 platform outbox 대역(`V1001..V1099`)은 baseline `1100`으로 건너뛰고, `1199`까지만 + 올린다 — 애플리케이션은 자기 outbox가 있어 platform outbox 표를 만들지 않는다. + `app.runtime.migration-on-startup=false`이면(다른 stream과 같은 스위치) 운영자가 V1101을 직접 적용한다. + - 버린 대안: `db/migration/messaging`을 기본 Flyway location에 추가. V1101이 `flyway_schema_history`에 + 들어가면 애플리케이션의 다음 마이그레이션(V22)이 적용된 버전보다 낮아져 out-of-order로 거부된다. ## destination 예시 @@ -79,9 +100,24 @@ handler 예시는 `MessagingInboxAutoConfigurationTest#exampleHandler`다. payload 타입 매핑과 결과 매핑 규칙을 먼저 정해야 해서 이번 범위보다 크다. 지금은 handler가 직접 use case를 부른다. +## 검증 + +- 단위: `MessagingInboxAutoConfigurationTest` — 조립 조건, inbox 마이그레이션 stream 조립 스위치, runner의 + 커밋·롤백, in-memory inbox로 중복 1회. decode 목록은 starter `MessagingConsumeConfigurationTest`. +- 실제 Kafka + PostgreSQL: `InboxRedeliveryIntegrationTest`(lane `messagingInboxRedeliveryIntegrationTest`). + Kafka capability, outbox relay, persistence-jpa, 이 leaf를 auto-configuration으로 띄운다. 앱 relay가 + PostgreSQL outbox 행을 Kafka로 발행하고, 소비자가 inbox 예약과 업무 쓰기를 한 JPA 트랜잭션에서 한다. + - offset을 0으로 되감고 다시 띄워 같은 레코드를 다시 읽혀도 handler 호출 1회, 업무 행 1개, inbox 행 1개. + - handler가 업무 쓰기 뒤 예외를 던지면 예약과 쓰기가 함께 롤백되고, platform 재시도에서 다시 처리돼 + handler 호출 2회, 업무 행 1개, inbox 행 1개. + - 소비 leaf가 기동하면 inbox 마이그레이션만 `flyway_messaging_inbox_history`에 적용되고 platform outbox + 표는 생기지 않는다. + - 테스트는 payload 타입을 등록하지 않고 inbox 표도 만들지 않는다 — 서비스가 받는 그대로다. + - 변이 확인(2026-11-03): `IdempotentConsumer`의 중복 예약 검사를 지우면 offset 되감기 테스트가 handler + 호출 2회·업무 행 2개로 실패한다. + - 이미지는 `config/testing/container-images.properties`(`kafka`, `postgres-16`). + ## 남은 것 -- 실제 Kafka + PostgreSQL로 같은 메시지 두 번 전달 시 부작용 1회를 확인하는 lane이 없다. 지금은 - platform `InboxMessageHandler`·`IdempotentConsumer`를 실제로 쓰고 inbox 저장소만 in-memory인 단위 - 테스트다. -- inbox migration location 연결과 inbox cleanup 스케줄은 이 leaf가 하지 않는다. +- 템플릿 relay가 보낸 메시지의 payload는 canonical envelope JSON 전체다. 소비자 record는 envelope 모양이다. +- inbox cleanup 스케줄(`InboxCleanupJob`을 어느 replica에서 언제 돌릴지)은 이 leaf가 하지 않는다. diff --git a/src/adapter/inbound/messaging/build.gradle b/src/adapter/inbound/messaging/build.gradle index 339dc526..c3de3ac8 100644 --- a/src/adapter/inbound/messaging/build.gradle +++ b/src/adapter/inbound/messaging/build.gradle @@ -15,6 +15,18 @@ plugins { // the application DataSource and a transaction runner over its PlatformTransactionManager — and is // where an application's message handlers live: an inbound adapter, which turns a delivery into a // use case call, the same role a controller plays for HTTP. + +// Every project shares the group dev.caskeleton, and the publish bridge is also named messaging +// (:adapter:outbound:messaging). Same group and name is the same module to Gradle: wherever both +// were reachable — a composition root selecting the consume side next to the Kafka capability — +// Gradle kept one and silently dropped the other, so the relay lost its publish port (found by the +// redelivery lane below). A group and a jar name of their own keep them apart, as +// adapter:outbound:messaging-kafka does for the same reason. +group = 'dev.caskeleton.adapter.inbound' +base { + archivesName = 'adapter-inbound-messaging' +} + dependencies { implementation project(':application-core') implementation project(':messaging:messaging-core-api') @@ -28,8 +40,64 @@ dependencies { } implementation 'org.springframework.boot:spring-boot-autoconfigure' + // MessagingInboxSchemaStream applies the platform's inbox migration as a stream of its own. + implementation 'org.flywaydb:flyway-core' implementation 'org.springframework:spring-jdbc' implementation 'org.springframework:spring-tx' testImplementation 'org.springframework.boot:spring-boot-starter-test' } + +testing { + suites { + // The consume path against a real Kafka and PostgreSQL (review 2026-11-01 06-08). + integrationTest(JvmTestSuite) { + dependencies { + implementation project() + } + } + } +} +configurations { + integrationTestImplementation.extendsFrom testImplementation + integrationTestRuntimeOnly.extendsFrom testRuntimeOnly +} + +// Test-only edges of the redelivery lane: the publishing side as a composition root selects it +// (the Kafka capability, the outbox relay, the JPA outbox over PostgreSQL), the port owner's event +// fixture, and the platform's MessageContracts holder the consumer registers its payload type in. +// Test edges are outside the registry gate. +dependencies { + integrationTestImplementation project(':adapter:outbound:messaging-kafka') + integrationTestImplementation project(':composition:outbox-relay') + integrationTestImplementation project(':adapter:outbound:persistence-jpa') + integrationTestImplementation project(':application-core') + integrationTestImplementation testFixtures(project(':application-core')) + integrationTestImplementation project(':shared-contract') + integrationTestImplementation project(':messaging:messaging-core-api') + integrationTestImplementation project(':messaging:messaging-spring-boot-starter') + integrationTestImplementation 'org.springframework:spring-jdbc' + integrationTestImplementation 'org.flywaydb:flyway-core' + integrationTestImplementation 'org.apache.kafka:kafka-clients' + integrationTestImplementation 'org.testcontainers:testcontainers-kafka' + integrationTestImplementation 'org.testcontainers:testcontainers-postgresql' +} + +// The application's consume path end to end: the application relay publishes an outbox row through +// the platform bridge to Kafka, the platform consumer hands it to an application handler wrapped in +// the inbox this leaf assembles, and the handler's write and the inbox reservation commit in one +// PostgreSQL transaction. The same message is then delivered again — by rewinding the group's offset, +// and by a handler failure the platform retries — and the business effect and the inbox row stay +// at one. The images come from config/testing/container-images.properties (`ca.test.image.*`). +// It joins :integrationCheck by its category. +strictTestLanes { + lane('messagingInboxRedeliveryIntegrationTest') { + integration() + sourceSet = 'integrationTest' + description = 'Delivers an application-published message twice through Kafka and the PostgreSQL inbox and asserts one effect.' + requires 'dev.caskeleton.adapter.inbound.messaging.InboxRedeliveryIntegrationTest' + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + shouldRunAfter 'test' + } +} diff --git a/src/adapter/inbound/messaging/gradle.lockfile b/src/adapter/inbound/messaging/gradle.lockfile index 4f61d2bc..30469b12 100644 --- a/src/adapter/inbound/messaging/gradle.lockfile +++ b/src/adapter/inbound/messaging/gradle.lockfile @@ -1,152 +1,218 @@ # This is a Gradle generated file for dependency locking. # Manual edits can break the build and are not advised. # This file is expected to be part of source control. -biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath -ch.qos.logback:logback-classic:1.5.38=testCompileClasspath,testRuntimeClasspath -ch.qos.logback:logback-core:1.5.38=testCompileClasspath,testRuntimeClasspath -com.fasterxml.jackson.core:jackson-annotations:2.21=testCompileClasspath,testRuntimeClasspath -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +at.yawk.lz4:lz4-java:1.10.1=integrationTestRuntimeClasspath +biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=integrationTestCompileClasspath,testCompileClasspath +ch.qos.logback:logback-classic:1.5.38=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml:classmate:1.7.3=integrationTestRuntimeClasspath +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.github.docker-java:docker-java-api:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath +com.github.docker-java:docker-java-transport-zerodep:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath +com.github.docker-java:docker-java-transport:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.github.luben:zstd-jni:1.5.6-10=integrationTestRuntimeClasspath com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs com.github.spotbugs:spotbugs:4.10.2=spotbugs com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.38.0=testCompileClasspath +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.38.0=integrationTestCompileClasspath,testCompileClasspath com.google.errorprone:error_prone_annotations:2.41.0=spotbugs com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.google.guava:guava:33.6.0-jre=checkstyle -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,testAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins -com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath +com.jayway.jsonpath:json-path:2.10.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath +com.sun.istack:istack-commons-runtime:4.1.2=integrationTestRuntimeClasspath +com.vaadin.external.google:android-json:0.0.20131108.vaadin1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.zaxxer:HikariCP:7.0.2=integrationTestRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-codec:commons-codec:1.19.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle +commons-io:commons-io:2.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath commons-io:commons-io:2.21.0=spotbugs -commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +commons-logging:commons-logging:1.3.6=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath -jakarta.annotation:jakarta.annotation-api:3.0.0=testCompileClasspath,testRuntimeClasspath -jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=testCompileClasspath,testRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +io.micrometer:micrometer-commons:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.projectreactor:reactor-core:3.8.7=integrationTestRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.inject:jakarta.inject-api:2.0.1=integrationTestRuntimeClasspath +jakarta.persistence:jakarta.persistence-api:3.2.0=integrationTestRuntimeClasspath +jakarta.transaction:jakarta.transaction-api:2.0.1=integrationTestRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +javax.inject:javax.inject:1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath -net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath -net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy-agent:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath +net.logstash.logback:logstash-logback-encoder:8.0=integrationTestRuntimeClasspath +net.minidev:accessors-smart:2.6.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.minidev:json-smart:2.6.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle +org.antlr:antlr4-runtime:4.13.2=checkstyle,integrationTestRuntimeClasspath org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs +org.apache.commons:commons-compress:1.28.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.apache.commons:commons-lang3:3.20.0=checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle org.apache.httpcomponents:httpclient:4.5.13=checkstyle org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.logging.log4j:log4j-api:2.25.5=spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.kafka:kafka-clients:4.1.2=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.apache.logging.log4j:log4j-api:2.25.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.logging.log4j:log4j-to-slf4j:2.25.5=testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.maven.doxia:doxia-core:1.12.0=checkstyle org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle -org.apache.tomcat.embed:tomcat-embed-core:11.0.24=testCompileClasspath,testRuntimeClasspath -org.apache.tomcat.embed:tomcat-embed-el:11.0.24=testCompileClasspath,testRuntimeClasspath -org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-core:11.0.24=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-el:11.0.24=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath -org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=integrationTestCompileClasspath,testCompileClasspath +org.aspectj:aspectjweaver:1.9.25.1=integrationTestRuntimeClasspath +org.assertj:assertj-core:3.27.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.awaitility:awaitility:4.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.checkerframework:checker-qual:3.55.1=integrationTestRuntimeClasspath org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs -org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.eclipse.angus:angus-activation:2.0.3=integrationTestRuntimeClasspath +org.flywaydb:flyway-core:11.14.1=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.flywaydb:flyway-database-postgresql:11.14.1=integrationTestRuntimeClasspath +org.glassfish.jaxb:jaxb-core:4.0.9=integrationTestRuntimeClasspath +org.glassfish.jaxb:jaxb-runtime:4.0.9=integrationTestRuntimeClasspath +org.glassfish.jaxb:txw2:4.0.9=integrationTestRuntimeClasspath +org.hamcrest:hamcrest:3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=integrationTestRuntimeClasspath +org.hibernate.models:hibernate-models:1.0.1=integrationTestRuntimeClasspath +org.hibernate.orm:hibernate-core:7.2.24.Final=integrationTestRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath -org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath +org.jboss.logging:jboss-logging:3.6.3.Final=integrationTestRuntimeClasspath +org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-engine:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-params:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-engine:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-launcher:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath +org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs -org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath -org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath -org.objenesis:objenesis:3.3=testRuntimeClasspath -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath -org.osgi:org.osgi.annotation.bundle:2.0.0=testCompileClasspath -org.osgi:org.osgi.annotation.versioning:1.1.2=testCompileClasspath -org.osgi:org.osgi.resource:1.0.0=testCompileClasspath -org.osgi:org.osgi.service.serviceloader:1.0.0=testCompileClasspath +org.latencyutils:LatencyUtils:2.0.3=integrationTestRuntimeClasspath +org.mockito:mockito-core:5.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,mockitoAgent,testCompileClasspath,testRuntimeClasspath +org.mockito:mockito-junit-jupiter:5.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.objenesis:objenesis:3.3=integrationTestRuntimeClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.osgi:org.osgi.annotation.bundle:2.0.0=integrationTestCompileClasspath,testCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=integrationTestCompileClasspath,testCompileClasspath +org.osgi:org.osgi.resource:1.0.0=integrationTestCompileClasspath,testCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=integrationTestCompileClasspath,testCompileClasspath org.ow2.asm:asm-analysis:9.10.1=spotbugs org.ow2.asm:asm-commons:9.10.1=spotbugs org.ow2.asm:asm-tree:9.10.1=spotbugs org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs -org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.ow2.asm:asm:9.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +org.postgresql:postgresql:42.7.13=integrationTestRuntimeClasspath +org.reactivestreams:reactive-streams:1.0.4=integrationTestRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle -org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath -org.slf4j:jul-to-slf4j:2.0.18=testCompileClasspath,testRuntimeClasspath -org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.rnorth.duct-tape:duct-tape:1.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.skyscreamer:jsonassert:1.5.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-actuator:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor -org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-logging:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-jdbc:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath -org.springframework:spring-tx:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath -org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-data-commons:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-data-jpa:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-flyway:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-hibernate:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-http-converter:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jdbc:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-jpa:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-persistence:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-sql:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-starter-data-jpa:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-starter-flyway:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jdbc:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-starter-json:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-transaction:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.data:spring-data-commons:4.0.7=integrationTestRuntimeClasspath +org.springframework.data:spring-data-jpa:4.0.7=integrationTestRuntimeClasspath +org.springframework.integration:spring-integration-core:7.0.6=integrationTestRuntimeClasspath +org.springframework.integration:spring-integration-jdbc:7.0.6=integrationTestRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-aspects:7.0.9=integrationTestRuntimeClasspath +org.springframework:spring-beans:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-jdbc:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-messaging:7.0.9=integrationTestRuntimeClasspath +org.springframework:spring-orm:7.0.9=integrationTestRuntimeClasspath +org.springframework:spring-test:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-tx:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-webmvc:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.testcontainers:testcontainers-database-commons:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.testcontainers:testcontainers-jdbc:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.testcontainers:testcontainers-kafka:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.testcontainers:testcontainers-postgresql:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.testcontainers:testcontainers:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath +org.xerial.snappy:snappy-java:1.1.10.7=integrationTestRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath -org.yaml:snakeyaml:2.5=testCompileClasspath,testRuntimeClasspath -tools.jackson.core:jackson-core:3.1.5=testCompileClasspath,testRuntimeClasspath -tools.jackson.core:jackson-databind:3.1.5=testCompileClasspath,testRuntimeClasspath -tools.jackson:jackson-bom:3.1.5=testCompileClasspath,testRuntimeClasspath +org.xmlunit:xmlunit-core:2.10.4=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.yaml:snakeyaml:2.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-core:3.1.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson:jackson-bom:3.1.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath empty= diff --git a/src/adapter/inbound/messaging/src/integrationTest/java/dev/caskeleton/adapter/inbound/messaging/InboxRedeliveryIntegrationTest.java b/src/adapter/inbound/messaging/src/integrationTest/java/dev/caskeleton/adapter/inbound/messaging/InboxRedeliveryIntegrationTest.java new file mode 100644 index 00000000..0670293e --- /dev/null +++ b/src/adapter/inbound/messaging/src/integrationTest/java/dev/caskeleton/adapter/inbound/messaging/InboxRedeliveryIntegrationTest.java @@ -0,0 +1,463 @@ +package dev.caskeleton.adapter.inbound.messaging; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.OutboxAppendPort; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.messaging.api.MessageId; +import dev.caskeleton.messaging.api.MessageType; +import dev.caskeleton.messaging.api.delivery.HandleResult; +import dev.caskeleton.messaging.api.delivery.MessageDelivery; +import dev.caskeleton.messaging.api.delivery.MessageHandler; +import dev.caskeleton.messaging.api.destination.DestinationName; +import dev.caskeleton.messaging.api.destination.MessageDestination; +import dev.caskeleton.shared.concurrency.DomainContextPropagator; +import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import javax.sql.DataSource; +import org.apache.kafka.clients.admin.Admin; +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.admin.NewTopic; +import org.apache.kafka.clients.consumer.OffsetAndMetadata; +import org.apache.kafka.common.TopicPartition; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.kafka.KafkaContainer; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * The application's consume path against a real Kafka and PostgreSQL (review 2026-11-01 06-08): the + * same message delivered twice changes the business state once. + * + *

        Booted the way a service gets it: the Kafka capability, the outbox relay, the JPA persistence + * module and this leaf on the classpath, auto-configuration on. The application relay claims a row + * from the PostgreSQL outbox and publishes it through the platform bridge; the platform consumer + * decodes it and, because the destination declares {@code INBOX_TRANSACTIONAL}, runs the handler + * inside the inbox this leaf assembles — the platform's JDBC inbox over the application datasource + * and a runner over the application's (JPA) transaction manager. The handler writes its effect the + * way a use case does, through the application's {@code TransactionPort}. + * + *

        What only this lane can show is that those parts share one transaction for real: a JDBC inbox + * that took a connection of its own, or a runner over a different transaction manager, passes every + * unit test and still commits a reservation whose effect rolled back. The failure path here sees + * that as a retry taken for a duplicate: one handler call, where the rolled-back attempt needs two. + * + *

        Nothing here registers the consumer's payload type, and nothing here creates the inbox table: + * a service writes neither. The platform decodes what the handler bean declares, and this leaf + * applies the platform's inbox migration on start — the way a service gets both. + */ +class InboxRedeliveryIntegrationTest { + + /** The logical destination every {@link OutboxEvents} fixture event is appended to. */ + private static final String DESTINATION = "testkit-events"; + + private static KafkaContainer kafka; + private static PostgreSQLContainer postgres; + private static JdbcTemplate database; + private static Admin admin; + + @BeforeAll + static void startInfrastructure() { + kafka = new KafkaContainer(System.getProperty("ca.test.image.kafka")); + postgres = new PostgreSQLContainer(System.getProperty("ca.test.image.postgres-16")); + kafka.start(); + postgres.start(); + admin = + Admin.create( + Map.of(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers())); + database = + new JdbcTemplate( + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())); + // The application stream (outbox, V1..V21) and the business table the handler writes. The + // inbox table is not created here: the leaf applies it when the context starts, the way a + // service gets it. The projection has no unique key on purpose: a second application of the + // effect is a second row, not an error that hides it. + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .locations("classpath:db/migration/postgresql") + .load() + .migrate(); + database.execute( + "CREATE TABLE lane_projection (event_id VARCHAR(64) NOT NULL," + + " aggregate_id VARCHAR(256) NOT NULL)"); + } + + @AfterAll + static void stopInfrastructure() { + if (admin != null) { + admin.close(); + } + if (postgres != null) { + postgres.stop(); + } + if (kafka != null) { + kafka.stop(); + } + } + + @Test + @DisplayName("relay가 발행한 메시지를 offset을 되감아 다시 전달해도 업무 효과와 inbox 행은 하나다") + void aMessageRedeliveredByRewindingTheGroupOffsetIsAppliedOnce() { + // given: the relay published one outbox row and the consumer applied it + Lane lane = Lane.create(); + Handled handled = new Handled(); + ValidatedIntegrationEvent event = event(); + try (ConfigurableApplicationContext context = start(lane, handled)) { + append(context, event); + awaitObserved(event, lane, handled, Observed.appliedOnce(1L)); + } + rewindToTheStart(lane); + + // when: the consumer starts again from offset 0 and reads the same record + try (ConfigurableApplicationContext context = start(lane, handled)) { + await().atMost(Duration.ofSeconds(90)).until(() -> committedOffset(lane) == 1L); + } + + // then: the redelivery was settled without running the handler again + assertThat(observe(event, lane, handled)).isEqualTo(Observed.appliedOnce(1L)); + } + + @Test + @DisplayName("handler가 업무 쓰기 뒤 예외를 던지면 inbox 예약도 롤백되고 재전달에서 다시 처리해 효과는 한 번이다") + void aHandlerFailingAfterItsWriteLeavesNoReservationAndTheRetryAppliesTheEffectOnce() { + // given: the handler's first attempt writes its effect and then fails + Lane lane = Lane.create(); + Handled handled = new Handled(); + ValidatedIntegrationEvent event = event(); + handled.failFirstAttemptOf(event); + + try (ConfigurableApplicationContext context = start(lane, handled)) { + // when + append(context, event); + + // then: the platform retried; the second attempt was not taken for a duplicate, and the + // first attempt's write rolled back with its reservation + awaitObserved(event, lane, handled, Observed.appliedOnce(2L)); + } + } + + @Test + @DisplayName("소비 leaf가 기동하면 inbox 마이그레이션만 자기 history 표로 적용하고 platform outbox 표는 만들지 않는다") + void startingTheConsumeSideAppliesOnlyTheInboxRangeIntoItsOwnHistory() { + // given + Lane lane = Lane.create(); + + // when + try (ConfigurableApplicationContext context = start(lane, new Handled())) { + // then + assertThat( + database.queryForList( + "SELECT version FROM " + + MessagingInboxSchemaStream.HISTORY_TABLE + + " WHERE success AND type = 'SQL' ORDER BY installed_rank", + String.class)) + .containsExactly("1101"); + assertThat( + database.queryForList( + "SELECT table_name FROM information_schema.tables WHERE table_name IN" + + " ('messaging_inbox', 'messaging_outbox'," + + " 'messaging_admin_operation_journal')", + String.class)) + .containsExactly("messaging_inbox"); + } + } + + /** + * Everything the two redeliveries can change, read together so a failure names all of it. + * + * @param outboxStatus the relay's verdict on the appended row + * @param committedOffset the consumer group's position on the lane's only partition + * @param handlerCalls how many times the application handler ran + * @param projectionRows the business effect + * @param inboxRows the reservation under this consumer group + */ + record Observed( + String outboxStatus, + long committedOffset, + long handlerCalls, + long projectionRows, + long inboxRows) { + + /** Published, settled, and applied once, after the handler ran {@code calls} times. */ + static Observed appliedOnce(long calls) { + return new Observed("PUBLISHED", 1L, calls, 1L, 1L); + } + } + + private static Observed observe(ValidatedIntegrationEvent event, Lane lane, Handled handled) { + String eventId = event.eventId().value(); + return new Observed( + database + .queryForList( + "SELECT status FROM outbox_event WHERE event_id = ?", String.class, eventId) + .stream() + .findFirst() + .orElse("ABSENT"), + committedOffset(lane), + handled.calls(event), + database.queryForObject( + "SELECT count(*) FROM lane_projection WHERE event_id = ?", Long.class, eventId), + database.queryForObject( + "SELECT count(*) FROM messaging_inbox WHERE message_id = ?::uuid AND consumer_id = ?", + Long.class, + eventId, + lane.group())); + } + + private static void awaitObserved( + ValidatedIntegrationEvent event, Lane lane, Handled handled, Observed expected) { + await() + .atMost(Duration.ofSeconds(90)) + .untilAsserted(() -> assertThat(observe(event, lane, handled)).isEqualTo(expected)); + } + + /** A fresh topic and consumer group per test, so offsets and records never leak between them. */ + private record Lane(String topic, String group) { + + static Lane create() { + String suffix = UUID.randomUUID().toString(); + Lane lane = new Lane("inbox-lane-" + suffix, "inbox-lane-projection-" + suffix); + createTopics(lane.topic(), lane.deadLetterTopic()); + return lane; + } + + String deadLetterTopic() { + return topic + ".dlt"; + } + } + + /** The event id is a UUIDv7: the platform's message id refuses any other version. */ + private static ValidatedIntegrationEvent event() { + String eventId = MessageId.newId().value().toString(); + return OutboxEvents.event(eventId, "aggregate-" + eventId, 1, Instant.now().minusSeconds(1)); + } + + private static void append(ConfigurableApplicationContext context, ValidatedIntegrationEvent e) { + OutboxAppendPort outbox = context.getBean(OutboxAppendPort.class); + context.getBean(TransactionPort.class).inWrite(() -> outbox.append(e)); + } + + private static ConfigurableApplicationContext start(Lane lane, Handled handled) { + String destination = "--app.messaging.destinations." + DESTINATION; + String deadLetter = destination + "-dlq"; + return new SpringApplicationBuilder(Application.class) + .initializers(context -> context.getBeanFactory().registerSingleton("handled", handled)) + .web(WebApplicationType.NONE) + .logStartupInfo(false) + .run( + "--APP_DATASOURCE_URL=" + postgres.getJdbcUrl(), + "--APP_DATASOURCE_USERNAME=" + postgres.getUsername(), + "--APP_DATASOURCE_PASSWORD=" + postgres.getPassword(), + // Migrated once above; a second start must not try again. + "--spring.flyway.enabled=false", + "--spring.jpa.open-in-view=false", + "--APP_MESSAGING_KAFKA_BROKERS=" + kafka.getBootstrapServers(), + "--APP_MESSAGING_PRODUCER_ID=inbox-lane", + "--app.messaging.shutdown.drain-deadline=5s", + "--app.outbox.enabled=true", + "--app.outbox.relay-enabled=true", + "--app.outbox.poll-interval=PT0.2S", + destination + ".broker=kafka", + destination + ".kind=EVENT_STREAM", + destination + ".physical.topic=" + lane.topic(), + destination + ".schema.message-types[0]=" + OutboxEvents.CONTRACT_ID, + destination + ".guarantees.delivery=AT_LEAST_ONCE", + destination + ".guarantees.external-side-effect=INBOX_TRANSACTIONAL", + destination + ".consumer.group=" + lane.group(), + // A failed attempt is redelivered from the paused partition, not parked at once. + destination + ".retry.mode=PAUSE_PARTITION", + destination + ".retry.max-attempts=3", + destination + ".retry.initial-delay=100ms", + destination + ".retry.max-delay=200ms", + destination + ".dlq.destination=" + DESTINATION + "-dlq", + deadLetter + ".broker=kafka", + deadLetter + ".kind=WORK_QUEUE", + deadLetter + ".physical.topic=" + lane.deadLetterTopic(), + deadLetter + ".schema.message-types[0]=" + OutboxEvents.CONTRACT_ID, + deadLetter + ".guarantees.delivery=AT_MOST_ONCE"); + } + + /** + * Created up front: a consumer that subscribes before its topic exists waits for the next + * metadata refresh before it is assigned anything. + */ + private static void createTopics(String... topics) { + try { + admin + .createTopics(List.of(topics).stream().map(t -> new NewTopic(t, 1, (short) 1)).toList()) + .all() + .get(30, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted creating " + List.of(topics), interrupted); + } catch (ExecutionException | TimeoutException failed) { + throw new IllegalStateException("could not create " + List.of(topics), failed); + } + } + + /** The group's committed offset on the lane's only partition; -1 before any commit. */ + private static long committedOffset(Lane lane) { + try { + OffsetAndMetadata committed = + admin + .listConsumerGroupOffsets(lane.group()) + .partitionsToOffsetAndMetadata() + .get(30, TimeUnit.SECONDS) + .get(new TopicPartition(lane.topic(), 0)); + return committed == null ? -1L : committed.offset(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted reading " + lane.group(), interrupted); + } catch (ExecutionException | TimeoutException failed) { + throw new IllegalStateException("could not read the offsets of " + lane.group(), failed); + } + } + + /** + * What an operator does to replay a topic: move the stopped group back to offset 0. The group + * must be empty; the consumer that just closed may still be leaving it. + */ + private static void rewindToTheStart(Lane lane) { + await() + .atMost(Duration.ofSeconds(60)) + .ignoreExceptions() + .until( + () -> { + admin + .alterConsumerGroupOffsets( + lane.group(), + Map.of(new TopicPartition(lane.topic(), 0), new OffsetAndMetadata(0L))) + .all() + .get(30, TimeUnit.SECONDS); + return committedOffset(lane) == 0L; + }); + } + + /** + * The canonical envelope an {@link OutboxEvents} fixture event carries, as the consumer reads it. + */ + record LaneEvent(String eventId, String aggregateId) {} + + /** What the handler was asked to do, shared by the contexts one test starts. */ + static final class Handled { + private final Map calls = new ConcurrentHashMap<>(); + private final Set failFirstAttempt = ConcurrentHashMap.newKeySet(); + + void failFirstAttemptOf(ValidatedIntegrationEvent event) { + failFirstAttempt.add(event.eventId().value()); + } + + long calls(ValidatedIntegrationEvent event) { + return calls.getOrDefault(event.eventId().value(), 0L); + } + + void called(String eventId) { + calls.merge(eventId, 1L, Long::sum); + } + + boolean failsThisAttempt(String eventId) { + return failFirstAttempt.remove(eventId); + } + } + + /** A use case's write, in the application's transaction (joined, never opened beside it). */ + static final class RecordProjection { + private final TransactionPort transactions; + private final JdbcTemplate jdbc; + + RecordProjection(TransactionPort transactions, JdbcTemplate jdbc) { + this.transactions = transactions; + this.jdbc = jdbc; + } + + void apply(LaneEvent event) { + transactions.inWrite( + () -> + jdbc.update( + "INSERT INTO lane_projection (event_id, aggregate_id) VALUES (?, ?)", + event.eventId(), + event.aggregateId())); + } + } + + /** The shape of an application handler: one delivery, one use case call. */ + static final class ProjectionHandler implements MessageHandler { + private final Handled handled; + private final RecordProjection useCase; + + ProjectionHandler(Handled handled, RecordProjection useCase) { + this.handled = handled; + this.useCase = useCase; + } + + @Override + public MessageDestination destination() { + return new MessageDestination<>( + new DestinationName(DESTINATION), + new MessageType(OutboxEvents.CONTRACT_ID), + LaneEvent.class); + } + + @Override + public CompletionStage handle(MessageDelivery delivery) { + LaneEvent event = delivery.message().payload(); + handled.called(event.eventId()); + useCase.apply(event); + if (handled.failsThisAttempt(event.eventId())) { + // After the write: only a rollback of the whole transaction undoes it. + throw new IllegalStateException("the projection failed after its write"); + } + return CompletableFuture.completedFuture(HandleResult.success()); + } + } + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration + static class Application { + + @Bean + ProjectionHandler projectionHandler( + Handled handled, TransactionPort transactions, DataSource dataSource) { + return new ProjectionHandler( + handled, new RecordProjection(transactions, new JdbcTemplate(dataSource))); + } + + /** What composition:service-runtime gives a service; the JPA audit context reads it. */ + @Bean + DomainContextPropagator domainContextPropagator() { + return new ThreadLocalDomainContextPropagator(); + } + + @Bean + Clock clock() { + return Clock.systemUTC(); + } + } +} diff --git a/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java b/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java index ac81ef9c..b45d514a 100644 --- a/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java +++ b/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfiguration.java @@ -8,6 +8,7 @@ import javax.sql.DataSource; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; @@ -29,6 +30,10 @@ import org.springframework.transaction.support.TransactionTemplate; * the reservation back with its effect, so the redelivery applies it. * * + *

        It also applies the platform's inbox migration to that datasource ({@link + * MessagingInboxSchemaStream}), so the table the inbox writes exists without a service copying the + * migration into its own stream. + * *

        Only while a {@link MessageHandler} exists — nothing to consume, nothing to assemble. Ordered * before the platform root so its bean conditions see these beans. */ @@ -49,6 +54,20 @@ public class MessagingInboxAutoConfiguration { return new JdbcInboxRepository(dataSource); } + /** + * Creates the inbox table on start ({@link MessagingInboxSchemaStream}), unless the deployment + * migrates out of band ({@code app.runtime.migration-on-startup=false}, the switch every other + * stream honours). A deployment that does applies {@code db/migration/messaging} V1101 itself. + */ + @Bean + @ConditionalOnProperty( + name = "app.runtime.migration-on-startup", + havingValue = "true", + matchIfMissing = true) + public MessagingInboxSchemaStream messagingInboxSchemaStream(DataSource dataSource) { + return new MessagingInboxSchemaStream(dataSource); + } + /** Runs the inbox reservation and the handler in one application transaction. */ @Bean @ConditionalOnMissingBean(IdempotentConsumer.TransactionRunner.class) diff --git a/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxSchemaStream.java b/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxSchemaStream.java new file mode 100644 index 00000000..a0d90ad1 --- /dev/null +++ b/src/adapter/inbound/messaging/src/main/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxSchemaStream.java @@ -0,0 +1,93 @@ +package dev.caskeleton.adapter.inbound.messaging; + +import java.util.Objects; +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.springframework.beans.factory.SmartInitializingSingleton; + +/** + * Applies the platform's inbox migration to the application database, as a stream of its own, so + * turning the consume side on is enough to get the {@code messaging_inbox} table. + * + *

        The table ships with the platform's JDBC inbox ({@code + * db/migration/messaging/V1101__messaging_inbox.sql} in {@code + * messaging-reliability-jdbc-postgresql}), and nothing applied it: the application's Flyway + * migrates {@code db/migration/postgresql} only, so every service that consumed had to copy the + * file or run it by hand, and one that forgot failed on the first delivery with a missing relation. + * + *

        The same shape as the other capability streams ({@code IdempotencySchemaStream}, {@code + * NotificationSchemaStream}): its own history table, applied after every singleton is built — so + * after the primary migration, and before any consumer starts, because consumers start with the + * context's lifecycle, which comes later. Adding {@code db/migration/messaging} to the primary + * location instead would put V1101 into {@code flyway_schema_history}, and the application's next + * migration (V22) would then sit below an applied version and be refused as out of order. + * + *

        The location is shared: the platform's own outbox and admin journal live there too, as {@code + * V1001..V1099}. The application has its own outbox and does not use them, so the stream starts + * from a baseline at {@code 1100} and stops at {@code 1199}, the inbox range: their tables are not + * created here, and a later platform migration outside the inbox range is not applied by it either. + * The baseline is taken explicitly when the history table is new, rather than through {@code + * baselineOnMigrate}, because that only fires on a non-empty schema — on an empty one it would + * apply the outbox range. + * + *

        Forward-only and idempotent, like its siblings: {@code cleanDisabled}, checksums validated, + * and a database that already has the inbox reports zero migrations executed. + */ +public final class MessagingInboxSchemaStream implements SmartInitializingSingleton { + + /** Where the platform ships its relational migrations, inbox included. */ + public static final String LOCATION = "classpath:db/migration/messaging"; + + /** This stream's history table, apart from the application's {@code flyway_schema_history}. */ + public static final String HISTORY_TABLE = "flyway_messaging_inbox_history"; + + /** Everything at or below this version is the platform outbox range, which this stream skips. */ + static final String BASELINE_VERSION = "1100"; + + /** + * The last version of the inbox range, as a target that need not exist yet: the trailing {@code + * ?} is Flyway's "do not fail when no migration has this version", and none does — it is a + * ceiling, not a migration. + */ + static final String LAST_INBOX_VERSION = "1199?"; + + private final DataSource dataSource; + + /** + * Creates the stream over the application database. + * + * @param dataSource the application's data source + */ + public MessagingInboxSchemaStream(DataSource dataSource) { + this.dataSource = Objects.requireNonNull(dataSource, "dataSource"); + } + + @Override + public void afterSingletonsInstantiated() { + apply(); + } + + /** + * Applies every outstanding inbox migration. + * + * @return how many migrations were applied + */ + public int apply() { + Flyway flyway = + Flyway.configure() + .dataSource(dataSource) + .locations(LOCATION) + .table(HISTORY_TABLE) + .baselineVersion(BASELINE_VERSION) + .baselineDescription("messaging inbox range starts above the platform outbox range") + .target(LAST_INBOX_VERSION) + .outOfOrder(false) + .cleanDisabled(true) + .validateOnMigrate(true) + .load(); + if (flyway.info().applied().length == 0) { + flyway.baseline(); + } + return flyway.migrate().migrationsExecuted; + } +} diff --git a/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java b/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java index 741d11e8..e5b7ed4f 100644 --- a/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java +++ b/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/MessagingInboxAutoConfigurationTest.java @@ -22,6 +22,7 @@ import dev.caskeleton.messaging.inbox.IdempotentConsumer; import dev.caskeleton.messaging.inbox.InboxMessageHandler; import dev.caskeleton.messaging.inbox.JdbcInboxRepository; import dev.caskeleton.messaging.reliability.InboxRepository; +import java.sql.SQLException; import java.time.Instant; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -50,11 +51,14 @@ class MessagingInboxAutoConfigurationTest { private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z"); private static final DestinationName ORDERS = new DestinationName("order-events"); + // The datasource is a mock, so the inbox migration — which runs against a real PostgreSQL in the + // redelivery lane — is switched off here unless a test is about it. private final ApplicationContextRunner runner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MessagingInboxAutoConfiguration.class)) .withBean(DataSource.class, () -> Mockito.mock(DataSource.class)) - .withBean(PlatformTransactionManager.class, RecordingTransactions::new); + .withBean(PlatformTransactionManager.class, RecordingTransactions::new) + .withPropertyValues("app.runtime.migration-on-startup=false"); @Test @DisplayName("메시지 handler가 있으면 애플리케이션 datasource 위의 inbox와 트랜잭션 runner를 조립한다") @@ -80,6 +84,43 @@ class MessagingInboxAutoConfigurationTest { }); } + @Test + @DisplayName("기동 중 마이그레이션이 꺼져 있으면 inbox 마이그레이션 stream을 만들지 않는다") + void withMigrationOnStartupOffTheInboxStreamIsNotAssembled() { + // when + runner + .withBean(MessageHandler.class, () -> exampleHandler(new ArrayList<>())) + .run( + context -> { + // then + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(MessagingInboxSchemaStream.class); + }); + } + + @Test + @DisplayName("기본값에서는 handler가 있으면 기동 중에 애플리케이션 datasource로 inbox 마이그레이션을 적용한다") + void byDefaultAHandlerAppliesTheInboxMigrationToTheApplicationDatasourceOnStart() + throws SQLException { + // given: the default switch, and a datasource that refuses every connection + DataSource unreachable = Mockito.mock(DataSource.class); + Mockito.when(unreachable.getConnection()).thenThrow(new SQLException("unreachable on purpose")); + + // when + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(MessagingInboxAutoConfiguration.class)) + .withBean(DataSource.class, () -> unreachable) + .withBean(PlatformTransactionManager.class, RecordingTransactions::new) + .withBean(MessageHandler.class, () -> exampleHandler(new ArrayList<>())) + .run( + context -> { + // then: the stream ran against that datasource during startup + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasStackTraceContaining("unreachable on purpose"); + }); + } + @Test @DisplayName("트랜잭션 runner는 성공하면 커밋하고 실패하면 롤백해 예약과 부작용을 함께 되돌린다") void theRunnerCommitsOnSuccessAndRollsBackOnFailure() { diff --git a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java index 204ee75f..4aad82e0 100644 --- a/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java @@ -33,6 +33,22 @@ public record JsonMergePatchDocument(ObjectNode root) { + " limit; the merge is recursive, and a stack overflow inside a request thread is " + "not something an exception handler can turn into a 400"); } + // Copied after the depth check, so the copy is bounded too. Keeping the caller's node would let + // whoever still holds it deepen the tree after it was checked. + root = root.deepCopy(); + } + + /** + * The patch document, as a copy. + * + *

        A copy for the same reason the constructor takes one: the depth bound holds only while + * nobody else can change the tree it was checked on. + * + * @return a copy of the patch document + */ + @Override + public ObjectNode root() { + return root.deepCopy(); } /** diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocumentTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocumentTest.java new file mode 100644 index 00000000..492758cd --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocumentTest.java @@ -0,0 +1,48 @@ +package dev.caskeleton.adapter.inbound.web.advanced.patch; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +/** + * The document is a value: what it validated at construction is what it holds afterwards. + * + *

        The depth bound is checked once, in the constructor. A document that kept the caller's node, + * or handed its own node out, could be deepened after that check by whoever held the node, and the + * recursive merge the bound protects would then run on a tree nobody checked. + */ +@Tag("web-advanced") +class JsonMergePatchDocumentTest { + + @Test + @DisplayName("생성 뒤 호출자가 넘긴 노드를 바꿔도 문서 내용은 바뀌지 않는다") + void callerMutatingTheNodeItPassedDoesNotChangeTheDocument() { + // given + ObjectNode node = JsonMapper.shared().createObjectNode().put("title", "before"); + JsonMergePatchDocument document = new JsonMergePatchDocument(node); + + // when + node.put("added", "after validation"); + + // then + assertThat(document.fieldNames()).containsExactly("title"); + } + + @Test + @DisplayName("root()로 받은 노드를 바꿔도 문서 내용은 바뀌지 않는다") + void mutatingTheReturnedRootDoesNotChangeTheDocument() { + // given + JsonMergePatchDocument document = + new JsonMergePatchDocument(JsonMapper.shared().createObjectNode().put("title", "before")); + + // when + document.root().put("added", "after validation"); + + // then + assertThat(document.fieldNames()).containsExactly("title"); + } +} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java index abedadcc..ab2f3093 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java @@ -180,8 +180,9 @@ public class TusController { expectedChunkSha256, context))); - UploadSessionView session = status.handle(new GetUploadStatusQuery(id, context)); - if (isComplete(session, appended)) { + // The append answers for itself. Asking the status use case here would require file:read + // from a writer whose bytes are already committed (review 05-12). + if (appended.reachedDeclaredLength()) { // Finalize reads the whole object back and moves it: transfer work, bounded by the same // executor as the append rather than holding a servlet thread for it. transferExecutor.call( @@ -193,7 +194,7 @@ public class TusController { return ResponseEntity.noContent() .header(TusHeaders.RESUMABLE, tusProperties.version()) .header(TusHeaders.UPLOAD_OFFSET, String.valueOf(appended.committedOffset())) - .header(TusHeaders.UPLOAD_EXPIRES, httpDate(session.expiresAt())) + .header(TusHeaders.UPLOAD_EXPIRES, httpDate(appended.expiresAt())) .build(); } @@ -205,17 +206,6 @@ public class TusController { return ResponseEntity.noContent().header(TusHeaders.RESUMABLE, tusProperties.version()).build(); } - /** - * Decides whether the upload just reached its declared length. - * - *

        An upload with a deferred length is never auto-finalized here: only the client knows when it - * is done, and finalizing early would publish a truncated object. - */ - private static boolean isComplete(UploadSessionView session, AppendUploadResult appended) { - return session.expectedLength().isPresent() - && session.expectedLength().getAsLong() == appended.committedOffset(); - } - private static String httpDate(Instant instant) { return HTTP_DATE.format(ZonedDateTime.ofInstant(instant, ZoneOffset.UTC)); } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java index 12accd51..16f66ff3 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java @@ -89,7 +89,12 @@ public final class InMemoryUploadApplicationService { } session.buffer.writeBytes(chunk.toByteArray()); return new AppendUploadResult( - session.buffer.size(), appended, sha256Hex(session.buffer.toByteArray())); + session.buffer.size(), + appended, + sha256Hex(session.buffer.toByteArray()), + session.request.expectedLength(), + // The same standard hour the status view answers. + FileserverWebFixtures.NOW.plus(Duration.ofHours(1))); } public UploadSessionView status(UploadId uploadId, RequestContext context) { diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java index 491a4293..b9f1db0c 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java @@ -14,6 +14,9 @@ import dev.caskeleton.adapter.inbound.web.fileserver.testkit.FileserverWebFixtur import dev.caskeleton.adapter.inbound.web.fileserver.testkit.InMemoryUploadApplicationService; import dev.caskeleton.adapter.inbound.web.fileserver.testkit.RecordingFinalizeService; import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Base64; @@ -246,6 +249,60 @@ class TusProtocolContractTest { .andExpect(status().is(413)); } + /** + * 05-12: the default write role carries {@code file:upload} but not {@code file:read}. The + * append's own result says where the upload stands, so the PATCH never asks the status use case — + * which would refuse a writer after its bytes were already committed. + */ + @Test + @DisplayName("file:read 없는 writer도 PATCH로 마지막 바이트를 쓰면 204와 offset을 받고 업로드가 finalize된다") + void aWriterWithoutReadPermissionCompletesAnUploadThroughPatch() throws Exception { + // given + MockMvc writerOnly = + MockMvcBuilders.standaloneSetup( + new TusController( + uploads.createPort(), + query -> { + throw new FileserverException( + "file:read is not granted", + FileserverFailureContext.of(FileserverErrorCode.ACCESS_DENIED, false)); + }, + uploads.appendPort(), + finalizeService.port(), + uploads.cancelPort(), + new TusRequestParser(TUS), + FileserverWebFixtures.contextFactory(), + FileserverWebFixtures.transferExecutor(), + TUS)) + .setControllerAdvice(new FileserverExceptionHandler()) + .build(); + String location = + writerOnly + .perform( + post("/v1/uploads") + .header(TusHeaders.RESUMABLE, "1.0.0") + .header(TusHeaders.UPLOAD_LENGTH, "3")) + .andReturn() + .getResponse() + .getHeader("Location"); + + // when + ResultActions patched = + writerOnly.perform( + patch(location) + .header(TusHeaders.RESUMABLE, "1.0.0") + .header(TusHeaders.UPLOAD_OFFSET, "0") + .contentType(TusHeaders.OFFSET_OCTET_STREAM) + .content("abc")); + + // then + patched + .andExpect(status().isNoContent()) + .andExpect(header().string(TusHeaders.UPLOAD_OFFSET, "3")) + .andExpect(header().exists(TusHeaders.UPLOAD_EXPIRES)); + assertThat(finalizeService.finalized()).containsExactly(uploadIdOf(location)); + } + private String create(long length) throws Exception { return mvc.perform( post("/v1/uploads") diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackIngressUnavailableException.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackIngressUnavailableException.java new file mode 100644 index 00000000..7a861f48 --- /dev/null +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackIngressUnavailableException.java @@ -0,0 +1,24 @@ +package dev.caskeleton.adapter.inbound.web.notification.platform.callback; + +/** + * The callback could not be judged now; the provider is asked to deliver it again. + * + *

        Thrown by a {@link ProviderCallbackIngress} when verification itself could not run — the + * provider's signing certificate was unreachable — so the event is neither accepted nor rejected. + * The endpoint answers 503 with {@code Retry-After}: SNS redelivers on a 5xx and gives up on a + * rejection, so a rejection here would lose a bounce or complaint for good (review 05-20). + */ +public final class CallbackIngressUnavailableException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** + * Creates the failure. + * + * @param reasonCode a stable, content-free code + * @param cause what made verification impossible + */ + public CallbackIngressUnavailableException(String reasonCode, Throwable cause) { + super("callback ingress unavailable: " + reasonCode, cause); + } +} diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcController.java index 1b23d6ec..809a1b03 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcController.java @@ -8,6 +8,7 @@ import java.util.Objects; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; @@ -55,7 +56,7 @@ public final class NotificationCallbackMvcController { public NotificationCallbackMvcController( ProviderCallbackIngress ingestion, CallbackRequestFactory requestFactory, - @Value("${app.notification.platform.callbacks.max-body-bytes:65508}") int maxBodyBytes) { + @Value("${app.notification.platform.callbacks.max-body-bytes:65251}") int maxBodyBytes) { this.ingestion = Objects.requireNonNull(ingestion, "ingestion"); this.requestFactory = Objects.requireNonNull(requestFactory, "requestFactory"); if (maxBodyBytes < 1 || maxBodyBytes > MAX_STORABLE_BODY_BYTES) { @@ -68,9 +69,12 @@ public final class NotificationCallbackMvcController { /** * The largest body that still fits the ciphertext column once encrypted. * - *

        65,536 minus the 12-byte nonce and 16-byte GCM tag the envelope adds. + *

        65,536 minus the largest envelope the protector writes: a version byte, a key-id length + * byte, a key id of up to 255 bytes, the 12-byte nonce and the 16-byte GCM tag. This leaf cannot + * see the protector, so {@code NotificationModuleDefaultsTest} in the notification composition, + * which assembles both, keeps this number equal to the protector's. */ - public static final int MAX_STORABLE_BODY_BYTES = 65_536 - 28; + public static final int MAX_STORABLE_BODY_BYTES = 65_536 - (1 + 1 + 255 + 12 + 16); /** * Receive one provider callback. @@ -102,4 +106,25 @@ public final class NotificationCallbackMvcController { public ResponseEntity onValidationFailure(CallbackValidationException failure) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); } + + /** + * Seconds a provider is asked to wait before delivering a callback that could not be verified. + * SNS follows its own delivery policy and ignores the header; it is here for any provider that + * reads it and for an operator reading the response. + */ + static final String RETRY_AFTER_SECONDS = "30"; + + /** + * A callback that could not be verified now is answered "try again", not "rejected". + * + *

        A 4xx tells the provider the callback was handled and it stops; a 5xx makes it deliver the + * callback again (review 05-20). Like a rejection, the answer carries no body. + */ + @ExceptionHandler(CallbackIngressUnavailableException.class) + public ResponseEntity onVerificationUnavailable( + CallbackIngressUnavailableException failure) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .header(HttpHeaders.RETRY_AFTER, RETRY_AFTER_SECONDS) + .build(); + } } diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackIngress.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackIngress.java index d96c1f52..dc9eaf53 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackIngress.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackIngress.java @@ -11,6 +11,15 @@ import dev.caskeleton.application.notification.platform.api.CallbackIngestionRes @FunctionalInterface public interface ProviderCallbackIngress { - /** Verify, normalize and durably ingest one raw HTTP callback. */ + /** + * Verify, normalize and durably ingest one raw HTTP callback. + * + * @param request the raw callback + * @return how many events were recorded and how many were duplicates + * @throws dev.caskeleton.application.notification.platform.api.error.CallbackValidationException + * when the callback is rejected for good + * @throws CallbackIngressUnavailableException when it could not be verified now and should be + * delivered again + */ CallbackIngestionResult ingest(ProviderCallbackHttpRequest request); } 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 9a5c89e3..16434929 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 @@ -43,7 +43,7 @@ import org.springframework.web.bind.annotation.RestController; havingValue = "true", matchIfMissing = true) @RequestMapping("/notifications") -public class NotificationSubmissionController { +public final class NotificationSubmissionController { private final AcceptNotificationUseCase accept; 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 13bfd13a..598dc701 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 @@ -46,7 +46,7 @@ import org.springframework.web.bind.annotation.RestController; havingValue = "true", matchIfMissing = true) @RequestMapping("/notification-templates") -public class NotificationTemplateController { +public final class NotificationTemplateController { private final PublishNotificationTemplateUseCase publish; 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 fc2a0c86..a1014ae1 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,6 +13,7 @@ import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; @@ -155,6 +156,26 @@ class NotificationCallbackMvcControllerTest { assertThat(response.getBody()).isNull(); } + @Test + @DisplayName("지금 검증할 수 없는 콜백은 503과 Retry-After로 답해 provider가 다시 보내게 한다") + void aCallbackThatCannotBeVerifiedNowIsAnsweredWithARetryableStatus() { + // given + var unavailable = + new CallbackIngressUnavailableException( + "SNS_CERTIFICATE_UNAVAILABLE", new java.io.IOException("unreachable")); + + // when + var response = controller.onVerificationUnavailable(unavailable); + + // then + assertThat( + List.of( + response.getStatusCode(), + response.getHeaders().getFirst(org.springframework.http.HttpHeaders.RETRY_AFTER))) + .containsExactly(HttpStatus.SERVICE_UNAVAILABLE, "30"); + assertThat(response.getBody()).isNull(); + } + private static MockHttpServletRequest request(String contentType, byte[] body) { var request = new MockHttpServletRequest( diff --git a/src/adapter/inbound/web/CLAUDE.md b/src/adapter/inbound/web/CLAUDE.md index d6976b13..fb4dfe4b 100644 --- a/src/adapter/inbound/web/CLAUDE.md +++ b/src/adapter/inbound/web/CLAUDE.md @@ -41,11 +41,15 @@ ArchUnit `WEB-ARCH-ADV`). - `:application-core` - `:domain-core` - `:shared-contract` +- `:adapter:outbound:support` — `StrictSettingsBinder` only. `app.security` (`SecuritySettings`, the + authentication mode included) is bound by the one strict binder every module uses (review + 2026-11-01 07-10); the ArchUnit inbound/outbound rules allow that class and nothing else from the + leaf. - Spring Web/Security/Validation dependencies. ## Forbidden -- Direct dependency on `adapter-persistence` or `adapter-outbound`. +- Direct dependency on `adapter-persistence` or any other `adapter-outbound` type. - Direct repository or JPA entity access from controllers. - Core business rules in controller, filter, config, mapper, or settings code. - DTO leakage into application or domain. diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 881276ff..b71ce115 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -422,6 +422,11 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML ### SecuritySettings - OIDC resource-server 설정. `issuerUri` 는 인증이 연결될 때 필수 — 없으면 Spring Boot oauth2 auto-config 가 기동 시 실패하므로 여기서 명확한 에러를 먼저 표면화한다. 나머지 knob 은 warn 후 폴백. +- `app.security` 전체(인증 모드 포함)의 유일한 소유자다. `SecuritySettingsConfig` 가 support 의 + `StrictSettingsBinder` 로 묶어(리뷰 07-10) 철자가 틀린 키(`app.security.audence`)나 어떤 설정도 아닌 + `APP_SECURITY_*` 환경 변수가 있으면 기동을 거부한다. 예전 `@ConfigurationProperties` 스캔 바인딩은 둘 다 + 무시했다. bootstrap 의 인증 모드 검사도 이 bean 의 `authMode()` 를 읽는다(같은 prefix 를 두 번 바인딩하지 + 않는다). 슬라이스 테스트는 `@Import(SecuritySettingsConfig.class)` 로 운영과 같은 바인딩을 쓴다. ### PresentationSettings - 검증 정책 "warn-and-default": 부재/잘못된 prefix 값은 앱을 멈추는 대신 빈 prefix 로 폴백 — 모든 엔드포인트가 diff --git a/src/adapter/inbound/web/build.gradle b/src/adapter/inbound/web/build.gradle index b343225e..38eb637e 100644 --- a/src/adapter/inbound/web/build.gradle +++ b/src/adapter/inbound/web/build.gradle @@ -24,6 +24,12 @@ dependencies { // No `application-fileserver`. The capability's HTTP surface is // `adapter:inbound:web-fileserver`, which depends on this leaf rather than living inside it. implementation project(':shared-contract') + // StrictSettingsBinder only (registry edge `adapter-inbound-web -> adapter-outbound-support`, + // review 2026-11-01 07-10): `app.security` is bound by the one strict binder every module uses, + // so a misspelt key or a stray APP_SECURITY_* variable stops startup. A second copy of the binder + // here would be a diverging duplicate; the ArchUnit inbound/outbound rules allow this one class + // and nothing else from that leaf. + implementation project(':adapter:outbound:support') implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server' diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java index d454781c..b5dbec59 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java @@ -36,7 +36,7 @@ import tools.jackson.databind.json.JsonMapper; * text (review 2026-11-01 02-06). A text client still gets the plain string. */ @RestControllerAdvice -public class EnvelopeBodyAdvice implements ResponseBodyAdvice { +public final class EnvelopeBodyAdvice implements ResponseBodyAdvice { private final ObjectMapper objectMapper; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java index 8d67834e..40a19f4e 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java @@ -12,17 +12,20 @@ import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; import dev.caskeleton.shared.response.Envelope; import dev.caskeleton.shared.tracing.SpanErrorRecorder; +import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.ConstraintViolationException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; @@ -104,11 +107,11 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(MethodArgumentTypeMismatchException.class) public ResponseEntity> handleTypeMismatch(MethodArgumentTypeMismatchException ex) { + Class requiredType = ex.getRequiredType(); Map details = - ex.getRequiredType() == null + requiredType == null ? Map.of("parameter", ex.getName()) - : Map.of( - "parameter", ex.getName(), "expectedType", ex.getRequiredType().getSimpleName()); + : Map.of("parameter", ex.getName(), "expectedType", requiredType.getSimpleName()); return ErrorResponseFactory.envelope(OperationalError.BAD_PARAMETER, details); } @@ -255,15 +258,14 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { WebRequest request) { // 405 carries the `Allow` header listing the supported methods. HttpHeaders responseHeaders = new HttpHeaders(); - if (ex.getSupportedHttpMethods() != null) { - responseHeaders.setAllow(new LinkedHashSet<>(ex.getSupportedHttpMethods())); + Set supportedMethods = ex.getSupportedHttpMethods(); + if (supportedMethods != null) { + responseHeaders.setAllow(new LinkedHashSet<>(supportedMethods)); } Map details = - ex.getSupportedHttpMethods() == null + supportedMethods == null ? null - : Map.of( - "supportedMethods", - ex.getSupportedHttpMethods().stream().map(Object::toString).toList()); + : Map.of("supportedMethods", supportedMethods.stream().map(Object::toString).toList()); return new ResponseEntity<>( ErrorResponseFactory.body(OperationalError.METHOD_NOT_ALLOWED, details), responseHeaders, @@ -399,10 +401,11 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { HttpHeaders headers, HttpStatusCode statusCode, WebRequest request) { - if (request instanceof ServletWebRequest servletRequest - && servletRequest.getResponse() != null - && servletRequest.getResponse().isCommitted()) { - return null; + if (request instanceof ServletWebRequest servletRequest) { + HttpServletResponse response = servletRequest.getResponse(); + if (response != null && response.isCommitted()) { + return null; + } } ApiErrorCode code = errorCodeFor(statusCode); if (code.httpStatus() >= 500) { 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 index e67d524e..34decefd 100644 --- 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 @@ -5,7 +5,7 @@ import dev.caskeleton.adapter.inbound.web.auth.JwtToAuthenticatedPrincipalConver import dev.caskeleton.adapter.inbound.web.auth.RedisSessionWebConfig; import dev.caskeleton.adapter.inbound.web.auth.SecurityConfig; import dev.caskeleton.adapter.inbound.web.settings.CorsSettings; -import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettingsConfig; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -31,8 +31,9 @@ import org.springframework.core.Ordered; */ @AutoConfiguration @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) -@EnableConfigurationProperties({CorsSettings.class, SecuritySettings.class}) +@EnableConfigurationProperties(CorsSettings.class) @Import({ + SecuritySettingsConfig.class, JwtDecoderConfig.class, JwtToAuthenticatedPrincipalConverter.class, RedisSessionWebConfig.class, 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 69df34c4..cdf7a8ab 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 @@ -46,7 +46,7 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; */ @RestController @RequestMapping("/operations") -public class DurableOperationController { +public final class DurableOperationController { private final SubmitDurableOperationUseCase submit; private final GetDurableOperationUseCase get; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java index 28f04d62..1b82ab5e 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettings.java @@ -1,8 +1,9 @@ package dev.caskeleton.adapter.inbound.web.settings; +import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder; import java.util.List; -import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.bind.ConstructorBinding; +import org.springframework.core.env.Environment; /** * Exclusive JWT or Redis-backed browser-session security policy bound from {@code app.security.*}. @@ -10,8 +11,14 @@ import org.springframework.boot.context.properties.bind.ConstructorBinding; *

        In JWT mode both {@code issuerUri} and {@code audience} are required. {@code audience} is a * comma-separated list: a token passes when its {@code aud} names any of them, and only those * clients' {@code resource_access} roles are read. + * + *

        The one owner of {@code app.security}, the authentication mode included: the composition + * root's exclusivity check reads {@link #authMode()} from this bean rather than binding the prefix + * a second time. Bound strictly ({@link #bind}, review 2026-11-01 07-10): a misspelt key under the + * prefix, or an {@code APP_SECURITY_*} variable that names no setting and no placeholder reads, + * stops startup. A scanned {@code @ConfigurationProperties} binding ignored both, so {@code + * app.security.audence} ran with no audience configured and said nothing. */ -@ConfigurationProperties(prefix = "app.security") public record SecuritySettings( AuthenticationMode authMode, String issuerUri, @@ -19,6 +26,9 @@ public record SecuritySettings( List publicPaths, SessionCookieSettings session) { + /** The prefix this record owns. */ + public static final String PREFIX = "app.security"; + @ConstructorBinding public SecuritySettings( AuthenticationMode authMode, @@ -63,6 +73,16 @@ public record SecuritySettings( this.session = session == null ? SessionCookieSettings.defaults() : session; } + /** + * Binds {@link #PREFIX} strictly. + * + * @param environment the environment to bind from + * @return the settings + */ + public static SecuritySettings bind(Environment environment) { + return StrictSettingsBinder.bind(environment, PREFIX, SecuritySettings.class); + } + /** A value still holding a {@code ${...}} placeholder was never resolved, so it is absent. */ private static String unresolvedAsMissing(String value) { return value != null && value.contains("${") ? null : value; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsConfig.java new file mode 100644 index 00000000..542134e8 --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsConfig.java @@ -0,0 +1,28 @@ +package dev.caskeleton.adapter.inbound.web.settings; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +/** + * Registers {@link SecuritySettings}, bound strictly, for the security chain and for the + * composition root's authentication-mode check. + * + *

        A configuration of its own rather than a method on the auto-configuration, so a slice test of + * the chain imports exactly the binding production uses instead of a lenient {@code + * EnableConfigurationProperties} of the same type. + */ +@Configuration(proxyBeanMethods = false) +public class SecuritySettingsConfig { + + /** + * The {@code app.security} settings. + * + * @param environment the environment to bind from + * @return the settings + */ + @Bean + public SecuritySettings securitySettings(Environment environment) { + return SecuritySettings.bind(environment); + } +} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/CorsSecurityFilterIntegrationTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/CorsSecurityFilterIntegrationTest.java index 104b5651..d335d2de 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/CorsSecurityFilterIntegrationTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/CorsSecurityFilterIntegrationTest.java @@ -6,7 +6,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.settings.CorsSettings; -import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettingsConfig; import jakarta.servlet.Filter; import java.util.List; import org.junit.jupiter.api.DisplayName; @@ -15,6 +15,7 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import org.springframework.http.HttpHeaders; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.test.web.servlet.MockMvc; @@ -284,7 +285,8 @@ class CorsSecurityFilterIntegrationTest { } @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties({SecuritySettings.class, CorsSettings.class}) + @EnableConfigurationProperties(CorsSettings.class) + @Import(SecuritySettingsConfig.class) static class PropertiesConfig {} @RestController diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtJwksSecurityFilterIntegrationTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtJwksSecurityFilterIntegrationTest.java index 22879c19..ce5ff188 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtJwksSecurityFilterIntegrationTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/JwtJwksSecurityFilterIntegrationTest.java @@ -15,7 +15,7 @@ import com.nimbusds.jwt.SignedJWT; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import dev.caskeleton.adapter.inbound.web.settings.CorsSettings; -import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettingsConfig; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.ClientErrorMessages; import jakarta.servlet.Filter; @@ -43,6 +43,7 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import org.springframework.http.HttpHeaders; import org.springframework.security.core.Authentication; import org.springframework.test.web.servlet.MockMvc; @@ -438,7 +439,8 @@ class JwtJwksSecurityFilterIntegrationTest { } @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties({SecuritySettings.class, CorsSettings.class}) + @EnableConfigurationProperties(CorsSettings.class) + @Import(SecuritySettingsConfig.class) static class PropertiesConfig {} @RestController diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/RedisSessionWebConfigTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/RedisSessionWebConfigTest.java index c807490b..29f9b0a7 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/RedisSessionWebConfigTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/RedisSessionWebConfigTest.java @@ -2,12 +2,12 @@ package dev.caskeleton.adapter.inbound.web.auth; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettingsConfig; import java.util.concurrent.ConcurrentHashMap; import org.junit.jupiter.api.Test; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.session.MapSessionRepository; @@ -68,6 +68,6 @@ class RedisSessionWebConfigTest { } @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties(SecuritySettings.class) + @Import(SecuritySettingsConfig.class) static class PropertiesConfig {} } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityModeWebContractTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityModeWebContractTest.java index 00aee3f5..12e28431 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityModeWebContractTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/SecurityModeWebContractTest.java @@ -9,7 +9,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import com.jayway.jsonpath.JsonPath; import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; import dev.caskeleton.adapter.inbound.web.settings.CorsSettings; -import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettingsConfig; import jakarta.servlet.Filter; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; @@ -206,7 +207,8 @@ class SecurityModeWebContractTest { } @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties({SecuritySettings.class, CorsSettings.class}) + @EnableConfigurationProperties(CorsSettings.class) + @Import(SecuritySettingsConfig.class) static class PropertiesConfig {} @RestController diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/authz/AuthorizationAdapterContractTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/authz/AuthorizationAdapterContractTest.java new file mode 100644 index 00000000..8bfa5ce4 --- /dev/null +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/authz/AuthorizationAdapterContractTest.java @@ -0,0 +1,30 @@ +package dev.caskeleton.adapter.inbound.web.authz; + +import dev.caskeleton.application.security.AuthorizationPort; +import dev.caskeleton.application.security.testkit.AuthorizationContract; +import dev.caskeleton.shared.security.Permission; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * The web adapter, over the role registry bound from {@code app.authz.role-permissions}, keeps the + * authorization contract the in-memory fake keeps. + */ +class AuthorizationAdapterContractTest extends AuthorizationContract { + + @Override + protected AuthorizationPort portGranting(Map> rolePermissions) { + Map> tokens = + rolePermissions.entrySet().stream() + .collect( + Collectors.toMap( + Map.Entry::getKey, + entry -> + entry.getValue().stream() + .map(permission -> permission.resource() + ":" + permission.action()) + .toList())); + return new AuthorizationAdapter(new RolePermissionRegistry(new RolePermissionPolicy(tokens))); + } +} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapterContractTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapterContractTest.java new file mode 100644 index 00000000..77d2d63e --- /dev/null +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/MdcCorrelationIdPortAdapterContractTest.java @@ -0,0 +1,26 @@ +package dev.caskeleton.adapter.inbound.web.observability; + +import dev.caskeleton.application.observability.CorrelationIdPort; +import dev.caskeleton.application.observability.testkit.CorrelationIdContract; +import dev.caskeleton.shared.observability.MdcKeys; +import org.junit.jupiter.api.AfterEach; +import org.slf4j.MDC; + +/** The web adapter, reading the request's MDC, keeps the contract the in-memory fake keeps. */ +class MdcCorrelationIdPortAdapterContractTest extends CorrelationIdContract { + + @AfterEach + void clearMdc() { + MDC.remove(MdcKeys.CORRELATION_ID); + } + + @Override + protected CorrelationIdPort portCarrying(String correlationId) { + if (correlationId == null) { + MDC.remove(MdcKeys.CORRELATION_ID); + } else { + MDC.put(MdcKeys.CORRELATION_ID, correlationId); + } + return new MdcCorrelationIdPortAdapter(); + } +} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java index 287feb42..cc621759 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/settings/SecuritySettingsTest.java @@ -4,11 +4,13 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; +import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.core.env.SystemEnvironmentPropertySource; class SecuritySettingsTest { @@ -53,6 +55,54 @@ class SecuritySettingsTest { }); } + @Test + @DisplayName("app.security 아래 철자가 틀린 키가 있으면 무시하지 않고 그 키 이름을 담아 기동을 거부한다") + void aMisspeltKeyUnderTheSecurityPrefixFailsStartupNamingIt() { + // given: audience spelt wrong, next to a complete JWT configuration + var misspelt = + runner.withPropertyValues( + "app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton", + "app.security.audience=ca-skeleton-api", + "app.security.audence=ca-skeleton-admin"); + + // when + misspelt.run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).hasStackTraceContaining("app.security.audence"); + }); + } + + @Test + @DisplayName("APP_SECURITY_로 시작하지만 어떤 설정도 아닌 환경 변수는 그 이름을 담아 기동을 거부한다") + void anEnvironmentVariableUnderTheSecurityPrefixThatNamesNoSettingFailsStartup() { + // given: a complete JWT configuration and a variable no setting or placeholder reads + var strayVariable = + runner + .withPropertyValues( + "app.security.issuer-uri=http://localhost:8081/realms/ca-skeleton", + "app.security.audience=ca-skeleton-api") + .withInitializer( + context -> + context + .getEnvironment() + .getPropertySources() + .addLast( + new SystemEnvironmentPropertySource( + "systemEnvironment", + Map.of("APP_SECURITY_JWT_AUDENCE", "ca-skeleton-admin")))); + + // when + strayVariable.run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasStackTraceContaining("APP_SECURITY_JWT_AUDENCE"); + }); + } + @Test void issuerUriMissingFailsStartup() { runner.run( @@ -170,6 +220,6 @@ class SecuritySettingsTest { } @Configuration - @EnableConfigurationProperties(SecuritySettings.class) + @Import(SecuritySettingsConfig.class) static class EnableProperties {} } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java index fbd61dd1..466ce11e 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java @@ -4,6 +4,7 @@ import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; /** @@ -60,8 +61,14 @@ public final class SerializedOutboundWriter { private final ReentrantLock queueLock = new ReentrantLock(); private final AtomicBoolean closed = new AtomicBoolean(); - private long written; - private long failed; + + /** + * Counted under the write lock but read without it, by whoever asks for the totals. Plain longs + * gave that reader no visibility guarantee (and on a 32-bit JVM no atomicity either). + */ + private final AtomicLong written = new AtomicLong(); + + private final AtomicLong failed = new AtomicLong(); /** * A writer for one connection. @@ -156,9 +163,9 @@ public final class SerializedOutboundWriter { OutboundMessage message = next.get(); try { sink.write(message.payload()); - written++; + written.incrementAndGet(); } catch (Exception refused) { - failed++; + failed.incrementAndGet(); // Stop at the first failure. Continuing would write the rest of the queue into a socket // that has already refused one message, and on a half-closed connection those writes // succeed silently into nothing. @@ -209,12 +216,12 @@ public final class SerializedOutboundWriter { /** How many messages reached the transport. */ public long written() { - return written; + return written.get(); } /** How many the transport refused. */ public long failed() { - return failed; + return failed.get(); } /** Which connection this writes to. */ diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java index 84addfad..7462a4ca 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java @@ -34,7 +34,7 @@ import org.springframework.web.socket.handler.TextWebSocketHandler; * attributes. Attributes are a {@code Map} the container also writes to, and * anything stored there is reachable by every other handler in the application. */ -public class PlatformWebSocketHandler extends TextWebSocketHandler implements SmartLifecycle { +public final class PlatformWebSocketHandler extends TextWebSocketHandler implements SmartLifecycle { private static final String SHUTTING_DOWN = "server is shutting down"; diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java index 67155a50..96a0da28 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java @@ -28,7 +28,7 @@ import org.springframework.messaging.simp.SimpMessagingTemplate; *

        The adapter never serializes a domain object. Feature modules must contribute exactly one * explicit {@link LiveEventProjector} for an event type; otherwise the event is dropped. */ -public class LiveEventStompBroadcaster { +public final class LiveEventStompBroadcaster { static final int MAX_FIELDS = 32; static final int MAX_EVENT_TYPE_LENGTH = 64; diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java index 82a9c004..7293605a 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java @@ -55,15 +55,16 @@ final class WebSocketInboundAuthorizationInterceptor implements ChannelIntercept if (command == StompCommand.SUBSCRIBE && !holdSubscription(accessor)) { throw new WebSocketPolicyViolationException(); } - if (command == StompCommand.UNSUBSCRIBE && accessor.getSessionId() != null) { - subscriptions.remove(accessor.getSessionId(), subscriptionId(accessor)); + String sessionId = accessor.getSessionId(); + if (command == StompCommand.UNSUBSCRIBE && sessionId != null) { + subscriptions.remove(sessionId, subscriptionId(accessor)); } - if (command == StompCommand.DISCONNECT && accessor.getSessionId() != null) { - subscriptions.remove(accessor.getSessionId()); + if (command == StompCommand.DISCONNECT && sessionId != null) { + subscriptions.remove(sessionId); } + String destination = accessor.getDestination(); if (command == StompCommand.SEND - && (accessor.getDestination() == null - || !accessor.getDestination().startsWith(APPLICATION_PREFIX))) { + && (destination == null || !destination.startsWith(APPLICATION_PREFIX))) { throw new WebSocketPolicyViolationException(); } return message; diff --git a/src/adapter/outbound/cache-redis/CLAUDE.md b/src/adapter/outbound/cache-redis/CLAUDE.md index 61f3823b..9060c016 100644 --- a/src/adapter/outbound/cache-redis/CLAUDE.md +++ b/src/adapter/outbound/cache-redis/CLAUDE.md @@ -128,7 +128,15 @@ Focused tests drive the semantic adapters against `InMemorySemanticRedisCommands served through `StubRedisRuntimeClient`. R1/R2 promotion requires a separate real Redis service lane; it may never be silently skipped when selected. -`redisTopologyTest` is the only real-server lane, declared through `ca.redis-topology-lane`. This +Two real-server lanes. `redisContainerContractTest` (integration category, in `integrationCheck` and +this leaf's `mainCheck`) starts its own Redis with Testcontainers — the `redis` image of +`config/testing/container-images.properties`, loading `infra/redis-sdk/acl/all-accounts.acl` — and +runs `LiveRedisCacheRegionContractTest` and `LiveRedisDistributedLeaseContractTest` (the +`application-core` port contracts the in-memory fakes also pass), `LiveRedisSemanticPortsTest` and +`LiveRedisSemanticScriptAclProbeTest`; a skip fails it (review 2026-11-01 05-16). `RedisTestContainer` +starts the server only when that lane names the ACL file. + +`redisTopologyTest` is the external-topology lane, declared through `ca.redis-topology-lane`. This leaf declares `standalone` and `cluster` (`LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest`); `redis-runtime` and `redis-sdk` declare their own lanes for their own classes. It is opt-in and fail-closed: the mode must be one of `standalone`, `sentinel`, `cluster`, `tls` and one this leaf declares; the endpoint diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index e3457087..0be4ad8e 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -293,10 +293,16 @@ Useful focused checks: ./gradlew :adapter:outbound:cache-redis:check ./gradlew :adapter:outbound:redis-runtime:check ./gradlew :adapter:outbound:cache-redis:test --tests '*RedisSemanticScriptAclProbeTest' +./gradlew :adapter:outbound:cache-redis:redisContainerContractTest # Docker: a real Redis ./gradlew :app-bootstrap:verifyEnvKeys ./gradlew architectureCheck ``` +`redisContainerContractTest` runs the cache-region and lease port contracts (the ones the in-memory +fakes pass) and the live semantic-port tests against a Redis it starts itself, under the standalone +topology's ACL file. It is in `integrationCheck` and `mainCheck`; the image is +`config/testing/container-images.properties` `redis`. + Live Redis/topology qualification remains separate from fast unit tests. A release claim for a specific Redis topology or ACL layout requires the corresponding live qualification lane; the in-memory gateway is for deterministic contract tests, not evidence that an external Redis diff --git a/src/adapter/outbound/cache-redis/build.gradle b/src/adapter/outbound/cache-redis/build.gradle index 71342859..fd9ac4d6 100644 --- a/src/adapter/outbound/cache-redis/build.gradle +++ b/src/adapter/outbound/cache-redis/build.gradle @@ -18,8 +18,12 @@ dependencies { // The in-memory gateway and the topology endpoint the semantic adapter tests run against. testImplementation testFixtures(project(':adapter:outbound:redis-runtime')) - // The lease port's ownership contract, which the Redis adapter runs like the in-memory fake. + // The lease, cache and idempotency ports' contracts, which the Redis adapters run like the + // in-memory fakes. testImplementation testFixtures(project(':application-core')) + // The container lane (redisContainerContractTest, below) starts its own Redis. Only + // RedisTestContainer touches it, and only when that lane selects it. + testImplementation 'org.testcontainers:testcontainers' // RedisReadinessGroupPostProcessorTest boots a real actuator health context: the readiness group // and its membership validation are what the post-processor exists to keep bootable. testImplementation 'org.springframework.boot:spring-boot-starter-actuator' @@ -52,7 +56,37 @@ dependencies { // of its lanes exists to run. Sentinel and TLS are qualified by redis-runtime and redis-sdk. redisTopologyLane { requiredClasses 'standalone', 'LiveRedisSemanticPortsTest', 'LiveRedisSemanticScriptAclProbeTest', - 'LiveRedisDistributedLeaseContractTest', 'LiveRedisCacheRegionContractTest' + 'LiveRedisDistributedLeaseContractTest', 'LiveRedisCacheRegionContractTest', + 'LiveRedisIdempotencyStoreContractTest' requiredClasses 'cluster', 'LiveRedisSemanticPortsTest', 'LiveRedisSemanticScriptAclProbeTest', - 'LiveRedisDistributedLeaseContractTest', 'LiveRedisCacheRegionContractTest' + 'LiveRedisDistributedLeaseContractTest', 'LiveRedisCacheRegionContractTest', + 'LiveRedisIdempotencyStoreContractTest' +} + +// The same live classes the standalone topology lane runs, against a Redis this build starts itself +// (review 2026-11-01 05-16; capability criterion 5). The topology lane above stays explicit-only — it +// needs coordinates of a topology someone else started — so until this lane existed the Redis +// adapters' port contracts reached a real server in no stage, and the fake and the adapter could hide +// the same defect (05-02, 05-03). The image is config/testing/container-images.properties' `redis`, +// and the ACL file is infra/redis-sdk's own, so the accounts and their rights are the standalone +// topology's. Integration category: integrationCheck runs it, and so does this leaf's mainCheck, like +// the HTTP client's Toxiproxy lane. Sentinel, cluster and TLS remain the topology lane's. +def redisAclDirectory = rootProject.projectDir.parentFile.toPath().resolve('infra/redis-sdk/acl').toFile() +strictTestLanes { + lane('redisContainerContractTest') { + integration() + description = 'Runs the Redis semantic adapters\' live contracts against a Testcontainers Redis on the pinned image.' + requires 'dev.caskeleton.adapter.outbound.cache.redis.cache.LiveRedisCacheRegionContractTest', + 'dev.caskeleton.adapter.outbound.cache.redis.lease.LiveRedisDistributedLeaseContractTest', + 'dev.caskeleton.adapter.outbound.cache.redis.LiveRedisSemanticPortsTest', + 'dev.caskeleton.adapter.outbound.cache.redis.capability.LiveRedisSemanticScriptAclProbeTest' + rejectSkipped = true + systemProperty 'redis.container.acl-file', new File(redisAclDirectory, 'all-accounts.acl').absolutePath + inputDirectory redisAclDirectory + shouldRunAfter 'test' + } +} + +tasks.named('mainCheck') { + dependsOn 'redisContainerContractTest' } diff --git a/src/adapter/outbound/cache-redis/gradle.lockfile b/src/adapter/outbound/cache-redis/gradle.lockfile index 7e0de2cd..05009344 100644 --- a/src/adapter/outbound/cache-redis/gradle.lockfile +++ b/src/adapter/outbound/cache-redis/gradle.lockfile @@ -9,6 +9,9 @@ com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,runtimeClasspath com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor +com.github.docker-java:docker-java-api:3.7.1=testCompileClasspath,testRuntimeClasspath +com.github.docker-java:docker-java-transport-zerodep:3.7.1=testCompileClasspath,testRuntimeClasspath +com.github.docker-java:docker-java-transport:3.7.1=testCompileClasspath,testRuntimeClasspath com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs com.github.spotbugs:spotbugs:4.10.2=spotbugs @@ -37,7 +40,9 @@ com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-codec:commons-codec:1.19.0=testCompileClasspath,testRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle +commons-io:commons-io:2.20.0=testCompileClasspath,testRuntimeClasspath commons-io:commons-io:2.21.0=spotbugs commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath info.picocli:picocli:4.7.7=checkstyle @@ -65,13 +70,15 @@ javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.java.dev.jna:jna:5.18.1=testCompileClasspath,testRuntimeClasspath net.logstash.logback:logstash-logback-encoder:8.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs +org.apache.commons:commons-compress:1.28.0=testCompileClasspath,testRuntimeClasspath +org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs,testCompileClasspath,testRuntimeClasspath org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle org.apache.httpcomponents:httpclient:4.5.13=checkstyle @@ -98,6 +105,7 @@ org.dom4j:dom4j:2.2.0=spotbugs org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath org.hdrhistogram:HdrHistogram:2.2.2=testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle +org.jetbrains:annotations:17.0.0=testCompileClasspath,testRuntimeClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath @@ -126,6 +134,7 @@ org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor org.reactivestreams:reactive-streams:1.0.4=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle +org.rnorth.duct-tape:duct-tape:1.0.8=testCompileClasspath,testRuntimeClasspath org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath org.slf4j:jul-to-slf4j:2.0.18=testCompileClasspath,testRuntimeClasspath org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath @@ -168,6 +177,7 @@ org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,te org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath +org.testcontainers:testcontainers:2.0.5=testCompileClasspath,testRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath org.yaml:snakeyaml:2.5=testCompileClasspath,testRuntimeClasspath diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCacheConfig.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCacheConfig.java index 51df86e3..cadf4349 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCacheConfig.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCacheConfig.java @@ -5,7 +5,7 @@ import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSe import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.support.CapabilitySelectors; import dev.caskeleton.application.cache.CacheRegionPort; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import java.time.Clock; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java index 3bf76b25..a1fd1d38 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java @@ -3,7 +3,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeAutoConfiguration; import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeys.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeys.java index 8379a3e9..6573cd27 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeys.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisKeys.java @@ -3,8 +3,8 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; -import dev.caskeleton.application.outbound.SecretReference; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretReference; +import dev.caskeleton.application.secret.SecretSourcePort; import dev.caskeleton.shared.digest.HmacSha256; import java.nio.charset.StandardCharsets; import java.util.HexFormat; diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java index 22b34e09..654c0bc0 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java @@ -17,14 +17,28 @@ import java.util.Map; import java.util.Optional; /** - * Builds, against the topology lane's endpoint, the runtime the composition root builds: one - * namespace from {@code app.redis.namespace}, the application account for data and — when asked — - * the advanced account for the script lane. + * Builds, against the live endpoint, the runtime the composition root builds: one namespace from + * {@code app.redis.namespace}, the application account for data and — when asked — the advanced + * account for the script lane. + * + *

        The live endpoint is the Testcontainers server on the container lane and the declared topology + * on the topology lane; see {@link #endpoint()}. */ public final class LiveRedisRuntime { private LiveRedisRuntime() {} + /** + * Returns the server the live tests run against. + * + * @return the container lane's Redis when that lane runs, the topology lane's endpoint otherwise + */ + public static RedisTopologyEndpoint endpoint() { + return RedisTestContainer.requested() + ? RedisTestContainer.endpoint() + : RedisTopologyEndpoint.fromSystemProperties(); + } + /** * Opens a runtime owner the caller must close. * @@ -33,7 +47,7 @@ public final class LiveRedisRuntime { * @return the owner */ public static RedisRuntimeOwner open(RedisNamespace namespace, boolean separateScriptAccount) { - RedisTopologyEndpoint endpoint = RedisTopologyEndpoint.fromSystemProperties(); + RedisTopologyEndpoint endpoint = endpoint(); RedisRuntimeSettings settings = new RedisRuntimeSettings(); settings.setEnabled(true); settings.setMode(endpoint.mode()); diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java index 00ddb74e..75960d15 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java @@ -72,7 +72,7 @@ class LiveRedisSemanticPortsTest { private static final RedisNamespace NAMESPACE = new RedisNamespace("prod", "order", "shared"); - private final RedisTopologyEndpoint endpoint = RedisTopologyEndpoint.fromSystemProperties(); + private final RedisTopologyEndpoint endpoint = LiveRedisRuntime.endpoint(); private RedisRuntimeOwner owner; diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java new file mode 100644 index 00000000..a23f444b --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java @@ -0,0 +1,92 @@ +package dev.caskeleton.adapter.outbound.cache.redis; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; +import java.util.Optional; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.utility.DockerImageName; +import org.testcontainers.utility.MountableFile; + +/** + * One Redis server for the container lane ({@code redisContainerContractTest}), so the live + * contracts run against a real server without an external topology (review 2026-11-01 05-16). + * + *

        The server is the standalone topology of {@code infra/redis-sdk}: the image is the {@code + * redis} entry of {@code config/testing/container-images.properties} (handed to every test JVM as + * {@code ca.test.image.redis}), and the ACL file is the one that topology loads, so the default + * user is off and the application and advanced accounts carry the same rights they carry there. A + * test that passes here passed under the deployment's ACL, not under an open server. + * + *

        The lane names the ACL file ({@value #ACL_FILE_PROPERTY}); its presence is what selects the + * container. Without it the live tests read the topology lane's endpoint, as before. A missing + * image fails the lane rather than skipping it. + */ +final class RedisTestContainer { + + /** The system property the container lane sets to the ACL file the server loads. */ + static final String ACL_FILE_PROPERTY = "redis.container.acl-file"; + + private static final String IMAGE_PROPERTY = "ca.test.image.redis"; + private static final String ACL_IN_CONTAINER = "/etc/redis/acl/all-accounts.acl"; + private static final int PORT = 6379; + + private static GenericContainer server; + + private RedisTestContainer() {} + + /** + * Reports whether this JVM runs the container lane. + * + * @return {@code true} when the lane named an ACL file + */ + static boolean requested() { + return System.getProperty(ACL_FILE_PROPERTY) != null; + } + + /** + * Starts the server on first use and returns its endpoint, authenticated as the application + * account. + * + * @return the standalone endpoint + */ + static synchronized RedisTopologyEndpoint endpoint() { + if (server == null) { + server = start(); + } + return new RedisTopologyEndpoint( + server.getHost(), + server.getMappedPort(PORT), + RedisDeploymentMode.STANDALONE, + Optional.empty(), + "ca-skeleton-application", + "fixture-application", + Optional.empty()); + } + + // The server outlives every test class in the JVM; the shutdown hook below stops it, and the + // Testcontainers reaper removes it if the JVM dies first. + @SuppressWarnings("resource") + private static GenericContainer start() { + GenericContainer redis = + new GenericContainer<>(DockerImageName.parse(require(IMAGE_PROPERTY))) + .withCopyFileToContainer( + MountableFile.forHostPath(require(ACL_FILE_PROPERTY)), ACL_IN_CONTAINER) + .withCommand( + "redis-server", "--appendonly", "no", "--save", "", "--aclfile", ACL_IN_CONTAINER) + .withExposedPorts(PORT) + .waitingFor(Wait.forLogMessage(".*Ready to accept connections.*\\n", 1)); + redis.start(); + Runtime.getRuntime().addShutdownHook(new Thread(redis::stop, "redis-test-container-stop")); + return redis; + } + + private static String require(String key) { + String value = System.getProperty(key); + if (value == null || value.isBlank()) { + throw new IllegalStateException( + "the Redis container lane requires -D" + key + "; it must never be skipped silently"); + } + return value; + } +} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityActivationTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityActivationTest.java index 88560f25..afbd3163 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityActivationTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityActivationTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import java.time.Clock; import java.util.ArrayList; import java.util.List; 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 8954bec8..16e01054 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 @@ -9,7 +9,7 @@ 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; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import dev.caskeleton.shared.ratelimit.EdgeRateLimitPort; import java.time.Clock; import java.time.Duration; diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/LiveRedisIdempotencyStoreContractTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/LiveRedisIdempotencyStoreContractTest.java new file mode 100644 index 00000000..56dfd764 --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/LiveRedisIdempotencyStoreContractTest.java @@ -0,0 +1,67 @@ +package dev.caskeleton.adapter.outbound.cache.redis.idempotency; + +import dev.caskeleton.adapter.outbound.cache.redis.LiveRedisRuntime; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; +import dev.caskeleton.application.idempotency.IdempotencyStorePort; +import dev.caskeleton.application.idempotency.testkit.IdempotencyStoreContract; +import java.time.Clock; +import java.time.Duration; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Tag; + +/** + * The Redis idempotency store, against a real server under the deployment's advanced account, held + * to the same owner-safe contract as the in-memory fake and the PostgreSQL store. + * + *

        Every transition is a Lua program on the server; the command fake's emulation of those + * programs repeated the renew defect of review 05-02 instead of catching it, so only a real server + * proves what the programs compare. Lease time is the server's, and passes for real here. + * + *

        The contract claims one fixed scope in every test, so each test gets a namespace domain of its + * own: a record a previous test completed or abandoned is never this test's starting state. + */ +@Tag("redis-topology") +@Tag("lane-standalone") +@Tag("lane-cluster") +class LiveRedisIdempotencyStoreContractTest extends IdempotencyStoreContract { + + private RedisRuntimeOwner owner; + + @AfterEach + void closeOwner() { + if (owner != null) { + owner.close(); + owner = null; + } + } + + @Override + protected IdempotencyStorePort store() { + RedisNamespace namespace = + new RedisNamespace("prod", "order", "c" + UUID.randomUUID().toString().substring(0, 8)); + owner = LiveRedisRuntime.open(namespace, true); + return new RedisIdempotencyStoreAdapter( + owner, + new RedisIdempotencyStoreAdapter.IdempotencyKeys(namespace, 1), + new IdempotencyScripts(), + Clock.systemUTC(), + Duration.ofSeconds(2)); + } + + @Override + protected Duration processingLease() { + return Duration.ofSeconds(1); + } + + @Override + protected void elapse(Duration duration) { + try { + Thread.sleep(duration.toMillis()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while letting the lease run", interrupted); + } + } +} diff --git a/src/adapter/outbound/fileserver/README.md b/src/adapter/outbound/fileserver/README.md index c3b00f9b..5e71124d 100644 --- a/src/adapter/outbound/fileserver/README.md +++ b/src/adapter/outbound/fileserver/README.md @@ -21,8 +21,11 @@ that binds the block is not processed, so nothing is created. See ## Tests - `platform/**`: auto-configuration, local storage, security and verification tests. -- `testkit/`: content-store contract, crash-recovery matrix, large-file memory bound and the NFS/PVC - certification helpers. +- `testkit/`: content-store contract (this adapter's internal `BlockingContentStore` SPI), + crash-recovery matrix, large-file memory bound and the NFS/PVC certification helpers. +- Port contracts come from `application-fileserver` testFixtures (`testFixtures(project( + ':application-fileserver'))`): `LocalUploadStorageContractTest` extends `UploadStoragePortContract`, + the same contract the application's `FakeUploadStorageGateway` passes. ```bash cd src diff --git a/src/adapter/outbound/fileserver/build.gradle b/src/adapter/outbound/fileserver/build.gradle index 7e29d813..5f34857b 100644 --- a/src/adapter/outbound/fileserver/build.gradle +++ b/src/adapter/outbound/fileserver/build.gradle @@ -25,4 +25,8 @@ dependencies { // (BOOT-017). The composition root still decides whether to wire it — that part is assembly. implementation 'io.micrometer:micrometer-core' + // The port contracts and fakes live with the ports (application-fileserver testFixtures); the + // local store extends the same contract the application's fake does. + testImplementation testFixtures(project(':application-fileserver')) + } diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverPlatformSettings.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverPlatformSettings.java index 4d371cf5..ab524585 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverPlatformSettings.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverPlatformSettings.java @@ -16,9 +16,10 @@ import org.springframework.util.unit.DataSize; * all. This record is instead bound by {@link FileserverPlatformSettingsBinder} from inside the * master-gated auto-configuration, so "off" means "never bound". * - *

        Every default here is the conservative one. The capability is off, the admin plane is off, the - * experimental protocol is off, delegation is off, and inline rendering is off. A deployment opts - * into each of those explicitly, so no surface appears merely because the dependency is present. + *

        Every default here is the conservative one. The admin plane is off, the experimental protocol + * is off, delegation is off, and inline rendering is off. A deployment opts into each of those + * explicitly, so no surface appears merely because the dependency is present. The cleanup worker is + * the exception that proves the rule: leaving it off is what is unsafe (review 05-13), so it is on. * *

        Validation lives in the compact constructors rather than in bean-validation annotations. It * therefore runs on every construction — including the ones tests make by hand — and can express @@ -28,11 +29,14 @@ import org.springframework.util.unit.DataSize; * @param enabled capability switch for the whole capability; on unless set to {@code false}, * because an application that selected this capability wants it * @param instanceId writer-lease owner for this node; must be unique per instance + * @param targetNamespaces namespaces copies and moves may write into besides {@code + * default-namespace}; empty means the default namespace only */ public record FileserverPlatformSettings( @DefaultValue("true") boolean enabled, @DefaultValue("local-node") String instanceId, @DefaultValue("default") String defaultNamespace, + @DefaultValue List targetNamespaces, @DefaultValue Storage storage, @DefaultValue Upload upload, @DefaultValue Download download, @@ -53,6 +57,10 @@ public record FileserverPlatformSettings( public FileserverPlatformSettings { requireText(instanceId, "instance-id"); requireText(defaultNamespace, "default-namespace"); + targetNamespaces = targetNamespaces == null ? List.of() : List.copyOf(targetNamespaces); + for (String namespace : targetNamespaces) { + requireText(namespace, "target-namespaces"); + } } /** @@ -201,6 +209,11 @@ public record FileserverPlatformSettings( requireRoles(readRoles, "security.read-roles"); requireRoles(writeRoles, "security.write-roles"); requireRoles(adminRoles, "security.admin-roles"); + // Copied after the check: the binder's lists stay reachable from outside, and an emptied one + // would no longer be what "at least one role" certified. + readRoles = List.copyOf(readRoles); + writeRoles = List.copyOf(writeRoles); + adminRoles = List.copyOf(adminRoles); } } @@ -222,13 +235,20 @@ public record FileserverPlatformSettings( } } - /** Transfer admission control and storage high-water marks. */ + /** + * Transfer admission control, storage high-water marks and the namespace quota limit. + * + * @param namespaceLimit the most bytes one namespace may hold, reserved and committed together; + * unset means unlimited, and a reservation past a set limit is refused with {@code + * QUOTA_EXCEEDED} + */ public record Quota( @DefaultValue("16") int instanceUploadPermits, @DefaultValue("4") int scopeUploadPermits, @DefaultValue("64") int directDownloadPermits, @DefaultValue("0.70") double softHighWater, - @DefaultValue("0.85") double hardHighWater) { + @DefaultValue("0.85") double hardHighWater, + DataSize namespaceLimit) { public Quota { requirePositive(instanceUploadPermits, "quota.instance-upload-permits"); @@ -236,6 +256,9 @@ public record FileserverPlatformSettings( requirePositive(directDownloadPermits, "quota.direct-download-permits"); requireFraction(softHighWater, "quota.soft-high-water"); requireFraction(hardHighWater, "quota.hard-high-water"); + if (namespaceLimit != null) { + requireSize(namespaceLimit, "quota.namespace-limit"); + } if (softHighWater >= hardHighWater) { throw new CapabilityStartupValidationException( PREFIX + ".quota.soft-high-water must be below quota.hard-high-water"); @@ -250,11 +273,14 @@ public record FileserverPlatformSettings( /** * Background reclamation. * - *

        Off by default: the worker deletes physical objects, and a template that started deleting on - * first boot would be deciding something the deployment has not yet decided. + *

        On by default (review 05-13). The worker only deletes what the cleanup queue names — staging + * of cancelled or expired uploads, rejected content, deleted files — and without it those bytes + * stay on the volume until the hard high-water mark stops every upload. A node may still turn it + * off, for instance when another node runs the worker; startup then logs a warning so the choice + * is visible. */ public record Cleanup( - @DefaultValue("false") boolean enabled, + @DefaultValue("true") boolean enabled, @DefaultValue("60s") Duration interval, @DefaultValue("100") int maxItems, @DefaultValue("1GB") DataSize maxBytes, diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageGatewayConfiguration.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageGatewayConfiguration.java index 857e76f1..52f57267 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageGatewayConfiguration.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageGatewayConfiguration.java @@ -7,7 +7,6 @@ import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalUploadCont import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalUploadStorage; import dev.caskeleton.application.fileserver.admin.OrphanScanPort; import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; -import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; import dev.caskeleton.application.fileserver.cleanup.CleanupContentPort; import dev.caskeleton.application.fileserver.lifecycle.CopyContentPort; import dev.caskeleton.application.fileserver.upload.UploadContentPort; @@ -30,10 +29,8 @@ class FileserverStorageGatewayConfiguration { UploadContentPort fileserverUploadContentGateway( LocalBlockingContentStore store, FileMetadataPort metadataStore, - UploadSessionPort sessionStore, FileserverPlatformSettings settings) { - return new LocalUploadContent( - store, metadataStore, sessionStore, settings.upload().maxFileSize().toBytes()); + return new LocalUploadContent(store, metadataStore, settings.upload().maxFileSize().toBytes()); } @Bean diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalBlockingContentStore.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalBlockingContentStore.java index f2ab2ba0..f949d00a 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalBlockingContentStore.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalBlockingContentStore.java @@ -143,7 +143,8 @@ public final class LocalBlockingContentStore if (command.expectedLength().isEmpty()) { return ceiling; } - return Math.min(ceiling, Math.max(command.expectedLength().getAsLong(), 1)); + // The declared length is the ceiling, 0 included: an empty upload refuses its first byte. + return Math.min(ceiling, command.expectedLength().getAsLong()); } @Override diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadContent.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadContent.java index 056d26a1..f1a87045 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadContent.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadContent.java @@ -11,11 +11,7 @@ import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; import dev.caskeleton.application.fileserver.api.metadata.FileRecord; import dev.caskeleton.application.fileserver.api.metadata.UploadSession; -import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; -import dev.caskeleton.application.fileserver.api.metadata.WriterLease; -import dev.caskeleton.application.fileserver.api.security.RequestContext; import dev.caskeleton.application.fileserver.upload.UploadContentPort; -import java.util.Optional; import java.util.OptionalLong; /** @@ -29,20 +25,15 @@ public final class LocalUploadContent implements UploadContentPort { private final LocalBlockingContentStore store; private final FileMetadataPort metadataStore; - private final UploadSessionPort sessionStore; private final long maximumFileSize; public LocalUploadContent( - LocalBlockingContentStore store, - FileMetadataPort metadataStore, - UploadSessionPort sessionStore, - long maximumFileSize) { + LocalBlockingContentStore store, FileMetadataPort metadataStore, long maximumFileSize) { if (maximumFileSize <= 0) { throw new IllegalArgumentException("maximumFileSize must be positive"); } this.store = store; this.metadataStore = metadataStore; - this.sessionStore = sessionStore; this.maximumFileSize = maximumFileSize; } @@ -72,42 +63,9 @@ public final class LocalUploadContent implements UploadContentPort { return store.finalizeUpload(handle, command); } - /** - * Gives up the writer lease this instance holds. - * - *

        Only the owning instance may release; a lease held by another node is left alone so a - * finalize on a stale session cannot unlock a writer that is still mid-flight elsewhere. A lease - * that already expired needs no release at all. - */ - @Override - public void releaseLease(UploadSession session, RequestContext context) { - Optional current = sessionStore.find(session.uploadId()); - if (current.isEmpty()) { - return; - } - UploadSession live = current.get(); - if (!live.leaseOwner().map(context.instanceId()::equals).orElse(false)) { - return; - } - Optional lease = - live.leaseToken() - .flatMap( - token -> - live.leaseUntil() - .map( - until -> - new WriterLease( - live.uploadId(), - live.leaseOwner().orElseThrow(), - token, - until, - live.version()))); - lease.ifPresent(held -> sessionStore.releaseLease(live.uploadId(), held)); - } - private long effectiveMaximum(FileRecord record) { return record.expectedSize().isPresent() - ? Math.min(maximumFileSize, Math.max(record.expectedSize().getAsLong(), 1)) + ? Math.min(maximumFileSize, record.expectedSize().getAsLong()) : maximumFileSize; } diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverSecuritySettingsTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverSecuritySettingsTest.java new file mode 100644 index 00000000..55a822d5 --- /dev/null +++ b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverSecuritySettingsTest.java @@ -0,0 +1,32 @@ +package dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The role lists are checked for "at least one role" when the settings are built. Lists the + * settings shared with the binder could be emptied afterwards, and the check would have certified a + * configuration that no longer exists. + */ +class FileserverSecuritySettingsTest { + + @Test + @DisplayName("검증을 통과한 역할 목록은 넘겨준 목록을 비워도 그대로 남는다") + void validatedRolesSurviveTheCallerClearingTheListItPassed() { + // given + List readRoles = new ArrayList<>(List.of("ROLE_FILE_READ")); + FileserverPlatformSettings.Security security = + new FileserverPlatformSettings.Security( + "required", readRoles, List.of("ROLE_FILE_WRITE"), List.of("ROLE_FILE_ADMIN")); + + // when + readRoles.clear(); + + // then + assertThat(security.readRoles()).containsExactly("ROLE_FILE_READ"); + } +} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorageContractTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorageContractTest.java new file mode 100644 index 00000000..9cdf32e2 --- /dev/null +++ b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorageContractTest.java @@ -0,0 +1,28 @@ +package dev.caskeleton.adapter.outbound.fileserver.platform.local; + +import dev.caskeleton.application.fileserver.api.content.PublishMode; +import dev.caskeleton.application.fileserver.testkit.UploadStoragePortContract; +import dev.caskeleton.application.fileserver.upload.UploadStoragePort; +import java.nio.file.Path; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; + +/** The local filesystem store passes the same upload-staging contract as the application's fake. */ +class LocalUploadStorageContractTest extends UploadStoragePortContract { + + @TempDir Path root; + + private LocalUploadStorage storage; + + @BeforeEach + void createStorage() { + storage = + new LocalUploadStorage( + LocalContentStoreFixture.store(root, PublishMode.ATOMIC_MOVE_PREFERRED)); + } + + @Override + protected UploadStoragePort storage() { + return storage; + } +} diff --git a/src/adapter/outbound/httpclient/CLAUDE.md b/src/adapter/outbound/httpclient/CLAUDE.md index bb917e63..9b819b9a 100644 --- a/src/adapter/outbound/httpclient/CLAUDE.md +++ b/src/adapter/outbound/httpclient/CLAUDE.md @@ -83,3 +83,10 @@ Default lane: `./gradlew :adapter:outbound:httpclient:test`. Additional lanes, a A selected lane never skips silently: the fault lane throws without Docker, the contract lane throws on an empty or unknown transport selection, and the performance lane prints which machine-dependent bounds were not asserted. + +The transport port (`BlockingTransportProvider`) has one abstract contract in the test fixtures, +`testkit/BlockingTransportProviderContract`. The engines pass it over a real socket +(`StableTransportProviderContractTest`, the contract lane, once per selected transport) and the +scripted fake the gateway tests stand on passes it in the default lane +(`ScriptedTransportContractTest`). A new transport, or a change to `ScriptedTransport`, inherits the +same class rather than a copy (AGENTS.md rule 6; review 2026-11-01 05-16). diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientActuatorEndpoint.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientActuatorEndpoint.java index 136a9fd7..cfa3ebfb 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientActuatorEndpoint.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientActuatorEndpoint.java @@ -19,7 +19,7 @@ import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; * store is, and "read-only" is not the same as "safe to publish". */ @Endpoint(id = "httpclients") -public class HttpClientActuatorEndpoint { +public final class HttpClientActuatorEndpoint { private final ClientRuntimeRegistry runtimes; diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientAuthenticationAutoConfiguration.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientAuthenticationAutoConfiguration.java index 992fc44b..bb2100b6 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientAuthenticationAutoConfiguration.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientAuthenticationAutoConfiguration.java @@ -7,8 +7,8 @@ import dev.caskeleton.adapter.outbound.httpclient.auth.NoAuthCredentialProvider; import dev.caskeleton.adapter.outbound.httpclient.auth.OAuth2CredentialProvider; import dev.caskeleton.adapter.outbound.httpclient.auth.StaticBearerCredentialProvider; import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; -import dev.caskeleton.application.outbound.SecretReference; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretReference; +import dev.caskeleton.application.secret.SecretSourcePort; import java.time.Clock; import java.util.Set; import java.util.function.Function; diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsBinder.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsBinder.java index ffa75946..69db2fda 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsBinder.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettingsBinder.java @@ -12,18 +12,18 @@ import org.springframework.core.env.Environment; * binder checks it the other way round — against the names of the fields it bound — for every * capability rather than, as before, for this one settings type by reflection over its records * (S3-lead-2). + * + *

        A key below the first level of a {@code clients[n]} or {@code dynamic-targets[n]} element — + * {@code clients[0].timeout.request-write-idle}, one of the settings removed by finding 05-15 — is + * refused by the shared binder too. This platform used to carry its own record-tree guard for it; + * the gap was the binder's, so it was closed there for every capability (review 2026-11-01 05-15). */ final class HttpClientPlatformSettingsBinder { private HttpClientPlatformSettingsBinder() {} static HttpClientPlatformSettings bind(Environment environment) { - HttpClientPlatformSettings settings = - StrictSettingsBinder.bind( - environment, HttpClientPlatformSettings.PREFIX, HttpClientPlatformSettings.class); - // The shared binder's unbound-key check stops at the first level of a list element; see - // ListElementKeyGuard for why, and why that matters for removed settings. - ListElementKeyGuard.requireKnownKeys(environment); - return settings; + return StrictSettingsBinder.bind( + environment, HttpClientPlatformSettings.PREFIX, HttpClientPlatformSettings.class); } } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileAutoConfiguration.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileAutoConfiguration.java index 13fb1151..74e984bb 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileAutoConfiguration.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileAutoConfiguration.java @@ -17,7 +17,7 @@ import dev.caskeleton.adapter.outbound.httpclient.security.TlsPolicyValidator; import dev.caskeleton.adapter.outbound.httpclient.security.TlsRuntimeRotationCoordinator; import dev.caskeleton.adapter.outbound.httpclient.transport.BlockingTransportProvider; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportLifecycleListener; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -73,7 +73,29 @@ public class HttpClientProfileAutoConfiguration { credentialProviders, executionSupport, lifecycleListener, - RandomGenerator.getDefault()); + jitterRandom()); + } + + /** + * The random source of the retry backoff jitter. + * + *

        {@code RandomGenerator.getDefault()} is {@code L32X64MixRandom}, which lives in the {@code + * jdk.random} module — and the runtime image is the slim Temurin JRE, which does not carry it. + * The all-adapters compose lane failed to start on exactly that (review 15절, r3-J). The outbox + * relay hit the same wall and chose a {@code java.base} generator for the same reason. + * + *

        {@link java.util.Random} rather than {@code SplittableRandom}: one generator is shared by + * every client's request threads, and {@code Random} is the {@code java.base} generator + * documented as safe to share. + * + *

        Predictable on purpose: jitter needs spread, not secrecy, and nothing security-relevant is + * derived from it ({@code PREDICTABLE_RANDOM} is excluded for this method, with that reason, in + * {@code config/spotbugs/exclude.xml}). + * + * @return a thread-safe generator from {@code java.base} + */ + static RandomGenerator jitterRandom() { + return new java.util.Random(); } /** diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientStartupValidator.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientStartupValidator.java index b0e221a5..f6dd5437 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientStartupValidator.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientStartupValidator.java @@ -26,6 +26,9 @@ import java.util.Set; */ public final class HttpClientStartupValidator { + /** The TLS violation the environment decides; see {@link #validate}. */ + private static final String PLAINTEXT_FALLBACK = "PLAINTEXT_FALLBACK_FORBIDDEN"; + private final ClientProfileValidator profileValidator = new ClientProfileValidator(); private final TlsPolicyValidator tlsPolicyValidator; @@ -64,8 +67,15 @@ public final class HttpClientStartupValidator { profileValidator.validate(profile, environment).stream() .map(ClientProfileViolation::toString) .forEach(violations::add); - tlsPolicyValidator - .validate(profile.tls()) + tlsPolicyValidator.validate(profile.tls()).stream() + // Whether plain HTTP may start is the one TLS question that depends on the + // environment, and only the profile validator above is told the environment: it + // refuses the fallback in production and allows it elsewhere, as the configuration + // reference documents. The TLS policy has no environment and refuses it everywhere, + // so asking it as well made every non-production plain-HTTP profile — the + // local-httpclient and all-adapters compose lanes — unable to start (review 15절, + // r3-J). In production the profile validator still reports it. + .filter(violation -> !PLAINTEXT_FALLBACK.equals(violation.code())) .forEach( violation -> violations.add( diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/ListElementKeyGuard.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/ListElementKeyGuard.java deleted file mode 100644 index b9989a83..00000000 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/ListElementKeyGuard.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.autoconfigure; - -import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.RecordComponent; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.TreeSet; -import org.springframework.boot.context.properties.source.ConfigurationPropertyName; -import org.springframework.boot.context.properties.source.ConfigurationPropertyName.Form; -import org.springframework.boot.context.properties.source.ConfigurationPropertySource; -import org.springframework.boot.context.properties.source.ConfigurationPropertySources; -import org.springframework.boot.context.properties.source.IterableConfigurationPropertySource; -import org.springframework.core.env.Environment; -import org.springframework.core.env.SystemEnvironmentPropertySource; - -/** - * Refuses a property under {@code clients[n]} or {@code dynamic-targets[n]} that names no setting. - * - *

        The strict binder cannot see these. Spring's {@code NoUnboundElementsBindHandler} treats every - * key beneath an element of a bound list as "an overridden collection element" once the element's - * first-level group was attempted, so {@code clients[0].timeout.request-wirte-idle} — or a key this - * platform removed, such as {@code clients[0].pool.shutdown-timeout} — bound nothing and failed - * nothing. Only a misspelt first-level group ({@code clients[0].timeuot}) was refused. Removing an - * inert setting is honest only if setting it afterwards fails, so the per-element key set is - * checked here against the record tree (finding 05-15). - * - *

        The system environment is not checked here: the strict binder already refuses an {@code - * APP_HTTPCLIENT_*} variable that bound nothing, and environment names cannot be split back into - * property paths unambiguously. - */ -final class ListElementKeyGuard { - - private static final String INDEX = "[]"; - - private ListElementKeyGuard() {} - - static void requireKnownKeys(Environment environment) { - check( - environment, - HttpClientPlatformSettings.PREFIX + ".clients", - knownPaths(HttpClientPlatformSettings.ClientSettings.class)); - check( - environment, - HttpClientPlatformSettings.PREFIX + ".dynamic-targets", - knownPaths(HttpClientPlatformSettings.DynamicTargetSettings.class)); - } - - private static void check(Environment environment, String listPrefix, Set known) { - ConfigurationPropertyName list = ConfigurationPropertyName.of(listPrefix); - Set unknown = new TreeSet<>(); - for (ConfigurationPropertySource source : ConfigurationPropertySources.get(environment)) { - if (source.getUnderlyingSource() instanceof SystemEnvironmentPropertySource - || !(source instanceof IterableConfigurationPropertySource iterable)) { - continue; - } - for (ConfigurationPropertyName name : iterable) { - if (!list.isAncestorOf(name) || !name.isNumericIndex(list.getNumberOfElements())) { - continue; - } - String path = relativePath(name, list.getNumberOfElements() + 1); - if (!path.isEmpty() && !known.contains(path)) { - unknown.add(name.toString()); - } - } - } - if (!unknown.isEmpty()) { - throw new CapabilityStartupValidationException( - "HTTPCLIENT_UNKNOWN_SETTING: " + unknown + " name no setting and would be ignored"); - } - } - - /** The key below the list index, uniform form, with every further index written as []. */ - private static String relativePath(ConfigurationPropertyName name, int from) { - List parts = new ArrayList<>(); - for (int i = from; i < name.getNumberOfElements(); i++) { - parts.add(name.isNumericIndex(i) ? INDEX : name.getElement(i, Form.UNIFORM)); - } - return String.join(".", parts); - } - - /** Every leaf path of a settings record, in the same form {@link #relativePath} produces. */ - static Set knownPaths(Class recordType) { - Set paths = new HashSet<>(); - collect(recordType, "", paths); - return Set.copyOf(paths); - } - - private static void collect(Class recordType, String prefix, Set out) { - for (RecordComponent component : recordType.getRecordComponents()) { - String path = prefix + component.getName().toLowerCase(Locale.ROOT); - Class type = component.getType(); - if (type.isRecord()) { - collect(type, path + ".", out); - } else if (List.class.isAssignableFrom(type)) { - Type element = ((ParameterizedType) component.getGenericType()).getActualTypeArguments()[0]; - if (element instanceof Class elementType && elementType.isRecord()) { - collect(elementType, path + "." + INDEX + ".", out); - } else { - out.add(path + "." + INDEX); - } - } else { - out.add(path); - } - } - } -} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java index 8350e0c3..234b5919 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java @@ -62,9 +62,9 @@ public final class JdkFailureClassifier implements TransportFailureClassifier { return TransportFailure.notSent( AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_TRANSIENT, "TLS_TRANSIENT_FAILURE"); } - if (cause instanceof InterruptedIOException - && !(cause instanceof HttpTimeoutException) - && !(cause instanceof SocketTimeoutException)) { + // HttpTimeoutException is an IOException, never an InterruptedIOException, so only the socket + // timeout needs excluding here; the JDK client's own timeouts are classified below. + if (cause instanceof InterruptedIOException && !(cause instanceof SocketTimeoutException)) { // Cancellation, not a timeout. Classifying it as a timeout let the retry engine reissue a // request the caller had just cancelled, and dropped the interrupt so the thread could not // see its own cancellation either. diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/TlsSettings.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/TlsSettings.java index e4428523..6a3c7d0f 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/TlsSettings.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/TlsSettings.java @@ -11,8 +11,10 @@ import java.util.Set; * here and resolved into an {@code SslContextMaterial} by {@code TlsMaterialProvider}. * *

        {@code trustAll} and {@code allowPlainHttp} exist only so an operator's unsafe intent is - * representable and therefore rejectable at startup. No code path acts on a true value: - * {@code ClientProfileValidator} and {@code TlsPolicyValidator} both fail closed on them. + * representable and therefore rejectable at startup. No code path acts on a true {@code + * trustAll}: {@code ClientProfileValidator} and {@code TlsPolicyValidator} both fail closed on it. + * {@code allowPlainHttp} is refused in production by {@code ClientProfileValidator}, which is the + * one told the environment; startup validation leaves that question to it (review 15절, r3-J). */ public record TlsSettings( Optional profileId, diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientJitterRandomTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientJitterRandomTest.java new file mode 100644 index 00000000..ba064c8c --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientJitterRandomTest.java @@ -0,0 +1,28 @@ +package dev.caskeleton.adapter.outbound.httpclient.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.random.RandomGenerator; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The backoff jitter's random source has to exist in the image the service ships on. + * + *

        The runtime image is the slim Temurin JRE, which has {@code java.base} and not {@code + * jdk.random}; {@code RandomGenerator.getDefault()} comes from the latter, and the all-adapters + * compose lane failed to start with "No implementation of the random number generator algorithm + * L32X64MixRandom is available". + */ +class HttpClientJitterRandomTest { + + @Test + @DisplayName("재시도 jitter 난수는 slim JRE 이미지에도 있는 java.base 구현을 쓴다") + void theJitterRandomComesFromJavaBase() { + // when + RandomGenerator random = HttpClientProfileAutoConfiguration.jitterRandom(); + + // then + assertThat(random.getClass().getModule().getName()).isEqualTo("java.base"); + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientStartupValidatorTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientStartupValidatorTest.java new file mode 100644 index 00000000..c449275c --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientStartupValidatorTest.java @@ -0,0 +1,82 @@ +package dev.caskeleton.adapter.outbound.httpclient.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpConfigurationException; +import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; +import dev.caskeleton.adapter.outbound.httpclient.profile.RuntimeEnvironment; +import dev.caskeleton.adapter.outbound.httpclient.profile.TlsSettings; +import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; +import java.net.URI; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Whether plain HTTP starts depends on the environment, and startup validation must ask the + * validator that knows it. + * + *

        The profile validator refuses a plain-HTTP fallback in production and allows it elsewhere — + * what {@code docs/httpclient/configuration-reference.md} documents and what the local-httpclient + * and all-adapters compose lanes configure. Startup also ran the TLS policy, which has no + * environment and refused it everywhere, so no plain-HTTP profile could ever start and the + * all-adapters lane stayed unhealthy (review 15절, r3-J). + */ +class HttpClientStartupValidatorTest { + + private final HttpClientStartupValidator validator = new HttpClientStartupValidator(); + + @Test + @DisplayName("비운영 환경에서는 평문 HTTP를 명시한 로컬 프로필이 기동 검증을 통과한다") + void aPlainHttpProfileStartsOutsideProduction() { + // given + ClientProfile local = plainHttpProfile(); + + // when + Throwable thrown = + catchThrowable( + () -> + validator.validate(Map.of(local.name(), local), RuntimeEnvironment.NON_PRODUCTION)); + + // then + assertThat(thrown).isNull(); + } + + @Test + @DisplayName("운영 환경에서는 평문 HTTP를 명시한 프로필이 기동 검증에서 거부된다") + void aPlainHttpProfileIsRefusedInProduction() { + // given + ClientProfile local = plainHttpProfile(); + + // when + Throwable thrown = + catchThrowable( + () -> validator.validate(Map.of(local.name(), local), RuntimeEnvironment.PRODUCTION)); + + // then + assertThat(thrown) + .isInstanceOf(HttpConfigurationException.class) + .hasMessageContainingAll("PLAINTEXT_FALLBACK_FORBIDDEN", "profile=local-app"); + } + + /** The profile the local-httpclient and all-adapters lanes configure for the app itself. */ + private static ClientProfile plainHttpProfile() { + return ClientProfiles.builder("local-app") + .baseUrl(URI.create("http://app:8080")) + .allowedHosts(Set.of("app")) + .allowedPorts(Set.of(8080)) + .tls( + new TlsSettings( + Optional.of("local-app"), + Set.of("TLSv1.3", "TLSv1.2"), + true, + false, + true, + Optional.empty(), + Optional.empty())) + .build(); + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/AllStableTransportsContractTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/AllStableTransportsContractTest.java deleted file mode 100644 index 6f51a078..00000000 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/AllStableTransportsContractTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.contract; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType; -import dev.caskeleton.adapter.outbound.httpclient.testkit.BlockingTransportContract; -import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; -import dev.caskeleton.adapter.outbound.httpclient.testkit.HttpClientContract; -import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; -import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; -import java.lang.reflect.Method; -import java.net.URI; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Stream; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * One semantic contract, executed against every selected Stable transport (design §28.2, §33). - * - *

        Transport selection is explicit and fail-closed: an empty or unknown selection is an error, so - * the suite cannot report success because it silently ran against nothing. After the suite it - * asserts that it ran the number of invocations the selection implies, so an under-run is a failure - * rather than an empty success. - */ -@Tag("httpclient-contract") -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -class AllStableTransportsContractTest { - - private final AtomicInteger executed = new AtomicInteger(); - - static Stream transports() { - return HttpClientContract.selectedTransports().stream(); - } - - @Test - void theSelectedTransportSetIsExplicit() { - assertThat(HttpClientContract.selectedTransports()).isNotEmpty(); - } - - @AfterAll - void everySelectedTransportRanEveryContract() { - long declared = - Stream.of(AllStableTransportsContractTest.class.getDeclaredMethods()) - .filter(method -> method.isAnnotationPresent(ParameterizedTest.class)) - .map(Method::getName) - .distinct() - .count(); - assertThat(executed.get()) - .as("each selected transport must run each declared contract") - .isEqualTo((int) (declared * transports().count())); - } - - private static TestGateways.Harness harness(String transport, URI baseUrl) { - TransportType type = "jdk".equals(transport) ? TransportType.JDK : TransportType.APACHE; - return TestGateways.forProfile( - ClientProfiles.builder("users").baseUrl(baseUrl).transport(type).build()); - } - - @ParameterizedTest - @MethodSource("transports") - void methodAndTemplateEncodingIsIdentical(String transport) throws Exception { - try (MockHttpServer server = MockHttpServer.start(); - TestGateways.Harness harness = harness(transport, server.uri("/"))) { - BlockingTransportContract.methodAndTemplateEncoding(harness, server); - } - executed.incrementAndGet(); - } - - @ParameterizedTest - @MethodSource("transports") - void notSentConnectFailureHasSameStableMetadata(String transport) { - BlockingTransportContract.connectFailureIsProvenNotSent(baseUrl -> harness(transport, baseUrl)); - executed.incrementAndGet(); - } - - @ParameterizedTest - @MethodSource("transports") - void absoluteUriIsRejectedOnEveryTransport(String transport) throws Exception { - try (MockHttpServer server = MockHttpServer.start(); - TestGateways.Harness harness = harness(transport, server.uri("/"))) { - BlockingTransportContract.absoluteUriIsRejectedBeforeAnyRequest(harness, server); - } - executed.incrementAndGet(); - } - - @ParameterizedTest - @MethodSource("transports") - void errorStatusMapsToTheSameStableException(String transport) throws Exception { - try (MockHttpServer server = MockHttpServer.start(); - TestGateways.Harness harness = harness(transport, server.uri("/"))) { - BlockingTransportContract.errorStatusBecomesAStableException(harness, server); - } - executed.incrementAndGet(); - } -} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/ScriptedTransportContractTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/ScriptedTransportContractTest.java new file mode 100644 index 00000000..5b7924db --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/ScriptedTransportContractTest.java @@ -0,0 +1,73 @@ +package dev.caskeleton.adapter.outbound.httpclient.contract; + +import dev.caskeleton.adapter.outbound.httpclient.auth.CredentialProviderRegistry; +import dev.caskeleton.adapter.outbound.httpclient.testkit.BlockingTransportProviderContract; +import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; +import dev.caskeleton.adapter.outbound.httpclient.testkit.ScriptedTransport; +import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; +import java.net.URI; + +/** + * The transport contract against the scripted fake the gateway tests stand on. + * + *

        The same contract the Apache and JDK engines pass ({@link + * StableTransportProviderContractTest}). No socket is opened: the upstream is the fake's script and + * its record of what was sent. + */ +class ScriptedTransportContractTest extends BlockingTransportProviderContract { + + private static final URI BASE_URL = URI.create("https://users.example.com/"); + + @Override + protected Upstream upstream() { + return new ScriptedUpstream(new ScriptedTransport()); + } + + @Override + protected TestGateways.Harness harness(Upstream upstream) { + return harnessOver(((ScriptedUpstream) upstream).transport()); + } + + @Override + protected TestGateways.Harness unreachableHarness() { + return harnessOver(new ScriptedTransport().refuseConnect()); + } + + private static TestGateways.Harness harnessOver(ScriptedTransport transport) { + return TestGateways.forProfile( + ClientProfiles.builder(PROFILE).baseUrl(BASE_URL).build(), + CredentialProviderRegistry.withNoAuth(), + transport); + } + + private record ScriptedUpstream(ScriptedTransport transport) implements Upstream { + + @Override + public URI baseUrl() { + return BASE_URL; + } + + @Override + public void respondJson(int status, String body) { + transport.json(status, body); + } + + @Override + public void respondStatus(int status) { + transport.status(status); + } + + @Override + public String nextRequestPath() { + return transport.sent().getFirst().uri().getRawPath(); + } + + @Override + public int requestCount() { + return transport.sent().size(); + } + + @Override + public void close() {} + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/StableTransportProviderContractTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/StableTransportProviderContractTest.java new file mode 100644 index 00000000..1d645d0d --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/StableTransportProviderContractTest.java @@ -0,0 +1,56 @@ +package dev.caskeleton.adapter.outbound.httpclient.contract; + +import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType; +import dev.caskeleton.adapter.outbound.httpclient.testkit.BlockingTransportProviderContract; +import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; +import dev.caskeleton.adapter.outbound.httpclient.testkit.HttpClientContract; +import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; +import java.net.URI; +import java.util.List; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * The transport contract against every selected Stable engine, over a real loopback socket (design + * §28.2, §33). + * + *

        Selection is explicit and fail-closed: {@code -Phttpclient.contract.transports} names the + * engines, an empty or unknown selection is an error ({@link HttpClientContract}), and a class run + * with no engine at all fails rather than passing on nothing. Each selected engine runs every + * inherited contract test. The scripted fake passes the same contract in {@link + * ScriptedTransportContractTest}. + */ +@Tag("httpclient-contract") +@ParameterizedClass +@MethodSource("transports") +class StableTransportProviderContractTest extends BlockingTransportProviderContract { + + @Parameter String transport; + + static List transports() { + return HttpClientContract.selectedTransports(); + } + + @Override + protected Upstream upstream() { + return serverUpstream(); + } + + @Override + protected TestGateways.Harness harness(Upstream upstream) { + return harnessAt(upstream.baseUrl()); + } + + @Override + protected TestGateways.Harness unreachableHarness() { + return harnessAt(unusedLoopbackTarget()); + } + + private TestGateways.Harness harnessAt(URI baseUrl) { + TransportType type = "jdk".equals(transport) ? TransportType.JDK : TransportType.APACHE; + return TestGateways.forProfile( + ClientProfiles.builder(PROFILE).baseUrl(baseUrl).transport(type).build()); + } +} diff --git a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/BlockingTransportContract.java b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/BlockingTransportContract.java deleted file mode 100644 index 2825537c..00000000 --- a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/BlockingTransportContract.java +++ /dev/null @@ -1,109 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.testkit; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; -import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpClientException; -import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpConnectException; -import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; -import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; -import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; -import dev.caskeleton.adapter.outbound.httpclient.api.result.HttpCallResult; -import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType; -import java.io.IOException; -import java.net.ServerSocket; -import java.net.URI; -import java.util.Map; - -/** - * The semantic contract every Stable blocking transport must satisfy (design §28.2, §33). - * - *

        Written once and executed against each transport: identical stable metadata across engines is - * the design's central portability claim, and a per-transport test suite could never prove it. - */ -public final class BlockingTransportContract { - - private BlockingTransportContract() {} - - public static void methodAndTemplateEncoding(TestGateways.Harness harness, MockHttpServer server) - throws Exception { - server.enqueueJson(200, "{\"id\":42,\"name\":\"ada\"}"); - HttpCallResult result = - harness - .gateway() - .exchange( - harness.profile().name(), - HttpOperation.get(new OperationName("get-user"), "/users/{id}", Map.of("id", 42)), - ResponseType.of(UserResponse.class)); - assertThat(result.status().value()).isEqualTo(200); - assertThat(result.attempts()).isEqualTo(1); - assertThat(result.evidence()).isEqualTo(ExecutionEvidence.RESPONSE_RECEIVED); - assertThat(server.takeRequest(java.time.Duration.ofSeconds(2)).path()).isEqualTo("/users/42"); - } - - public static void connectFailureIsProvenNotSent( - java.util.function.Function harnessFactory) { - URI blackhole = unusedLoopbackTarget(); - try (TestGateways.Harness harness = harnessFactory.apply(blackhole)) { - HttpClientException failure = - org.assertj.core.api.Assertions.catchThrowableOfType( - HttpClientException.class, - () -> - harness - .gateway() - .exchange( - harness.profile().name(), - HttpOperation.get(new OperationName("probe"), "/probe", Map.of()), - ResponseType.of(String.class))); - assertThat(failure).isNotNull(); - assertThat(failure.metadata().stage()).isEqualTo(AttemptStage.CONNECT); - assertThat(failure.metadata().evidence()).isEqualTo(ExecutionEvidence.NOT_SENT); - assertThat(failure).isInstanceOf(HttpConnectException.class); - } - } - - public static void absoluteUriIsRejectedBeforeAnyRequest( - TestGateways.Harness harness, MockHttpServer server) { - assertThatThrownBy( - () -> - harness - .gateway() - .exchange( - harness.profile().name(), - HttpOperation.get( - new OperationName("probe"), "https://evil.example.com/", Map.of()), - ResponseType.of(String.class))) - .isInstanceOf( - dev.caskeleton.adapter.outbound.httpclient.api.error.HttpTargetRejectedException.class); - assertThat(server.requestCount()).isZero(); - } - - public static void errorStatusBecomesAStableException( - TestGateways.Harness harness, MockHttpServer server) { - server.enqueueStatus(500); - HttpClientException failure = - org.assertj.core.api.Assertions.catchThrowableOfType( - HttpClientException.class, - () -> - harness - .gateway() - .exchange( - harness.profile().name(), - HttpOperation.get(new OperationName("get-user"), "/users/1", Map.of()), - ResponseType.of(UserResponse.class))); - assertThat(failure).isNotNull(); - assertThat(failure.metadata().status()).isPresent(); - assertThat(failure.metadata().evidence()).isEqualTo(ExecutionEvidence.RESPONSE_RECEIVED); - assertThat(failure.getMessage()).doesNotContain("http://").doesNotContain("https://"); - } - - /** A port that is bound and immediately closed: connecting to it is refused, not blackholed. */ - public static URI unusedLoopbackTarget() { - try (ServerSocket socket = new ServerSocket(0)) { - return URI.create("http://127.0.0.1:" + socket.getLocalPort() + "/"); - } catch (IOException failure) { - throw new IllegalStateException("could not reserve a loopback port", failure); - } - } -} diff --git a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/BlockingTransportProviderContract.java b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/BlockingTransportProviderContract.java new file mode 100644 index 00000000..94ecdb38 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/BlockingTransportProviderContract.java @@ -0,0 +1,303 @@ +package dev.caskeleton.adapter.outbound.httpclient.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus; +import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpClientException; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpConnectException; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpTargetRejectedException; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; +import dev.caskeleton.adapter.outbound.httpclient.api.result.HttpCallResult; +import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType; +import dev.caskeleton.adapter.outbound.httpclient.transport.BlockingTransportProvider; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.ServerSocket; +import java.net.URI; +import java.time.Duration; +import java.util.Map; +import java.util.Optional; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * The semantic contract every {@link BlockingTransportProvider} satisfies (design §28.2, §33). + * + *

        The transport is the HTTP client platform's port: the gateway above it owns templates, target + * policy, retry and error mapping, and a transport only moves one request and reports what it can + * prove about it. Identical stable metadata across engines is the design's central portability + * claim, so the claim is written once, here, and every implementation inherits it: the Apache and + * JDK engines against a real socket ({@code StableTransportProviderContractTest}), the scripted + * fake the gateway tests stand on ({@code ScriptedTransportContractTest}), and a transport a + * derived service adds. A fake that drifted from the engines would let a gateway test pass for a + * behaviour no deployment has (AGENTS.md rule 6; review 2026-11-01 05-16). + * + *

        An implementation supplies the {@link Upstream} its transport talks to — a server for an + * engine, a script for a fake — and a gateway over the transport. + */ +public abstract class BlockingTransportProviderContract { + + /** The client profile every contract call is made through. */ + protected static final String PROFILE = "users"; + + private static final Duration RECEIVE_WAIT = Duration.ofSeconds(2); + + private Upstream upstream; + private TestGateways.Harness harness; + private TestGateways.Harness unreachable; + + /** + * The other end of the transport, as the contract needs to see it. + * + *

        For an engine this is a real server; for a fake it is the fake's script and its record of + * what was sent. The contract only scripts answers and reads what arrived. + */ + public interface Upstream extends AutoCloseable { + + /** + * Returns the base URL a profile reaches this upstream at. + * + * @return the base URL + */ + URI baseUrl(); + + /** + * Queues a JSON answer for the next request. + * + * @param status the status + * @param body the JSON body + */ + void respondJson(int status, String body); + + /** + * Queues a bodiless answer for the next request. + * + * @param status the status + */ + void respondStatus(int status); + + /** + * Returns the path of the next request that arrived, failing when none did. + * + * @return the raw path + */ + String nextRequestPath(); + + /** + * Returns how many requests arrived. + * + * @return the count + */ + int requestCount(); + + @Override + void close(); + } + + /** + * Opens the upstream one contract test talks to. + * + * @return a fresh upstream + */ + protected abstract Upstream upstream(); + + /** + * Builds a gateway serving profile {@value #PROFILE} at the upstream's base URL through the + * transport under test. + * + * @param upstream the upstream + * @return the harness + */ + protected abstract TestGateways.Harness harness(Upstream upstream); + + /** + * Builds a gateway serving profile {@value #PROFILE} through the transport under test at a target + * that refuses the connection. + * + * @return the harness + */ + protected abstract TestGateways.Harness unreachableHarness(); + + @BeforeEach + void openUpstream() { + upstream = upstream(); + harness = harness(upstream); + } + + @AfterEach + void closeUpstream() { + harness.close(); + upstream.close(); + if (unreachable != null) { + unreachable.close(); + } + } + + @Test + void aTemplatedGetIsAnsweredWithTheUpstreamsStatusInOneAttempt() { + // given + upstream.respondJson(200, "{\"id\":42,\"name\":\"ada\"}"); + + // when + HttpCallResult result = getUser(harness, "/users/{id}", Map.of("id", 42)); + + // then + assertThat(result) + .extracting(HttpCallResult::status, HttpCallResult::attempts, HttpCallResult::evidence) + .containsExactly(new HttpStatus(200), 1, ExecutionEvidence.RESPONSE_RECEIVED); + } + + @Test + void aTemplatedGetReachesTheUpstreamWithItsVariableExpanded() { + // given + upstream.respondJson(200, "{\"id\":42,\"name\":\"ada\"}"); + getUser(harness, "/users/{id}", Map.of("id", 42)); + + // when + String path = upstream.nextRequestPath(); + + // then + assertThat(path).isEqualTo("/users/42"); + } + + @Test + void aRefusedConnectionIsAConnectFailureProvenNotSent() { + // given + unreachable = unreachableHarness(); + + // when + Throwable failure = catchThrowable(() -> getUser(unreachable, "/users/1", Map.of())); + + // then + assertThat(failure) + .isInstanceOf(HttpConnectException.class) + .extracting( + thrown -> ((HttpClientException) thrown).metadata().stage(), + thrown -> ((HttpClientException) thrown).metadata().evidence()) + .containsExactly(AttemptStage.CONNECT, ExecutionEvidence.NOT_SENT); + } + + @Test + void anAbsoluteUriIsRejectedBeforeAnyRequestLeaves() { + // when + Throwable failure = + catchThrowable(() -> getUser(harness, "https://evil.example.com/", Map.of())); + + // then + assertThat(failure).isInstanceOf(HttpTargetRejectedException.class); + assertThat(upstream.requestCount()).isZero(); + } + + @Test + void anErrorStatusFailsWithTheStatusAndTheResponseAsEvidence() { + // given + upstream.respondStatus(500); + + // when + Throwable failure = catchThrowable(() -> getUser(harness, "/users/1", Map.of())); + + // then + assertThat(failure) + .isInstanceOf(HttpClientException.class) + .extracting( + thrown -> ((HttpClientException) thrown).metadata().status(), + thrown -> ((HttpClientException) thrown).metadata().evidence()) + .containsExactly(Optional.of(new HttpStatus(500)), ExecutionEvidence.RESPONSE_RECEIVED); + } + + @Test + void anErrorStatusFailureNamesNoUrl() { + // given + upstream.respondStatus(500); + + // when + Throwable failure = catchThrowable(() -> getUser(harness, "/users/1", Map.of())); + + // then + assertThat(failure.getMessage()).doesNotContain("http://").doesNotContain("https://"); + } + + /** + * Opens an upstream on a real loopback server, for an engine's contract test. + * + * @return the upstream + */ + public static Upstream serverUpstream() { + try { + return new ServerUpstream(MockHttpServer.start()); + } catch (IOException failure) { + throw new UncheckedIOException("could not start the contract server", failure); + } + } + + /** + * Returns a port that is bound and immediately closed: connecting to it is refused, not + * blackholed. + * + * @return the target + */ + public static URI unusedLoopbackTarget() { + try (ServerSocket socket = new ServerSocket(0)) { + return URI.create("http://127.0.0.1:" + socket.getLocalPort() + "/"); + } catch (IOException failure) { + throw new IllegalStateException("could not reserve a loopback port", failure); + } + } + + private static HttpCallResult getUser( + TestGateways.Harness gateway, String template, Map variables) { + return gateway + .gateway() + .exchange( + gateway.profile().name(), + HttpOperation.get(new OperationName("get-user"), template, variables), + ResponseType.of(UserResponse.class)); + } + + private record ServerUpstream(MockHttpServer server) implements Upstream { + + @Override + public URI baseUrl() { + return server.uri("/"); + } + + @Override + public void respondJson(int status, String body) { + server.enqueueJson(status, body); + } + + @Override + public void respondStatus(int status) { + server.enqueueStatus(status); + } + + @Override + public String nextRequestPath() { + try { + return server.takeRequest(RECEIVE_WAIT).path(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted waiting for a request", interrupted); + } + } + + @Override + public int requestCount() { + return server.requestCount(); + } + + @Override + public void close() { + try { + server.close(); + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + } + } +} diff --git a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ScriptedTransport.java b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ScriptedTransport.java index 92e217d6..f9619465 100644 --- a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ScriptedTransport.java +++ b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/ScriptedTransport.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.httpclient.testkit; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; import dev.caskeleton.adapter.outbound.httpclient.profile.HttpProtocol; @@ -12,6 +13,7 @@ import dev.caskeleton.adapter.outbound.httpclient.transport.TransportId; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportLifecycleListener; import java.io.ByteArrayInputStream; import java.io.InputStream; +import java.net.ConnectException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Deque; @@ -34,6 +36,11 @@ import org.springframework.http.client.ClientHttpResponse; *

        No socket is opened, so a test can drive redirect hops across hosts that do not exist and * assert on exactly what each hop carried. It declares every capability, so it can stand in for any * transport type, including one serving a Dynamic Target. + * + *

        It passes the same {@link BlockingTransportProviderContract} the Apache and JDK engines pass + * ({@code ScriptedTransportContractTest}), so a gateway test standing on it stands on a transport + * that behaves like the real ones where the contract speaks: a refused connection proven not sent, + * an answered request reported as answered. */ public final class ScriptedTransport implements BlockingTransportProvider { @@ -46,7 +53,12 @@ public final class ScriptedTransport implements BlockingTransportProvider { } } - private record Reply(int status, Map headers, String body) {} + private record Reply(int status, Map headers, String body, boolean refused) { + + private Reply(int status, Map headers, String body) { + this(status, headers, body, false); + } + } private final Deque replies = new ConcurrentLinkedDeque<>(); private final List sent = new CopyOnWriteArrayList<>(); @@ -61,6 +73,28 @@ public final class ScriptedTransport implements BlockingTransportProvider { return this; } + /** + * Answers the next request with a status and no body. + * + * @param status the status + * @return this transport + */ + public ScriptedTransport status(int status) { + replies.add(new Reply(status, Map.of(), "")); + return this; + } + + /** + * Refuses the next request's connection, as an engine does when nothing listens: the request is + * not recorded as sent, and the failure classifies as a connect failure proven not sent. + * + * @return this transport + */ + public ScriptedTransport refuseConnect() { + replies.add(new Reply(0, Map.of(), "", true)); + return this; + } + public List sent() { return List.copyOf(sent); } @@ -84,7 +118,15 @@ public final class ScriptedTransport implements BlockingTransportProvider { @Override public TransportFailureClassifier failureClassifier() { - return (failure, stage) -> TransportFailure.notSent(stage, FailureCategory.UNKNOWN, "scripted"); + return (failure, stage) -> { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof ConnectException) { + return TransportFailure.notSent( + AttemptStage.CONNECT, FailureCategory.CONNECT, "CONNECT_FAILED"); + } + } + return TransportFailure.notSent(stage, FailureCategory.UNKNOWN, "scripted"); + }; } @Override @@ -111,7 +153,13 @@ public final class ScriptedTransport implements BlockingTransportProvider { } @Override - protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) { + protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) + throws ConnectException { + Reply next = replies.peek(); + if (next != null && next.refused()) { + replies.poll(); + throw new ConnectException("scripted: connection refused for " + uri); + } Map> copy = new LinkedHashMap<>(); headers.forEach((name, values) -> copy.put(name, List.copyOf(values))); sent.add( diff --git a/src/adapter/outbound/identifier/CLAUDE.md b/src/adapter/outbound/identifier/CLAUDE.md index f89d9805..0c1a7c11 100644 --- a/src/adapter/outbound/identifier/CLAUDE.md +++ b/src/adapter/outbound/identifier/CLAUDE.md @@ -27,6 +27,9 @@ build choices) live in [README.md](README.md). ## Allowed - `:application-core` (declared in [build.gradle](build.gradle)); the registry entry is the SSOT. +- `:shared-contract`, for `HmacSha256` only (review 2026-11-01 01-11). The pseudonym is the hex HMAC + of the principal; `HmacUserPrincipalPseudonymizerVectorTest` pins it to a vector computed outside + the JVM, because logs written before and after a release are joined on it. ## Forbidden diff --git a/src/adapter/outbound/identifier/build.gradle b/src/adapter/outbound/identifier/build.gradle index 138a95cf..577351c6 100644 --- a/src/adapter/outbound/identifier/build.gradle +++ b/src/adapter/outbound/identifier/build.gradle @@ -7,6 +7,8 @@ plugins { // resolved the Fileserver use cases. It lives with the capability now. dependencies { implementation project(':application-core') + // HmacSha256 for the pseudonym (review 2026-11-01 01-11). + implementation project(':shared-contract') // A feature's server-assigned id adapter implements its domain `*IdFactory` port here // (registry edge `adapter:outbound:identifier -> domain-core`); docs/manual/02-new-feature.md. implementation project(':domain-core') diff --git a/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizer.java b/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizer.java index 53bd99d0..8b6fc4b0 100644 --- a/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizer.java +++ b/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizer.java @@ -1,12 +1,8 @@ package dev.caskeleton.adapter.outbound.identifier; import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort; -import java.nio.charset.StandardCharsets; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; +import dev.caskeleton.shared.digest.HmacSha256; import java.util.HexFormat; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; /** * HMAC-SHA-256 implementation of {@link UserPrincipalPseudonymizerPort}: returns a stable @@ -15,17 +11,14 @@ import javax.crypto.spec.SecretKeySpec; */ public final class HmacUserPrincipalPseudonymizer implements UserPrincipalPseudonymizerPort { - private static final String ALGORITHM = "HmacSHA256"; - - private final SecretKeySpec key; + private final byte[] key; public HmacUserPrincipalPseudonymizer(byte[] salt) { if (salt == null || salt.length == 0) { throw new IllegalArgumentException( "HMAC salt must not be null or empty — supplied by APP_PRIVACY_PSEUDONYMIZATION_SALT"); } - byte[] saltCopy = salt.clone(); // defensive copy; caller's array is not retained - this.key = new SecretKeySpec(saltCopy, ALGORITHM); + this.key = salt.clone(); // defensive copy; caller's array is not retained } @Override @@ -34,15 +27,7 @@ public final class HmacUserPrincipalPseudonymizer implements UserPrincipalPseudo return null; } - try { - Mac mac = Mac.getInstance(ALGORITHM); // Mac is not thread-safe — fresh instance per call - mac.init(key); - byte[] digest = mac.doFinal(rawPrincipal.getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(digest); - } catch (NoSuchAlgorithmException | InvalidKeyException e) { - // Unreachable: HmacSHA256 is a mandatory JDK algorithm and the key spec is valid. - throw new IllegalStateException( - "HmacSHA256 unavailable or key invalid — this should never happen on a compliant JDK", e); - } + // shared-contract's one HMAC-SHA256 (review 2026-11-01 01-11); it takes a fresh Mac per call. + return HexFormat.of().formatHex(HmacSha256.sign(key, rawPrincipal)); } } diff --git a/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizerVectorTest.java b/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizerVectorTest.java new file mode 100644 index 00000000..ce005a54 --- /dev/null +++ b/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/HmacUserPrincipalPseudonymizerVectorTest.java @@ -0,0 +1,32 @@ +package dev.caskeleton.adapter.outbound.identifier; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The pseudonym is a published, stable value: logs and audit rows written before a release are + * joined with ones written after it. This pins the exact output against a vector computed outside + * the JVM (Python {@code hmac.new(salt, principal, sha256).hexdigest()}), so moving the computation + * onto shared-contract's {@code HmacSha256} (review 2026-11-01 01-11) cannot change it. + */ +class HmacUserPrincipalPseudonymizerVectorTest { + + @Test + @DisplayName("가명은 salt와 principal의 HMAC-SHA256 소문자 hex로 이전 출력과 같다") + void thePseudonymIsTheLowercaseHexHmacOfThePrincipal() { + // given + HmacUserPrincipalPseudonymizer pseudonymizer = + new HmacUserPrincipalPseudonymizer( + "pseudonymization-salt".getBytes(StandardCharsets.UTF_8)); + + // when + String pseudonym = pseudonymizer.pseudonymize("alice@example.com"); + + // then + assertThat(pseudonym) + .isEqualTo("5e825434952f19c942279f7168c8c684833f3d12b119b5fc36db51526ea14944"); + } +} diff --git a/src/adapter/outbound/messaging-kafka/build.gradle b/src/adapter/outbound/messaging-kafka/build.gradle index bba266f8..e80caa39 100644 --- a/src/adapter/outbound/messaging-kafka/build.gradle +++ b/src/adapter/outbound/messaging-kafka/build.gradle @@ -75,10 +75,12 @@ strictTestLanes { requires 'dev.caskeleton.adapter.outbound.messaging.kafka.relay.ApplicationRelayKafkaIntegrationTest' rejectSkipped = true jvmArgs '-Duser.timezone=UTC' - // Pinned like the platform's certification lane: a red run must name the broker it ran on. - // Not under messaging.*: the platform refuses any property with that old prefix at startup. + // The image is config/testing/container-images.properties' `kafka` (digest-pinned, review + // 08-04), as for every other Kafka lane; -PmessagingKafkaImage overrides it like the + // platform's certification lane. Not under messaging.*: the platform refuses any property + // with that old prefix at startup. systemProperty 'relayLane.kafkaImage', - (project.findProperty('messagingKafkaImage') ?: 'apache/kafka:4.1.0').toString() + (project.findProperty('messagingKafkaImage') ?: testContainerImages['kafka']).toString() shouldRunAfter 'test' } } diff --git a/src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java b/src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java index 67f7fdd1..bd113251 100644 --- a/src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java +++ b/src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java @@ -69,7 +69,9 @@ class ApplicationRelayKafkaIntegrationTest { @BeforeAll static void startBroker() throws Exception { - kafka = new KafkaContainer(System.getProperty("relayLane.kafkaImage", "apache/kafka:4.1.0")); + kafka = + new KafkaContainer( + System.getProperty("relayLane.kafkaImage", System.getProperty("ca.test.image.kafka"))); kafka.start(); Properties admin = new Properties(); admin.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers()); diff --git a/src/adapter/outbound/messaging/build.gradle b/src/adapter/outbound/messaging/build.gradle index c7e3fdd7..e768936c 100644 --- a/src/adapter/outbound/messaging/build.gradle +++ b/src/adapter/outbound/messaging/build.gradle @@ -13,6 +13,9 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-json' implementation 'org.slf4j:slf4j-api' + // The application port owner's publish contracts and fakes (TEST-F-1): the bridges inherit the + // contracts the fakes are held to. + testImplementation testFixtures(project(':application-core')) // Test-only: MessagingEvidenceSchemaValidatorTest holds the common evidence schema to Draft 2020-12. testImplementation libs.json.schema.validator // Test-only (owner decision 29): MessagingCapabilityRegistryContractTest reads the capability diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java index ef3443d9..63097de6 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapterTest.java @@ -3,76 +3,74 @@ package dev.caskeleton.adapter.outbound.messaging.outbox; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.event.AggregateIdentity; -import dev.caskeleton.application.messaging.event.AggregateOrder; -import dev.caskeleton.application.messaging.event.EventId; -import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.messaging.event.testkit.BrokerAnswer; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventPublisher; import dev.caskeleton.application.outbox.ClaimedOutboxEvent; -import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.application.outbox.OutboxPublishAmbiguousException; import dev.caskeleton.application.outbox.OutboxPublishOutcome; import dev.caskeleton.application.outbox.OutboxPublishRefusedException; -import dev.caskeleton.shared.digest.Sha256; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.ArrayList; +import dev.caskeleton.application.outbox.testkit.OutboxMessagePublishContract; import java.util.List; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -class OutboxMessagePublishAdapterTest { +/** + * The relay's publish port over the canonical one, held to {@link OutboxMessagePublishContract} + * (review 2026-11-01 TEST-F-1), plus what only this adapter promises: the exception types the + * throwing method uses. + */ +class OutboxMessagePublishAdapterTest extends OutboxMessagePublishContract { - private final RecordingCanonicalPublisher canonical = new RecordingCanonicalPublisher(); - private final OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(canonical); + private final FakeIntegrationEventPublisher canonical = new FakeIntegrationEventPublisher(); + + @Override + protected OutboxMessagePublishPort publisherOverABrokerThat(BrokerAnswer answer) { + canonical.answering(FakeIntegrationEventPublisher.outcomeOf(answer)); + return new OutboxMessagePublishAdapter(canonical); + } + + @Override + protected List eventIdsTheBrokerReceived() { + return canonical.published().stream().map(event -> event.eventId().value()).toList(); + } @Test + @DisplayName("claim한 행은 다시 그리지 않고 그 행이 담은 검증된 event 그대로 넘긴다") void aClaimedRowIsPublishedAsTheExactValidatedEventItCarries() { // given - ClaimedOutboxEvent claim = claim(); + OutboxMessagePublishPort adapter = publisherOverABrokerThat(BrokerAnswer.CONFIRMS); + ClaimedOutboxEvent claim = claimedRow(); // when adapter.publishForOutcome(claim); // then - assertThat(canonical.events).containsExactly(claim.event()); - } - - @Test - void thePlatformOutcomeIsPassedThroughUnchanged() { - // given - canonical.result = OutboxPublishOutcome.REJECTED_AFTER_BROKER; - - // when - OutboxPublishOutcome outcome = adapter.publishForOutcome(claim()); - - // then - assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_AFTER_BROKER); + assertThat(canonical.published()).containsExactly(claim.event()); } @Test + @DisplayName("확인을 받지 못한 발행은 예외로 알리는 메서드에서 AMBIGUOUS 신호를 던진다") void anAmbiguousPublishThrowsTheAmbiguousSignalFromTheThrowingMethod() { // given - canonical.result = OutboxPublishOutcome.AMBIGUOUS; + OutboxMessagePublishPort adapter = publisherOverABrokerThat(BrokerAnswer.NEVER_CONFIRMS); // when - Throwable thrown = catchThrowable(() -> adapter.publish(claim())); + Throwable thrown = catchThrowable(() -> adapter.publish(claimedRow())); // then assertThat(thrown).isInstanceOf(OutboxPublishAmbiguousException.class); } @Test + @DisplayName("거부된 발행은 예외로 알리는 메서드에서 그 거부의 결과를 담아 던진다") void aRefusedPublishThrowsTheRefusalWithItsOutcome() { // given - canonical.result = OutboxPublishOutcome.REJECTED_BEFORE_SEND; + OutboxMessagePublishPort adapter = + publisherOverABrokerThat(BrokerAnswer.REFUSES_BEFORE_SENDING); // when - Throwable thrown = catchThrowable(() -> adapter.publish(claim())); + Throwable thrown = catchThrowable(() -> adapter.publish(claimedRow())); // then assertThat(thrown) @@ -80,44 +78,4 @@ class OutboxMessagePublishAdapterTest { .extracting("outcome") .isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND); } - - private static ClaimedOutboxEvent claim() { - String partition = "a".repeat(64); - byte[] envelope = "{\"wire\":\"exact\"}".getBytes(StandardCharsets.UTF_8); - Sha256 zero = new Sha256(new byte[32]); - ValidatedIntegrationEvent event = - new ValidatedIntegrationEvent( - new EventId("01994e11-4d88-7000-8000-000000000001"), - new ContractId("portfolio.worklog.reserved"), - 1, - 1, - new LogicalDestinationId("portfolio-domain-events"), - new AggregateIdentity("tenant-a", "worklog", "worklog-42"), - new AggregateOrder(17, 2), - Instant.parse("2026-09-18T03:00:00Z"), - "corr-1", - Optional.empty(), - partition, - partition.getBytes(StandardCharsets.US_ASCII), - envelope, - "application/json", - zero, - Sha256.of(envelope), - zero, - zero, - "catalog-r1", - "binding-r1"); - return new ClaimedOutboxEvent(event, OutboxEventStatus.IN_FLIGHT, 1); - } - - private static final class RecordingCanonicalPublisher implements IntegrationEventPublishPort { - private final List events = new ArrayList<>(); - private OutboxPublishOutcome result = OutboxPublishOutcome.CONFIRMED; - - @Override - public CompletionStage publish(ValidatedIntegrationEvent event) { - events.add(event); - return CompletableFuture.completedFuture(result); - } - } } diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java index b8f248ac..41564585 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java @@ -10,6 +10,8 @@ import dev.caskeleton.application.messaging.event.AggregateOrder; import dev.caskeleton.application.messaging.event.EventId; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.messaging.event.testkit.BrokerAnswer; +import dev.caskeleton.application.messaging.event.testkit.IntegrationEventPublishContract; import dev.caskeleton.application.outbox.OutboxPublishOutcome; import dev.caskeleton.messaging.api.ContentType; import dev.caskeleton.messaging.api.MessageEnvelope; @@ -29,6 +31,8 @@ import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; +import java.util.ArrayList; +import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -38,7 +42,13 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -class PlatformIntegrationEventPublishAdapterTest { +/** + * The platform bridge, held to {@link IntegrationEventPublishContract} over a scripted platform + * publisher (review 2026-11-01 TEST-F-1), plus the mapping only a bridge has: identity, routing and + * the exact envelope bytes. The real broker path is the Kafka relay lane in {@code + * adapter:outbound:messaging-kafka}. + */ +class PlatformIntegrationEventPublishAdapterTest extends IntegrationEventPublishContract { private static final String EVENT_ID = "0190f4aa-0000-7000-8000-000000000001"; private static final String CAUSATION_ID = "0190f4aa-0000-7000-8000-000000000002"; @@ -239,6 +249,36 @@ class PlatformIntegrationEventPublishAdapterTest { "binding-r1"); } + private RecordingPublisher broker; + + @Override + protected IntegrationEventPublishPort publisherOverABrokerThat(BrokerAnswer answer) { + broker = + new RecordingPublisher( + switch (answer) { + case CONFIRMS -> confirmed(); + case NEVER_CONFIRMS -> ambiguous(); + case REFUSES_FOR_NOW -> + PublishResult.rejected( + Duration.ZERO, + FailureDescriptor.of( + FailureCategory.TRANSIENT_INFRASTRUCTURE, + "SHUTTING_DOWN", + "the messaging runtime stopped accepting new publishes")); + case REFUSES_BEFORE_SENDING -> rejected(PublishEvidence.notTransmitted()); + case REFUSES_AFTER_RECEIVING -> + rejected( + new PublishEvidence( + true, TransmissionEvidence.TRANSMITTED, false, ConfirmationLevel.NONE)); + }); + return new PlatformIntegrationEventPublishAdapter(broker, "contract-service"); + } + + @Override + protected List eventIdsTheBrokerReceived() { + return List.copyOf(broker.received); + } + private static PublishResult confirmed() { return new PublishResult( PublishCompletion.CONFIRMED, @@ -277,6 +317,7 @@ class PlatformIntegrationEventPublishAdapterTest { private static final class RecordingPublisher implements EncodedMessagePublisher { private PublishResult result; private int calls; + private final List received = new ArrayList<>(); private MessageDestination destination; private MessageEnvelope envelope; @@ -290,6 +331,7 @@ class PlatformIntegrationEventPublishAdapterTest { MessageEnvelope message, PublishOptions options) { calls++; + received.add(message.messageId().value().toString()); this.destination = destination; this.envelope = message; return CompletableFuture.completedFuture(result); diff --git a/src/adapter/outbound/notification/build.gradle b/src/adapter/outbound/notification/build.gradle index b7fa5aef..0d21c40b 100644 --- a/src/adapter/outbound/notification/build.gradle +++ b/src/adapter/outbound/notification/build.gradle @@ -2,6 +2,7 @@ plugins { id 'ca.spring-library' id 'ca.spring-config' id 'ca.api-surface' + id 'java-test-fixtures' } dependencies { @@ -32,6 +33,11 @@ dependencies { // - jackson-databind: provider payloads, callback bodies and the canonical variables payload are // JSON. It stays inside this adapter; application-core never sees a JSON type. implementation 'org.springframework.boot:spring-boot-starter-mail' + // The Angus SMTP transport the starter already puts on the runtime classpath, on the compile + // classpath too: its exceptions carry the server's reply code (SMTPAddressFailedException and + // friends) and mark a refused connection (MailConnectException). Without them every SMTP + // failure read as "may have been delivered" (review 05-11). + implementation 'org.eclipse.angus:angus-mail' implementation 'org.springframework.boot:spring-boot-starter-json' // JSON Schema 2020-12 validation of template variables, using the same validator and version the // messaging adapter already depends on rather than a second implementation of the same spec. @@ -47,6 +53,15 @@ dependencies { // adapter that renders strings and never serves a request. implementation 'org.thymeleaf:thymeleaf' + // Port contracts live with the port they hold (capability criterion 5): the provider adapter + // contract and its fault harness in application-notification's test fixtures, the callback + // adapter contract in this leaf's own (`callback.testkit`), since ProviderCallbackAdapter is a + // port of this leaf. An adapter in any leaf extends the same contract. + testImplementation testFixtures(project(':application-notification')) + testFixturesImplementation project(':application-notification') + testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' + testFixturesImplementation 'org.assertj:assertj-core' + implementation(libs.json.schema.validator) { exclude group: 'tools.jackson.dataformat', module: 'jackson-dataformat-yaml' exclude group: 'com.fasterxml.jackson.dataformat', module: 'jackson-dataformat-yaml' diff --git a/src/adapter/outbound/notification/gradle.lockfile b/src/adapter/outbound/notification/gradle.lockfile index ebeaae35..d7c50277 100644 --- a/src/adapter/outbound/notification/gradle.lockfile +++ b/src/adapter/outbound/notification/gradle.lockfile @@ -2,73 +2,73 @@ # Manual edits can break the build and are not advised. # This file is expected to be part of source control. biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=compileClasspath,testCompileClasspath -ch.qos.logback:logback-classic:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -com.ethlo.time:itu:1.14.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.f4b6a3:uuid-creator:6.1.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +ch.qos.logback:logback-classic:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.ethlo.time:itu:1.14.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.github.f4b6a3:uuid-creator:6.1.1=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,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,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,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,testAnnotationProcessor +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.errorprone:error_prone_annotations:2.38.0=compileClasspath,testCompileClasspath com.google.errorprone:error_prone_annotations:2.41.0=spotbugs com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,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,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath -com.networknt:json-schema-validator:3.0.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.networknt:json-schema-validator:3.0.2=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle -commons-codec:commons-codec:1.19.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +commons-codec:commons-codec:1.19.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle commons-io:commons-io:2.21.0=spotbugs -commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -jakarta.activation:jakarta.activation-api:2.1.4=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -jakarta.mail:jakarta.mail-api:2.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +jakarta.mail:jakarta.mail-api:2.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=testCompileClasspath,testRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -ognl:ognl:3.3.4=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +ognl:ognl:3.3.4=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.apache.httpcomponents:httpcore:4.4.16=checkstyle,compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.apache.logging.log4j:log4j-api:2.25.5=compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.httpcomponents:httpclient:4.5.13=checkstyle,compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.apache.httpcomponents:httpcore:4.4.16=checkstyle,compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-api:2.25.5=compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.logging.log4j:log4j-to-slf4j:2.25.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.apache.maven.doxia:doxia-core:1.12.0=checkstyle org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle @@ -77,36 +77,36 @@ org.apache.tomcat.embed:tomcat-embed-core:11.0.24=testCompileClasspath,testRunti org.apache.tomcat.embed:tomcat-embed-el:11.0.24=testCompileClasspath,testRuntimeClasspath org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=testCompileClasspath,testRuntimeClasspath org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath -org.attoparser:attoparser:2.0.7.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath,testFixturesCompileClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.attoparser:attoparser:2.0.7.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs -org.eclipse.angus:angus-activation:2.0.3=runtimeClasspath,testRuntimeClasspath -org.eclipse.angus:angus-mail:2.0.5=runtimeClasspath,testRuntimeClasspath +org.eclipse.angus:angus-activation:2.0.3=runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.eclipse.angus:angus-mail:2.0.5=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath -org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle -org.javassist:javassist:3.29.0-GA=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath +org.javassist:javassist:3.29.0-GA=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit:junit-bom:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs -org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath +org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath org.objenesis:objenesis:3.3=testRuntimeClasspath -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.osgi:org.osgi.annotation.bundle:2.0.0=compileClasspath,testCompileClasspath org.osgi:org.osgi.annotation.versioning:1.1.2=compileClasspath,testCompileClasspath org.osgi:org.osgi.resource:1.0.0=compileClasspath,testCompileClasspath @@ -117,83 +117,83 @@ org.ow2.asm:asm-tree:9.10.1=spotbugs org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor -org.reactivestreams:reactive-streams:1.0.4=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +org.reactivestreams:reactive-streams:1.0.4=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath -org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springframework.boot:spring-boot-actuator-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-actuator:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-actuator-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-actuator:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor -org.springframework.boot:spring-boot-health:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-health:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-jackson:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-mail:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-mail:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-json:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-logging:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-mail:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-json:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-mail:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-context-support:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-context-support:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath -org.thymeleaf:thymeleaf:3.1.5.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.unbescape:unbescape:1.1.6.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.thymeleaf:thymeleaf:3.1.5.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.unbescape:unbescape:1.1.6.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath -org.yaml:snakeyaml:2.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:annotations:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:apache-client:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:auth:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:aws-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:aws-json-protocol:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:checksums-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:checksums:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:endpoints-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:http-auth-aws-eventstream:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:http-auth-aws:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:http-auth-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:http-auth:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:http-client-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:identity-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:json-utils:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:metrics-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:profiles:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:protocol-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:regions:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:retries-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:retries:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:sdk-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:sesv2:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:third-party-jackson-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:utils:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.eventstream:eventstream:1.0.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -tools.jackson.core:jackson-core:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -tools.jackson.core:jackson-databind:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -tools.jackson:jackson-bom:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.yaml:snakeyaml:2.5=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:annotations:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:apache-client:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:auth:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:aws-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:aws-json-protocol:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:checksums-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:checksums:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:endpoints-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-aws-eventstream:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-aws:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-client-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:identity-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:json-utils:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:metrics-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:profiles:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:protocol-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:regions:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:retries-spi:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:retries:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:sdk-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:sesv2:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:third-party-jackson-core:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:utils:2.30.0=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.eventstream:eventstream:1.0.1=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +tools.jackson.core:jackson-core:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +tools.jackson:jackson-bom:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath empty= diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java index b9e7e7d6..97cb53a8 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; +import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationUnavailableException; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SnsCertificateProvider; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -71,19 +72,31 @@ class NotificationCallbackProviderConfig { client.send(request, HttpResponse.BodyHandlers.ofInputStream()); try (InputStream body = response.body()) { if (response.statusCode() / 100 != 2) { - throw new IllegalStateException( - "SNS signing certificate fetch failed with HTTP " + response.statusCode()); + throw certificateUnavailable( + new IOException( + "SNS signing certificate fetch failed with HTTP " + response.statusCode())); } return body.readNBytes(MAX_SNS_CERTIFICATE_BYTES); } } catch (IOException unreachable) { - throw new IllegalStateException("SNS signing certificate could not be fetched", unreachable); + throw certificateUnavailable(unreachable); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); - throw new IllegalStateException("SNS signing certificate fetch was interrupted", interrupted); + throw certificateUnavailable(interrupted); } } + /** + * A certificate that could not be fetched says nothing about the message it was meant to verify. + * + *

        It is the "try again later" answer, not a rejection (review 05-20): SNS redelivers a + * callback that got a 5xx, and the next delivery may find the certificate host reachable. It used + * to be an {@code IllegalStateException} that left the endpoint as an unclassified 500. + */ + private static CallbackVerificationUnavailableException certificateUnavailable(Throwable cause) { + return new CallbackVerificationUnavailableException("SNS_CERTIFICATE_UNAVAILABLE", cause); + } + /** * The certificate cache over a fetch. * diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationHealthEndpoint.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationHealthEndpoint.java index e1922006..5ef1ab07 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationHealthEndpoint.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationHealthEndpoint.java @@ -26,7 +26,7 @@ import org.springframework.boot.health.contributor.HealthIndicator; * is public. */ @Endpoint(id = "notifications") -class NotificationHealthEndpoint implements HealthIndicator { +final class NotificationHealthEndpoint implements HealthIndicator { private final NotificationHealthReporter reporter; diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformObservabilityConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformObservabilityConfig.java index 70b102fe..383ed1d9 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformObservabilityConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformObservabilityConfig.java @@ -7,7 +7,6 @@ import dev.caskeleton.adapter.outbound.notification.platform.observation.Logging import dev.caskeleton.adapter.outbound.notification.platform.observation.MicrometerNotificationMetrics; import dev.caskeleton.adapter.outbound.notification.platform.observation.NotificationHealthReporter; import dev.caskeleton.adapter.outbound.notification.platform.observation.NotificationServingThresholds; -import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import dev.caskeleton.application.notification.platform.inbox.NotificationInboxSignalPort; import dev.caskeleton.application.notification.platform.observation.CardinalityGuard; import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; @@ -80,9 +79,12 @@ class NotificationPlatformObservabilityConfig { NotificationProviderAssembly.AssembledPlatform platform, NotificationServingStatePort servingState) { NotificationPlatformSettings.ServingThresholds thresholds = settings.servingThresholds(); + // The profiles the assembly built a runtime for, not every configured one. A disabled profile + // and every profile under INGEST_ONLY has no runtime by design; watching them reported each + // one UNREGISTERED and kept a platform with the shipped defaults DOWN forever. return new NotificationHealthReporter( runtimes, - settings.providers().keySet().stream().map(ProviderProfileId::new).toList(), + runtimes.registeredProfiles(), servingState, platform.routes().keySet(), new NotificationServingThresholds( diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java index d6ac50d5..15e9eb5d 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java @@ -200,7 +200,13 @@ public record NotificationPlatformSettings( public static Callbacks defaults() { // The storable maximum, not the column size: the envelope adds a version byte, a key id, a // nonce and a tag, so a default of 65,536 was a default that could not be stored. - return new Callbacks(false, MAX_BODY_CEILING, Duration.ofMinutes(5)); + // The replay window covers SNS's whole HTTP/S retry period (review 05-20): five minutes + // dropped every bounce and complaint SNS redelivered after an outage longer than that. + return new Callbacks( + false, + MAX_BODY_CEILING, + dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesCallbackAdapter + .SNS_HTTP_RETRY_HORIZON); } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssembly.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssembly.java index d6000da5..b9cb9da7 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssembly.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssembly.java @@ -127,9 +127,15 @@ public final class NotificationProviderAssembly { ? callbackAssembler.assemble(profileId, profile) : null; // INGEST_ONLY is deliberately callback-capable without being dispatch-capable. Building a - // runtime or a route here would make an ingest-only deployment able to send merely because a - // provider transport happened to be present on the classpath. + // runtime here would make an ingest-only deployment able to send merely because a provider + // transport happened to be present on the classpath — so it builds none. + // + // It does record the route. A request is planned at acceptance and delivered later on that + // plan; an ingest-only deployment that recorded no route accepted every request with an empty + // plan, and the SERVING deployment that took over delivered none of them (review 15절, r3-I). + // The channel is a property of the family, so the route name needs no assembler. if (mode == NotificationPlatformMode.INGEST_ONLY) { + claim(routes, claimants, type.channel(), id, profile); if (callback != null) { callbacks.put(id, callback); } @@ -151,15 +157,7 @@ public final class NotificationProviderAssembly { } runtimes.register(assembled.runtime()); - claimants.computeIfAbsent(assembled.channel(), channel -> new ArrayList<>()).add(profileId); - // The marked primary wins outright; otherwise the first (and, once the ambiguity check below - // has run, only) claimant takes the channel. Falling back to putIfAbsent alone would let a - // declared primary lose the route to whichever id sorts first. - if (profile.primaryForChannel()) { - routes.put(assembled.channel(), id); - } else { - routes.putIfAbsent(assembled.channel(), id); - } + claim(routes, claimants, assembled.channel(), id, profile); assembled .callback() .ifPresentOrElse( @@ -179,6 +177,27 @@ public final class NotificationProviderAssembly { runtimes, Map.copyOf(routes), Map.copyOf(callbacks), Map.copyOf(reconciliations), mode); } + /** + * Records that a profile serves a channel. + * + *

        The marked primary wins outright; otherwise the first (and, once the ambiguity check has + * run, only) claimant takes the channel. Falling back to putIfAbsent alone would let a declared + * primary lose the route to whichever id sorts first. + */ + private static void claim( + Map routes, + Map> claimants, + Channel channel, + ProviderProfileId id, + NotificationPlatformSettings.Provider profile) { + claimants.computeIfAbsent(channel, ignored -> new ArrayList<>()).add(id.value()); + if (profile.primaryForChannel()) { + routes.put(channel, id); + } else { + routes.putIfAbsent(channel, id); + } + } + private static String missingAssemblerMessage(String profileId, ProviderType type) { if (type == ProviderType.SMTP) { return "notification provider profile '" @@ -248,7 +267,8 @@ public final class NotificationProviderAssembly { * Everything the composition root needs, built from configuration in one place. * * @param runtimes the registry the dispatch gateway routes through - * @param routes the channel-to-profile map the route planner uses + * @param routes the channel-to-profile map the route planner uses; recorded in INGEST_ONLY too, + * where no runtime exists, so an accepted request carries the route it is later delivered on * @param callbacks callback adapters by profile * @param reconciliations status-query capabilities by profile * @param mode whether this deployment can deliver @@ -272,7 +292,7 @@ public final class NotificationProviderAssembly { /** * Whether this deployment can deliver. * - * @return true when at least one route was assembled + * @return true in SERVING; an INGEST_ONLY deployment records routes but delivers on none */ public boolean serving() { return mode == NotificationPlatformMode.SERVING; diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/CallbackVerificationUnavailableException.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/CallbackVerificationUnavailableException.java new file mode 100644 index 00000000..6d90a2e4 --- /dev/null +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/CallbackVerificationUnavailableException.java @@ -0,0 +1,39 @@ +package dev.caskeleton.adapter.outbound.notification.platform.callback; + +import java.util.Objects; + +/** + * Verification could not be carried out now; the callback was neither accepted nor rejected. + * + *

        An invalid callback is answered once and for good, and a provider that is told "rejected" does + * not send it again. A callback whose signing material could not be fetched is a different case: + * nothing is known about it yet, and the only answer that keeps the event is "try again later" + * (review 05-20). An SNS certificate fetch that failed used to escape as an {@code + * IllegalStateException} and leave as an unclassified 500. + */ +public final class CallbackVerificationUnavailableException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private final String reasonCode; + + /** + * Creates the failure. + * + * @param reasonCode a stable, content-free code for audit and metrics + * @param cause what made verification impossible + */ + public CallbackVerificationUnavailableException(String reasonCode, Throwable cause) { + super("callback verification unavailable: " + reasonCode, cause); + this.reasonCode = Objects.requireNonNull(reasonCode, "reasonCode"); + } + + /** + * The stable reason code. + * + * @return the code + */ + public String reasonCode() { + return reasonCode; + } +} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/ProviderCallbackAdapter.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/ProviderCallbackAdapter.java index 16a6c264..43ca7c6e 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/ProviderCallbackAdapter.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/callback/ProviderCallbackAdapter.java @@ -9,6 +9,14 @@ public interface ProviderCallbackAdapter { ProviderId providerId(); + /** + * Verifies one raw callback. + * + * @param request the raw callback + * @return valid, or invalid with a reason — an answer the provider is not asked to repeat + * @throws CallbackVerificationUnavailableException when the verification itself could not run now + * (signing material unreachable); the provider should deliver the callback again + */ CallbackVerificationResult verify(ProviderCallbackVerificationRequest request); List normalize(VerifiedCallback callback); diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistry.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistry.java index 75413b6a..06a75c75 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistry.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistry.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.notification.platform.dispatch; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import dev.caskeleton.application.notification.platform.provider.ProviderRuntimeState; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; @@ -57,6 +58,20 @@ public final class ProviderRuntimeRegistry implements AutoCloseable { return Optional.ofNullable(current.get(profileId)); } + /** + * The profiles that have a runtime, in profile-id order. + * + *

        What the assembly actually built: an enabled profile in a dispatching mode. A configured but + * disabled profile, and every profile under {@code INGEST_ONLY}, has none, so it is not here. + * + * @return the registered profile ids + */ + public List registeredProfiles() { + return current.keySet().stream() + .sorted(Comparator.comparing(ProviderProfileId::value)) + .toList(); + } + /** * Swap in a new generation and start draining the old one. * diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java index 1124d0fc..78e583ae 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationResult; +import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationUnavailableException; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapter; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackVerificationRequest; import dev.caskeleton.adapter.outbound.notification.platform.callback.VerifiedCallback; @@ -29,9 +30,24 @@ import tools.jackson.databind.JsonNode; * and have AWS sign for it, and a signed message stays signed forever. So the topic must be one * this profile subscribed to, and the message must be recent, before the signature is even checked * — which also keeps an unwanted message from triggering a certificate fetch. + * + *

        "Recent" is measured against how long SNS keeps redelivering, not against clock skew. SNS + * retries an HTTP/S delivery that got no 2xx with the original {@code Timestamp} (it is part of the + * signed string), for up to {@link #SNS_HTTP_RETRY_HORIZON}. A window of five minutes threw away + * every bounce and complaint that arrived after an outage longer than that, and with them the + * suppressions they should have created (review 05-20). Accepting a replay inside the window costs + * nothing: the provider event ledger is unique on {@code (provider_profile_id, provider_event_id)}, + * so a second delivery of the same event is a duplicate, not a second event. */ public final class SesCallbackAdapter implements ProviderCallbackAdapter { + /** + * The longest an SNS HTTP/S delivery policy may keep retrying: AWS caps the total retry time of + * an HTTP/S endpoint at 3,600 seconds and does not raise it. A message older than this is not a + * redelivery SNS would make, so the default replay window ends here. + */ + public static final Duration SNS_HTTP_RETRY_HORIZON = Duration.ofHours(1); + private static final ProviderId PROVIDER_ID = new ProviderId("ses"); private final SnsSignatureVerifier verifier; @@ -45,7 +61,8 @@ public final class SesCallbackAdapter implements ProviderCallbackAdapter { * @param verifier the SNS signature check * @param normalizer turns an SES event into provider events * @param allowedTopicArns the topics this profile subscribed to; any other is rejected - * @param replayWindow how far the message timestamp may be from receipt, either way + * @param replayWindow how far the message timestamp may be from receipt, either way; {@link + * #SNS_HTTP_RETRY_HORIZON} unless a deployment chose otherwise */ public SesCallbackAdapter( SnsSignatureVerifier verifier, @@ -63,6 +80,12 @@ public final class SesCallbackAdapter implements ProviderCallbackAdapter { return PROVIDER_ID; } + /** + * {@inheritDoc} + * + * @throws CallbackVerificationUnavailableException when the signing certificate could not be + * fetched; the message is neither accepted nor rejected and SNS is asked to deliver it again + */ @Override public CallbackVerificationResult verify(ProviderCallbackVerificationRequest request) { Objects.requireNonNull(request, "request"); diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java index a13d3117..60980d15 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java @@ -4,10 +4,13 @@ import dev.caskeleton.adapter.outbound.notification.platform.provider.EmailAttac import dev.caskeleton.adapter.outbound.notification.platform.provider.EmailRecipients; import dev.caskeleton.adapter.outbound.notification.platform.security.ProviderCredentialManager; import dev.caskeleton.application.notification.platform.api.ProviderId; +import dev.caskeleton.application.notification.platform.api.error.FailureCategory; +import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.contact.EmailAddress; import dev.caskeleton.application.notification.platform.dispatch.AttachmentIntegrityGuard; import dev.caskeleton.application.notification.platform.provider.NotificationProviderAdapter; +import dev.caskeleton.application.notification.platform.provider.ProviderCallNotStartedException; import dev.caskeleton.application.notification.platform.provider.ProviderCapabilities; import dev.caskeleton.application.notification.platform.provider.ProviderSubmission; import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; @@ -136,9 +139,21 @@ public final class SesNotificationProviderAdapter * per-profile rotation inexpressible. */ private AwsCredentials credentialOf(ProviderSubmission submission) { - byte[] secret = - credentials.materialFor( - submission.profile().profileId(), submission.profile().credentialGeneration()); + byte[] secret; + try { + secret = + credentials.materialFor( + submission.profile().profileId(), submission.profile().credentialGeneration()); + } catch (IllegalStateException noCredential) { + // No request has been built, let alone sent. Left unclassified, this was recorded as "the + // provider may have it" and sent to reconciliation that can only ever answer "unknown" + // (review 05-11). + throw new ProviderCallNotStartedException( + NotificationFailureCode.PROVIDER_CONFIGURATION_INVALID, + FailureCategory.AUTHENTICATION, + false, + "SES profile has no usable credential at the planned generation"); + } return AwsBasicCredentials.create(accessKeyId, new String(secret, StandardCharsets.UTF_8)); } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesRequestMapper.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesRequestMapper.java index db1a5c3a..27036310 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesRequestMapper.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesRequestMapper.java @@ -89,7 +89,8 @@ public final class SesRequestMapper { Objects.requireNonNull(attachments, "attachments"); Objects.requireNonNull(credentials, "credentials"); if (!(submission.content().content() instanceof EmailContent email)) { - throw new IllegalArgumentException("SES requires email content"); + // Refused before a request exists, so recorded as not sent (review 05-11), not as unknown. + throw rejection(new IllegalArgumentException("SES requires email content")); } SendEmailRequest.Builder request = diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsCertificateProvider.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsCertificateProvider.java index 7791eda1..fd590ca3 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsCertificateProvider.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsCertificateProvider.java @@ -11,6 +11,16 @@ import java.security.PublicKey; */ public interface SnsCertificateProvider { - /** Public key of the certificate at a URL that has already been host-checked. */ + /** + * Public key of the certificate at a URL that has already been host-checked. + * + * @param certificateUrl the host-checked certificate URL + * @return the certificate's public key + * @throws IllegalArgumentException when the document is not an SNS signing certificate — the + * message that named it is invalid + * @throws + * dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationUnavailableException + * when the certificate could not be fetched now — nothing is known about the message yet + */ PublicKey publicKeyFor(URI certificateUrl); } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsSignatureVerifier.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsSignatureVerifier.java index a5d1dadc..757336d9 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsSignatureVerifier.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsSignatureVerifier.java @@ -51,7 +51,16 @@ public final class SnsSignatureVerifier { this.certificates = Objects.requireNonNull(certificates, "certificates"); } - /** Verify one SNS envelope. */ + /** + * Verify one SNS envelope. + * + *

        A certificate that cannot be fetched is not a signature that does not match: the {@code + * CallbackVerificationUnavailableException} the certificate source throws passes through, so the + * caller answers "try again" instead of "rejected" (review 05-20). + * + * @param envelope the flattened SNS envelope + * @return whether the envelope carries a valid SNS signature + */ public boolean isValid(Map envelope) { Objects.requireNonNull(envelope, "envelope"); String certificateUrl = envelope.get("SigningCertURL"); diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatch.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatch.java index 933ed55b..b19ef84a 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatch.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatch.java @@ -1,9 +1,22 @@ package dev.caskeleton.adapter.outbound.notification.platform.provider.smtp; +import jakarta.mail.MessagingException; import jakarta.mail.internet.MimeMessage; +import java.net.ConnectException; +import java.net.UnknownHostException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; import java.util.Objects; import java.util.Optional; +import org.eclipse.angus.mail.smtp.SMTPAddressFailedException; +import org.eclipse.angus.mail.smtp.SMTPSendFailedException; +import org.eclipse.angus.mail.smtp.SMTPSenderFailedException; +import org.eclipse.angus.mail.util.MailConnectException; +import org.springframework.mail.MailAuthenticationException; import org.springframework.mail.MailException; +import org.springframework.mail.MailSendException; import org.springframework.mail.javamail.JavaMailSender; /** @@ -16,10 +29,21 @@ import org.springframework.mail.javamail.JavaMailSender; * runtime registry constructed empty. * *

        Failures are translated rather than propagated. {@link SmtpDispatchException} is what {@code - * SmtpFailureClassifier} reads to decide retryable from permanent, and a raw {@link MailException} - * reaching the dispatch loop would be classified as an unknown failure — which this platform treats - * as ambiguous, and ambiguous means the attempt is not retried, because a message that may already - * have been delivered must not be sent twice. + * SmtpFailureClassifier} reads to decide retryable from permanent, so the translation carries the + * two facts it needs (review 05-11): the server's reply code, when the server answered, and whether + * the body may have reached the relay. Every failure used to be reported as "no reply code, body + * committed", so the classifier's 4xx and 550 branches never ran and a relay that was down went to + * an operator as "may have been delivered". + * + *

          + *
        • A reply code from the Angus SMTP exceptions ({@code SMTPAddressFailedException}, {@code + * SMTPSenderFailedException}, {@code SMTPSendFailedException}) is the server's explicit + * answer: the message was refused, not lost. + *
        • A refused connection or a failed login happens before any message is handed over, so + * nothing is committed and the attempt may be retried. + *
        • Anything else keeps the conservative answer: committed, because a connection that broke + * after {@code DATA} may have left the message with the relay. + *
        */ public final class JavaMailSenderSmtpDispatch implements SmtpDispatch { @@ -41,14 +65,80 @@ public final class JavaMailSenderSmtpDispatch implements SmtpDispatch { Objects.requireNonNull(message, "message"); try { sender.send(message); + } catch (MailAuthenticationException loginRefused) { + throw new SmtpDispatchException( + "SMTP_AUTHENTICATION_FAILED", Optional.empty(), false, loginRefused); } catch (MailException failure) { - // dataCommitted = true, deliberately and conservatively. Spring collapses every JavaMail - // outcome into MailException subtypes that do not say whether the body reached the server - // before the connection broke, and the platform reads this flag to decide whether a retry - // could duplicate a delivered message. Claiming "not committed" without evidence is the - // assumption that sends a notification twice; claiming "committed" costs a delivery that has - // to be reconciled, which is the failure this platform is built to survive. - throw new SmtpDispatchException("SMTP_TRANSPORT_FAILURE", Optional.empty(), true, failure); + throw translate(failure); } } + + private static SmtpDispatchException translate(MailException failure) { + List causes = causesOf(failure); + for (Throwable cause : causes) { + Optional replyCode = replyCodeOf(cause); + if (replyCode.isPresent()) { + // The server answered. A refused envelope (sender or recipient) is answered before DATA; + // a refused body is answered after it, and the relay said it will not deliver either way. + // Angus reports the three as sibling SendFailedException types, so only the body refusal + // is an SMTPSendFailedException. + boolean afterData = cause instanceof SMTPSendFailedException; + return new SmtpDispatchException("SMTP_REFUSED", replyCode, afterData, failure); + } + } + for (Throwable cause : causes) { + if (cause instanceof MailConnectException + || cause instanceof ConnectException + || cause instanceof UnknownHostException) { + return new SmtpDispatchException( + "SMTP_CONNECTION_REFUSED", Optional.empty(), false, failure); + } + } + // dataCommitted = true, deliberately and conservatively. Nothing above says whether the body + // reached the server before the connection broke, and the platform reads this flag to decide + // whether a retry could duplicate a delivered message. Claiming "not committed" without + // evidence + // is the assumption that sends a notification twice; claiming "committed" costs a delivery that + // has to be reconciled, which is the failure this platform is built to survive. + return new SmtpDispatchException("SMTP_TRANSPORT_FAILURE", Optional.empty(), true, failure); + } + + private static Optional replyCodeOf(Throwable cause) { + int code = -1; + if (cause instanceof SMTPAddressFailedException address) { + code = address.getReturnCode(); + } else if (cause instanceof SMTPSenderFailedException sender) { + code = sender.getReturnCode(); + } else if (cause instanceof SMTPSendFailedException send) { + code = send.getReturnCode(); + } + return code >= 200 && code < 600 ? Optional.of(code) : Optional.empty(); + } + + /** + * Every throwable under the failure: the cause chain, JavaMail's {@code getNextException} chain, + * and the per-message exceptions Spring collects in {@link MailSendException}. + */ + private static List causesOf(MailException failure) { + List found = new ArrayList<>(); + Deque pending = new ArrayDeque<>(); + pending.add(failure); + if (failure instanceof MailSendException send) { + pending.addAll(List.of(send.getMessageExceptions())); + } + while (!pending.isEmpty() && found.size() < 32) { + Throwable next = pending.removeFirst(); + if (found.stream().anyMatch(seen -> seen == next)) { + continue; + } + found.add(next); + if (next.getCause() != null) { + pending.add(next.getCause()); + } + if (next instanceof MessagingException messaging && messaging.getNextException() != null) { + pending.add(messaging.getNextException()); + } + } + return found; + } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpDispatchException.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpDispatchException.java index 919be2cf..c3ee1bae 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpDispatchException.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpDispatchException.java @@ -4,7 +4,7 @@ import java.util.Objects; import java.util.Optional; /** An SMTP send that did not complete with a final acceptance. */ -public class SmtpDispatchException extends RuntimeException { +public final class SmtpDispatchException extends RuntimeException { private static final long serialVersionUID = 1L; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifier.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifier.java index b5736d58..f1026b9e 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifier.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifier.java @@ -10,7 +10,10 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.json.JsonMapper; @@ -37,6 +40,25 @@ final class NotificationEvidenceVerifier { ":application-notification:test", new EvidenceLane("application-notification/src/test/java/", null, null, List.of())); + /** + * Where the shared port contracts live: one abstract contract per port, in the port owner's + * testFixtures (AGENTS.md). A store's contract test against PostgreSQL is a subclass that may + * declare no test method of its own — its cases are the contract's. A superclass is followed only + * into these roots and the evidence's own source root; one found in neither leaves the evidence + * without a test, so the check fails closed. + */ + private static final List CONTRACT_ROOTS = + List.of( + "application-notification/src/testFixtures/java/", + "adapter/outbound/notification/src/testFixtures/java/"); + + /** A contract may extend a base; a longer chain is not followed. */ + private static final int MAX_SUPERCLASS_DEPTH = 3; + + private static final Pattern SUPERCLASS = + Pattern.compile("\\bclass\\s+\\w+\\s+extends\\s+(\\w+)"); + private static final Pattern PACKAGE = Pattern.compile("(?m)^package\\s+([\\w.]+)\\s*;"); + private NotificationEvidenceVerifier() {} static NotificationEvidenceResult verify( @@ -272,12 +294,7 @@ final class NotificationEvidenceVerifier { problems.add("claim '" + claim.name() + "' names empty evidence: " + path); continue; } - boolean looksExecutable = - source.contains("@Test") - || source.contains("@ParameterizedTest") - || source.contains("@RepeatedTest") - || source.contains("@TestFactory"); - if (!looksExecutable) { + if (!runsATest(projectDirectory, path, source)) { problems.add( "claim '" + claim.name() + "' names evidence with no executable test: " + path); continue; @@ -300,6 +317,66 @@ final class NotificationEvidenceVerifier { return problems; } + /** Whether running this source runs a test: it declares one, or a superclass it names does. */ + private static boolean runsATest(File projectDirectory, String path, String source) { + String currentPath = path; + String currentSource = source; + for (int depth = 0; depth < MAX_SUPERCLASS_DEPTH; depth++) { + if (declaresATest(currentSource)) { + return true; + } + Optional superclass = superclassPath(projectDirectory, currentPath, currentSource); + if (superclass.isEmpty()) { + return false; + } + currentPath = superclass.get(); + currentSource = read(new File(projectDirectory, currentPath)); + } + return declaresATest(currentSource); + } + + private static boolean declaresATest(String source) { + return source.contains("@Test") + || source.contains("@ParameterizedTest") + || source.contains("@RepeatedTest") + || source.contains("@TestFactory"); + } + + /** + * The source file of the class {@code source} extends, by its import or else its package, looked + * up in {@link #CONTRACT_ROOTS} and in the source root {@code path} belongs to. + */ + private static Optional superclassPath( + File projectDirectory, String path, String source) { + Matcher declaration = SUPERCLASS.matcher(source); + if (!declaration.find()) { + return Optional.empty(); + } + String simpleName = declaration.group(1); + Matcher imported = + Pattern.compile("(?m)^import\\s+([\\w.]+\\." + Pattern.quote(simpleName) + ")\\s*;") + .matcher(source); + Matcher declaredPackage = PACKAGE.matcher(source); + String qualifiedName; + if (imported.find()) { + qualifiedName = imported.group(1); + } else if (declaredPackage.find()) { + qualifiedName = declaredPackage.group(1) + "." + simpleName; + } else { + qualifiedName = simpleName; + } + String relative = qualifiedName.replace('.', '/') + ".java"; + List roots = new ArrayList<>(CONTRACT_ROOTS); + int javaRoot = path.indexOf("/java/"); + if (javaRoot >= 0) { + roots.add(path.substring(0, javaRoot + "/java/".length())); + } + return roots.stream() + .map(root -> root + relative) + .filter(candidate -> new File(projectDirectory, candidate).isFile()) + .findFirst(); + } + private static String optionalText(JsonNode node, String field) { JsonNode value = node == null ? null : node.get(field); if (value == null || value.isNull()) { diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifierTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifierTest.java index d87ff7d6..b56efb04 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifierTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifierTest.java @@ -73,6 +73,77 @@ class NotificationEvidenceVerifierTest { failure.getMessage().contains("claim 'delivery' is marked satisfied with no evidence")); } + @Test + void evidenceThatInheritsItsTestsFromASharedContractCountsAsExecutable(@TempDir Path temp) + throws Exception { + // given + Fixture fixture = fixture(temp); + Files.createDirectories(fixture.contract().getParent()); + Files.writeString( + fixture.contract(), + """ + package contract; + + public abstract class DeliveryContract { + @Test + void provesDelivery() {} + } + """); + Files.writeString( + fixture.evidence(), + """ + import contract.DeliveryContract; + + final class DeliveryContractTest extends DeliveryContract {} + """); + + // when + NotificationEvidenceResult result = + NotificationEvidenceVerifier.verify( + fixture.manifest().toFile(), + fixture.repositoryRoot().toFile(), + fixture.projectRoot().toFile()); + + // then + assertEquals(1, result.satisfiedClaimCount()); + } + + @Test + void evidenceWhoseSuperclassDeclaresNoTestStillFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Files.createDirectories(fixture.contract().getParent()); + Files.writeString( + fixture.contract(), + """ + package contract; + + public abstract class DeliveryContract { + void provesNothing() {} + } + """); + Files.writeString( + fixture.evidence(), + """ + import contract.DeliveryContract; + + final class DeliveryContractTest extends DeliveryContract {} + """); + + // when + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> + NotificationEvidenceVerifier.verify( + fixture.manifest().toFile(), + fixture.repositoryRoot().toFile(), + fixture.projectRoot().toFile())); + + // then + assertTrue(failure.getMessage().contains("names evidence with no executable test")); + } + @Test void unknownGradeInAssigningTableFails(@TempDir Path temp) throws Exception { Fixture fixture = fixture(temp); @@ -181,8 +252,17 @@ class NotificationEvidenceVerifierTest { | --- | --- | | email | Stable | """); - return new Fixture(repositoryRoot, projectRoot, manifest, matrix); + Path contract = + projectRoot.resolve( + "application-notification/src/testFixtures/java/contract/DeliveryContract.java"); + return new Fixture(repositoryRoot, projectRoot, manifest, matrix, evidence, contract); } - private record Fixture(Path repositoryRoot, Path projectRoot, Path manifest, Path matrix) {} + private record Fixture( + Path repositoryRoot, + Path projectRoot, + Path manifest, + Path matrix, + Path evidence, + Path contract) {} } diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationHealthWiringTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationHealthWiringTest.java new file mode 100644 index 00000000..cd6acd49 --- /dev/null +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationHealthWiringTest.java @@ -0,0 +1,91 @@ +package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.notification.platform.observation.NotificationHealthReporter; +import dev.caskeleton.adapter.outbound.notification.platform.observation.NotificationHealthSnapshot; +import dev.caskeleton.application.notification.platform.observation.NotificationServingState; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * Which provider profiles the platform's health watches, as the auto-configuration wires it. + * + *

        It watched every configured profile. The shipped defaults configure {@code ses} and {@code + * smtp} switched off, and {@code INGEST_ONLY} builds no runtime at all, so a deployment that turned + * the platform on reported each of them {@code UNREGISTERED}, health {@code DOWN}, and never became + * ready — found by booting the compose lanes, which every static check had passed (review + * 2026-11-01 r3-i). A profile the assembly did not build a runtime for has nothing to watch. + */ +class NotificationHealthWiringTest { + + @ParameterizedTest(name = "{0}, profile enabled={1}") + @CsvSource({"INGEST_ONLY, true", "INGEST_ONLY, false"}) + void underIngestOnlyNoProfileIsWatched(NotificationPlatformMode mode, boolean enabled) { + // given + NotificationPlatformSettings settings = + settings( + mode, Map.of("ses", NotificationProviderAssemblyTest.profile("SES", enabled, false))); + NotificationProviderAssembly.AssembledPlatform platform = + new NotificationProviderAssembly(List.of()).assemble(settings, mode); + + // when + NotificationHealthSnapshot snapshot = reporter(settings, platform).snapshot(); + + // then + assertThat(snapshot) + .extracting(NotificationHealthSnapshot::healthy, health -> health.providers().size()) + .containsExactly(true, 0); + } + + @Test + @DisplayName("SERVING에서는 조립된 profile만 지켜보고, 꺼진 profile 때문에 health가 내려가지 않는다") + void underServingOnlyTheAssembledProfileIsWatched() { + // given + NotificationPlatformSettings settings = + settings( + NotificationPlatformMode.SERVING, + Map.of( + "smtp", NotificationProviderAssemblyTest.profile("SMTP", true, false), + "ses", NotificationProviderAssemblyTest.profile("SES", false, false))); + NotificationProviderAssembly.AssembledPlatform platform = + new NotificationProviderAssembly( + List.of(NotificationProviderAssemblyTest.fakeAssembler(ProviderType.SMTP))) + .assemble(settings, NotificationPlatformMode.SERVING); + + // when + NotificationHealthSnapshot snapshot = reporter(settings, platform).snapshot(); + + // then + assertThat(snapshot) + .extracting( + NotificationHealthSnapshot::healthy, + health -> + health.providers().stream() + .map(NotificationHealthSnapshot.ProviderHealth::profileId) + .toList()) + .containsExactly(true, List.of("smtp")); + } + + private static NotificationPlatformSettings settings( + NotificationPlatformMode mode, Map providers) { + return new NotificationPlatformSettings( + true, + mode, + NotificationPlatformSettings.Dispatch.defaults(), + NotificationPlatformSettings.Callbacks.defaults(), + providers); + } + + private static NotificationHealthReporter reporter( + NotificationPlatformSettings settings, + NotificationProviderAssembly.AssembledPlatform platform) { + return new NotificationPlatformObservabilityConfig() + .notificationHealthReporter( + platform.runtimes(), settings, platform, () -> NotificationServingState.IDLE); + } +} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java index 8e7ec0d5..f1118c54 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java @@ -209,6 +209,46 @@ class NotificationProviderAssemblyTest { assertThat(platform.serving()).isFalse(); } + @Test + @DisplayName("INGEST_ONLY는 runtime 없이 accept 때 고정할 route 이름을 기록한다") + void ingestOnlyRecordsTheRouteNameWithoutARuntime() { + // given + Map providers = + Map.of("email-main", profile("SES", true, false)); + + // when + NotificationProviderAssembly.AssembledPlatform platform = + assemble(providers, NotificationPlatformMode.INGEST_ONLY); + + // then + assertThat( + List.of( + platform.routeFor(Channel.EMAIL), + platform.runtimes().find(new ProviderProfileId("email-main")).isPresent(), + platform.serving())) + .as("the plan fixed at acceptance names the route a later SERVING deployment delivers on") + .containsExactly(Optional.of(new ProviderProfileId("email-main")), false, false); + } + + @Test + @DisplayName("INGEST_ONLY에서도 한 채널을 primary 없이 두 profile이 차지하면 기동을 거부한다") + void ingestOnlyRefusesTwoProfilesClaimingOneChannelWithNoPrimary() { + // given + Map providers = + Map.of("email-a", profile("SES", true, false), "email-b", profile("SES", true, false)); + + // when + Throwable refused = + org.assertj.core.api.Assertions.catchThrowable( + () -> assemble(providers, NotificationPlatformMode.INGEST_ONLY)); + + // then + assertThat(refused) + .as("the route recorded at acceptance must not depend on map iteration order") + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("none is marked primary-for-channel"); + } + @Test @DisplayName("two assemblers for one family are refused at construction") void twoAssemblersForOneFamilyAreRefused() { @@ -220,9 +260,18 @@ class NotificationProviderAssemblyTest { .hasMessageContaining("bean ordering"); } + /** + * This case used to assert that INGEST_ONLY assembles no route. That contradicted the handoff + * contract — a request accepted while ingest-only is delivered later, by a SERVING deployment, on + * the route fixed at acceptance — because a request accepted with no route has an empty plan and + * is never delivered (the local-notification-handoff lane saw zero deliveries). The decision + * (review 15절, r3-I) is that INGEST_ONLY records the route name at acceptance, without a runtime; + * so the route is now expected and the runtime is still not. + */ @Test - @DisplayName("INGEST_ONLY assembles a callback-capable profile without a dispatch transport") + @DisplayName("INGEST_ONLY는 dispatch transport 없이 콜백 profile을 조립하고 route 이름만 기록한다") void ingestOnlyAssemblesCallbackWithoutDispatchTransport() { + // given NotificationPlatformSettings settings = new NotificationPlatformSettings( true, @@ -231,12 +280,14 @@ class NotificationProviderAssemblyTest { new NotificationPlatformSettings.Callbacks(true, 1_024, Duration.ofMinutes(5)), Map.of("ses-events", profile("SES", true, false))); + // when NotificationProviderAssembly.AssembledPlatform platform = new NotificationProviderAssembly( List.of(), List.of(fakeCallbackAssembler(ProviderType.SES))) .assemble(settings, NotificationPlatformMode.INGEST_ONLY); - assertThat(platform.routes()).isEmpty(); + // then + assertThat(platform.routeFor(Channel.EMAIL)).hasValue(new ProviderProfileId("ses-events")); assertThat(platform.runtimes().find(new ProviderProfileId("ses-events"))).isEmpty(); assertThat(platform.callbacks()).containsKey(new ProviderProfileId("ses-events")); assertThat(platform.callbacks().get(new ProviderProfileId("ses-events")).providerId()) @@ -346,7 +397,8 @@ class NotificationProviderAssemblyTest { return new NotificationProviderAssembly(List.of(assemblers)).assemble(settings, mode); } - private static NotificationPlatformSettings.Provider profile( + /** A complete profile of {@code type}; also used by {@code NotificationHealthWiringTest}. */ + static NotificationPlatformSettings.Provider profile( String type, boolean enabled, boolean primary) { NotificationPlatformSettings.Ses ses = "SES".equals(type) @@ -393,7 +445,10 @@ class NotificationProviderAssemblyTest { } /** An assembler that produces a runtime without a transport, so the wiring is what is tested. */ - private static ProviderRuntimeAssembler fakeAssembler(ProviderType type) { + /** + * A dispatch-only runtime for {@code type}; also used by {@code NotificationHealthWiringTest}. + */ + static ProviderRuntimeAssembler fakeAssembler(ProviderType type) { return new ProviderRuntimeAssembler() { @Override diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateCacheTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateCacheTest.java index 95fe8daa..d76977d5 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateCacheTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateCacheTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationUnavailableException; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SnsCertificateProvider; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -95,6 +96,30 @@ class SnsCertificateCacheTest { .hasMessageContaining("CN=sns.test.invalid"); } + @Test + @DisplayName("인증서 호스트에 연결하지 못하면 서명 불일치가 아니라 검증 불가로 알린다") + void anUnreachableCertificateHostIsReportedAsVerificationUnavailable() throws Exception { + // given + int closedPort; + try (java.net.ServerSocket probe = new java.net.ServerSocket(0)) { + closedPort = probe.getLocalPort(); + } + SnsCertificateProvider fetching = + new NotificationCallbackProviderConfig().snsCertificateProvider(); + URI unreachable = + URI.create("http://127.0.0.1:" + closedPort + "/SimpleNotificationService-test.pem"); + + // when + Throwable failure = catchThrowable(() -> fetching.publicKeyFor(unreachable)); + + // then + assertThat(failure) + .isInstanceOfSatisfying( + CallbackVerificationUnavailableException.class, + unavailable -> + assertThat(unavailable.reasonCode()).isEqualTo("SNS_CERTIFICATE_UNAVAILABLE")); + } + private SnsCertificateProvider serving(String pem) { return NotificationCallbackProviderConfig.cachingCertificates( uri -> { diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/SubmissionCompatibilityTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/SubmissionCompatibilityTest.java index ef82853f..5bf1d06a 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/SubmissionCompatibilityTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/SubmissionCompatibilityTest.java @@ -5,10 +5,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmContactPointProtector; import dev.caskeleton.adapter.outbound.notification.platform.security.SecurityFixtures; -import dev.caskeleton.adapter.outbound.notification.platform.testkit.ProviderFixtures; import dev.caskeleton.application.notification.platform.api.content.NotificationContent; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.contact.EmailAddress; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderFixtures; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import java.util.Optional; import org.junit.jupiter.api.DisplayName; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapterTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapterTest.java index 2febfcc8..d425bf65 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapterTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapterTest.java @@ -1,8 +1,11 @@ package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.NotificationPlatformSettings; import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationResult; +import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationUnavailableException; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackVerificationRequest; import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationJsonMapper; import dev.caskeleton.application.notification.platform.api.ProviderId; @@ -19,6 +22,7 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Set; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** @@ -78,6 +82,68 @@ class SesCallbackAdapterTest { .containsExactly(false, "SNS_TIMESTAMP_OUT_OF_WINDOW"); } + @Test + @DisplayName("장애 뒤 SNS가 50분 늦게 다시 보낸 콜백은 기본 replay 창 안이라 받아들여진다") + void aCallbackSnsRedeliversFiftyMinutesAfterAnOutageIsAcceptedByTheDefaultWindow() { + // given + byte[] body = signed(ALLOWED_TOPIC, RECEIVED_AT.minus(Duration.ofMinutes(50))); + + // when + CallbackVerificationResult result = withDefaultWindow().verify(request(body)); + + // then + assertThat(result.valid()).isTrue(); + } + + @Test + @DisplayName("SNS가 더는 다시 보내지 않는 1시간 넘은 콜백은 기본 replay 창 밖이라 거절된다") + void aCallbackOlderThanSnsWouldRedeliverIsRejectedByTheDefaultWindow() { + // given + byte[] body = signed(ALLOWED_TOPIC, RECEIVED_AT.minus(Duration.ofMinutes(61))); + + // when + CallbackVerificationResult result = withDefaultWindow().verify(request(body)); + + // then + assertThat(result.reasonCode()).isEqualTo("SNS_TIMESTAMP_OUT_OF_WINDOW"); + } + + @Test + @DisplayName("서명 인증서를 가져오지 못하면 거절하지 않고 검증 불가로 알린다") + void aSigningCertificateThatCannotBeFetchedIsReportedAsUnavailableNotAsARejection() { + // given + SesCallbackAdapter unreachableCertificates = + new SesCallbackAdapter( + new SnsSignatureVerifier( + certificateUrl -> { + throw new CallbackVerificationUnavailableException( + "SNS_CERTIFICATE_UNAVAILABLE", new java.io.IOException("unreachable")); + }), + new SesEventNormalizer(), + Set.of(ALLOWED_TOPIC), + Duration.ofMinutes(5)); + ProviderCallbackVerificationRequest request = request(signed(ALLOWED_TOPIC, RECEIVED_AT)); + + // when + Throwable failure = catchThrowable(() -> unreachableCertificates.verify(request)); + + // then + assertThat(failure) + .isInstanceOfSatisfying( + CallbackVerificationUnavailableException.class, + unavailable -> + assertThat(unavailable.reasonCode()).isEqualTo("SNS_CERTIFICATE_UNAVAILABLE")); + } + + /** The adapter with the window a deployment gets when it sets nothing. */ + private static SesCallbackAdapter withDefaultWindow() { + return new SesCallbackAdapter( + new SnsSignatureVerifier(certificateUrl -> SNS_KEYS.getPublic()), + new SesEventNormalizer(), + Set.of(ALLOWED_TOPIC), + NotificationPlatformSettings.Callbacks.defaults().replaySkew()); + } + private static ProviderCallbackVerificationRequest request(byte[] body) { return new ProviderCallbackVerificationRequest( new ProviderId("ses"), diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackContractTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackContractTest.java new file mode 100644 index 00000000..9f47c995 --- /dev/null +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackContractTest.java @@ -0,0 +1,106 @@ +package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; + +import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapter; +import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackVerificationRequest; +import dev.caskeleton.adapter.outbound.notification.platform.callback.testkit.CallbackContract; +import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationJsonMapper; +import dev.caskeleton.application.notification.platform.api.ProviderId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** The SES callback adapter held to the callback contract every provider callback adapter keeps. */ +class SesCallbackContractTest extends CallbackContract { + + private static final Instant RECEIVED_AT = Instant.parse("2026-11-03T00:00:00Z"); + private static final String TOPIC = "arn:aws:sns:us-east-1:123456789012:ses-events"; + private static final KeyPair SNS_KEYS = rsa(); + + private final SesCallbackAdapter adapter = + new SesCallbackAdapter( + new SnsSignatureVerifier(certificateUrl -> SNS_KEYS.getPublic()), + new SesEventNormalizer(), + Set.of(TOPIC), + Duration.ofMinutes(5)); + + @Override + protected ProviderCallbackAdapter adapter() { + return adapter; + } + + @Override + protected ProviderCallbackVerificationRequest signedRequest() { + return request(envelope(true)); + } + + @Override + protected ProviderCallbackVerificationRequest tamperedRequest() { + Map envelope = envelope(true); + envelope.put("Message", envelope.get("Message").replace("Delivery", "Bounce")); + return request(envelope); + } + + @Override + protected ProviderCallbackVerificationRequest unsignedRequest() { + return request(envelope(false)); + } + + private static Map envelope(boolean signed) { + Map envelope = new LinkedHashMap<>(); + envelope.put("Type", "Notification"); + envelope.put("MessageId", "sns-message-1"); + envelope.put("TopicArn", TOPIC); + envelope.put("Timestamp", RECEIVED_AT.toString()); + envelope.put( + "Message", + "{\"eventType\":\"Delivery\",\"mail\":{\"messageId\":\"ses-request-1\"}," + + "\"delivery\":{\"timestamp\":\"" + + RECEIVED_AT + + "\",\"recipients\":[\"leak-canary@example.com\"]}}"); + envelope.put( + "SigningCertURL", "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-test.pem"); + envelope.put("SignatureVersion", "2"); + if (signed) { + try { + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(SNS_KEYS.getPrivate()); + signer.update( + SnsSignatureVerifier.canonicalString(envelope).getBytes(StandardCharsets.UTF_8)); + envelope.put("Signature", Base64.getEncoder().encodeToString(signer.sign())); + } catch (GeneralSecurityException impossible) { + throw new IllegalStateException(impossible); + } + } + return envelope; + } + + private static ProviderCallbackVerificationRequest request(Map envelope) { + return new ProviderCallbackVerificationRequest( + new ProviderId("ses"), + new ProviderProfileId("ses-events"), + "https://callback.example/internal/notification/callbacks/ses/ses-events", + "POST", + Optional.of("application/json"), + Map.of(), + NotificationJsonMapper.mapper().writeValueAsBytes(envelope), + RECEIVED_AT); + } + + private static KeyPair rsa() { + try { + return KeyPairGenerator.getInstance("RSA").generateKeyPair(); + } catch (GeneralSecurityException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java index 809e3084..8e8adfe1 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.notification.platform.provider.UnconfiguredAttachmentResolver; import dev.caskeleton.adapter.outbound.notification.platform.provider.smtp.SmtpMimeMessageFactory; @@ -9,9 +10,6 @@ import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmCont import dev.caskeleton.adapter.outbound.notification.platform.security.ProviderCredentialManager; import dev.caskeleton.adapter.outbound.notification.platform.security.SecurityFixtures; import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationJsonMapper; -import dev.caskeleton.adapter.outbound.notification.platform.testkit.ProviderAdapterContract; -import dev.caskeleton.adapter.outbound.notification.platform.testkit.ProviderFaultHarness; -import dev.caskeleton.adapter.outbound.notification.platform.testkit.ProviderFixtures; import dev.caskeleton.application.notification.platform.api.content.AttachmentDisposition; import dev.caskeleton.application.notification.platform.api.content.AttachmentRef; import dev.caskeleton.application.notification.platform.api.content.EmailContent; @@ -26,8 +24,12 @@ import dev.caskeleton.application.notification.platform.contact.EmailAddress; import dev.caskeleton.application.notification.platform.dispatch.AttachmentIntegrityGuard; import dev.caskeleton.application.notification.platform.provider.AttachmentResolver; import dev.caskeleton.application.notification.platform.provider.NotificationProviderAdapter; +import dev.caskeleton.application.notification.platform.provider.ProviderCallNotStartedException; import dev.caskeleton.application.notification.platform.provider.ProviderSubmission; import dev.caskeleton.application.notification.platform.provider.ResolvedAttachment; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderAdapterContract; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderFaultHarness; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderFixtures; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import jakarta.mail.Session; import java.io.ByteArrayInputStream; @@ -269,19 +271,22 @@ class SesNotificationProviderAdapterTest extends ProviderAdapterContract { } @Test + @DisplayName("profile 자격 증명이 없으면 요청을 만들기 전에 전송 전 실패로 거절되고 아무것도 보내지 않는다") void aProfileWithNoActivatedCredentialIsRefusedBeforeTheRequest() { + // given harness.respondWith(200, successBody(), Map.of()); + var withoutThisProfile = + adapter( + SecurityFixtures.credentials("some-other-profile"), + new UnconfiguredAttachmentResolver()); - assertThatThrownBy( - () -> - adapter( - SecurityFixtures.credentials("some-other-profile"), - new UnconfiguredAttachmentResolver()) - .submit(submission()) - .toCompletableFuture() - .join()) - .isInstanceOf(IllegalStateException.class); + // when + Throwable failure = + catchThrowable(() -> withoutThisProfile.submit(submission()).toCompletableFuture().join()); + // then — not sent, and said so: an unclassified IllegalStateException was recorded as "the + // provider may have it" and sent to a reconciliation SES cannot answer (review 05-11) + assertThat(failure).isInstanceOf(ProviderCallNotStartedException.class); assertThat(harness.received()).isEmpty(); } diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatchTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatchTest.java new file mode 100644 index 00000000..4fd987ad --- /dev/null +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatchTest.java @@ -0,0 +1,243 @@ +package dev.caskeleton.adapter.outbound.notification.platform.provider.smtp; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowableOfType; + +import jakarta.mail.Session; +import jakarta.mail.internet.InternetAddress; +import jakarta.mail.internet.MimeMessage; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Optional; +import java.util.Properties; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.mail.MailAuthenticationException; +import org.springframework.mail.javamail.JavaMailSenderImpl; + +/** + * What the real JavaMail stack throws, and what the dispatch makes of it (review 05-11). + * + *

        Every {@code MailException} used to become "no reply code, body committed", so the + * classifier's 4xx and 550 branches never ran in production and a relay that was down, or a + * recipient the relay refused, went to an operator as "may have been delivered". These tests drive + * Spring's {@link JavaMailSenderImpl} and the Angus SMTP transport against a scripted SMTP server + * on loopback, so the exceptions are the ones production sees rather than hand-built stand-ins. + */ +class JavaMailSenderSmtpDispatchTest { + + @Test + @DisplayName("수신자를 550 으로 거절한 SMTP 응답은 reply code 550 과 본문 미전송으로 보고된다") + void aRecipientRefusedWith550IsReportedWithItsReplyCodeAndNothingCommitted() throws Exception { + // given + try (ScriptedSmtpServer server = + ScriptedSmtpServer.refusingRecipientWith("550 5.1.1 no such user")) { + JavaMailSenderSmtpDispatch dispatch = new JavaMailSenderSmtpDispatch(sender(server.port())); + + // when + SmtpDispatchException failure = sendExpectingFailure(dispatch); + + // then + assertThat(List.of(failure.replyCode(), failure.dataCommitted())) + .containsExactly(Optional.of(550), false); + } + } + + @Test + @DisplayName("수신자에 대한 일시 거절 451 은 재시도 가능한 reply code 로 보고된다") + void aTemporaryRecipientRefusalIsReportedWithItsReplyCode() throws Exception { + // given + try (ScriptedSmtpServer server = + ScriptedSmtpServer.refusingRecipientWith("451 4.3.0 try later")) { + JavaMailSenderSmtpDispatch dispatch = new JavaMailSenderSmtpDispatch(sender(server.port())); + + // when + SmtpDispatchException failure = sendExpectingFailure(dispatch); + + // then + assertThat(List.of(failure.replyCode(), failure.dataCommitted())) + .containsExactly(Optional.of(451), false); + } + } + + @Test + @DisplayName("본문을 받은 뒤 554 로 거절한 응답은 서버의 명시적 거절로 reply code 와 함께 보고된다") + void aMessageRefusedAfterTheBodyIsReportedWithItsReplyCode() throws Exception { + // given + try (ScriptedSmtpServer server = ScriptedSmtpServer.refusingTheBodyWith("554 5.7.1 rejected")) { + JavaMailSenderSmtpDispatch dispatch = new JavaMailSenderSmtpDispatch(sender(server.port())); + + // when + SmtpDispatchException failure = sendExpectingFailure(dispatch); + + // then + assertThat(failure.replyCode()).contains(554); + } + } + + @Test + @DisplayName("릴레이에 연결하지 못하면 아무것도 보내지 않았으므로 본문 미전송으로 보고된다") + void aRelayThatCannotBeReachedIsReportedAsNothingCommitted() throws Exception { + // given + int closedPort; + try (ServerSocket probe = new ServerSocket(0)) { + closedPort = probe.getLocalPort(); + } + JavaMailSenderSmtpDispatch dispatch = new JavaMailSenderSmtpDispatch(sender(closedPort)); + + // when + SmtpDispatchException failure = sendExpectingFailure(dispatch); + + // then + assertThat(List.of(failure.replyCode(), failure.dataCommitted())) + .containsExactly(Optional.empty(), false); + } + + @Test + @DisplayName("본문을 보낸 뒤 연결이 끊기면 전달됐을 수 있으므로 본문 전송으로 보고된다") + void aConnectionLostAfterTheBodyIsReportedAsCommitted() throws Exception { + // given + try (ScriptedSmtpServer server = ScriptedSmtpServer.droppingAfterTheBody()) { + JavaMailSenderSmtpDispatch dispatch = new JavaMailSenderSmtpDispatch(sender(server.port())); + + // when + SmtpDispatchException failure = sendExpectingFailure(dispatch); + + // then + assertThat(List.of(failure.replyCode(), failure.dataCommitted())) + .containsExactly(Optional.empty(), true); + } + } + + @Test + @DisplayName("릴레이 인증 실패는 메시지를 넘기기 전이므로 본문 미전송으로 보고된다") + void anAuthenticationFailureIsReportedAsNothingCommitted() { + // given + JavaMailSenderImpl refusing = + new JavaMailSenderImpl() { + @Override + public void send(MimeMessage... messages) { + throw new MailAuthenticationException("535 5.7.8 authentication failed"); + } + }; + JavaMailSenderSmtpDispatch dispatch = new JavaMailSenderSmtpDispatch(refusing); + + // when + SmtpDispatchException failure = sendExpectingFailure(dispatch); + + // then + assertThat(List.of(failure.replyCode(), failure.dataCommitted())) + .containsExactly(Optional.empty(), false); + } + + private static SmtpDispatchException sendExpectingFailure(JavaMailSenderSmtpDispatch dispatch) { + return catchThrowableOfType(SmtpDispatchException.class, () -> dispatch.send(message())); + } + + private static JavaMailSenderImpl sender(int port) { + JavaMailSenderImpl sender = new JavaMailSenderImpl(); + sender.setHost("127.0.0.1"); + sender.setPort(port); + Properties properties = new Properties(); + properties.setProperty("mail.smtp.connectiontimeout", "2000"); + properties.setProperty("mail.smtp.timeout", "2000"); + sender.setJavaMailProperties(properties); + return sender; + } + + private static MimeMessage message() { + try { + MimeMessage message = new MimeMessage(Session.getInstance(new Properties())); + message.setFrom(new InternetAddress("sender@example.test")); + message.setRecipient( + jakarta.mail.Message.RecipientType.TO, new InternetAddress("user@example.test")); + message.setSubject("subject"); + message.setText("body"); + return message; + } catch (jakarta.mail.MessagingException impossible) { + throw new IllegalStateException(impossible); + } + } + + /** One-connection SMTP server that answers from a script. */ + private static final class ScriptedSmtpServer implements AutoCloseable { + private final ServerSocket socket; + private final Thread worker; + + private ScriptedSmtpServer(String recipientReply, String bodyReply) throws IOException { + socket = new ServerSocket(0); + worker = Thread.ofVirtual().start(() -> serve(recipientReply, bodyReply)); + } + + static ScriptedSmtpServer refusingRecipientWith(String reply) throws IOException { + return new ScriptedSmtpServer(reply, "250 queued"); + } + + static ScriptedSmtpServer refusingTheBodyWith(String reply) throws IOException { + return new ScriptedSmtpServer("250 ok", reply); + } + + /** Takes the whole body and then closes the connection without a final reply. */ + static ScriptedSmtpServer droppingAfterTheBody() throws IOException { + return new ScriptedSmtpServer("250 ok", null); + } + + int port() { + return socket.getLocalPort(); + } + + private void serve(String recipientReply, String bodyReply) { + try (Socket client = socket.accept(); + BufferedReader in = + new BufferedReader( + new InputStreamReader(client.getInputStream(), StandardCharsets.US_ASCII)); + OutputStream out = client.getOutputStream()) { + reply(out, "220 scripted"); + String line; + while ((line = in.readLine()) != null) { + String command = line.toUpperCase(java.util.Locale.ROOT); + if (command.startsWith("EHLO") || command.startsWith("HELO")) { + reply(out, "250 scripted"); + } else if (command.startsWith("MAIL FROM")) { + reply(out, "250 ok"); + } else if (command.startsWith("RCPT TO")) { + reply(out, recipientReply); + } else if (command.startsWith("DATA")) { + reply(out, "354 go ahead"); + while ((line = in.readLine()) != null && !line.equals(".")) { + // the body + } + if (bodyReply == null) { + return; + } + reply(out, bodyReply); + } else if (command.startsWith("QUIT")) { + reply(out, "221 bye"); + return; + } else { + reply(out, "250 ok"); + } + } + } catch (IOException closed) { + // the test is over + } + } + + private static void reply(OutputStream out, String line) throws IOException { + out.write((line + "\r\n").getBytes(StandardCharsets.US_ASCII)); + out.flush(); + } + + @Override + public void close() throws Exception { + socket.close(); + worker.join(5_000); + } + } +} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpAttachmentBodyTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpAttachmentBodyTest.java index 4d8c7bce..f7f68632 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpAttachmentBodyTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpAttachmentBodyTest.java @@ -5,11 +5,11 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmContactPointProtector; import dev.caskeleton.adapter.outbound.notification.platform.security.SecurityFixtures; -import dev.caskeleton.adapter.outbound.notification.platform.testkit.ProviderFixtures; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.contact.EmailAddress; import dev.caskeleton.application.notification.platform.provider.ProviderSubmission; import dev.caskeleton.application.notification.platform.provider.ResolvedAttachment; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderFixtures; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import jakarta.mail.Session; import jakarta.mail.internet.MimeMessage; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpNotificationProviderAdapterTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpNotificationProviderAdapterTest.java index 899a37ff..562491ab 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpNotificationProviderAdapterTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/SmtpNotificationProviderAdapterTest.java @@ -5,7 +5,6 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmContactPointProtector; import dev.caskeleton.adapter.outbound.notification.platform.security.SecurityFixtures; -import dev.caskeleton.adapter.outbound.notification.platform.testkit.ProviderFixtures; import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; @@ -16,6 +15,7 @@ import dev.caskeleton.application.notification.platform.contact.EmailAddress; import dev.caskeleton.application.notification.platform.contact.PhoneNumber; import dev.caskeleton.application.notification.platform.provider.ProviderCallNotStartedException; import dev.caskeleton.application.notification.platform.provider.ProviderSubmission; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderFixtures; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import jakarta.mail.Session; import java.time.Duration; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ContractAdapters.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ContractAdapters.java index ba132e37..97dcb76b 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ContractAdapters.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ContractAdapters.java @@ -14,6 +14,8 @@ import dev.caskeleton.application.notification.platform.contact.EmailAddress; import dev.caskeleton.application.notification.platform.dispatch.AttachmentIntegrityGuard; import dev.caskeleton.application.notification.platform.provider.NotificationProviderAdapter; import dev.caskeleton.application.notification.platform.provider.ProviderSubmission; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderFaultHarness; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderFixtures; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import jakarta.mail.Session; import java.time.Clock; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/CrossProviderContractSuiteTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/CrossProviderContractSuiteTest.java index 3319eb9d..5098ecdf 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/CrossProviderContractSuiteTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/CrossProviderContractSuiteTest.java @@ -7,6 +7,8 @@ import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOut import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderFaultHarness; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderFixtures; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/NotificationChaosSecurityTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/NotificationChaosSecurityTest.java index 199d6ba1..83bf3261 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/NotificationChaosSecurityTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/NotificationChaosSecurityTest.java @@ -5,6 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderFaultHarness; +import dev.caskeleton.application.notification.platform.provider.testkit.ProviderFixtures; import java.util.ArrayList; import java.util.List; import java.util.Map; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/CallbackContract.java b/src/adapter/outbound/notification/src/testFixtures/java/dev/caskeleton/adapter/outbound/notification/platform/callback/testkit/CallbackContract.java similarity index 80% rename from src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/CallbackContract.java rename to src/adapter/outbound/notification/src/testFixtures/java/dev/caskeleton/adapter/outbound/notification/platform/callback/testkit/CallbackContract.java index f3549586..aee14bc6 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/CallbackContract.java +++ b/src/adapter/outbound/notification/src/testFixtures/java/dev/caskeleton/adapter/outbound/notification/platform/callback/testkit/CallbackContract.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.notification.platform.testkit; +package dev.caskeleton.adapter.outbound.notification.platform.callback.testkit; import static org.assertj.core.api.Assertions.assertThat; @@ -7,6 +7,7 @@ import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCa import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackVerificationRequest; import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** @@ -17,7 +18,10 @@ import org.junit.jupiter.api.Test; * order, and they can be forged by anyone who can reach the endpoint. A per-provider test tends to * cover whichever of the three that provider's documentation happens to mention. * - *

        Subclasses supply a signed request and a tampered one; the assertions live here. + *

        Subclasses supply a signed request and a tampered one; the assertions live here. It sits in + * this leaf's test fixtures because {@link ProviderCallbackAdapter} is this leaf's port: an adapter + * written in another leaf extends the same contract (capability criterion 5). It lived in {@code + * src/test} with no subclass at all, so nothing ran it (review 05-16). */ public abstract class CallbackContract { @@ -34,6 +38,7 @@ public abstract class CallbackContract { protected abstract ProviderCallbackVerificationRequest unsignedRequest(); @Test + @DisplayName("서명이 맞는 콜백은 받아들여지고 검증된 콜백을 싣는다") void aValidSignatureIsAcceptedAndCarriesTheVerifiedCallback() { CallbackVerificationResult verification = adapter().verify(signedRequest()); @@ -42,6 +47,7 @@ public abstract class CallbackContract { } @Test + @DisplayName("서명된 필드 하나가 바뀐 콜백은 거절되고 ledger에 닿지 않는다") void aTamperedFieldIsRejectedAndNeverReachesTheLedger() { CallbackVerificationResult verification = adapter().verify(tamperedRequest()); @@ -53,6 +59,7 @@ public abstract class CallbackContract { } @Test + @DisplayName("서명이 없는 콜백은 인증 없는 요청으로 통과하지 않고 거절된다") void anUnsignedCallbackIsRejectedRatherThanTreatedAsUnauthenticated() { CallbackVerificationResult verification = adapter().verify(unsignedRequest()); @@ -61,6 +68,7 @@ public abstract class CallbackContract { } @Test + @DisplayName("같은 콜백을 두 번 받아도 같은 이벤트가 나온다") void verificationIsPureSoADuplicateDeliveryProducesTheSameEvents() { ProviderCallbackVerificationRequest request = signedRequest(); @@ -76,6 +84,7 @@ public abstract class CallbackContract { } @Test + @DisplayName("정규화한 이벤트는 모두 provider 요청 식별자를 싣는다") void normalizationProducesEventsCarryingAProviderCorrelationHandle() { List events = adapter().normalize(adapter().verify(signedRequest()).verifiedCallback().orElseThrow()); @@ -87,6 +96,7 @@ public abstract class CallbackContract { } @Test + @DisplayName("거절 사유와 요청 표현에 본문이 드러나지 않는다") void aRejectedVerificationNeverEchoesTheBody() { CallbackVerificationResult verification = adapter().verify(tamperedRequest()); diff --git a/src/adapter/outbound/objectstorage/README.md b/src/adapter/outbound/objectstorage/README.md index dbcd9ba1..26eed116 100644 --- a/src/adapter/outbound/objectstorage/README.md +++ b/src/adapter/outbound/objectstorage/README.md @@ -92,6 +92,17 @@ cd src ./gradlew :adapter:outbound:objectstorage:check --console=plain ``` +### Provider contract for a new provider + +`ObjectStorageProviderContract` is in this leaf's test fixtures, because the `ObjectStorageProvider` +SPI is this leaf's own. The local-dev provider (`LocalDevObjectStorageProviderTest`) and the S3 +provider against MinIO (`MinioS3ManagedObjectProviderContractTest`) both extend it. A provider a +derived service adds extends the same class instead of copying it: + +```groovy +testImplementation testFixtures(project(':adapter:outbound:objectstorage')) +``` + ### MinIO qualification lanes `objectStorageMinioContractTest` and `objectStorageMinioFaultTest` (in `mainCheck`) run a real MinIO diff --git a/src/adapter/outbound/objectstorage/build.gradle b/src/adapter/outbound/objectstorage/build.gradle index 7ed416a4..ff65bbb7 100644 --- a/src/adapter/outbound/objectstorage/build.gradle +++ b/src/adapter/outbound/objectstorage/build.gradle @@ -1,6 +1,10 @@ plugins { id 'ca.spring-library' id 'ca.spring-config' + // The provider contract (ObjectStorageProviderContract) is the port owner's to publish: the + // provider SPI is this leaf's own, so a derived service's provider inherits the same contract + // the local-dev and S3 providers pass (AGENTS.md rule 6, capability criterion 5; review 05-16). + id 'java-test-fixtures' } // Driven adapter: provider-neutral semantic object-storage ports plus a bounded local-development @@ -26,6 +30,7 @@ testing { integrationTest(JvmTestSuite) { dependencies { implementation project() + implementation testFixtures(project()) } } objectStorageAwsQualificationTest(JvmTestSuite) { @@ -78,6 +83,14 @@ dependencies { integrationTestImplementation 'org.testcontainers:testcontainers-toxiproxy' testImplementation libs.archunit.junit5 testImplementation libs.jqwik + + // The contract's own signature names the provider SPI's application-objectstorage types, so an + // inheriting test sees them through the fixtures (api), and it is a JUnit test class written with + // AssertJ. It named an application-core type too until CallBudget moved into + // application-objectstorage (review 2026-11-01 01-10), so that edge went with it. + testFixturesApi project(':application-objectstorage') + testFixturesApi 'org.junit.jupiter:junit-jupiter-api' + testFixturesImplementation 'org.assertj:assertj-core' } def objectStorageReadinessRegistry = rootProject.projectDir.parentFile.toPath() diff --git a/src/adapter/outbound/objectstorage/gradle.lockfile b/src/adapter/outbound/objectstorage/gradle.lockfile index 1a4b6cc5..70507bf9 100644 --- a/src/adapter/outbound/objectstorage/gradle.lockfile +++ b/src/adapter/outbound/objectstorage/gradle.lockfile @@ -5,33 +5,33 @@ biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=integrationTestCompileClasspath,obj ch.qos.logback:logback-classic:1.5.38=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath ch.qos.logback:logback-core:1.5.38=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath com.fasterxml.jackson.core:jackson-annotations:2.21=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.github.docker-java:docker-java-api:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath com.github.docker-java:docker-java-transport-zerodep:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath com.github.docker-java:docker-java-transport:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,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,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs com.google.code.gson:gson:2.13.2=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.errorprone:error_prone_annotations:2.38.0=objectStorageAwsQualificationTestCompileClasspath,testCompileClasspath com.google.errorprone:error_prone_annotations:2.41.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,spotbugs com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,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,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle @@ -42,38 +42,38 @@ com.tngtech.archunit:archunit-junit5:1.3.0=integrationTestCompileClasspath,integ com.tngtech.archunit:archunit:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath com.vaadin.external.google:android-json:0.0.20131108.vaadin1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle -commons-codec:commons-codec:1.19.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath +commons-codec:commons-codec:1.19.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle commons-io:commons-io:2.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath commons-io:commons-io:2.21.0=spotbugs -commons-logging:commons-logging:1.3.6=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +commons-logging:commons-logging:1.3.6=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath eu.rekawek.toxiproxy:toxiproxy-java:2.1.11=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -io.micrometer:micrometer-commons:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-buffer:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-base:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-compression:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-http2:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-http:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-marshalling:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-protobuf:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-common:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-handler:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-resolver:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-transport-classes-epoll:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-transport-native-unix-common:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-transport:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.micrometer:micrometer-commons:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-buffer:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-codec-base:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-codec-compression:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-codec-http2:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-codec-http:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-codec-marshalling:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-codec-protobuf:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-codec:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-common:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-handler:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-resolver:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-transport-classes-epoll:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-transport-native-unix-common:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-transport:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath jakarta.activation:jakarta.activation-api:2.1.4=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor +javax.inject:javax.inject:1=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy-agent:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath net.jqwik:jqwik-api:1.9.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath net.jqwik:jqwik-engine:1.9.1=integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestRuntimeClasspath,testRuntimeClasspath @@ -89,8 +89,8 @@ org.apache.commons:commons-compress:1.28.0=integrationTestCompileClasspath,integ org.apache.commons:commons-lang3:3.20.0=checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,spotbugs org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath -org.apache.httpcomponents:httpcore:4.4.16=checkstyle,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath +org.apache.httpcomponents:httpclient:4.5.13=checkstyle,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.apache.httpcomponents:httpcore:4.4.16=checkstyle,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-api:2.25.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-core:2.25.5=spotbugs org.apache.logging.log4j:log4j-to-slf4j:2.25.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -102,8 +102,8 @@ org.apache.tomcat.embed:tomcat-embed-core:11.0.24=integrationTestCompileClasspat org.apache.tomcat.embed:tomcat-embed-el:11.0.24=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.assertj:assertj-core:3.27.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testRuntimeClasspath +org.assertj:assertj-core:3.27.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.awaitility:awaitility:4.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle @@ -113,20 +113,20 @@ org.dom4j:dom4j:2.2.0=spotbugs org.hamcrest:hamcrest:3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestAnnotationProcessor,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestAnnotationProcessor,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-params:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestRuntimeClasspath,testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestRuntimeClasspath,testRuntimeClasspath -org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs org.mockito:mockito-core:5.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,mockitoAgent,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.mockito:mockito-junit-jupiter:5.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.objenesis:objenesis:3.3=integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestRuntimeClasspath,testRuntimeClasspath -org.opentest4j:opentest4j:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.osgi:org.osgi.annotation.bundle:2.0.0=integrationTestCompileClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioFaultTestCompileClasspath,testCompileClasspath org.osgi:org.osgi.annotation.versioning:1.1.2=integrationTestCompileClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioFaultTestCompileClasspath,testCompileClasspath org.osgi:org.osgi.resource:1.0.0=integrationTestCompileClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioFaultTestCompileClasspath,testCompileClasspath @@ -137,16 +137,16 @@ org.ow2.asm:asm-tree:9.10.1=spotbugs org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs org.ow2.asm:asm:9.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.pcollections:pcollections:4.0.1=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor -org.reactivestreams:reactive-streams:1.0.4=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,integrationTestAnnotationProcessor,objectStorageAwsQualificationTestAnnotationProcessor,objectStorageMinioContractTestAnnotationProcessor,objectStorageMinioFaultTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +org.reactivestreams:reactive-streams:1.0.4=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.rnorth.duct-tape:duct-tape:1.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath org.skyscreamer:jsonassert:1.5.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.slf4j:jul-to-slf4j:2.0.18=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.slf4j:slf4j-api:2.0.18=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor org.springframework.boot:spring-boot-http-converter:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-jackson:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -167,12 +167,12 @@ org.springframework.boot:spring-boot-tomcat:4.0.8=integrationTestCompileClasspat org.springframework.boot:spring-boot-web-server:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-webmvc-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-webmvc:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-aop:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-beans:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-context:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-core:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-expression:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-web:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -182,36 +182,36 @@ org.testcontainers:testcontainers:2.0.5=integrationTestCompileClasspath,integrat org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.yaml:snakeyaml:2.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:annotations:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:apache-client:2.30.0=integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath -software.amazon.awssdk:arns:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:auth:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:aws-core:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:aws-query-protocol:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:aws-xml-protocol:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:checksums-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:checksums:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:crt-core:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:endpoints-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:http-auth-aws-eventstream:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:http-auth-aws:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:http-auth-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:http-auth:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:http-client-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:identity-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:json-utils:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:metrics-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:netty-nio-client:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:profiles:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:protocol-core:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:regions:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:retries-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:retries:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:s3:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:sdk-core:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:third-party-jackson-core:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.awssdk:utils:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -software.amazon.eventstream:eventstream:1.0.1=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:annotations:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:apache-client:2.30.0=integrationTestRuntimeClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:arns:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:auth:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:aws-core:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:aws-query-protocol:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:aws-xml-protocol:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:checksums-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:checksums:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:crt-core:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:endpoints-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-aws-eventstream:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-aws:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-auth:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:http-client-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:identity-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:json-utils:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:metrics-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:netty-nio-client:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:profiles:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:protocol-core:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:regions:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:retries-spi:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:retries:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:s3:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:sdk-core:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:third-party-jackson-core:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.awssdk:utils:2.30.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +software.amazon.eventstream:eventstream:1.0.1=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath tools.jackson.core:jackson-core:3.1.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath tools.jackson.core:jackson-databind:3.1.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath tools.jackson:jackson-bom:3.1.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,objectStorageAwsQualificationTestCompileClasspath,objectStorageAwsQualificationTestRuntimeClasspath,objectStorageMinioContractTestCompileClasspath,objectStorageMinioContractTestRuntimeClasspath,objectStorageMinioFaultTestCompileClasspath,objectStorageMinioFaultTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java index 78941106..3738c9ad 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java @@ -5,7 +5,7 @@ import dev.caskeleton.adapter.outbound.objectstorage.kernel.ObjectPublicationHan import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectMutationAdapter; import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectReadAdapter; import dev.caskeleton.adapter.outbound.objectstorage.s3.S3ObjectStorageProviderContribution; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import java.time.Clock; import java.util.Arrays; import java.util.List; diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageDestinationSettings.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageDestinationSettings.java index eb8e5a2d..978386f8 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageDestinationSettings.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageDestinationSettings.java @@ -32,15 +32,18 @@ public record ObjectStorageDestinationSettings( encryptionRequirement == null ? ObjectEncryptionRequirement.PROVIDER_MANAGED : encryptionRequirement; + // Both branches end in an unmodifiable copy. The default used to be the EnumSet itself, so a + // destination that relied on it handed out a set any holder could shrink. capabilityRequirements = - capabilityRequirements == null - ? EnumSet.of( - ObjectCapabilityRequirement.IMMUTABLE_CREATE, - ObjectCapabilityRequirement.EXACT_VERSION_READ, - ObjectCapabilityRequirement.CONDITIONAL_RETIREMENT, - ObjectCapabilityRequirement.SHA_256_VERIFICATION, - ObjectCapabilityRequirement.RESPONSE_LOSS_RECONCILIATION) - : Set.copyOf(capabilityRequirements); + Set.copyOf( + capabilityRequirements == null + ? EnumSet.of( + ObjectCapabilityRequirement.IMMUTABLE_CREATE, + ObjectCapabilityRequirement.EXACT_VERSION_READ, + ObjectCapabilityRequirement.CONDITIONAL_RETIREMENT, + ObjectCapabilityRequirement.SHA_256_VERIFICATION, + ObjectCapabilityRequirement.RESPONSE_LOSS_RECONCILIATION) + : capabilityRequirements); minimumReplayHorizon = minimumReplayHorizon == null ? Duration.ofDays(7) : minimumReplayHorizon; } } diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalObjectStreamTransfer.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalObjectStreamTransfer.java index 704d499d..2c5eb06f 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalObjectStreamTransfer.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/filesystem/LocalObjectStreamTransfer.java @@ -166,7 +166,7 @@ public final class LocalObjectStreamTransfer { } private static void requireActive( - dev.caskeleton.application.outbound.CallBudget budget, boolean cancelled) { + dev.caskeleton.application.objectstorage.content.CallBudget budget, boolean cancelled) { if (cancelled) { throw new ObjectStorageProviderException( ObjectStorageProviderException.Failure.CANCELLED, "object transfer is cancelled"); diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/provider/ObjectStorageProvider.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/provider/ObjectStorageProvider.java index 13f41406..4212768b 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/provider/ObjectStorageProvider.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/provider/ObjectStorageProvider.java @@ -1,12 +1,12 @@ package dev.caskeleton.adapter.outbound.objectstorage.provider; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.content.ObjectContentConsumer; import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectReadRange; -import dev.caskeleton.application.outbound.CallBudget; import java.util.Objects; import java.util.Optional; diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/provider/ObjectStorageProviderOperation.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/provider/ObjectStorageProviderOperation.java index 08961f7d..4ddff77e 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/provider/ObjectStorageProviderOperation.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/provider/ObjectStorageProviderOperation.java @@ -1,10 +1,10 @@ package dev.caskeleton.adapter.outbound.objectstorage.provider; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectMediaType; -import dev.caskeleton.application.outbound.CallBudget; import java.util.Objects; /** Exact bounded internal create request; the physical key is adapter-generated and canonical. */ diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java index 3688afa5..7e5f9d2b 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ObjectStorageProviderContribution.java @@ -7,7 +7,7 @@ import dev.caskeleton.adapter.outbound.objectstorage.config.SelectedObjectStorag import dev.caskeleton.adapter.outbound.objectstorage.control.CanonicalJsonObjectControlRecordCodec; import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProvider; import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderDescriptor; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import java.time.Clock; import java.util.Arrays; import java.util.Set; diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfigTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfigTest.java index fb832749..68756149 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfigTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfigTest.java @@ -7,6 +7,7 @@ import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProvi import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderDescriptor; import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectMutationAdapter; import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectReadAdapter; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; import dev.caskeleton.application.objectstorage.identity.ObjectOperationEpoch; @@ -22,7 +23,6 @@ import dev.caskeleton.application.objectstorage.model.ObjectRetentionRequirement import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; import dev.caskeleton.application.objectstorage.port.ObjectScanMaintenancePort; import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; -import dev.caskeleton.application.outbound.CallBudget; import java.nio.file.Path; import java.time.Duration; import java.util.EnumSet; diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageDestinationSettingsTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageDestinationSettingsTest.java new file mode 100644 index 00000000..6b164a54 --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageDestinationSettingsTest.java @@ -0,0 +1,38 @@ +package dev.caskeleton.adapter.outbound.objectstorage.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.objectstorage.model.ObjectCapabilityRequirement; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The capability requirements a destination declares are what the binding compiler checks the + * provider against. A set that a holder of the settings can shrink afterwards weakens a destination + * that has already been accepted. + */ +class ObjectStorageDestinationSettingsTest { + + @Test + @DisplayName("기본 capability 요구 집합은 받은 쪽에서 줄일 수 없다") + void theDefaultCapabilityRequirementsCannotBeShrunkByTheirHolder() { + // given + ObjectStorageDestinationSettings settings = + new ObjectStorageDestinationSettings( + "local", "route", "binding-v1", "policy-v1", null, null, null, null, null, null); + + // when + Throwable refused = + catchThrowable( + () -> + settings + .capabilityRequirements() + .remove(ObjectCapabilityRequirement.SHA_256_VERIFICATION)); + + // then + assertThat(refused).isInstanceOf(UnsupportedOperationException.class); + assertThat(settings.capabilityRequirements()) + .contains(ObjectCapabilityRequirement.SHA_256_VERIFICATION); + } +} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/StagedObjectPublicationLifecycleTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/StagedObjectPublicationLifecycleTest.java index ae1c0244..2cbc577b 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/StagedObjectPublicationLifecycleTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/StagedObjectPublicationLifecycleTest.java @@ -23,6 +23,7 @@ import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProvi import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectMutationAdapter; import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectReadAdapter; import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectScanMaintenanceAdapter; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; import dev.caskeleton.application.objectstorage.identity.ObjectOperationEpoch; @@ -56,7 +57,6 @@ import dev.caskeleton.application.objectstorage.request.ObjectReadRequest; import dev.caskeleton.application.objectstorage.request.ObjectScanVerdictRequest; import dev.caskeleton.application.objectstorage.request.ObjectStageRequest; import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; -import dev.caskeleton.application.outbound.CallBudget; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Path; diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/routing/RoutingObjectStorageAdapterTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/routing/RoutingObjectStorageAdapterTest.java index c16f793b..576dda34 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/routing/RoutingObjectStorageAdapterTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/routing/RoutingObjectStorageAdapterTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.objectstorage.routing; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageCapabilityConfig; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; import dev.caskeleton.application.objectstorage.identity.ObjectOperationEpoch; @@ -24,7 +25,6 @@ import dev.caskeleton.application.objectstorage.port.ObjectInspectionPort; import dev.caskeleton.application.objectstorage.port.ObjectTransferPort; import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; import dev.caskeleton.application.objectstorage.request.ObjectReadRequest; -import dev.caskeleton.application.outbound.CallBudget; import java.io.ByteArrayOutputStream; import java.nio.file.Path; import java.time.Duration; diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridgeTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridgeTest.java index b9db9a95..f854e2cb 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridgeTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncRequestBodyBridgeTest.java @@ -107,7 +107,8 @@ class S3AsyncRequestBodyBridgeTest { dev.caskeleton.application.objectstorage.model.ObjectDigest.sha256( new byte[] {9})), operation.mediaType(), - dev.caskeleton.application.outbound.CallBudget.fromNow(Duration.ofSeconds(5)), + dev.caskeleton.application.objectstorage.content.CallBudget.fromNow( + Duration.ofSeconds(5)), operation.cancellation(), operation.maximumChunkBytes(), operation.maximumObjectBytes()); diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridgeTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridgeTest.java index 80dc41b1..ace4c3db 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridgeTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3AsyncResponseBodyBridgeTest.java @@ -7,9 +7,9 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.objectstorage.contract.ObjectStorageProviderContract; import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProvider; import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderException; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.model.ObjectReadRange; -import dev.caskeleton.application.outbound.CallBudget; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.time.Duration; diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ManagedObjectProviderTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ManagedObjectProviderTest.java index d5f328d5..fb9095ae 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ManagedObjectProviderTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ManagedObjectProviderTest.java @@ -12,9 +12,9 @@ import dev.caskeleton.adapter.outbound.objectstorage.contract.ObjectStorageProvi import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProvider; import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderException; import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderOperation; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.model.ObjectReadRange; -import dev.caskeleton.application.outbound.CallBudget; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.time.Clock; diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderCompositionTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderCompositionTest.java index 9737b70c..531ab178 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderCompositionTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/s3/S3ProviderCompositionTest.java @@ -20,7 +20,7 @@ import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageProvide import dev.caskeleton.adapter.outbound.objectstorage.config.SelectedObjectStorageProviderFactory; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; import dev.caskeleton.application.objectstorage.model.ObjectCapabilityRequirement; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import java.nio.file.Path; import java.time.Clock; import java.time.Duration; diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/ObjectStorageProviderContract.java b/src/adapter/outbound/objectstorage/src/testFixtures/java/dev/caskeleton/adapter/outbound/objectstorage/contract/ObjectStorageProviderContract.java similarity index 52% rename from src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/ObjectStorageProviderContract.java rename to src/adapter/outbound/objectstorage/src/testFixtures/java/dev/caskeleton/adapter/outbound/objectstorage/contract/ObjectStorageProviderContract.java index ace0020d..38146d51 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/ObjectStorageProviderContract.java +++ b/src/adapter/outbound/objectstorage/src/testFixtures/java/dev/caskeleton/adapter/outbound/objectstorage/contract/ObjectStorageProviderContract.java @@ -2,32 +2,47 @@ package dev.caskeleton.adapter.outbound.objectstorage.contract; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.objectstorage.codec.ObjectDataKeyCodec; import dev.caskeleton.adapter.outbound.objectstorage.kernel.ObjectRouteToken; import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProvider; import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderException; import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderOperation; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; +import dev.caskeleton.application.objectstorage.content.ObjectChunkSource; +import dev.caskeleton.application.objectstorage.content.ObjectContentConsumptionException; import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; +import dev.caskeleton.application.objectstorage.content.ObjectContentProductionException; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; import dev.caskeleton.application.objectstorage.identity.ObjectId; import dev.caskeleton.application.objectstorage.identity.ObjectOperationEpoch; import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; +import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectDigest; import dev.caskeleton.application.objectstorage.model.ObjectMediaType; import dev.caskeleton.application.objectstorage.model.ObjectReadRange; -import dev.caskeleton.application.outbound.CallBudget; import java.io.ByteArrayOutputStream; import java.time.Duration; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -/** Non-skipping bounded provider contract. Optional capabilities assert descriptors explicitly. */ +/** + * Non-skipping bounded provider contract. Optional capabilities assert descriptors explicitly. + * + *

        Published in this leaf's test fixtures because the {@link ObjectStorageProvider} SPI is this + * leaf's own: the local-dev provider, the S3 provider against MinIO and a provider a derived + * service adds all inherit this one class ({@code testImplementation + * testFixtures(project(':adapter:outbound:objectstorage'))}), so no provider is held to a copy. + */ public abstract class ObjectStorageProviderContract { protected static final int CHUNK_BYTES = 64; @@ -36,21 +51,34 @@ public abstract class ObjectStorageProviderContract { protected abstract ObjectStorageProvider provider(); @Test - void storesBoundarySizesWithoutAWholeObjectProviderApi() { + @DisplayName("청크 경계 크기(0·1·청크-1·청크·청크+1·최대)의 객체를 저장하면 같은 내용 식별자로 다시 조회된다") + void objectsAtEveryChunkBoundarySizeAreStoredWithTheirContentIdentity() { + // given int[] sizes = {0, 1, CHUNK_BYTES - 1, CHUNK_BYTES, CHUNK_BYTES + 1, MAXIMUM_BYTES}; - for (int index = 0; index < sizes.length; index++) { - byte[] content = content(sizes[index]); - ObjectStorageProvider.StoredData stored = - provider() - .create(operation(index + 1, content, CancellationView.never()), producer(content)); + List contents = + Arrays.stream(sizes).mapToObj(ObjectStorageProviderContract::content).toList(); - assertThat(stored.contentIdentity()).isEqualTo(identity(content)); - assertThat(provider().inspect(stored.canonicalDataKey())).contains(stored); + // when + List stored = new ArrayList<>(); + for (int index = 0; index < contents.size(); index++) { + byte[] content = contents.get(index); + stored.add( + provider() + .create(operation(index + 1, content, CancellationView.never()), producer(content))); + } + + // then + for (int index = 0; index < contents.size(); index++) { + assertThat(stored.get(index).contentIdentity()).isEqualTo(identity(contents.get(index))); + assertThat(provider().inspect(stored.get(index).canonicalDataKey())) + .contains(stored.get(index)); } } @Test - void immutableCreateConflictsAndResolutionDoesNotReplayProducer() { + @DisplayName("같은 operation으로 다시 만들면 충돌로 거부되고, 처음 만든 결과는 APPLIED로 확인되며 producer를 다시 부르지 않는다") + void aSecondCreateOfTheSameOperationConflictsAndTheFirstResolvesAsAppliedWithoutReplay() { + // given: the operation was applied once, through a producer that records being called byte[] content = content(10); ObjectStorageProviderOperation operation = operation(20, content, CancellationView.never()); AtomicBoolean invoked = new AtomicBoolean(); @@ -62,10 +90,13 @@ public abstract class ObjectStorageProviderContract { invoked.set(true); sink.write(content, 0, content.length); }); - invoked.set(false); - assertThatThrownBy(() -> provider().create(operation, producer(content))) - .isInstanceOf(ObjectStorageProviderException.class); + + // when + Throwable conflict = catchThrowable(() -> provider().create(operation, producer(content))); + + // then + assertThat(conflict).isInstanceOf(ObjectStorageProviderException.class); assertThat(provider().resolveCreate(operation)) .isEqualTo(ObjectStorageProvider.Resolution.APPLIED); assertThat(invoked).isFalse(); @@ -73,116 +104,181 @@ public abstract class ObjectStorageProviderContract { } @Test - void fullAndContiguousRangeReadsAreBoundedAndInvalidateTheSource() { + @DisplayName("전체 읽기는 저장한 바이트를 그대로 주고, transfer가 끝난 뒤 그 source는 더 읽을 수 없다") + void aFullReadReturnsEveryStoredByteAndInvalidatesItsSourceAfterTheTransfer() { + // given byte[] content = content(200); ObjectStorageProvider.StoredData stored = provider().create(operation(30, content, CancellationView.never()), producer(content)); - AtomicReference escaped = - new AtomicReference<>(); + AtomicReference escaped = new AtomicReference<>(); ByteArrayOutputStream full = new ByteArrayOutputStream(); + + // when provider() .transfer( read(stored, ObjectReadRange.of(0, content.length)), (context, source) -> { escaped.set(source); - byte[] buffer = new byte[CHUNK_BYTES]; - for (int count = source.read(buffer, 0, buffer.length); - count != -1; - count = source.read(buffer, 0, buffer.length)) { - full.write(buffer, 0, count); - } - }); - - ByteArrayOutputStream range = new ByteArrayOutputStream(); - provider() - .transfer( - read(stored, ObjectReadRange.of(17, 83)), - (context, source) -> { - byte[] buffer = new byte[19]; - for (int count = source.read(buffer, 0, buffer.length); - count != -1; - count = source.read(buffer, 0, buffer.length)) { - range.write(buffer, 0, count); - } + drain(source, CHUNK_BYTES, full); }); + // then assertThat(full.toByteArray()).containsExactly(content); - assertThat(range.toByteArray()).containsExactly(Arrays.copyOfRange(content, 17, 100)); assertThatThrownBy(() -> escaped.get().read(new byte[1], 0, 1)) .isInstanceOf(IllegalStateException.class); } @Test - void shortFailingAndCancelledProductionLeavesNoPublishedData() { + @DisplayName("연속 범위 읽기는 그 범위의 바이트만 준다") + void aContiguousRangeReadReturnsExactlyThatRange() { + // given + byte[] content = content(200); + ObjectStorageProvider.StoredData stored = + provider().create(operation(31, content, CancellationView.never()), producer(content)); + ByteArrayOutputStream range = new ByteArrayOutputStream(); + + // when + provider() + .transfer( + read(stored, ObjectReadRange.of(17, 83)), + (context, source) -> drain(source, 19, range)); + + // then + assertThat(range.toByteArray()).containsExactly(Arrays.copyOfRange(content, 17, 100)); + } + + @Test + @DisplayName("producer가 선언한 크기보다 적게 쓰면 create가 실패하고 게시된 데이터가 남지 않는다") + void aProducerThatWritesLessThanDeclaredFailsAndPublishesNothing() { + // given byte[] content = content(20); ObjectStorageProviderOperation shortOperation = operation(40, content, CancellationView.never()); - assertThatThrownBy( + + // when + Throwable failure = + catchThrowable( () -> provider() .create( shortOperation, - (context, sink) -> sink.write(content, 0, content.length - 1))) - .isInstanceOf(ObjectStorageProviderException.class); - assertThat(provider().inspect(shortOperation.canonicalDataKey())).isEmpty(); + (context, sink) -> sink.write(content, 0, content.length - 1))); + // then + assertThat(failure).isInstanceOf(ObjectStorageProviderException.class); + assertThat(provider().inspect(shortOperation.canonicalDataKey())).isEmpty(); + } + + @Test + @DisplayName("producer가 실패하면 create가 실패하고 게시된 데이터가 남지 않는다") + void aFailingProducerFailsTheCreateAndPublishesNothing() { + // given + byte[] content = content(20); ObjectStorageProviderOperation failing = operation(41, content, CancellationView.never()); - assertThatThrownBy( + + // when + Throwable failure = + catchThrowable( () -> provider() .create( failing, (context, sink) -> { - throw new dev.caskeleton.application.objectstorage.content - .ObjectContentProductionException("producer failed"); - })) - .isInstanceOf(ObjectStorageProviderException.class); - assertThat(provider().inspect(failing.canonicalDataKey())).isEmpty(); + throw new ObjectContentProductionException("producer failed"); + })); + // then + assertThat(failure).isInstanceOf(ObjectStorageProviderException.class); + assertThat(provider().inspect(failing.canonicalDataKey())).isEmpty(); + } + + @Test + @DisplayName("취소된 operation의 create는 실패하고 게시된 데이터가 남지 않는다") + void aCancelledCreateFailsAndPublishesNothing() { + // given + byte[] content = content(20); ObjectStorageProviderOperation cancelled = operation(42, content, () -> true); - assertThatThrownBy(() -> provider().create(cancelled, producer(content))) - .isInstanceOf(ObjectStorageProviderException.class); + + // when + Throwable failure = catchThrowable(() -> provider().create(cancelled, producer(content))); + + // then + assertThat(failure).isInstanceOf(ObjectStorageProviderException.class); assertThat(provider().inspect(cancelled.canonicalDataKey())).isEmpty(); } @Test - void checksumMismatchFailsAndExactVersionRetirementIsConditional() { + @DisplayName("내용이 선언한 digest와 다르면 create가 실패한다") + void aCreateWhoseContentDoesNotMatchTheDeclaredDigestFails() { + // given byte[] content = content(32); + ObjectStorageProviderOperation declared = operation(50, content, CancellationView.never()); ObjectStorageProviderOperation wrongDigest = new ObjectStorageProviderOperation( - operation(50, content, CancellationView.never()).operationKey(), - operation(50, content, CancellationView.never()).canonicalDataKey(), + declared.operationKey(), + declared.canonicalDataKey(), new ObjectContentIdentity(content.length, ObjectDigest.sha256(new byte[] {9})), ObjectMediaType.of("application/octet-stream"), CallBudget.fromNow(Duration.ofMinutes(1)), CancellationView.never(), CHUNK_BYTES, MAXIMUM_BYTES); - assertThatThrownBy(() -> provider().create(wrongDigest, producer(content))) - .isInstanceOf(ObjectStorageProviderException.class); + // when + Throwable failure = catchThrowable(() -> provider().create(wrongDigest, producer(content))); + + // then + assertThat(failure).isInstanceOf(ObjectStorageProviderException.class); + } + + @Test + @DisplayName("저장된 것과 다른 version으로 retire하면 거부된다") + void retiringWithAVersionOtherThanTheStoredOneIsRefused() { + // given + byte[] content = content(32); ObjectStorageProvider.StoredData stored = provider().create(operation(51, content, CancellationView.never()), producer(content)); - assertThat( - provider() - .retire( - new ObjectStorageProvider.RetireOperation( - stored.canonicalDataKey(), - dev.caskeleton.application.objectstorage.identity.ObjectVersionToken.parse( - "osv1.0123456789ab.11111111111111111111111111.36da73f19a")))) - .isFalse(); - assertThat( - provider() - .retire( - new ObjectStorageProvider.RetireOperation( - stored.canonicalDataKey(), stored.exactVersion()))) - .isTrue(); + ObjectVersionToken otherVersion = + ObjectVersionToken.parse("osv1.0123456789ab.11111111111111111111111111.36da73f19a"); + + // when + boolean retired = + provider() + .retire( + new ObjectStorageProvider.RetireOperation(stored.canonicalDataKey(), otherVersion)); + + // then + assertThat(retired).isFalse(); + } + + @Test + @DisplayName("저장된 정확한 version으로 retire하면 데이터가 사라진다") + void retiringTheExactStoredVersionRemovesTheData() { + // given + byte[] content = content(32); + ObjectStorageProvider.StoredData stored = + provider().create(operation(52, content, CancellationView.never()), producer(content)); + + // when + boolean retired = + provider() + .retire( + new ObjectStorageProvider.RetireOperation( + stored.canonicalDataKey(), stored.exactVersion())); + + // then + assertThat(retired).isTrue(); assertThat(provider().inspect(stored.canonicalDataKey())).isEmpty(); } @Test + @DisplayName("지원하지 않는 선택 기능은 건너뛰지 않고 UNSUPPORTED로 선언한다") void unsupportedOptionalCapabilitiesAreDeclaredRatherThanSkipped() { - assertThat(provider().descriptor().support()) + // when + var support = provider().descriptor().support(); + + // then + assertThat(support) .containsEntry( ObjectStorageProvider.Capability.MULTI_NODE_LINEARIZABLE_CAS, ObjectStorageProvider.Support.UNSUPPORTED) @@ -237,6 +333,16 @@ public abstract class ObjectStorageProviderContract { return new ObjectContentIdentity(content.length, ObjectDigest.sha256(content)); } + private static void drain(ObjectChunkSource source, int bufferBytes, ByteArrayOutputStream into) + throws ObjectContentConsumptionException { + byte[] buffer = new byte[bufferBytes]; + for (int count = source.read(buffer, 0, buffer.length); + count != -1; + count = source.read(buffer, 0, buffer.length)) { + into.write(buffer, 0, count); + } + } + private static byte[] content(int size) { byte[] value = new byte[size]; for (int index = 0; index < size; index++) { diff --git a/src/adapter/outbound/persistence-fileserver/CLAUDE.md b/src/adapter/outbound/persistence-fileserver/CLAUDE.md index 38c3600d..d4ae3bf1 100644 --- a/src/adapter/outbound/persistence-fileserver/CLAUDE.md +++ b/src/adapter/outbound/persistence-fileserver/CLAUDE.md @@ -11,6 +11,9 @@ store adapters that implement `application-fileserver` ports. Root `AGENTS.md` a - package root — the store adapters (`Jpa*`), `FileEntityMapper`, and the `@Configuration` classes that register them as beans. +`persistence-notification` follows the same rule (`platform.entity`, `platform.repository`, adapters +in `platform`), so the two capability leaves read the same way (review 04-16). + ## Rules - **Transactions.** A store never opens one. Every write starts with @@ -36,12 +39,23 @@ store adapters that implement `application-fileserver` ports. Root `AGENTS.md` a ## Tests -- `src/test` — this leaf's own tests, no container (`AssignedIdEntityTest` runs Hibernate on H2). - Run: `./gradlew :adapter:outbound:persistence-fileserver:test --console=plain`. +- `src/test` — this leaf's own tests, no container. Run: + `./gradlew :adapter:outbound:persistence-fileserver:test --console=plain`. + - `FileserverStoreCallerTransactionTest` — every guarded write of every store refuses without a + caller transaction before it touches a repository (the Transactions rule above, one case per + write; Spring Data repositories are mocks). + - `FileserverPersistenceActivationTest` — the scan covers this package only, behind + `app.fileserver-platform.enabled`, and runs before the JPA root auto-configuration. + - `repository.CleanupClaimSqlTest` — the claim keeps its one-statement shape (the Claims rule). + - `entity.AssignedIdEntityTest` — newness from `Persistable`, on Hibernate over H2. + A new store write adds its case to the guard test; a new auto-configuration adds its line to the + activation test. - Port contracts live in `application-fileserver` testFixtures (`*PortContract`). The in-memory fakes and the PostgreSQL tests both extend them. - The real-PostgreSQL tests are still in `persistence-jpa`'s `postgresqlIntegrationTest` source - set, which owns the container and Flyway wiring: + set, which owns the container and Flyway wiring, and the JPA readiness card + (`config/jpa/readiness-cards.yaml`, checked by `JpaReadinessRegistryTest`) names them as that + leaf's tasks — moving them means moving the card's tasks and selectors with them (review 04-04): `postgresqlFileserverMigrationIntegrationTest`, `postgresqlFileserverMetadataIntegrationTest`, `postgresqlFileserverReclamationIntegrationTest` (`./gradlew :adapter:outbound:persistence-jpa: --console=plain`). diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuota.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuota.java index be610c33..939f972b 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuota.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuota.java @@ -81,6 +81,11 @@ public class JpaFileQuota implements FileQuotaPort { reservations.release(reservation.reservationId(), clock.instant()); } + @Override + public long usedBytes(QuotaScope scope) { + return reservedBytes(scope) + committedBytes(scope); + } + /** Bytes currently reserved but not yet committed for a scope. */ public long reservedBytes(QuotaScope scope) { return reservations.sumReservedBytes(scope.type(), scope.value(), clock.instant()); diff --git a/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverPersistenceActivationTest.java b/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverPersistenceActivationTest.java new file mode 100644 index 00000000..38ba7a86 --- /dev/null +++ b/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverPersistenceActivationTest.java @@ -0,0 +1,79 @@ +package dev.caskeleton.adapter.outbound.persistence.fileserver; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.persistence.autoconfigure.EntityScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +/** + * How the leaf turns on: by being on the classpath, behind the capability switch, and early enough + * for its entities to be in the persistence unit — the same three facts the notification leaf's + * activation test states for that leaf. + */ +class FileserverPersistenceActivationTest { + + private static final String PACKAGE = "dev.caskeleton.adapter.outbound.persistence.fileserver"; + + @Test + @DisplayName("엔티티·리포지토리 스캔은 이 leaf 패키지만, 기능 스위치 뒤에서 하고 스위치가 없으면 켜진다") + void theScanCoversThisPackageOnlyAndIsBehindTheCapabilitySwitch() { + // given + Class configuration = FileserverJpaPersistenceConfig.class; + + // when + ConditionalOnProperty condition = configuration.getAnnotation(ConditionalOnProperty.class); + + // then + assertThat( + List.of( + condition.prefix(), + List.of(condition.name()), + condition.havingValue(), + condition.matchIfMissing(), + List.of(configuration.getAnnotation(EntityScan.class).basePackages()), + List.of(configuration.getAnnotation(EnableJpaRepositories.class).basePackages()))) + .as("entities without repositories is half a scan, and fails at the first query") + .containsExactly( + "app.fileserver-platform", + List.of("enabled"), + "true", + true, + List.of(PACKAGE), + List.of(PACKAGE)); + } + + @Test + @DisplayName("이 leaf의 auto-configuration은 JPA 루트보다 먼저 돈다") + void theConfigurationIsThisLeafsAutoConfigurationOrderedBeforeTheJpaRoot() throws IOException { + // given + Path imports = + Path.of( + "src/main/resources/META-INF/spring/" + + "org.springframework.boot.autoconfigure.AutoConfiguration.imports"); + + // when + AutoConfiguration root = + FileserverJpaPersistenceConfig.class.getAnnotation(AutoConfiguration.class); + + // then + assertThat( + List.of( + Files.readString(imports, StandardCharsets.UTF_8).strip(), + List.of(root.beforeName()))) + .as("an @EntityScan that arrives after the EntityManagerFactory is built is not in it") + .containsExactly( + FileserverJpaPersistenceConfig.class.getName(), + List.of( + "dev.caskeleton.adapter.outbound.persistence.autoconfigure." + + "PersistenceJpaAutoConfiguration")); + } +} diff --git a/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverStoreCallerTransactionTest.java b/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverStoreCallerTransactionTest.java new file mode 100644 index 00000000..d0cc0acc --- /dev/null +++ b/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverStoreCallerTransactionTest.java @@ -0,0 +1,127 @@ +package dev.caskeleton.adapter.outbound.persistence.fileserver; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockingDetails; + +import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileTransitionRepository; +import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileserverCleanupRepository; +import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileserverQuotaRepository; +import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileserverRecoveryRepository; +import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.JpaFileRepository; +import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.JpaUploadSessionRepository; +import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.UploadLeaseRepository; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Every write of this leaf's stores refuses to run without the caller's transaction, before it + * touches a repository — the leaf's first rule (owner decision 33), checked here without a + * database. + * + *

        A store that opened its own transaction, or wrote statement by statement, would commit half of + * a use case that failed later. The guard is the first statement of every write, so each write is + * called here with no transaction open and arguments that are never read; the repositories are + * Spring Data mocks, and none of them may have been called when the refusal arrives. The real + * PostgreSQL tests cover what the writes do inside a transaction ({@code persistence-jpa}'s + * fileserver lanes). + */ +class FileserverStoreCallerTransactionTest { + + @ParameterizedTest(name = "{0}") + @MethodSource("writes") + void aWriteOutsideACallerTransactionIsRefusedBeforeAnyStatement(String operation, Write write) { + // given + Stores stores = new Stores(); + + // when + Throwable refused = catchThrowable(() -> write.run(stores)); + + // then + assertThat(List.of(refused.getClass(), refused.getMessage(), stores.repositoryCalls())) + .containsExactly( + IllegalStateException.class, operation + " requires an active caller transaction", 0); + } + + static Stream writes() { + return Stream.of( + write("cleanup queue enqueue", s -> s.cleanup.enqueue(null)), + write("cleanup queue claimDue", s -> s.cleanup.claimDue(null, 1, null)), + write("cleanup queue reclaimExpiredClaims", s -> s.cleanup.reclaimExpiredClaims(null, 1)), + write("cleanup queue markDone", s -> s.cleanup.markDone(null)), + write("cleanup queue markFailed", s -> s.cleanup.markFailed(null, null, null)), + write("cleanup queue markAbandoned", s -> s.cleanup.markAbandoned(null, null)), + write("file metadata insert", s -> s.metadata.insert(null)), + write("file metadata transition", s -> s.metadata.transition(null, 0, null, null, null)), + write("file metadata markDeleting", s -> s.metadata.markDeleting(null, 0)), + write("file metadata relocate", s -> s.metadata.relocate(null, 0, null)), + write("file quota reserve", s -> s.quota.reserve(null, 0, null)), + write("file quota extend", s -> s.quota.extend(null, 0)), + write("file quota commit", s -> s.quota.commit(null, 0)), + write("file quota release", s -> s.quota.release(null)), + write("quota commit commit", s -> s.quotaCommit.commit(null, 0)), + write("quota commit release", s -> s.quotaCommit.release(null)), + write("quota reclaim reclaim", s -> s.quotaReclaim.reclaim(null, 0)), + write("recovery queue enqueue", s -> s.recovery.enqueue(null, null)), + write("recovery queue resolve", s -> s.recovery.resolve(null, null)), + write("upload session create", s -> s.uploads.create(null)), + write( + "upload session acquireLease", s -> s.uploads.acquireLease(null, null, null, null, 0)), + write("upload session renewLease", s -> s.uploads.renewLease(null, null, null)), + write("upload session commitOffset", s -> s.uploads.commitOffset(null, null, 0, 0)), + write("upload session releaseLease", s -> s.uploads.releaseLease(null, null)), + write("upload session terminate", s -> s.uploads.terminate(null)), + write("upload session claimForCleanup", s -> s.uploads.claimForCleanup(null, null))); + } + + private static Arguments write(String operation, Write write) { + return Arguments.of(operation, write); + } + + /** One write of one store. */ + @FunctionalInterface + interface Write { + + void run(Stores stores); + } + + /** The leaf's stores over Spring Data mocks, built fresh for every case. */ + static final class Stores { + + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-11-03T00:00:00Z"), ZoneOffset.UTC); + + private final JpaFileRepository files = mock(JpaFileRepository.class); + private final FileTransitionRepository transitions = mock(FileTransitionRepository.class); + private final FileserverCleanupRepository cleanupItems = + mock(FileserverCleanupRepository.class); + private final FileserverQuotaRepository reservations = mock(FileserverQuotaRepository.class); + private final FileserverRecoveryRepository recoveryItems = + mock(FileserverRecoveryRepository.class); + private final JpaUploadSessionRepository sessions = mock(JpaUploadSessionRepository.class); + private final UploadLeaseRepository leases = mock(UploadLeaseRepository.class); + + final JpaCleanupQueue cleanup = new JpaCleanupQueue(cleanupItems, CLOCK); + final JpaFileMetadata metadata = new JpaFileMetadata(files, transitions, CLOCK); + final JpaFileQuota quota = new JpaFileQuota(reservations, CLOCK); + final JpaQuotaCommit quotaCommit = new JpaQuotaCommit(reservations, metadata, CLOCK); + final JpaQuotaReclaim quotaReclaim = new JpaQuotaReclaim(reservations, CLOCK); + final JpaRecoveryQueue recovery = new JpaRecoveryQueue(recoveryItems, CLOCK); + final JpaUploadSession uploads = new JpaUploadSession(sessions, leases, CLOCK); + + int repositoryCalls() { + // Object, not the inferred Repository supertype: its entity bound is package-private. + return Stream.of( + files, transitions, cleanupItems, reservations, recoveryItems, sessions, leases) + .mapToInt(repository -> mockingDetails(repository).getInvocations().size()) + .sum(); + } + } +} diff --git a/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSqlTest.java b/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSqlTest.java new file mode 100644 index 00000000..882b5c42 --- /dev/null +++ b/src/adapter/outbound/persistence-fileserver/src/test/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSqlTest.java @@ -0,0 +1,51 @@ +package dev.caskeleton.adapter.outbound.persistence.fileserver.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The claim statement keeps the shape the leaf's claim rule names: one statement that locks the + * rows it picks, skips rows another claim holds, gives every row a fresh token and a higher fence, + * and returns them in the same round trip. The PostgreSQL lane runs it; this pins the shape without + * a database, so a rewrite into a select-then-update fails here first. + */ +class CleanupClaimSqlTest { + + @Test + @DisplayName("claim은 고른 행을 잠그고, 다른 claim이 잡은 행은 기다리지 않고 건너뛴다") + void theClaimLocksWhatItPicksAndSkipsWhatAnotherClaimHolds() { + // when + String claim = CleanupClaimSql.CLAIM_DUE; + + // then + assertThat(claim).contains("FOR UPDATE SKIP LOCKED").startsWith("WITH claimable AS ("); + } + + @Test + @DisplayName("claim한 행마다 새 토큰과 하나 높은 fence를 받고 같은 왕복에 돌아온다") + void everyClaimedRowGetsAFreshTokenAndAHigherFenceInTheSameRoundTrip() { + // when + String claim = CleanupClaimSql.CLAIM_DUE; + + // then + assertThat( + List.of( + claim.contains("claim_token = gen_random_uuid()"), + claim.contains("claim_fence = c.claim_fence + 1"), + claim.contains("RETURNING c.cleanup_id, c.claim_token"))) + .containsOnly(true); + } + + @Test + @DisplayName("이름 있는 매개변수를 JDBC 자리표시자로 바꿀 때 PostgreSQL 형 변환은 건드리지 않는다") + void positionalParametersDoNotRewritePostgreSqlCasts() { + // when + String positional = CleanupClaimSql.positional("payload::jsonb @> :expected::jsonb"); + + // then + assertThat(positional).isEqualTo("payload::jsonb @> ?::jsonb"); + } +} diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index a6c476f2..5b563043 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -160,8 +160,9 @@ decide which claim repository is registered. None of those feature classes impor `config/PersistenceVendorSettings` binds the selector to an enum, so an unknown value fails at startup instead of loading neither composition and surfacing as a missing `OutboxClaimRepository`. -The profiles state the choice: `application-local.yml`, `application-dev.yml` and -`application-prod.yml` all default to PostgreSQL. H2 is an explicit developer opt-out selected by +The module states the choice: its `config/module-defaults/persistence-jpa.yml` defaults the vendor to +PostgreSQL and `spring.flyway.enabled` to `APP_FLYWAY_ENABLED` (true) for every profile; the composition +root's profile files no longer restate them (07-08). H2 is an explicit developer opt-out selected by the `bootRunH2` task. `PersistenceVendorProdSafetyValidator` (`startup`) refuses H2 under prod whatever property source supplies it. Under `bootRunH2` the idempotency provider must be `disabled` or `redis`: the `postgresql` provider refuses an H2 data source at startup. diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index b8e3a295..5c31cfbd 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -386,6 +386,12 @@ state revision을 SQL predicate로 다시 검증한다. expired `CLAIMED`만 tak `EXECUTING`은 `ABANDONED`로 닫고 reconciliation을 요구한다. raw client key는 저장하지 않고 versioned HMAC scope digest만 쓴다. +Redis store·in-memory fake와 같은 계약(`IdempotencyStoreContract`)을 실 PostgreSQL에서 통과한다 +(`PostgreSqlIdempotencyStoreContractTest`, `jpaPlatformContractTest`). 그 계약에 맞춰 두 가지를 +정했다(review 2026-11-01 01-05). 이전 revision의 핸들은 owner 튜플이 다르므로 `NOT_OWNER`다 +(`OPERATION_CONFLICT`는 같은 operation id가 다른 인자로 이미 적용된 경우만). renew는 `EXECUTING`의 +lease만 늘리고, 시작 전 `CLAIMED`는 `NOT_IN_PROGRESS`다. + ### outbox V2 (삭제됨) immutable outbox storage·polling delivery V2(`jpa/outbox-storage`, `jpa/outbox-polling` stream과 diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index 6820015f..be148436 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -186,6 +186,7 @@ def readinessLanes = [ postgresqlOutboxConcurrentRelayIntegrationTest : ['PostgreSqlOutboxConcurrentRelayIntegrationTest'], postgresqlOutboxRowLifecycleIntegrationTest : ['PostgreSqlOutboxRowLifecycleIntegrationTest'], postgresqlOutboxAggregateSequenceIntegrationTest : ['PostgreSqlOutboxAggregateSequenceIntegrationTest'], + postgresqlOutboxOrderKeyRunbookIntegrationTest : ['PostgreSqlOutboxOrderKeyRunbookIntegrationTest'], postgresqlFileserverMigrationIntegrationTest : ['PostgreSqlFileserverMigrationIntegrationTest'], postgresqlFileserverMetadataIntegrationTest : ['PostgreSqlFileserverMetadataStoreIntegrationTest'], postgresqlFileserverReclamationIntegrationTest : ['PostgreSqlFileserverReclamationIntegrationTest'], @@ -242,6 +243,15 @@ strictTestLanes { } } +// The V21 pre-deploy check and cleanup are SQL an operator runs from the outbox runbook (review +// 2026-11-01, README 15 decision). The lane reads them out of the runbook, so the document is one of +// its inputs: editing either block reruns the lane against real PostgreSQL. +tasks.named('postgresqlOutboxOrderKeyRunbookIntegrationTest', Test) { + def outboxRunbook = new File(rootProject.projectDir.parentFile, 'docs/runbooks/outbox-dead-letter.md') + inputs.file(outboxRunbook).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('outboxRunbook') + systemProperty 'outbox.runbook', outboxRunbook.absolutePath +} + tasks.named('postgresqlSecurityBaselineIntegrationTest') { // Cross-leaf task edge: see the handoff. verifyCleanArchitectureDependencies inspects // configurations, not the task graph, so this edge is invisible to it. @@ -276,6 +286,9 @@ tasks.named('test') { .withPropertyName('notificationMigrations') inputs.dir(file('../persistence-fileserver/src/main/resources/db/migration')) .withPropertyName('fileserverMigrations') + // ...and the messaging platform's tree, whose inbox range the consume side applies here. + inputs.dir(file('../../../messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration')) + .withPropertyName('messagingMigrations') } // verifyJpaApiSurface — every public type this leaf exposes is a committed decision. diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java index 6e1cc5db..ceeabdc9 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java @@ -36,7 +36,7 @@ import org.springframework.transaction.TransactionTimedOutException; * loss that is a retryable {@code DB_UNAVAILABLE} before the commit is an undetermined outcome * during it (ADR-JPA-003). */ -public class PersistenceExceptionTranslator { +public final class PersistenceExceptionTranslator { /** SQLState class prefix for connection failures → {@code DB_UNAVAILABLE}. */ private static final String CONNECTION_CLASS_PREFIX = diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyTransitionGateway.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyTransitionGateway.java index 736169f0..d10e2d3f 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyTransitionGateway.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyTransitionGateway.java @@ -50,7 +50,7 @@ final class IdempotencyTransitionGateway { updated_at = clock_timestamp() where scope_hash = ? and record_version = 2 - and status in ('CLAIMED', 'EXECUTING') + and status = 'EXECUTING' and owner_token = ? and attempt = ? and claim_operation_id = ? diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java index 73431d9c..846aa9be 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java @@ -55,7 +55,7 @@ import org.springframework.jdbc.core.JdbcOperations; * second store beside its own, which the composition root refuses. The persistence leaf builds it * for {@code provider=postgresql} and only while the JPA capability is enabled. */ -public class PostgreSqlIdempotencyStore implements IdempotencyStorePort { +public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { static final int INLINE_RESPONSE_MAX_BYTES = 8 * 1024; @@ -440,13 +440,16 @@ public class PostgreSqlIdempotencyStore implements IdempotencyStorePort { } } + // A handle at an older revision is a stale owner tuple, so it is NOT_OWNER — what the Redis store + // and the in-memory fake answer (IdempotencyStoreContract). OPERATION_CONFLICT keeps its one + // meaning: the same operation id already applied this transition with different arguments. private IdempotencyStartOutcome classifyStartMismatch( IdempotencyRecordRow row, IdempotencyOwner owner) { if (!sameOwnerIdentity(row, owner)) { return IdempotencyStartOutcome.NOT_OWNER; } if (row.stateRevision() != owner.stateRevision()) { - return IdempotencyStartOutcome.OPERATION_CONFLICT; + return IdempotencyStartOutcome.NOT_OWNER; } if (row.state() != IdempotencyState.CLAIMED) { return IdempotencyStartOutcome.NOT_CLAIMED; @@ -460,9 +463,12 @@ public class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return IdempotencyRenewOutcome.NOT_OWNER; } if (row.stateRevision() != owner.stateRevision()) { - return IdempotencyRenewOutcome.OPERATION_CONFLICT; + return IdempotencyRenewOutcome.NOT_OWNER; } - if (row.state() != IdempotencyState.CLAIMED && row.state() != IdempotencyState.EXECUTING) { + // Only an executing operation's lease is renewed, as in every other store + // (IdempotencyStoreContract): a claim that has not started has nothing in flight to protect, + // and its caller starts it rather than holding it. + if (row.state() != IdempotencyState.EXECUTING) { return IdempotencyRenewOutcome.NOT_IN_PROGRESS; } return null; @@ -474,7 +480,7 @@ public class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return IdempotencyCompleteOutcome.NOT_OWNER; } if (row.stateRevision() != owner.stateRevision()) { - return IdempotencyCompleteOutcome.OPERATION_CONFLICT; + return IdempotencyCompleteOutcome.NOT_OWNER; } if (row.state() != IdempotencyState.EXECUTING) { return IdempotencyCompleteOutcome.NOT_IN_PROGRESS; @@ -488,7 +494,7 @@ public class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return IdempotencyFailOutcome.NOT_OWNER; } if (row.stateRevision() != owner.stateRevision()) { - return IdempotencyFailOutcome.OPERATION_CONFLICT; + return IdempotencyFailOutcome.NOT_OWNER; } if (row.state() != IdempotencyState.EXECUTING) { return IdempotencyFailOutcome.NOT_IN_PROGRESS; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplay.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplay.java index 9a932fd1..26e345af 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplay.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplay.java @@ -33,7 +33,7 @@ import org.springframework.jdbc.core.JdbcOperations; * The counter update and event insert share this method's transaction, so a failed event insert * also rolls the allocation back. */ -public class JpaLiveEventReplay implements LiveEventReplayPort { +public final class JpaLiveEventReplay implements LiveEventReplayPort { /** The most one replay call will load, whatever the caller asks for. */ public static final int MAX_REPLAY_LIMIT = 500; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java index b3903ba6..40b83209 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java @@ -59,8 +59,10 @@ public class JpaOutboxStore @Override public void append(ValidatedIntegrationEvent event) { // Outside a caller transaction the row commits on its own, apart from the business write it - // announces — the dual write the outbox exists to prevent. - requireTransaction("append"); + // announces — the dual write the outbox exists to prevent. Inside a read-only one it is lost + // without a word: the JPA transaction manager never flushes a read-only session, so the save + // simply never reaches the database (OutboxAppendContract, review 2026-11-01 01-05). + CallerTransaction.requireReadWrite("outbox append", null); Objects.requireNonNull(event, "event must not be null"); OutboxEventEntity entity = new OutboxEventEntity(); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformEndpoint.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformEndpoint.java index b4a0dc1f..fc12e102 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformEndpoint.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformEndpoint.java @@ -18,7 +18,7 @@ import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; * change when something has gone wrong. */ @Endpoint(id = "jpaplatform") -class JpaPlatformEndpoint { +final class JpaPlatformEndpoint { private final Supplier reportSupplier; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidator.java index 1fd0cb3c..7c2bfba3 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidator.java @@ -10,8 +10,8 @@ import org.springframework.core.env.Environment; /** * Keeps the in-memory development datastore out of production. * - *

        {@code application-prod.yml} already pins {@code app.persistence.vendor=postgresql}, but a - * YAML default only wins against the property sources quieter than it: an environment variable or a + *

        This module's own defaults already set {@code app.persistence.vendor=postgresql}, but a + * default only wins against the property sources quieter than it: an environment variable or a * container override outranks every committed file. The two ways prod could end up on H2 are * therefore checked at startup, where the source of the value no longer matters. * diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java index c86691cd..911ff56c 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java @@ -39,7 +39,7 @@ import org.springframework.transaction.support.TransactionTemplate; * PersistenceExceptionTranslator#translateCommitFailure}, which reports a lost connection as * completion-unknown rather than retryable (ADR-JPA-003). */ -public class SpringTransaction implements TransactionPort { +public final class SpringTransaction implements TransactionPort { /** Upper bound on one {@link #inNew} transaction; the former compensation budget. */ static final int REQUIRES_NEW_TIMEOUT_SECONDS = 30; diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml b/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml index a694c225..95ee9b53 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml @@ -123,6 +123,11 @@ spring: # per-environment override re-enables them under the prod profile. # --------------------------------------------------------------------------- flyway: + # true | false. Flyway owns the schema in every profile; the H2 developer task (bootRunH2) turns + # it off, since the migration tree is PostgreSQL DDL. Shipped here rather than pinned in the + # composition root's dev/prod profile files (07-08): those pins outlived the module and + # outranked APP_FLYWAY_ENABLED, so the variable the registry documents was read only by local. + enabled: ${APP_FLYWAY_ENABLED:true} # false: never auto-baseline an existing schema — keep the missing-migration # safety net (FLYWAY-C6). Enabling under prod is forbidden (D4). baseline-on-migrate: false @@ -135,7 +140,7 @@ spring: jpa: hibernate: # none | validate | update | create | create-drop - # prod accepts only none|validate; JpaSchemaSafetyValidator rejects schema-writing modes. + # prod accepts only none|validate; JpaDangerousConfigurationGuard rejects schema-writing modes. ddl-auto: ${APP_DATASOURCE_DDL_AUTO:validate} # true | false show-sql: ${APP_DATASOURCE_SHOW_SQL:false} @@ -177,6 +182,8 @@ app: read-timeout: 30s persistence: # postgresql | h2 — the vendor composition (claim SQL, SQLState mapping, Flyway location). + # The one place every profile takes it from; PersistenceVendorProdSafetyValidator refuses h2 + # under prod whatever source sets it. vendor: ${APP_PERSISTENCE_VENDOR:postgresql} runtime: # true | false (whether to run Flyway migrations automatically at startup) diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStoreContractTest.java new file mode 100644 index 00000000..04b31d23 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStoreContractTest.java @@ -0,0 +1,106 @@ +package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; + +import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; +import dev.caskeleton.application.idempotency.IdempotencyStorePort; +import dev.caskeleton.application.idempotency.testkit.IdempotencyStoreContract; +import java.time.Duration; +import java.util.function.Supplier; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; + +/** + * The PostgreSQL store, against a real database through the shipped migrations, held to the same + * owner-safe contract as the in-memory fake use-case tests run over and the Redis store. + * + *

        Every call runs in its own {@link SpringTransaction} write transaction, as the executor's + * calls do; the store refuses to run outside one. Time is the database's ({@code + * clock_timestamp()}), so the timed case lets it pass for real with a one-second lease. + */ +@Tag("jpa-contract") +class PostgreSqlIdempotencyStoreContractTest extends IdempotencyStoreContract { + + private static JpaPlatformContractSupport support; + private static JdbcTemplate jdbc; + private static SpringTransaction transactions; + + @BeforeAll + static void start() { + support = JpaPlatformContractSupport.start(); + migrate("classpath:db/migration/postgresql", "flyway_schema_history", null); + migrate( + "classpath:db/migration/jpa/core", "flyway_jpa_core_history", "explicit-jpa-core-adoption"); + migrate( + "classpath:db/migration/jpa/idempotency", + "flyway_jpa_idempotency_history", + "explicit-jpa-idempotency-adoption"); + jdbc = new JdbcTemplate(support.dataSource()); + jdbc.update( + "update capability_schema_registry set lifecycle_state = 'ACTIVE' " + + "where capability_id = 'jpa-idempotency-owner-safe-v2'"); + transactions = new SpringTransaction(new DataSourceTransactionManager(support.dataSource())); + } + + @AfterAll + static void stop() { + if (support != null) { + support.close(); + } + } + + @BeforeEach + void empty() { + jdbc.update("delete from idempotency_record where record_version = 2"); + } + + @Override + protected IdempotencyStorePort store() { + return new PostgreSqlIdempotencyStore(jdbc); + } + + @Override + protected T inTransaction(Supplier work) { + return transactions.inWrite(work); + } + + @Override + protected Duration processingLease() { + return Duration.ofSeconds(1); + } + + @Override + protected void elapse(Duration duration) { + try { + Thread.sleep(duration.toMillis()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while letting the lease run", interrupted); + } + } + + /** + * Applies one migration stream; the two capability streams are adopted over a baseline, as a + * deployment that turns them on does. + */ + private static void migrate(String location, String historyTable, String baseline) { + var configuration = + Flyway.configure() + .dataSource(support.dataSource()) + .locations(location) + .table(historyTable) + .baselineOnMigrate(false) + .outOfOrder(false); + if (baseline == null) { + configuration.load().migrate(); + return; + } + Flyway flyway = configuration.baselineVersion("0").baselineDescription(baseline).load(); + flyway.baseline(); + flyway.migrate(); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayContractTest.java new file mode 100644 index 00000000..b8b1b3cf --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayContractTest.java @@ -0,0 +1,147 @@ +package dev.caskeleton.adapter.outbound.persistence.liveevent; + +import dev.caskeleton.adapter.outbound.persistence.liveevent.entity.LiveEventEntity; +import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; +import dev.caskeleton.application.realtime.LiveEventReplayPort; +import dev.caskeleton.application.realtime.testkit.LiveEventReplayContract; +import dev.caskeleton.application.transaction.TransactionPort; +import jakarta.persistence.EntityManagerFactory; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.Map; +import javax.sql.DataSource; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * The shipped {@link JpaLiveEventReplay}, through Spring Data and a Spring transaction, against + * real PostgreSQL, held to the same replay contract as the in-memory history. + * + *

        {@link LiveEventLogContractTest} proves the schema with raw SQL; this proves the adapter that + * talks to it — the retention filter on the clock it is given, the window, and that an append + * allocates through the position counter rather than reusing a swept position. + */ +@Tag("jpa-contract") +class JpaLiveEventReplayContractTest extends LiveEventReplayContract { + + private static final Duration RETENTION = Duration.ofHours(1); + + private static JpaPlatformContractSupport support; + private static AnnotationConfigApplicationContext context; + + private JpaLiveEventReplay adapter; + + @BeforeAll + static void start() throws SQLException, IOException { + support = JpaPlatformContractSupport.start(); + execute(migration("V12__live_event_log.sql")); + execute(migration("V15__live_event_stream_position.sql")); + context = new AnnotationConfigApplicationContext(); + context.getBeanFactory().registerSingleton("dataSource", support.dataSource()); + context.register(AdapterConfiguration.class); + context.refresh(); + } + + @AfterAll + static void stop() { + if (context != null) { + context.close(); + } + if (support != null) { + support.close(); + } + } + + private JpaLiveEventReplay adapter() { + if (adapter == null) { + adapter = + new JpaLiveEventReplay( + context.getBean(LiveEventJpaRepository.class), + new JdbcTemplate(support.dataSource()), + clock(), + RETENTION); + } + return adapter; + } + + @Override + protected LiveEventReplayPort replay() { + return adapter(); + } + + @Override + protected long append(String streamId, String payload) { + // The writer appends inside its own transaction; the adapter refuses to run outside one. + return context + .getBean(TransactionPort.class) + .inWrite(() -> adapter().append(streamId, payload)); + } + + @Override + protected Duration retention() { + return RETENTION; + } + + private static void execute(String sql) throws SQLException { + try (Connection connection = support.connection(); + Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } + + private static String migration(String name) throws IOException { + try (InputStream resource = + JpaLiveEventReplayContractTest.class + .getClassLoader() + .getResourceAsStream("db/migration/postgresql/" + name)) { + if (resource == null) { + throw new IOException(name + " is missing from the classpath"); + } + return new String(resource.readAllBytes(), StandardCharsets.UTF_8); + } + } + + @Configuration + @EnableJpaRepositories(basePackageClasses = LiveEventJpaRepository.class) + static class AdapterConfiguration { + + @Bean + LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setDataSource(dataSource); + factory.setPackagesToScan(LiveEventEntity.class.getPackageName()); + factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + factory.setJpaPropertyMap( + Map.of( + "hibernate.hbm2ddl.auto", "validate", + "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect")); + return factory; + } + + @Bean + PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } + + @Bean + TransactionPort transactionPort(PlatformTransactionManager transactionManager) { + return new SpringTransaction(transactionManager); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/AdminOperationClaimContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/AdminOperationClaimContractTest.java deleted file mode 100644 index b9f729be..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/AdminOperationClaimContractTest.java +++ /dev/null @@ -1,196 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.UUID; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * Whether two operators presenting one operation id can both act. - * - *

        They could. The admin path was find, then side effect, then save: both callers read "not - * found", both ran the redrive, and the unique constraint failed the *second save* — after the - * second side effect had already happened. An idempotency key that is checked but never held - * prevents a repeat and does nothing about a race, which is precisely the case a destructive - * operation needs it for. - * - *

        The claim is the insert. Exactly one caller creates the row; everyone else reads what that - * caller is doing. - */ -@Tag("jpa-contract") -class AdminOperationClaimContractTest { - - private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); - private static final String FINGERPRINT = "a".repeat(64); - - private static JpaPlatformContractSupport support; - - @BeforeAll - static void startServer() { - support = JpaPlatformContractSupport.start(); - } - - @AfterAll - static void stopServer() { - if (support != null) { - support.close(); - } - } - - @BeforeEach - void migrate() throws SQLException, IOException { - try (Connection connection = support.connection(); - Statement statement = connection.createStatement()) { - statement.execute("DROP SCHEMA public CASCADE"); - statement.execute("CREATE SCHEMA public"); - for (String migration : NotificationFixtures.migrations()) { - statement.execute(migration); - } - } - } - - @Test - @DisplayName("exactly one of two concurrent claims on the same id wins") - void exactlyOneClaimWins() throws SQLException { - assertThat(claim("op-1", FINGERPRINT)).isEqualTo(1); - assertThat(claim("op-1", FINGERPRINT)) - .as("both callers used to read 'not found' and both ran the operation") - .isZero(); - } - - @Test - @DisplayName("a different operation id claims independently") - void aDifferentIdClaimsIndependently() throws SQLException { - assertThat(claim("op-1", FINGERPRINT)).isEqualTo(1); - assertThat(claim("op-2", FINGERPRINT)).isEqualTo(1); - } - - @Test - @DisplayName("the claim records the phase, so a second caller can tell doing from done") - void theClaimRecordsThePhase() throws SQLException { - claim("op-1", FINGERPRINT); - - assertThat(phaseOf("op-1")) - .as("a row in CLAIMED means the work is under way, which is not the same as finished") - .isEqualTo("CLAIMED"); - } - - @Test - @DisplayName("a claimed row is completed in place rather than inserted a second time") - void claimedRowCompletesInPlace() throws SQLException { - assertThat(claim("op-1", FINGERPRINT)).isEqualTo(1); - - assertThat(complete("op-1", "done")).isEqualTo(1); - assertThat(phaseOf("op-1")).isEqualTo("COMPLETED"); - assertThat(reasonOf("op-1")).isEqualTo("done"); - assertThat(rowCount("op-1")).isEqualTo(1); - } - - @Test - @DisplayName("the claim records the fingerprint it was made with") - void theClaimRecordsItsFingerprint() throws SQLException { - claim("op-1", FINGERPRINT); - - assertThat(fingerprintOf("op-1")) - .as("the same id with a different command is a conflict, not an idempotent repeat") - .isEqualTo(FINGERPRINT); - } - - @Test - @DisplayName("the phase check constraint refuses an unknown phase") - void thePhaseConstraintRefusesAnUnknownPhase() throws SQLException { - claim("op-1", FINGERPRINT); - - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "UPDATE notification_admin_audit SET phase = 'ALMOST' WHERE operation_id = ?")) { - statement.setString(1, "op-1"); - org.assertj.core.api.Assertions.assertThatThrownBy(statement::executeUpdate) - .isInstanceOf(SQLException.class); - } - } - - private int claim(String operationId, String fingerprint) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "INSERT INTO notification_admin_audit (" - + " id, operation_id, action, actor_ref, attributes, dry_run, occurred_at," - + " command_fingerprint, phase, claimed_at)" - + " VALUES (?, ?, 'REDRIVE', 'operator-1', '{}'::jsonb, false, ?, ?," - + " 'CLAIMED', ?)" - + " ON CONFLICT (operation_id) DO NOTHING")) { - statement.setObject(1, UUID.randomUUID()); - statement.setString(2, operationId); - statement.setTimestamp(3, Timestamp.from(NOW)); - statement.setString(4, fingerprint); - statement.setTimestamp(5, Timestamp.from(NOW)); - return statement.executeUpdate(); - } - } - - private int complete(String operationId, String reasonCode) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "UPDATE notification_admin_audit" - + " SET reason_code = ?, phase = 'COMPLETED', occurred_at = ?" - + " WHERE operation_id = ? AND phase = 'CLAIMED'")) { - statement.setString(1, reasonCode); - statement.setTimestamp(2, Timestamp.from(NOW.plusSeconds(1))); - statement.setString(3, operationId); - return statement.executeUpdate(); - } - } - - private int rowCount(String operationId) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "SELECT count(*) FROM notification_admin_audit WHERE operation_id = ?")) { - statement.setString(1, operationId); - try (ResultSet rows = statement.executeQuery()) { - return rows.next() ? rows.getInt(1) : 0; - } - } - } - - private String reasonOf(String operationId) throws SQLException { - return column(operationId, "reason_code"); - } - - private String phaseOf(String operationId) throws SQLException { - return column(operationId, "phase"); - } - - private String fingerprintOf(String operationId) throws SQLException { - return column(operationId, "command_fingerprint"); - } - - private String column(String operationId, String column) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "SELECT " + column + " FROM notification_admin_audit WHERE operation_id = ?")) { - statement.setString(1, operationId); - try (ResultSet rows = statement.executeQuery()) { - return rows.next() ? rows.getString(1) : null; - } - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/LateEventBindingContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/LateEventBindingContractTest.java deleted file mode 100644 index 039749ce..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/LateEventBindingContractTest.java +++ /dev/null @@ -1,201 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.List; -import java.util.UUID; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * A callback that arrives before the attempt it belongs to. - * - *

        This is an ordinary race, not an edge case: providers routinely answer faster than the - * submitting transaction commits, so the event is stored with no attempt. Nothing ever went back - * for it — the repository carried a {@code bindAttemptIfUnbound} statement with no caller — so a - * callback-before-outcome event stayed unmatched permanently and its delivery was never confirmed. - * - *

        The statements under test are the ones the adapter runs: the bind is conditional on the event - * still being unbound, which is what makes two matchers racing for it resolve to one winner and - * therefore one projection. - */ -@Tag("jpa-contract") -class LateEventBindingContractTest { - - private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); - private static final String TENANT = "tenant-a"; - private static final String HASH = "a".repeat(64); - - private static JpaPlatformContractSupport support; - - private UUID attemptId; - - @BeforeAll - static void startServer() { - support = JpaPlatformContractSupport.start(); - } - - @AfterAll - static void stopServer() { - if (support != null) { - support.close(); - } - } - - @BeforeEach - void migrate() throws SQLException, IOException { - try (Connection connection = support.connection(); - Statement statement = connection.createStatement()) { - statement.execute("DROP SCHEMA public CASCADE"); - statement.execute("CREATE SCHEMA public"); - for (String migration : migrations()) { - statement.execute(migration); - } - } - attemptId = NotificationFixtures.insertAttempt(support, TENANT, NOW, "email-main"); - } - - @Test - @DisplayName("an event stored before its attempt is bound once the attempt records its hash") - void anEarlyEventIsBoundWhenTheAttemptArrives() throws SQLException { - UUID eventId = insertUnmatchedEvent("email-main", HASH); - - assertThat(bind("email-main", HASH)).isEqualTo(1); - assertThat(boundAttempt(eventId)).isEqualTo(attemptId); - } - - @Test - @DisplayName("binding twice binds nothing the second time, so the projection runs once") - void bindingTwiceBindsNothingTheSecondTime() throws SQLException { - insertUnmatchedEvent("email-main", HASH); - - assertThat(bind("email-main", HASH)).isEqualTo(1); - assertThat(bind("email-main", HASH)) - .as("two matchers racing must resolve to one winner, and only the winner projects") - .isZero(); - } - - @Test - @DisplayName("the same hash under another profile binds nothing") - void theSameHashUnderAnotherProfileBindsNothing() throws SQLException { - UUID otherProfileEvent = insertUnmatchedEvent("sms-main", HASH); - - assertThat(bind("email-main", HASH)) - .as("providers can mint the same request id; binding on the hash alone crosses tenants") - .isZero(); - assertThat(boundAttempt(otherProfileEvent)).isNull(); - } - - @Test - @DisplayName("an event that is already bound is left alone") - void anAlreadyBoundEventIsLeftAlone() throws SQLException { - UUID eventId = insertUnmatchedEvent("email-main", HASH); - bind("email-main", HASH); - UUID secondAttempt = NotificationFixtures.insertAttempt(support, TENANT, NOW, "email-main"); - - assertThat(bindTo("email-main", HASH, secondAttempt)).isZero(); - assertThat(boundAttempt(eventId)) - .as("a sweep must not move an event from the attempt that already owns it") - .isEqualTo(attemptId); - } - - @Test - @DisplayName("an unknown hash binds nothing") - void anUnknownHashBindsNothing() throws SQLException { - insertUnmatchedEvent("email-main", HASH); - - assertThat(bind("email-main", "b".repeat(64))).isZero(); - } - - private int bind(String profileId, String hash) throws SQLException { - return bindTo(profileId, hash, attemptId); - } - - /** The adapter's two statements: find the unbound events of a profile, then claim each. */ - private int bindTo(String profileId, String hash, UUID target) throws SQLException { - int bound = 0; - for (UUID candidate : unboundEvents(profileId, hash)) { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "UPDATE notification_provider_event SET attempt_id = ?" - + " WHERE id = ? AND attempt_id IS NULL")) { - statement.setObject(1, target); - statement.setObject(2, candidate); - bound += statement.executeUpdate(); - } - } - return bound; - } - - private List unboundEvents(String profileId, String hash) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "SELECT id FROM notification_provider_event" - + " WHERE provider_profile_id = ? AND provider_request_id_hash = ?" - + " AND attempt_id IS NULL" - + " ORDER BY received_at")) { - statement.setString(1, profileId); - statement.setString(2, hash); - List ids = new java.util.ArrayList<>(); - try (ResultSet rows = statement.executeQuery()) { - while (rows.next()) { - ids.add(rows.getObject(1, UUID.class)); - } - } - return List.copyOf(ids); - } - } - - private UUID boundAttempt(UUID eventId) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "SELECT attempt_id FROM notification_provider_event WHERE id = ?")) { - statement.setObject(1, eventId); - try (ResultSet rows = statement.executeQuery()) { - return rows.next() ? rows.getObject(1, UUID.class) : null; - } - } - } - - private UUID insertUnmatchedEvent(String profileId, String hash) throws SQLException { - UUID id = UUID.randomUUID(); - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "INSERT INTO notification_provider_event (" - + " id, provider_profile_id, event_fingerprint, provider_request_id_hash," - + " event_type, provider_native_type, event_source, received_at," - + " signature_verified, raw_payload_digest, projection_status)" - + " VALUES (?, ?, ?, ?, 'DELIVERY_CONFIRMED', 'delivered', 'CALLBACK', ?," - + " true, ?, 'PENDING')")) { - statement.setObject(1, id); - statement.setString(2, profileId); - statement.setString(3, UUID.randomUUID().toString().replace("-", "").repeat(2)); - statement.setString(4, hash); - statement.setTimestamp(5, Timestamp.from(NOW)); - statement.setString(6, "c".repeat(64)); - statement.executeUpdate(); - } - return id; - } - - private static List migrations() throws IOException { - return NotificationFixtures.migrations(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java index 183e2df2..d88d0217 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationFixtures.java @@ -48,7 +48,8 @@ final class NotificationFixtures { migration("jpa/notification-platform", "V9__notification_evidence_certainty.sql"), migration("jpa/notification-platform", "V10__variables_payload_envelope_guard.sql"), migration("jpa/notification-platform", "V11__notification_reconciliation_claim_lease.sql"), - migration("jpa/notification-platform", "V12__notification_suppression_target_unique.sql")); + migration("jpa/notification-platform", "V12__notification_suppression_target_unique.sql"), + migration("jpa/notification-platform", "V13__notification_request_acceptance.sql")); } /** diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaStack.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaStack.java index 9c9f1a29..8408e920 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaStack.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaStack.java @@ -69,6 +69,27 @@ public final class NotificationJpaStack implements AutoCloseable { return new JdbcTemplate(database.dataSource()); } + /** + * Deletes every row of the delivery tables, children first, so a contract case starts empty. + * + *

        One server per test class keeps the lane fast; this is what makes each case independent of + * the one before it. + */ + public void emptyDeliveryTables() { + JdbcTemplate jdbc = jdbc(); + for (String table : + new String[] { + "notification_provider_event", + "notification_delivery_attempt", + "notification_recipient_delivery", + "notification_request", + "notification_contact_point", + "notification_suppression" + }) { + jdbc.update("DELETE FROM " + table); + } + } + @Override public void close() { try { diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationTestCodecs.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationTestCodecs.java new file mode 100644 index 00000000..4fe784a8 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationTestCodecs.java @@ -0,0 +1,116 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationRecordMapper; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRoutingPlanCodecPort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationVariablesCodecPort; +import dev.caskeleton.application.notification.platform.policy.RouteCandidate; +import dev.caskeleton.application.notification.platform.security.NotificationPayloadProtection; +import dev.caskeleton.application.notification.platform.template.TemplateContentCodecPort; +import dev.caskeleton.application.notification.platform.template.TemplateContentDefinition; +import dev.caskeleton.application.notification.platform.template.TemplateSlot; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * The codecs a notification store test gives the record mapper when the encoded content is not what + * it is about: empty variables, an empty routing plan and a payload protection that stores the + * bytes it is given. The production codecs live in the notification adapter, which this lane does + * not carry. + */ +public final class NotificationTestCodecs { + + private NotificationTestCodecs() {} + + /** + * A record mapper over the codecs below. + * + * @return the mapper + */ + public static NotificationRecordMapper recordMapper() { + return new NotificationRecordMapper( + new EmptyRoutingPlans(), new EmptyVariables(), new Opaque()); + } + + /** Variables that encode to {@code {}} and decode to nothing. */ + public static final class EmptyVariables implements NotificationVariablesCodecPort { + + @Override + public String encode(Map variables) { + return "{}"; + } + + @Override + public Map decode(String payload) { + return Map.of(); + } + } + + /** A routing plan that encodes to {@code []} and decodes to no routes. */ + public static final class EmptyRoutingPlans implements NotificationRoutingPlanCodecPort { + + @Override + public String encode(List routes) { + return "[]"; + } + + @Override + public List decode(String payload) { + return List.of(); + } + } + + /** Payload protection that keeps the bytes as they are. */ + public static final class Opaque implements NotificationPayloadProtection { + + @Override + public byte[] protect(byte[] plaintext) { + return plaintext.clone(); + } + + @Override + public byte[] reveal(byte[] envelope) { + return envelope.clone(); + } + } + + /** + * Template slots as a flat JSON object of strings, which is what the {@code jsonb} column needs; + * decoding tolerates the spacing and key order PostgreSQL gives the value back in. + */ + public static final class SlotJson implements TemplateContentCodecPort { + + private static final Pattern ENTRY = + Pattern.compile("\"([A-Z_]+)\"\\s*:\\s*\"((?:\\\\.|[^\"\\\\])*)\""); + + @Override + public String encode(TemplateContentDefinition content) { + StringBuilder json = new StringBuilder("{"); + content + .slots() + .forEach( + (slot, value) -> { + if (json.length() > 1) { + json.append(','); + } + json.append('"').append(slot.name()).append("\":\""); + json.append(value.replace("\\", "\\\\").replace("\"", "\\\"")).append('"'); + }); + return json.append('}').toString(); + } + + @Override + public TemplateContentDefinition decode(String payload) { + Map slots = new EnumMap<>(TemplateSlot.class); + Matcher entry = ENTRY.matcher(payload); + while (entry.find()) { + slots.put( + TemplateSlot.valueOf(entry.group(1)), + entry.group(2).replace("\\\"", "\"").replace("\\\\", "\\")); + } + return new TemplateContentDefinition(slots); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlAdminOperationStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlAdminOperationStoreContractTest.java new file mode 100644 index 00000000..36fb329f --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlAdminOperationStoreContractTest.java @@ -0,0 +1,95 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaAdminOperationStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.AdminAuditJpaRepository; +import dev.caskeleton.application.notification.platform.admin.AdminActor; +import dev.caskeleton.application.notification.platform.admin.AdminOperationStorePort; +import dev.caskeleton.application.notification.platform.admin.testkit.AdminOperationStoreContract; +import java.time.Clock; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataIntegrityViolationException; + +/** + * {@link JpaAdminOperationStore} held to the admin operation contract against a real PostgreSQL. + * + *

        The overlapping-claim case is the reason this runs here: the admin path used to be find, then + * side effect, then save, so two operators presenting one id both read "not found" and both acted. + * The claim is now the insert ({@code ON CONFLICT DO NOTHING}), and only a real database shows the + * second insert waiting for the first one's row. + */ +@Tag("jpa-contract") +class PostgreSqlAdminOperationStoreContractTest extends AdminOperationStoreContract { + + private static NotificationJpaStack stack; + private static JpaAdminOperationStore store; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + store = + new JpaAdminOperationStore( + stack.repository(AdminAuditJpaRepository.class), UUID::randomUUID, Clock.systemUTC()); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.jdbc().update("DELETE FROM notification_admin_audit"); + } + + @Override + protected AdminOperationStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } + + @Test + @DisplayName("audit 행의 phase 제약은 모르는 phase를 거부한다") + void thePhaseConstraintRefusesAnUnknownPhase() { + // given + inTransaction( + () -> + store.claim( + "op-1", + "a".repeat(64), + new AdminActor("operator-1", Set.of(), Optional.empty()), + "ADMIN_REDRIVE")); + + // when + Throwable refused = + catchThrowable( + () -> + stack + .jdbc() + .update( + "UPDATE notification_admin_audit SET phase = 'ALMOST'" + + " WHERE operation_id = 'op-1'")); + + // then + assertThat(refused) + .as("a row in a phase the store does not know is neither in progress nor a result") + .isInstanceOf(DataIntegrityViolationException.class); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlContactPointStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlContactPointStoreContractTest.java new file mode 100644 index 00000000..ab4204d5 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlContactPointStoreContractTest.java @@ -0,0 +1,49 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaContactPointStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ContactPointJpaRepository; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.ContactPointStoreContract; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaContactPointStore} held to the contact point contract against a real PostgreSQL: the + * lookups are the tenant-scoped finders, and the fingerprint is the {@code char(64)} column the + * identity index covers. + */ +@Tag("jpa-contract") +class PostgreSqlContactPointStoreContractTest extends ContactPointStoreContract { + + private static NotificationJpaStack stack; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.emptyDeliveryTables(); + } + + @Override + protected ContactPointStorePort store() { + return new JpaContactPointStore(stack.repository(ContactPointJpaRepository.class), clock()); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeduplicationStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeduplicationStoreContractTest.java new file mode 100644 index 00000000..c067cdcc --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeduplicationStoreContractTest.java @@ -0,0 +1,60 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaPolicyStores; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.DeduplicationClaimJpaRepository; +import dev.caskeleton.application.notification.platform.policy.DeduplicationStorePort; +import dev.caskeleton.application.notification.platform.policy.testkit.DeduplicationStoreContract; +import java.time.Clock; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaPolicyStores.DeduplicationClaims} held to the deduplication contract against a real + * PostgreSQL. + * + *

        The overlapping case is why: the loser used to insert, catch the unique violation and read the + * winner in the transaction the violation had just aborted, so on PostgreSQL it got a refusal + * instead of the winner's notification id. + */ +@Tag("jpa-contract") +class PostgreSqlDeduplicationStoreContractTest extends DeduplicationStoreContract { + + private static NotificationJpaStack stack; + private static JpaPolicyStores.DeduplicationClaims store; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + store = + new JpaPolicyStores.DeduplicationClaims( + stack.repository(DeduplicationClaimJpaRepository.class), + UUID::randomUUID, + Clock.systemUTC()); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.jdbc().update("DELETE FROM notification_deduplication_claim"); + } + + @Override + protected DeduplicationStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryAttemptResolverContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryAttemptResolverContractTest.java new file mode 100644 index 00000000..c9af26da --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryAttemptResolverContractTest.java @@ -0,0 +1,103 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaContactPointStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaDeliveryAttemptStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ContactPointJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.DeliveryAttemptJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort; +import dev.caskeleton.application.notification.platform.callback.testkit.DeliveryAttemptResolverContract; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointRecord; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.NotificationRows; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaDeliveryAttemptStore}'s resolver held to the resolver contract against a real + * PostgreSQL: the lookups are the partial index on profile and request id hash. + */ +@Tag("jpa-contract") +class PostgreSqlDeliveryAttemptResolverContractTest extends DeliveryAttemptResolverContract { + + private static final ProviderRequestIdHasherPort HASHER = new Sha256ProviderRequestIdHasher(); + + private static NotificationJpaStack stack; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.emptyDeliveryTables(); + } + + @Override + protected NotificationRequestStorePort requests() { + return new JpaNotificationRequestStore( + stack.repository(NotificationRequestJpaRepository.class), + stack.repository(RecipientDeliveryJpaRepository.class), + NotificationTestCodecs.recordMapper(), + clock()); + } + + @Override + protected DeliveryAttemptStorePort attempts() { + return store(); + } + + @Override + protected ProviderRequestIdHasherPort hasher() { + return HASHER; + } + + @Override + protected ContactPointId givenAContactPoint(TenantId tenant) { + ContactPointRecord contactPoint = + NotificationRows.contactPoint( + tenant, UUID.randomUUID().toString().replace("-", "").repeat(2), clock().instant()); + return inTransaction( + () -> + new JpaContactPointStore(stack.repository(ContactPointJpaRepository.class), clock()) + .save(contactPoint)) + .id(); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } + + private JpaDeliveryAttemptStore store() { + return new JpaDeliveryAttemptStore( + stack.repository(DeliveryAttemptJpaRepository.class), + stack.repository(RecipientDeliveryJpaRepository.class), + HASHER, + clock()); + } + + @Override + protected DeliveryAttemptResolverPort resolver() { + return store(); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryAttemptStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryAttemptStoreContractTest.java new file mode 100644 index 00000000..4043f978 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryAttemptStoreContractTest.java @@ -0,0 +1,100 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaContactPointStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaDeliveryAttemptStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ContactPointJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.DeliveryAttemptJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointRecord; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.DeliveryAttemptStoreContract; +import dev.caskeleton.application.notification.platform.dispatch.testkit.NotificationRows; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaDeliveryAttemptStore} held to the attempt store contract against a real PostgreSQL. + * + *

        The evidence is four value-and-certainty column pairs; the round trip is what used to lose the + * certainty. The CHECK constraints behind them are the vendor's half and stay in {@code + * EvidenceCertaintyContractTest}. + */ +@Tag("jpa-contract") +class PostgreSqlDeliveryAttemptStoreContractTest extends DeliveryAttemptStoreContract { + + private static final ProviderRequestIdHasherPort HASHER = new Sha256ProviderRequestIdHasher(); + + private static NotificationJpaStack stack; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.emptyDeliveryTables(); + } + + @Override + protected NotificationRequestStorePort requests() { + return new JpaNotificationRequestStore( + stack.repository(NotificationRequestJpaRepository.class), + stack.repository(RecipientDeliveryJpaRepository.class), + NotificationTestCodecs.recordMapper(), + clock()); + } + + @Override + protected DeliveryAttemptStorePort attempts() { + return store(); + } + + @Override + protected ProviderRequestIdHasherPort hasher() { + return HASHER; + } + + @Override + protected ContactPointId givenAContactPoint(TenantId tenant) { + ContactPointRecord contactPoint = + NotificationRows.contactPoint( + tenant, UUID.randomUUID().toString().replace("-", "").repeat(2), clock().instant()); + return inTransaction( + () -> + new JpaContactPointStore(stack.repository(ContactPointJpaRepository.class), clock()) + .save(contactPoint)) + .id(); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } + + private JpaDeliveryAttemptStore store() { + return new JpaDeliveryAttemptStore( + stack.repository(DeliveryAttemptJpaRepository.class), + stack.repository(RecipientDeliveryJpaRepository.class), + HASHER, + clock()); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryProjectionStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryProjectionStoreContractTest.java new file mode 100644 index 00000000..026973dd --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlDeliveryProjectionStoreContractTest.java @@ -0,0 +1,143 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaContactPointStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaDeliveryAttemptStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ContactPointJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.DeliveryAttemptJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.callback.DeliveryProjection; +import dev.caskeleton.application.notification.platform.callback.DeliveryProjectionStorePort; +import dev.caskeleton.application.notification.platform.callback.testkit.DeliveryProjectionStoreContract; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointRecord; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptRecord; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.NotificationRows; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * {@link JpaDeliveryAttemptStore}'s projection half held to the projection contract against a real + * PostgreSQL. + * + *

        This replaces {@code ProjectionFactDurabilityContractTest}, which ran an {@code UPDATE} it had + * written itself; the monotonic facts are the entity's, and the contract now goes through the + * store. The projection version column is the vendor's half and stays below. + */ +@Tag("jpa-contract") +class PostgreSqlDeliveryProjectionStoreContractTest extends DeliveryProjectionStoreContract { + + private static final ProviderRequestIdHasherPort HASHER = new Sha256ProviderRequestIdHasher(); + + private static NotificationJpaStack stack; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.emptyDeliveryTables(); + } + + @Override + protected NotificationRequestStorePort requests() { + return new JpaNotificationRequestStore( + stack.repository(NotificationRequestJpaRepository.class), + stack.repository(RecipientDeliveryJpaRepository.class), + NotificationTestCodecs.recordMapper(), + clock()); + } + + @Override + protected DeliveryAttemptStorePort attempts() { + return store(); + } + + @Override + protected ProviderRequestIdHasherPort hasher() { + return HASHER; + } + + @Override + protected ContactPointId givenAContactPoint(TenantId tenant) { + ContactPointRecord contactPoint = + NotificationRows.contactPoint( + tenant, UUID.randomUUID().toString().replace("-", "").repeat(2), clock().instant()); + return inTransaction( + () -> + new JpaContactPointStore(stack.repository(ContactPointJpaRepository.class), clock()) + .save(contactPoint)) + .id(); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } + + private JpaDeliveryAttemptStore store() { + return new JpaDeliveryAttemptStore( + stack.repository(DeliveryAttemptJpaRepository.class), + stack.repository(RecipientDeliveryJpaRepository.class), + HASHER, + clock()); + } + + @Override + protected DeliveryProjectionStorePort projections() { + return store(); + } + + @Test + @DisplayName("projection을 저장할 때마다 projection version이 올라가 오래된 snapshot을 알아볼 수 있다") + void theProjectionVersionAdvances() { + // given + DeliveryAttemptRecord attempt = givenADispatchingAttempt(givenAJob(), 1); + long before = projectionVersionOf(attempt.id()); + + // when + inTransaction( + () -> { + projections().save(attempt.id(), DeliveryProjection.accepted()); + return null; + }); + + // then + assertThat(projectionVersionOf(attempt.id())) + .as("an operator comparing a snapshot with a ledger fold needs to know which is older") + .isGreaterThan(before); + } + + private static long projectionVersionOf(DeliveryAttemptId id) { + return stack + .jdbc() + .queryForObject( + "SELECT projection_version FROM notification_delivery_attempt WHERE id = ?", + Long.class, + id.value()); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlNotificationRequestStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlNotificationRequestStoreContractTest.java new file mode 100644 index 00000000..77048bb4 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlNotificationRequestStoreContractTest.java @@ -0,0 +1,61 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.NotificationRequestStoreContract; +import java.time.Clock; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaNotificationRequestStore} held to the request store contract against a real PostgreSQL. + * + *

        The key claim is an {@code INSERT ... ON CONFLICT DO NOTHING}; the overlapping case is the one + * that used to fail here, when a unique violation aborted the loser's transaction before it could + * read the winner. + */ +@Tag("jpa-contract") +class PostgreSqlNotificationRequestStoreContractTest extends NotificationRequestStoreContract { + + private static NotificationJpaStack stack; + private static JpaNotificationRequestStore store; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + store = + new JpaNotificationRequestStore( + stack.repository(NotificationRequestJpaRepository.class), + stack.repository(RecipientDeliveryJpaRepository.class), + NotificationTestCodecs.recordMapper(), + Clock.systemUTC()); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.jdbc().update("DELETE FROM notification_recipient_delivery"); + stack.jdbc().update("DELETE FROM notification_request"); + } + + @Override + protected NotificationRequestStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlNotificationSideEffectContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlNotificationSideEffectContractTest.java new file mode 100644 index 00000000..db419094 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlNotificationSideEffectContractTest.java @@ -0,0 +1,66 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaContactPointStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaSuppressionStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ContactPointJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.SuppressionJpaRepository; +import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort; +import dev.caskeleton.application.notification.platform.callback.testkit.NotificationSideEffectContract; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; +import dev.caskeleton.application.notification.platform.dispatch.SuppressionSideEffect; +import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * The projection side effect over the JPA contact point and suppression stores, held to the same + * contract as over their fakes: the status change and the suppression upsert both refuse to run + * outside the caller's transaction, and this is where that is exercised. + */ +@Tag("jpa-contract") +class PostgreSqlNotificationSideEffectContractTest extends NotificationSideEffectContract { + + private static NotificationJpaStack stack; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.emptyDeliveryTables(); + } + + @Override + protected NotificationSideEffectPort sideEffects() { + return new SuppressionSideEffect(contactPoints(), suppressions(), UUID::randomUUID, clock()); + } + + @Override + protected ContactPointStorePort contactPoints() { + return new JpaContactPointStore(stack.repository(ContactPointJpaRepository.class), clock()); + } + + @Override + protected SuppressionStorePort suppressions() { + return new JpaSuppressionStore( + stack.repository(SuppressionJpaRepository.class), UUID::randomUUID, clock()); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlPreferenceStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlPreferenceStoreContractTest.java index 9c050dbf..07286b41 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlPreferenceStoreContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlPreferenceStoreContractTest.java @@ -1,7 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.notification; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaPolicyStores; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.PreferenceJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.PreferenceJpaRepository; import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort; import dev.caskeleton.application.notification.platform.policy.testkit.PreferenceStoreContract; import java.time.Clock; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlProviderEventLedgerContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlProviderEventLedgerContractTest.java new file mode 100644 index 00000000..215631ad --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlProviderEventLedgerContractTest.java @@ -0,0 +1,114 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaContactPointStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaDeliveryAttemptStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaProviderEventLedger; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ContactPointJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.DeliveryAttemptJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ProviderEventJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; +import dev.caskeleton.application.notification.platform.callback.testkit.ProviderEventLedgerContract; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointRecord; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.NotificationRows; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaProviderEventLedger} held to the ledger contract against a real PostgreSQL. + * + *

        The duplicate cases run against the two unique indexes and {@code ON CONFLICT DO NOTHING}; the + * binding cases against the conditional {@code UPDATE ... WHERE attempt_id IS NULL}. This replaces + * {@code LateEventBindingContractTest}, which ran that SQL over a bare connection rather than + * through the ledger (review 2026-11-01 04-14). + */ +@Tag("jpa-contract") +class PostgreSqlProviderEventLedgerContractTest extends ProviderEventLedgerContract { + + private static final ProviderRequestIdHasherPort HASHER = new Sha256ProviderRequestIdHasher(); + + private static NotificationJpaStack stack; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.emptyDeliveryTables(); + } + + @Override + protected NotificationRequestStorePort requests() { + return new JpaNotificationRequestStore( + stack.repository(NotificationRequestJpaRepository.class), + stack.repository(RecipientDeliveryJpaRepository.class), + NotificationTestCodecs.recordMapper(), + clock()); + } + + @Override + protected DeliveryAttemptStorePort attempts() { + return store(); + } + + @Override + protected ProviderRequestIdHasherPort hasher() { + return HASHER; + } + + @Override + protected ContactPointId givenAContactPoint(TenantId tenant) { + ContactPointRecord contactPoint = + NotificationRows.contactPoint( + tenant, UUID.randomUUID().toString().replace("-", "").repeat(2), clock().instant()); + return inTransaction( + () -> + new JpaContactPointStore(stack.repository(ContactPointJpaRepository.class), clock()) + .save(contactPoint)) + .id(); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } + + private JpaDeliveryAttemptStore store() { + return new JpaDeliveryAttemptStore( + stack.repository(DeliveryAttemptJpaRepository.class), + stack.repository(RecipientDeliveryJpaRepository.class), + HASHER, + clock()); + } + + @Override + protected ProviderEventLedger ledger() { + return new JpaProviderEventLedger( + stack.repository(ProviderEventJpaRepository.class), + store(), + HASHER, + new NotificationTestCodecs.EmptyVariables(), + UUID::randomUUID); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientDeliveryStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientDeliveryStoreContractTest.java new file mode 100644 index 00000000..83b683f8 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientDeliveryStoreContractTest.java @@ -0,0 +1,74 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientDeliveryStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientLeaseStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.RecipientDeliveryStoreContract; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaRecipientDeliveryStore} held to the recipient contract against a real PostgreSQL. + * + *

        The fenced writes are single conditional {@code UPDATE}s on owner and fence; the superseded + * case is the one the optimistic {@code version} column could not catch, because the late worker's + * read was recent enough to win. + */ +@Tag("jpa-contract") +class PostgreSqlRecipientDeliveryStoreContractTest extends RecipientDeliveryStoreContract { + + private static NotificationJpaStack stack; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.emptyDeliveryTables(); + } + + @Override + protected RecipientDeliveryStorePort deliveries() { + return new JpaRecipientDeliveryStore( + stack.repository(RecipientDeliveryJpaRepository.class), + NotificationTestCodecs.recordMapper(), + clock()); + } + + @Override + protected RecipientLeaseStorePort leases() { + return new JpaRecipientLeaseStore( + stack.repository(RecipientDeliveryJpaRepository.class), clock()); + } + + @Override + protected NotificationRequestStorePort requests() { + return new JpaNotificationRequestStore( + stack.repository(NotificationRequestJpaRepository.class), + stack.repository(RecipientDeliveryJpaRepository.class), + NotificationTestCodecs.recordMapper(), + clock()); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientLeaseStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientLeaseStoreContractTest.java new file mode 100644 index 00000000..fe4134f7 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlRecipientLeaseStoreContractTest.java @@ -0,0 +1,125 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientDeliveryStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientLeaseStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; +import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.NotificationRows; +import dev.caskeleton.application.notification.platform.dispatch.testkit.RecipientLeaseStoreContract; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * {@link JpaRecipientLeaseStore} held to the lease contract against a real PostgreSQL. + * + *

        The claim is the statement {@code RecipientClaimSql} holds, run through the repository the + * adapter uses; {@code SKIP LOCKED} and the fence column are what the racing and superseded cases + * exercise here and what the fake only models. This replaces {@code RecipientClaimContractTest}, + * which ran the SQL text over a bare connection — the cases are the contract's now, and the one + * that is about the vendor (the JPA version column) stays below (review 2026-11-01 04-14). + */ +@Tag("jpa-contract") +class PostgreSqlRecipientLeaseStoreContractTest extends RecipientLeaseStoreContract { + + private static NotificationJpaStack stack; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.emptyDeliveryTables(); + } + + @Override + protected RecipientLeaseStorePort leases() { + return new JpaRecipientLeaseStore( + stack.repository(RecipientDeliveryJpaRepository.class), clock()); + } + + @Override + protected RecipientDeliveryStorePort deliveries() { + return new JpaRecipientDeliveryStore( + stack.repository(RecipientDeliveryJpaRepository.class), + NotificationTestCodecs.recordMapper(), + clock()); + } + + @Override + protected NotificationRequestStorePort requests() { + return new JpaNotificationRequestStore( + stack.repository(NotificationRequestJpaRepository.class), + stack.repository(RecipientDeliveryJpaRepository.class), + NotificationTestCodecs.recordMapper(), + clock()); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } + + @Test + @DisplayName("claim은 JPA version을 올려 claim 전에 읽은 엔티티의 flush가 lease를 덮어쓰지 못한다") + void theClaimAdvancesTheJpaVersion() { + // given + NotificationRequestRecord request = + NotificationRows.request(new TenantId("tenant-a"), "idem-version", NOW); + RecipientDeliveryRecord job = + NotificationRows.job( + request, + RecipientDeliveryState.READY_TO_DISPATCH, + Optional.of(NOW), + Optional.empty(), + NOW); + inTransaction(() -> requests().insert(request, List.of(job))); + long before = versionOf(job.id()); + + // when + inTransaction(() -> leases().claim("worker-a", 10, Duration.ofMinutes(5))); + + // then + assertThat(versionOf(job.id())) + .as( + "a managed entity loaded before the claim still holds the old version; without this" + + " its flush succeeds and writes the pre-claim lease and state back") + .isGreaterThan(before); + } + + private static long versionOf(RecipientDeliveryId id) { + return stack + .jdbc() + .queryForObject( + "SELECT version FROM notification_recipient_delivery WHERE id = ?", + Long.class, + id.value()); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlReconciliationJobStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlReconciliationJobStoreContractTest.java new file mode 100644 index 00000000..0777441f --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlReconciliationJobStoreContractTest.java @@ -0,0 +1,74 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JdbcReconciliationJobStore; +import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.ReconciliationJobStoreContract; +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Clock; +import java.time.ZoneOffset; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * {@link JdbcReconciliationJobStore} held to the reconciliation job contract against a real + * PostgreSQL. + * + *

        Every handle runs on its own pooled autocommit connection, as the worker's do: no transaction + * spans the claim and the provider call, so ownership has to be in the row. Row locks and {@code + * SKIP LOCKED} are what the concurrent-claim case exercises here, and what the fake only models. + */ +@Tag("jpa-contract") +class PostgreSqlReconciliationJobStoreContractTest extends ReconciliationJobStoreContract { + + private static final String TENANT = "tenant-a"; + + private static JpaPlatformContractSupport support; + + @BeforeAll + static void startServer() { + support = JpaPlatformContractSupport.start(); + } + + @AfterAll + static void stopServer() { + if (support != null) { + support.close(); + } + } + + @BeforeEach + void migrate() throws SQLException, IOException { + try (Connection connection = support.connection(); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA public CASCADE"); + statement.execute("CREATE SCHEMA public"); + for (String migration : NotificationFixtures.migrations()) { + statement.execute(migration); + } + } + } + + @Override + protected ReconciliationJobStorePort store() { + return new JdbcReconciliationJobStore( + new JdbcTemplate(support.dataSource()), Clock.fixed(NOW, ZoneOffset.UTC)); + } + + @Override + protected DeliveryAttemptId givenAnAttempt() { + try { + return new DeliveryAttemptId( + NotificationFixtures.insertAttempt(support, TENANT, NOW, PROFILE)); + } catch (SQLException failed) { + throw new IllegalStateException("could not insert the attempt row", failed); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlSuppressionStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlSuppressionStoreContractTest.java index a78e1a17..5199db24 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlSuppressionStoreContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlSuppressionStoreContractTest.java @@ -1,7 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.notification; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaSuppressionStore; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.SuppressionJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.SuppressionJpaRepository; import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; import dev.caskeleton.application.notification.platform.policy.testkit.SuppressionStoreContract; import java.time.Clock; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlTemplateRegistryContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlTemplateRegistryContractTest.java new file mode 100644 index 00000000..4f108506 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/PostgreSqlTemplateRegistryContractTest.java @@ -0,0 +1,62 @@ +package dev.caskeleton.adapter.outbound.persistence.notification; + +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaTemplateRegistry; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.TemplateVersionJpaRepository; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.template.TemplateRegistry; +import dev.caskeleton.application.notification.platform.template.testkit.TemplateRegistryContract; +import java.time.Clock; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaTemplateRegistry} held to the template registry contract against a real PostgreSQL. + * + *

        The registry reads candidates by channel and resolves the locale over them, the fake looks the + * locale up first; the contract is what keeps the two answering the same. + */ +@Tag("jpa-contract") +class PostgreSqlTemplateRegistryContractTest extends TemplateRegistryContract { + + private static NotificationJpaStack stack; + private static JpaTemplateRegistry registry; + + @BeforeAll + static void start() { + stack = NotificationJpaStack.start(); + registry = + new JpaTemplateRegistry( + stack.repository(TemplateVersionJpaRepository.class), + new NotificationTestCodecs.SlotJson(), + () -> new TenantId("tenant-a"), + UUID::randomUUID, + Clock.systemUTC(), + PLATFORM_DEFAULT); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.jdbc().update("DELETE FROM notification_template_version"); + } + + @Override + protected TemplateRegistry registry() { + return registry; + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ProjectionFactDurabilityContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ProjectionFactDurabilityContractTest.java deleted file mode 100644 index 85015255..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ProjectionFactDurabilityContractTest.java +++ /dev/null @@ -1,271 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.List; -import java.util.UUID; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * Whether a fact the platform observed survives a reload. - * - *

        It did not. The store read the outcome columns back and then passed {@code - * EngagementFacts.NONE} and {@code SuppressionFacts.NONE}, so every open, click, read, complaint - * and hard bounce existed only for the lifetime of one projection call. - * - *

        That breaks a rule the projector states outright: a hard bounce makes a later "delivered" - * meaningless, and it is deliberately ignored. After a restart the hard-bounce fact was gone, the - * late event was applied, and the delivery came back to life on a contact point the provider had - * already reported dead. - */ -@Tag("jpa-contract") -class ProjectionFactDurabilityContractTest { - - private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); - private static final String TENANT = "tenant-a"; - - private static JpaPlatformContractSupport support; - - private UUID attemptId; - - @BeforeAll - static void startServer() { - support = JpaPlatformContractSupport.start(); - } - - @AfterAll - static void stopServer() { - if (support != null) { - support.close(); - } - } - - @BeforeEach - void migrate() throws SQLException, IOException { - try (Connection connection = support.connection(); - Statement statement = connection.createStatement()) { - statement.execute("DROP SCHEMA public CASCADE"); - statement.execute("CREATE SCHEMA public"); - for (String migration : migrations()) { - statement.execute(migration); - } - } - attemptId = insertAttempt(); - } - - @Test - @DisplayName("a hard bounce is still there after the row is read back") - void aHardBounceSurvivesAReload() throws SQLException { - applyFacts(false, false, false, true, false); - - assertThat(flag("suppression_hard_bounced")) - .as("the fact used to live only in memory, so a later delivered event was applied") - .isTrue(); - } - - @Test - @DisplayName("engagement facts accumulate rather than replacing each other") - void engagementFactsAccumulate() throws SQLException { - applyFacts(true, false, false, false, false); - applyFacts(false, true, false, false, false); - - assertThat(flag("engagement_opened")).isTrue(); - assertThat(flag("engagement_clicked")) - .as("a second event that does not mention the open must not unset it") - .isTrue(); - } - - @Test - @DisplayName("a read is not withdrawn by a later event that says nothing about it") - void aReadIsNotWithdrawn() throws SQLException { - applyFacts(false, false, true, false, false); - applyFacts(true, false, false, false, false); - - assertThat(flag("engagement_read")).isTrue(); - } - - @Test - @DisplayName("a complaint and a delivery coexist") - void aComplaintAndADeliveryCoexist() throws SQLException { - applyFacts(false, false, false, false, true); - applyFacts(true, false, false, false, false); - - assertThat(flag("suppression_complained")).isTrue(); - assertThat(flag("engagement_opened")).isTrue(); - } - - @Test - @DisplayName("the projection version advances so a stale snapshot is recognisable") - void theProjectionVersionAdvances() throws SQLException { - long before = projectionVersion(); - applyFacts(true, false, false, false, false); - - assertThat(projectionVersion()) - .as("an operator comparing a snapshot with a ledger fold needs to know which is older") - .isGreaterThan(before); - } - - @Test - @DisplayName("the suppression side effect can be claimed exactly once") - void theSuppressionSideEffectIsClaimedOnce() throws SQLException { - assertThat(claimSideEffect()).isTrue(); - assertThat(claimSideEffect()) - .as("the ledger is replayed by design, so 'the facts say suppressed' is true every time") - .isFalse(); - } - - private void applyFacts( - boolean opened, boolean clicked, boolean read, boolean hardBounced, boolean complained) - throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "UPDATE notification_delivery_attempt SET" - + " engagement_opened = engagement_opened OR ?," - + " engagement_clicked = engagement_clicked OR ?," - + " engagement_read = engagement_read OR ?," - + " suppression_hard_bounced = suppression_hard_bounced OR ?," - + " suppression_complained = suppression_complained OR ?," - + " projection_version = projection_version + 1" - + " WHERE id = ?")) { - statement.setBoolean(1, opened); - statement.setBoolean(2, clicked); - statement.setBoolean(3, read); - statement.setBoolean(4, hardBounced); - statement.setBoolean(5, complained); - statement.setObject(6, attemptId); - statement.executeUpdate(); - } - } - - private boolean claimSideEffect() throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "UPDATE notification_delivery_attempt" - + " SET suppression_side_effect_applied = true" - + " WHERE id = ? AND suppression_side_effect_applied = false")) { - statement.setObject(1, attemptId); - return statement.executeUpdate() == 1; - } - } - - private boolean flag(String column) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "SELECT " + column + " FROM notification_delivery_attempt WHERE id = ?")) { - statement.setObject(1, attemptId); - try (ResultSet rows = statement.executeQuery()) { - return rows.next() && rows.getBoolean(1); - } - } - } - - private long projectionVersion() throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "SELECT projection_version FROM notification_delivery_attempt WHERE id = ?")) { - statement.setObject(1, attemptId); - try (ResultSet rows = statement.executeQuery()) { - return rows.next() ? rows.getLong(1) : -1L; - } - } - } - - private UUID insertAttempt() throws SQLException { - UUID requestId = UUID.randomUUID(); - UUID deliveryId = UUID.randomUUID(); - UUID contactId = UUID.randomUUID(); - UUID id = UUID.randomUUID(); - try (Connection connection = support.connection()) { - try (PreparedStatement statement = - connection.prepareStatement( - "INSERT INTO notification_request (" - + " id, tenant_id, idempotency_key, request_fingerprint, category," - + " template_id, template_version, strategy_type, variables_payload," - + " request_status, metadata_json, created_at, updated_at)" - + " VALUES (?, ?, ?, ?, 'TRANSACTIONAL', 'welcome', 1, 'SingleRoute', '{}'," - + " 'VALIDATED', '{}'::jsonb, ?, ?)")) { - statement.setObject(1, requestId); - statement.setString(2, TENANT); - statement.setString(3, "idem-" + requestId); - statement.setString(4, "0".repeat(64)); - statement.setTimestamp(5, Timestamp.from(NOW)); - statement.setTimestamp(6, Timestamp.from(NOW)); - statement.executeUpdate(); - } - try (PreparedStatement statement = - connection.prepareStatement( - "INSERT INTO notification_recipient_delivery (" - + " id, notification_id, tenant_id, recipient_ref, routing_plan_json," - + " route_cursor, delivery_state, submission_outcome, delivery_outcome," - + " evidence_level, attempt_count, created_at, updated_at)" - + " VALUES (?, ?, ?, 'user-1', '[]'::jsonb, 0, 'DISPATCHING', 'NOT_SUBMITTED'," - + " 'UNKNOWN', 'PLATFORM_QUEUED', 1, ?, ?)")) { - statement.setObject(1, deliveryId); - statement.setObject(2, requestId); - statement.setString(3, TENANT); - statement.setTimestamp(4, Timestamp.from(NOW)); - statement.setTimestamp(5, Timestamp.from(NOW)); - statement.executeUpdate(); - } - try (PreparedStatement statement = - connection.prepareStatement( - "INSERT INTO notification_contact_point (" - + " id, tenant_id, owner_ref, type, environment, ciphertext, nonce," - + " lookup_hmac, key_id, status, created_at, updated_at)" - + " VALUES (?, ?, 'user-1', 'EMAIL', 'PRODUCTION', ?, ?, ?, 'key-1', 'ACTIVE'," - + " ?, ?)")) { - statement.setObject(1, contactId); - statement.setString(2, TENANT); - statement.setBytes(3, new byte[] {1, 2, 3}); - statement.setBytes(4, new byte[] {4, 5, 6}); - statement.setString(5, "1".repeat(64)); - statement.setTimestamp(6, Timestamp.from(NOW)); - statement.setTimestamp(7, Timestamp.from(NOW)); - statement.executeUpdate(); - } - try (PreparedStatement statement = - connection.prepareStatement( - "INSERT INTO notification_delivery_attempt (" - + " id, recipient_delivery_id, contact_point_id, attempt_no, channel," - + " provider_id, provider_profile_id, request_started, request_body_committed," - + " provider_response_received, submission_outcome, delivery_outcome," - + " confirmation, evidence_level, started_at, credential_generation," - + " rendered_content_digest, created_at, updated_at)" - + " VALUES (?, ?, ?, 1, 'EMAIL', 'ses', 'email-main', true, true, true," - + " 'CONFIRMED_ACCEPTED', 'UNKNOWN', 'CONFIRMED', 'PROVIDER_ACCEPTED', ?, 1," - + " ?, ?, ?)")) { - statement.setObject(1, id); - statement.setObject(2, deliveryId); - statement.setObject(3, contactId); - statement.setTimestamp(4, Timestamp.from(NOW)); - statement.setString(5, "0".repeat(64)); - statement.setTimestamp(6, Timestamp.from(NOW)); - statement.setTimestamp(7, Timestamp.from(NOW)); - statement.executeUpdate(); - } - } - return id; - } - - private static List migrations() throws IOException { - return NotificationFixtures.migrations(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/RecipientClaimContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/RecipientClaimContractTest.java deleted file mode 100644 index d902ca35..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/RecipientClaimContractTest.java +++ /dev/null @@ -1,320 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientClaimSql; -import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * When a queued notification becomes claimable, against a real PostgreSQL. - * - *

        Scheduled deliveries were written {@code PENDING} and the claim query read only {@code - * READY_TO_DISPATCH} and {@code RETRY_WAITING}, so every {@code schedule(...)} request sat in the - * table forever. The partial index listed {@code PENDING} — the index was written for the query the - * author meant, and the query for two of its three states. - * - *

        The statement under test is the one the adapter runs: {@link RecipientClaimSql} is the single - * source, and this test rewrites only its parameter placeholders. Retyping the SQL here would prove - * that two authors agreed about a query rather than that the query is right. - */ -@Tag("jpa-contract") -class RecipientClaimContractTest { - - private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); - private static final String TENANT = "tenant-a"; - - private static JpaPlatformContractSupport support; - - private UUID notificationId; - - @BeforeAll - static void startServer() { - support = JpaPlatformContractSupport.start(); - } - - @AfterAll - static void stopServer() { - if (support != null) { - support.close(); - } - } - - @BeforeEach - void migrate() throws SQLException, IOException { - try (Connection connection = support.connection(); - Statement statement = connection.createStatement()) { - // Everything the streams below create, so each test starts from an empty database rather - // than from whatever the previous one left. - statement.execute("DROP SCHEMA public CASCADE"); - statement.execute("CREATE SCHEMA public"); - for (String migration : migrations()) { - statement.execute(migration); - } - } - notificationId = insertRequest(); - } - - @Test - @DisplayName("a delivery due one microsecond from now is not claimed yet") - void aDeliveryNotYetDueIsNotClaimed() throws SQLException { - insertDelivery("READY_TO_DISPATCH", NOW.plusNanos(1_000), null); - - assertThat(claim(NOW, 10, "worker-a")).isEmpty(); - } - - @Test - @DisplayName("a delivery due exactly now is claimed exactly once") - void aDeliveryDueNowIsClaimedOnce() throws SQLException { - insertDelivery("READY_TO_DISPATCH", NOW, null); - - assertThat(claim(NOW, 10, "worker-a")).hasSize(1); - assertThat(claim(NOW, 10, "worker-a")) - .as("the claim moved it to DISPATCHING and took the lease, so a second poll finds nothing") - .isEmpty(); - } - - @Test - @DisplayName("a delivery scheduled in the past is claimed immediately") - void aPastScheduleIsClaimedImmediately() throws SQLException { - insertDelivery("READY_TO_DISPATCH", NOW.minus(Duration.ofHours(3)), null); - - assertThat(claim(NOW, 10, "worker-a")).hasSize(1); - } - - @Test - @DisplayName("a row left PENDING by an older instance is still claimed") - void aPendingRowFromAnOlderInstanceIsStillClaimed() throws SQLException { - insertDelivery("PENDING", NOW, null); - - assertThat(claim(NOW, 10, "worker-a")) - .as("this is the exact state every scheduled delivery used to be stranded in") - .hasSize(1); - } - - @Test - @DisplayName("a delivery past its expiry is never claimed") - void anExpiredDeliveryIsNeverClaimed() throws SQLException { - insertDelivery("READY_TO_DISPATCH", NOW.minus(Duration.ofHours(1)), NOW.minusSeconds(1)); - - assertThat(claim(NOW, 10, "worker-a")).isEmpty(); - } - - @Test - @DisplayName("a delivery whose expiry is still ahead is claimed") - void aDeliveryInsideItsWindowIsClaimed() throws SQLException { - insertDelivery("READY_TO_DISPATCH", NOW, NOW.plusSeconds(1)); - - assertThat(claim(NOW, 10, "worker-a")).hasSize(1); - } - - @Test - @DisplayName("an expired delivery is retired to EXPIRED rather than left looking stuck") - void anExpiredDeliveryIsRetired() throws SQLException { - UUID id = - insertDelivery("READY_TO_DISPATCH", NOW.minus(Duration.ofHours(1)), NOW.minusSeconds(1)); - - assertThat(expireOverdue(NOW, 10)).isEqualTo(1); - assertThat(stateOf(id)).isEqualTo("EXPIRED"); - } - - @Test - @DisplayName("two workers racing for one delivery produce exactly one claim") - void twoWorkersRacingProduceExactlyOneClaim() throws SQLException { - insertDelivery("READY_TO_DISPATCH", NOW, null); - - List first = claim(NOW, 10, "worker-a"); - List second = claim(NOW, 10, "worker-b"); - - assertThat(first).hasSize(1); - assertThat(second) - .as("SKIP LOCKED plus the state transition leaves nothing for the second") - .isEmpty(); - } - - @Test - @DisplayName("the claim advances the JPA version so a stale entity flush cannot overwrite it") - void theClaimAdvancesTheJpaVersion() throws SQLException { - UUID id = insertDelivery("READY_TO_DISPATCH", NOW, null); - long before = versionOf(id); - - claim(NOW, 10, "worker-a"); - - assertThat(versionOf(id)) - .as( - "a managed entity loaded before the claim still holds the old version; without this" - + " its flush succeeds and writes the pre-claim lease and state back") - .isGreaterThan(before); - } - - @Test - @DisplayName("the claim advances the fence so a stale holder can be told apart") - void theClaimAdvancesTheFence() throws SQLException { - UUID id = insertDelivery("READY_TO_DISPATCH", NOW, null); - - claim(NOW, 10, "worker-a"); - long afterFirst = fenceOf(id); - // The lease expires and the row returns to the queue the way recovery puts it back. - requeue(id); - claim(NOW, 10, "worker-b"); - - assertThat(fenceOf(id)).isGreaterThan(afterFirst); - } - - private List claim(Instant now, int batchSize, String owner) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - RecipientClaimSql.positional(RecipientClaimSql.CLAIM_BATCH))) { - // Placeholder order follows the statement text: now, now, now, batchSize, owner, leaseUntil, - // now. - statement.setTimestamp(1, Timestamp.from(now)); - statement.setTimestamp(2, Timestamp.from(now)); - statement.setTimestamp(3, Timestamp.from(now)); - statement.setInt(4, batchSize); - statement.setString(5, owner); - statement.setTimestamp(6, Timestamp.from(now.plus(Duration.ofMinutes(5)))); - statement.setTimestamp(7, Timestamp.from(now)); - List claimed = new ArrayList<>(); - try (ResultSet rows = statement.executeQuery()) { - while (rows.next()) { - claimed.add(rows.getObject(1, UUID.class)); - } - } - return List.copyOf(claimed); - } - } - - private int expireOverdue(Instant now, int batchSize) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - RecipientClaimSql.positional(RecipientClaimSql.EXPIRE_OVERDUE))) { - statement.setTimestamp(1, Timestamp.from(now)); - statement.setTimestamp(2, Timestamp.from(now)); - statement.setInt(3, batchSize); - return statement.executeUpdate(); - } - } - - private String stateOf(UUID id) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "SELECT delivery_state FROM notification_recipient_delivery WHERE id = ?")) { - statement.setObject(1, id); - try (ResultSet rows = statement.executeQuery()) { - return rows.next() ? rows.getString(1) : null; - } - } - } - - private long versionOf(UUID id) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "SELECT version FROM notification_recipient_delivery WHERE id = ?")) { - statement.setObject(1, id); - try (ResultSet rows = statement.executeQuery()) { - return rows.next() ? rows.getLong(1) : -1L; - } - } - } - - private long fenceOf(UUID id) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "SELECT lease_fence FROM notification_recipient_delivery WHERE id = ?")) { - statement.setObject(1, id); - try (ResultSet rows = statement.executeQuery()) { - return rows.next() ? rows.getLong(1) : -1L; - } - } - } - - private void requeue(UUID id) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "UPDATE notification_recipient_delivery" - + " SET delivery_state = 'READY_TO_DISPATCH', lease_until = NULL" - + " WHERE id = ?")) { - statement.setObject(1, id); - statement.executeUpdate(); - } - } - - private UUID insertRequest() throws SQLException { - UUID id = UUID.randomUUID(); - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "INSERT INTO notification_request (" - + " id, tenant_id, idempotency_key, request_fingerprint, category," - + " template_id, template_version, strategy_type, variables_payload," - + " request_status, correlation_id, metadata_json, created_at, updated_at)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, '{}', 'VALIDATED', ?, '{}'::jsonb, ?, ?)")) { - statement.setObject(1, id); - statement.setString(2, TENANT); - statement.setString(3, "idem-" + id); - statement.setString(4, "0".repeat(64)); - statement.setString(5, "TRANSACTIONAL"); - statement.setString(6, "welcome"); - statement.setLong(7, 1L); - statement.setString(8, "SingleRoute"); - statement.setString(9, "corr-1"); - statement.setTimestamp(10, Timestamp.from(NOW)); - statement.setTimestamp(11, Timestamp.from(NOW)); - statement.executeUpdate(); - } - return id; - } - - private UUID insertDelivery(String state, Instant dueAt, Instant expiresAt) throws SQLException { - UUID id = UUID.randomUUID(); - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "INSERT INTO notification_recipient_delivery (" - + " id, notification_id, tenant_id, recipient_ref, routing_plan_json," - + " route_cursor, delivery_state, submission_outcome, delivery_outcome," - + " evidence_level, next_dispatch_at, expires_at, attempt_count," - + " created_at, updated_at)" - + " VALUES (?, ?, ?, ?, '[]'::jsonb, 0, ?, 'NOT_SUBMITTED', 'UNKNOWN'," - + " 'PLATFORM_QUEUED', ?, ?, 0, ?, ?)")) { - statement.setObject(1, id); - statement.setObject(2, notificationId); - statement.setString(3, TENANT); - statement.setString(4, "user-1"); - statement.setString(5, state); - statement.setTimestamp(6, Timestamp.from(dueAt)); - statement.setTimestamp(7, expiresAt == null ? null : Timestamp.from(expiresAt)); - statement.setTimestamp(8, Timestamp.from(NOW)); - statement.setTimestamp(9, Timestamp.from(NOW)); - statement.executeUpdate(); - } - return id; - } - - private static List migrations() throws IOException { - return NotificationFixtures.migrations(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ReconciliationJobClaimContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ReconciliationJobClaimContractTest.java deleted file mode 100644 index 3384ef60..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/ReconciliationJobClaimContractTest.java +++ /dev/null @@ -1,257 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.notification.platform.JdbcReconciliationJobStore; -import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; -import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; -import dev.caskeleton.application.notification.platform.api.ProviderProfileId; -import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJob; -import java.io.IOException; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.core.JdbcTemplate; - -/** - * Whether two instances polling the reconciliation table can take the same job, against a real - * PostgreSQL. - * - *

        Every call runs on its own pooled autocommit connection, as the worker's do: no transaction - * spans the claim and the provider call, so ownership has to be in the row. Row locks and {@code - * SKIP LOCKED} are vendor semantics a fake would only restate. - */ -@Tag("jpa-contract") -class ReconciliationJobClaimContractTest { - - private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); - private static final String TENANT = "tenant-a"; - private static final String PROFILE = "email-main"; - private static final Duration LEASE = Duration.ofMinutes(2); - - private static JpaPlatformContractSupport support; - - @BeforeAll - static void startServer() { - support = JpaPlatformContractSupport.start(); - } - - @AfterAll - static void stopServer() { - if (support != null) { - support.close(); - } - } - - @BeforeEach - void migrate() throws SQLException, IOException { - try (Connection connection = support.connection(); - Statement statement = connection.createStatement()) { - statement.execute("DROP SCHEMA public CASCADE"); - statement.execute("CREATE SCHEMA public"); - for (String migration : NotificationFixtures.migrations()) { - statement.execute(migration); - } - } - } - - @Test - @DisplayName("한 인스턴스가 가져간 정산 job은 다른 인스턴스의 claim에 다시 나오지 않는다") - void aClaimedJobIsNotHandedToAnotherInstance() throws SQLException { - // given - scheduleDueJob(); - JdbcReconciliationJobStore first = store(); - JdbcReconciliationJobStore second = store(); - List firstClaim = first.claimDue(10, NOW, LEASE); - - // when - List secondClaim = second.claimDue(10, NOW, LEASE); - - // then - assertThat(firstClaim).hasSize(1); - assertThat(secondClaim) - .as( - "the claim commits with its statement; only the lease in the row still says who owns it") - .isEmpty(); - } - - @Test - @DisplayName("두 연결이 동시에 claim하면 겹쳐서 가져간 job이 없다") - void twoConcurrentClaimsShareNoJob() throws Exception { - // given - for (int i = 0; i < 40; i++) { - scheduleDueJob(); - } - CountDownLatch start = new CountDownLatch(1); - Callable> claimer = - () -> { - start.await(); - return store().claimDue(40, NOW, LEASE).stream().map(ReconciliationJob::id).toList(); - }; - ExecutorService pool = Executors.newFixedThreadPool(2); - List a; - List b; - try { - Future> left = pool.submit(claimer); - Future> right = pool.submit(claimer); - - // when - start.countDown(); - a = left.get(); - b = right.get(); - } finally { - pool.shutdownNow(); - } - - // then - Set overlap = new HashSet<>(a); - overlap.retainAll(b); - assertThat(overlap).as("a job taken by both instances is asked about twice").isEmpty(); - assertThat(a.size() + b.size()).isEqualTo(40); - } - - @Test - @DisplayName("lease가 지난 job은 다른 인스턴스가 다시 가져간다") - void aJobWhoseLeaseHasPassedIsClaimedAgain() throws SQLException { - // given - UUID id = scheduleDueJob(); - store().claimDue(10, NOW, LEASE); - - // when - List reclaimed = store().claimDue(10, NOW.plus(LEASE), LEASE); - - // then - assertThat(reclaimed) - .as("a holder that died mid-pass must not strand its jobs") - .extracting(ReconciliationJob::id) - .containsExactly(id); - } - - @Test - @DisplayName("lease가 1마이크로초라도 남은 job은 다른 인스턴스가 가져가지 못한다") - void aJobWhoseLeaseHasNotPassedIsNotClaimed() throws SQLException { - // given - scheduleDueJob(); - store().claimDue(10, NOW, LEASE); - - // when - List early = store().claimDue(10, NOW.plus(LEASE).minusNanos(1_000), LEASE); - - // then - assertThat(early).isEmpty(); - } - - @Test - @DisplayName("다른 인스턴스가 다시 가져간 job은 이전 소유자가 완료해도 지워지지 않는다") - void aSupersededHolderCannotCompleteTheJob() throws SQLException { - // given - UUID id = scheduleDueJob(); - ReconciliationJob stale = store().claimDue(10, NOW, LEASE).get(0); - store().claimDue(10, NOW.plus(LEASE), LEASE); - - // when - store().complete(stale); - - // then - assertThat(rowExists(id)).as("the new holder has not answered yet").isTrue(); - } - - @Test - @DisplayName("다른 인스턴스가 다시 가져간 job은 이전 소유자의 재예약이 시도 횟수를 올리지 않는다") - void aSupersededHolderCannotRescheduleTheJob() throws SQLException { - // given - UUID id = scheduleDueJob(); - ReconciliationJob stale = store().claimDue(10, NOW, LEASE).get(0); - store().claimDue(10, NOW.plus(LEASE), LEASE); - - // when - store().reschedule(stale, "STILL_UNKNOWN", NOW.plus(Duration.ofHours(1))); - - // then - assertThat(attemptsOf(id)) - .as("two holders counting one question would reach the attempt limit early") - .isZero(); - } - - @Test - @DisplayName("현재 소유자가 재예약하면 claim이 풀려 lease 만료 전이라도 다음 확인 시각에 다시 나온다") - void theHoldersRescheduleReleasesTheClaim() throws SQLException { - // given - UUID id = scheduleDueJob(); - ReconciliationJob held = store().claimDue(10, NOW, LEASE).get(0); - Instant nextCheck = NOW.plusSeconds(30); - store().reschedule(held, "STILL_UNKNOWN", nextCheck); - - // when - List next = store().claimDue(10, nextCheck, LEASE); - - // then - assertThat(next).extracting(ReconciliationJob::id).containsExactly(id); - assertThat(next.get(0).attempts()).isEqualTo(1); - } - - @Test - @DisplayName("현재 소유자가 완료하면 job이 지워진다") - void theHolderCompletesTheJob() throws SQLException { - // given - UUID id = scheduleDueJob(); - ReconciliationJob held = store().claimDue(10, NOW, LEASE).get(0); - - // when - store().complete(held); - - // then - assertThat(rowExists(id)).isFalse(); - } - - private static boolean rowExists(UUID id) { - Integer rows = - new JdbcTemplate(support.dataSource()) - .queryForObject( - "SELECT count(*) FROM notification_reconciliation_job WHERE id = ?", - Integer.class, - id); - return rows != null && rows > 0; - } - - private static int attemptsOf(UUID id) { - Integer attempts = - new JdbcTemplate(support.dataSource()) - .queryForObject( - "SELECT attempts FROM notification_reconciliation_job WHERE id = ?", - Integer.class, - id); - return attempts == null ? -1 : attempts; - } - - private UUID scheduleDueJob() throws SQLException { - UUID attemptId = NotificationFixtures.insertAttempt(support, TENANT, NOW, PROFILE); - return store() - .schedule(new DeliveryAttemptId(attemptId), new ProviderProfileId(PROFILE), NOW) - .id(); - } - - private static JdbcReconciliationJobStore store() { - return new JdbcReconciliationJobStore( - new JdbcTemplate(support.dataSource()), Clock.fixed(NOW, ZoneOffset.UTC)); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/WorkerCrashRecoveryContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/WorkerCrashRecoveryContractTest.java index 5689842e..0cddeb3c 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/WorkerCrashRecoveryContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/WorkerCrashRecoveryContractTest.java @@ -85,16 +85,30 @@ class WorkerCrashRecoveryContractTest { assertThat(attemptCount(delivery)).isZero(); } + /** + * The attempt row is written before the call and keeps the factory's "unknown" evidence for the + * whole call (review 05-01), so a crash anywhere between the insert and the provider's answer + * leaves the same row. Recovery cannot tell "never called" from "called and died", so the row + * goes to reconciliation rather than back to the queue. + */ @Test - @DisplayName("a crash between writing the attempt row and starting the call is recoverable") - void aCrashBeforeTheCallStartsIsRecoverable() throws SQLException { + @DisplayName("attempt 행을 쓴 뒤 호출이 끝나기 전 죽으면 시작 여부 불명인 미완료 attempt 가 남아 reconcile 대상이 된다") + void aCrashAfterTheAttemptRowIsWrittenLeavesAnUnfinishedAttemptOfUnknownStart() + throws SQLException { + // given UUID delivery = deliveryHeldByADeadWorker(); - UUID attempt = attemptOn(delivery, false, "PROVEN", false, "PROVEN"); - assertThat(isClaimableAgain(delivery)).isTrue(); + // when + UUID attempt = attemptOn(delivery, false, "UNKNOWN", false, "UNKNOWN"); + + // then assertThat(evidenceOf(attempt)) - .as("the row records, with certainty, that nothing started") - .containsExactly("false", "PROVEN", "false", "PROVEN"); + .as("the row the factory writes records that whether the call started is not known") + .containsExactly("false", "UNKNOWN", "false", "UNKNOWN"); + assertThat(isUnfinished(attempt)) + .as("an unfinished attempt is what recovery hands to reconciliation") + .isTrue(); + assertThat(isClaimableAgain(delivery)).isTrue(); } @Test @@ -147,7 +161,7 @@ class WorkerCrashRecoveryContractTest { // hand-picked row. deliveries.add(deliveryHeldByADeadWorker()); UUID beforeCall = deliveryHeldByADeadWorker(); - attemptOn(beforeCall, false, "PROVEN", false, "PROVEN"); + attemptOn(beforeCall, false, "UNKNOWN", false, "UNKNOWN"); deliveries.add(beforeCall); UUID started = deliveryHeldByADeadWorker(); attemptOn(started, true, "PROVEN", false, "UNKNOWN"); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxBulkReadVersionContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/InboxBulkReadVersionContractTest.java similarity index 96% rename from src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxBulkReadVersionContractTest.java rename to src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/InboxBulkReadVersionContractTest.java index 8caecf72..76863346 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxBulkReadVersionContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/InboxBulkReadVersionContractTest.java @@ -1,9 +1,10 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.persistence.notification.NotificationJpaStack; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.InboxItemEntity; import java.sql.Timestamp; import java.time.Instant; import java.util.UUID; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientExpiryVersionContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientExpiryVersionContractTest.java similarity index 96% rename from src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientExpiryVersionContractTest.java rename to src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientExpiryVersionContractTest.java index 11cbd8f0..5265290f 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientExpiryVersionContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientExpiryVersionContractTest.java @@ -1,9 +1,10 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.persistence.notification.NotificationJpaStack; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.RecipientDeliveryEntity; import java.sql.Timestamp; import java.time.Instant; import java.util.UUID; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java index 2d883e2b..d2fef3bf 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java @@ -390,6 +390,26 @@ class PostgreSqlFileserverMetadataStoreIntegrationTest extends FileMetadataPortC assertThat(quota.reservedBytes(scope)).isZero(); } + /** What a configured namespace limit (05-07) is compared against: live plus committed bytes. */ + @Test + void usedBytesCountsLiveReservationsAndCommittedUsageButNotReleasedOnes() { + // given + QuotaScope scope = QuotaScope.ofNamespace("used-bytes"); + QuotaReservation committed = + transactions.execute(ignored -> quota.reserve(scope, 1000, Duration.ofHours(1))); + transactions.executeWithoutResult(ignored -> quota.commit(committed, 600)); + transactions.execute(ignored -> quota.reserve(scope, 300, Duration.ofHours(1))); + QuotaReservation released = + transactions.execute(ignored -> quota.reserve(scope, 5000, Duration.ofHours(1))); + transactions.executeWithoutResult(ignored -> quota.release(released)); + + // when + long used = quota.usedBytes(scope); + + // then + assertThat(used).isEqualTo(900); + } + @Test void aReleasedReservationCanNeverBeCommittedOrExtended() { QuotaScope scope = QuotaScope.ofTenant("tenant-b"); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java index 21070929..64057dae 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java @@ -313,22 +313,26 @@ class PostgreSqlIdempotencyIntegrationTest { @Test void aRenewalRepeatedUnderOneOperationIdWithADifferentLeaseIsAConflict() { - IdempotencyOwner claimed = claim("claim-renew-conflict"); + // Started first: only an executing operation's lease is renewed (IdempotencyStoreContract). + IdempotencyOwner executing = claimAndStart("claim-renew-conflict", "start-renew-conflict"); IdempotencyRenewOutcome first = transactions .execute( - ignored -> store.renew(claimed, Duration.ofSeconds(30), new OperationId("renew-1"))) + ignored -> + store.renew(executing, Duration.ofSeconds(30), new OperationId("renew-1"))) .outcome(); IdempotencyRenewOutcome same = transactions .execute( - ignored -> store.renew(claimed, Duration.ofSeconds(30), new OperationId("renew-1"))) + ignored -> + store.renew(executing, Duration.ofSeconds(30), new OperationId("renew-1"))) .outcome(); IdempotencyRenewOutcome different = transactions .execute( - ignored -> store.renew(claimed, Duration.ofMinutes(45), new OperationId("renew-1"))) + ignored -> + store.renew(executing, Duration.ofMinutes(45), new OperationId("renew-1"))) .outcome(); assertThat(first).isEqualTo(IdempotencyRenewOutcome.RENEWED); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlInboxCutoffIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlInboxCutoffIntegrationTest.java index 66b35d87..20f4def0 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlInboxCutoffIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlInboxCutoffIntegrationTest.java @@ -2,7 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxItemJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.InboxItemJpaRepository; import java.sql.Types; import java.time.Instant; import java.util.List; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java index ac80e995..74d09587 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java @@ -4,23 +4,31 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderEventReplayWorker; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.DeliveryAttemptJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.NotificationTestCodecs; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaDeliveryAttemptStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaProviderEventLedger; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientDeliveryStore; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientLeaseStore; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationRecordMapper; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.ProviderEventJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientDeliveryJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.DeliveryAttemptJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ProviderEventJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; +import dev.caskeleton.application.notification.platform.api.CollapseScope; +import dev.caskeleton.application.notification.platform.api.CollapseSpec; import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.CorrelationId; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.NormalizedEventType; import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; +import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.api.ProviderId; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.RequestStatus; import dev.caskeleton.application.notification.platform.api.TemplateSelection; +import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.api.content.EmailContent; import dev.caskeleton.application.notification.platform.api.content.EmailOptions; import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; @@ -35,8 +43,7 @@ import dev.caskeleton.application.notification.platform.callback.ProviderEventPr import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord; import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFactory; import dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService; -import dev.caskeleton.application.notification.platform.dispatch.NotificationRoutingPlanCodecPort; -import dev.caskeleton.application.notification.platform.dispatch.NotificationVariablesCodecPort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord; import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; @@ -46,7 +53,6 @@ import dev.caskeleton.application.notification.platform.policy.RouteCandidate; import dev.caskeleton.application.notification.platform.provider.ProviderCapabilities; import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot; import dev.caskeleton.application.notification.platform.provider.ReconciliationResult; -import dev.caskeleton.application.notification.platform.security.NotificationPayloadProtection; import dev.caskeleton.application.notification.platform.template.RenderedNotificationContent; import dev.caskeleton.application.transaction.TransactionPort; import jakarta.persistence.EntityManagerFactory; @@ -144,7 +150,7 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { context.getBean(ProviderEventJpaRepository.class), attempts, (profile, requestId) -> sha256Hex(requestId), - new EmptyAttributes(), + new NotificationTestCodecs.EmptyVariables(), UUID::randomUUID); projection = new ProviderEventProjectionService( @@ -182,6 +188,51 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { assertThat(deliveryState(delivery)).isEqualTo("READY_TO_DISPATCH"); } + @Test + @org.junit.jupiter.api.DisplayName("요청 저장은 collapse 와 dedup DROP 판정을 함께 남겨 같은 키 재조회가 같은 답을 준다") + void aStoredRequestKeepsItsCollapseAndItsDropVerdict() { + // given + JpaNotificationRequestStore requests = + new JpaNotificationRequestStore( + context.getBean(NotificationRequestJpaRepository.class), + context.getBean(RecipientDeliveryJpaRepository.class), + NotificationTestCodecs.recordMapper(), + clock); + Instant now = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS); + NotificationRequestRecord dropped = + new NotificationRequestRecord( + new NotificationId(UUID.randomUUID()), + new TenantId("tenant-a"), + "idem-dropped", + "0".repeat(64), + "TRANSACTIONAL", + new TemplateSelection("welcome", 1L, Locale.KOREAN), + "SingleRoute", + "{}", + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.of(new CollapseSpec("order-42", CollapseScope.RECIPIENT)), + RequestStatus.CREATED, + new CorrelationId("correlation-1"), + Map.of(), + now, + now) + .droppedAsDuplicate(); + + // when + transactions.inWrite(() -> requests.insert(dropped, List.of())); + + // then + NotificationRequestRecord stored = + transactions + .inRead(() -> requests.findByIdempotency(new TenantId("tenant-a"), "idem-dropped")) + .orElseThrow(); + assertThat(List.of(stored.collapse(), stored.receipt())) + .as("the native insert named every column but these, so both were silently lost") + .containsExactly(dropped.collapse(), dropped.receipt()); + } + @Test void recoveryRetiresADeliveryWhoseWindowClosed() { // given @@ -316,10 +367,7 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { } private JpaRecipientDeliveryStore deliveries(RecipientDeliveryJpaRepository recipients) { - return new JpaRecipientDeliveryStore( - recipients, - new NotificationRecordMapper(new EmptyRoutingPlans(), new EmptyAttributes(), new Opaque()), - clock); + return new JpaRecipientDeliveryStore(recipients, NotificationTestCodecs.recordMapper(), clock); } private static void migrate(DataSource dataSource) { @@ -584,45 +632,6 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { } } - private static final class EmptyAttributes implements NotificationVariablesCodecPort { - - @Override - public String encode(Map variables) { - return "{}"; - } - - @Override - public Map decode(String payload) { - return Map.of(); - } - } - - private static final class EmptyRoutingPlans implements NotificationRoutingPlanCodecPort { - - @Override - public String encode(List routes) { - return "[]"; - } - - @Override - public List decode(String payload) { - return List.of(); - } - } - - private static final class Opaque implements NotificationPayloadProtection { - - @Override - public byte[] protect(byte[] plaintext) { - return plaintext.clone(); - } - - @Override - public byte[] reveal(byte[] envelope) { - return envelope.clone(); - } - } - private static final class NoMetrics implements NotificationMetricsPort { @Override diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationPersistenceUnitIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationPersistenceUnitIntegrationTest.java index ef78e513..52bca244 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationPersistenceUnitIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationPersistenceUnitIntegrationTest.java @@ -3,8 +3,8 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.AdminAuditJpaRepository; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaAdminOperationStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.AdminAuditJpaRepository; import dev.caskeleton.application.notification.platform.admin.AdminActor; import dev.caskeleton.application.notification.platform.admin.AdminOperationClaim; import dev.caskeleton.application.notification.platform.admin.AdminOperationResult; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java index 309f1908..f25dfaee 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java @@ -102,12 +102,14 @@ final class PostgreSqlOptionalStreamLifecycle { // hold one job. // V12 makes a suppression unique per target and reason, so the store can upsert with ON // CONFLICT instead of a find-then-insert two webhooks could both win. + // V13 records whether a stored request was accepted or dropped by a deduplication window, + // so a retry with the same idempotency key gets the same receipt (review 05-23c). // // This list is the stream's contract, not a note about its length: the lifecycle below // disables, re-enables and interrupts the stream and asserts the applied set is unchanged // each time. So a migration added to the stream belongs here, and the version that landed // without being added is why the lane failed the first time anybody ran it. - List.of("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"), + List.of("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"), List.of()); } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAppendTransactionalIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAppendTransactionalIntegrationTest.java index 5034b48c..7679e4ae 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAppendTransactionalIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAppendTransactionalIntegrationTest.java @@ -5,12 +5,8 @@ import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.testkit.OutboxAppendContract; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import javax.sql.DataSource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** @@ -18,56 +14,45 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext * transaction; on rollback the outbox row is absent. * *

        Proves the no-dual-write guarantee (D2): if the business transaction rolls back, the outbox - * row vanishes with it — there is no separate out-of-band insert. + * row vanishes with it — there is no separate out-of-band insert. The cases are {@link + * OutboxAppendContract}'s, which the in-memory store runs too (review 2026-11-01 01-05); the commit + * and rollback cases this class held before are two of them. */ -class PostgreSqlOutboxAppendTransactionalIntegrationTest { +class PostgreSqlOutboxAppendTransactionalIntegrationTest extends OutboxAppendContract { private static PostgreSqlReadinessSupport postgres; - private static DataSource sharedDataSource; + private static AnnotationConfigApplicationContext context; @BeforeAll static void setup() { postgres = PostgreSqlReadinessSupport.start(); - sharedDataSource = postgres.dataSource(); - OutboxIntegrationSupport.migrate(sharedDataSource); + OutboxIntegrationSupport.migrate(postgres.dataSource()); + context = + OutboxIntegrationSupport.buildContext(postgres.dataSource(), e -> {}, Clock.systemUTC()); } @AfterAll static void cleanup() { + if (context != null) { + context.close(); + } if (postgres != null) { postgres.close(); } } - @Test - void sameTransactionAppendRollbackRemovesOutboxRowCharacterization() { - Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC); - - try (AnnotationConfigApplicationContext ctx = - OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { - - TransactionPort tx = ctx.getBean(TransactionPort.class); - OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); - - OutboxEventJpaRepository repo = ctx.getBean(OutboxEventJpaRepository.class); - OutboxAppendContract.verifyRollbackRemovesEvent( - tx, append, eventId -> repo.findById(eventId).isPresent(), clock); - } + @Override + protected TransactionPort transactions() { + return context.getBean(TransactionPort.class); } - @Test - void outboxRowIsPresentWhenTransactionCommits() { - Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC); + @Override + protected OutboxAppendPort append() { + return context.getBean(OutboxAppendPort.class); + } - try (AnnotationConfigApplicationContext ctx = - OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) { - - TransactionPort tx = ctx.getBean(TransactionPort.class); - OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); - - OutboxEventJpaRepository repo = ctx.getBean(OutboxEventJpaRepository.class); - OutboxAppendContract.verifyCommitPersistsEvent( - tx, append, eventId -> repo.findById(eventId).isPresent(), clock); - } + @Override + protected boolean committed(String eventId) { + return context.getBean(OutboxEventJpaRepository.class).findById(eventId).isPresent(); } } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java new file mode 100644 index 00000000..98ab6ecf --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java @@ -0,0 +1,276 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.Assertions.tuple; + +import com.zaxxer.hikari.HikariDataSource; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore; +import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Instant; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.FlywayException; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * The V21 pre-deploy procedure of the outbox runbook ({@code docs/runbooks/outbox-dead-letter.md} + * §8), run as written against real PostgreSQL. + * + *

        V21 adds a unique index on the outbox order key, and a database that already holds two rows + * under one key fails the migration (README 15 decision: kept). The runbook gives the operator a + * check query and a cleanup. Both are read out of the runbook here, not copied, so a runbook edit + * that breaks either one fails this lane: each test builds a database at V20 — the schema an + * operator runs them on — with rows appended through the real JPA store. + */ +class PostgreSqlOutboxOrderKeyRunbookIntegrationTest { + + private static final Instant OCCURRED = Instant.parse("2026-11-01T00:00:00Z"); + + private static PostgreSqlReadinessSupport postgres; + private static String duplicateCheck; + private static String removePublishedDuplicates; + + @BeforeAll + static void setup() throws IOException { + String runbook = + Files.readString(Path.of(System.getProperty("outbox.runbook")), StandardCharsets.UTF_8); + duplicateCheck = runbookSql(runbook, "v21-duplicate-order-keys"); + removePublishedDuplicates = runbookSql(runbook, "v21-remove-published-duplicates"); + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void cleanup() { + if (postgres != null) { + postgres.close(); + } + } + + @Test + @DisplayName("V21 이전 DB에 같은 순서 키를 쓰는 행이 둘 있으면 runbook 확인 쿼리가 그 키를 찾는다") + void theCheckFindsTheOrderKeyTwoRowsShare() throws SQLException { + try (BeforeV21 database = BeforeV21.create()) { + // given + String shared = "shared-" + UUID.randomUUID(); + database.append(shared, 3); + database.append(shared, 3); + database.append("alone-" + UUID.randomUUID(), 3); + + // when + List> found = database.jdbc().queryForList(duplicateCheck); + + // then + assertThat(found) + .extracting(row -> row.get("aggregate_id"), row -> row.get("row_count")) + .containsExactly(tuple(shared, 2L)); + } + } + + @Test + @DisplayName("같은 순서 키를 쓰는 행이 없으면 runbook 확인 쿼리는 0행이다") + void theCheckFindsNothingWhenEveryOrderKeyIsUsedOnce() throws SQLException { + try (BeforeV21 database = BeforeV21.create()) { + // given + String aggregate = "ordered-" + UUID.randomUUID(); + database.append(aggregate, 1); + database.append(aggregate, 2); + database.append("other-" + UUID.randomUUID(), 1); + + // when + List> found = database.jdbc().queryForList(duplicateCheck); + + // then + assertThat(found).isEmpty(); + } + } + + @Test + @DisplayName("중복이 남아 있으면 V21이 실패하고 DB는 V20 상태 그대로 남는다") + void aRemainingDuplicateFailsV21AndLeavesTheDatabaseAtV20() throws SQLException { + try (BeforeV21 database = BeforeV21.create()) { + // given + String shared = "shared-" + UUID.randomUUID(); + database.append(shared, 1); + database.append(shared, 1); + + // when + Throwable thrown = catchThrowable(database::migrateToLatest); + + // then + assertThat( + List.of( + thrown instanceof FlywayException, + database.flyway(null).info().current().getVersion().getVersion(), + database.tableExists("outbox_aggregate_sequence"))) + .containsExactly(true, "20", false); + } + } + + @Test + @DisplayName("runbook 정리 SQL은 모두 발행된 키의 나중 행만 옮겨 지우고 미발행 행이 있는 키는 남긴다") + void theCleanupRemovesOnlyTheLaterCopiesOfFullyPublishedKeys() throws SQLException { + try (BeforeV21 database = BeforeV21.create()) { + // given: one key whose rows were both sent, one whose second row still waits + String published = "published-" + UUID.randomUUID(); + String first = database.append(published, 5); + String second = database.append(published, 5); + database.mark(first, "PUBLISHED"); + database.mark(second, "PUBLISHED"); + String waiting = "waiting-" + UUID.randomUUID(); + database.mark(database.append(waiting, 5), "PUBLISHED"); + database.append(waiting, 5); + + // when + database.jdbc().execute(removePublishedDuplicates); + + // then + assertThat( + List.of( + database.eventIdsOf(published), + database + .jdbc() + .queryForList( + "SELECT event_id FROM outbox_event_v21_duplicates", String.class), + database.jdbc().queryForList(duplicateCheck).stream() + .map(row -> row.get("aggregate_id")) + .toList())) + .containsExactly(List.of(first), List.of(second), List.of(waiting)); + } + } + + @Test + @DisplayName("runbook 정리 뒤에는 V21이 적용되고 확인 쿼리는 0행이다") + void afterTheCleanupV21Applies() throws SQLException { + try (BeforeV21 database = BeforeV21.create()) { + // given + String shared = "shared-" + UUID.randomUUID(); + database.mark(database.append(shared, 2), "PUBLISHED"); + database.mark(database.append(shared, 2), "PUBLISHED"); + database.jdbc().execute(removePublishedDuplicates); + + // when + database.migrateToLatest(); + + // then + assertThat( + List.of( + database.indexExists("ux_outbox_event_aggregate_order"), + database.jdbc().queryForList(duplicateCheck).isEmpty())) + .containsExactly(true, true); + } + } + + /** The SQL block that follows {@code } in the runbook. */ + private static String runbookSql(String runbook, String id) { + String marker = ""; + int at = runbook.indexOf(marker); + if (at < 0) { + throw new IllegalStateException("the outbox runbook has no SQL block marked " + id); + } + int open = runbook.indexOf("```sql\n", at); + int close = runbook.indexOf("\n```", open + 1); + if (open < 0 || close < 0) { + throw new IllegalStateException("the block marked " + id + " is not a closed sql fence"); + } + return runbook.substring(open + "```sql\n".length(), close); + } + + /** + * A fresh database migrated to V20 with the JPA outbox store over it, the state an operator runs + * the runbook on. + */ + private static final class BeforeV21 implements AutoCloseable { + + private final HikariDataSource dataSource; + private final AnnotationConfigApplicationContext context; + private final JdbcTemplate jdbc; + private long appended; + + private BeforeV21(HikariDataSource dataSource) { + this.dataSource = dataSource; + flyway("20").migrate(); + this.context = OutboxIntegrationSupport.buildContext(dataSource, e -> {}, Clock.systemUTC()); + this.jdbc = new JdbcTemplate(dataSource); + } + + static BeforeV21 create() throws SQLException { + String name = "v21_" + UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ROOT); + return new BeforeV21(postgres.createDatabase(name)); + } + + Flyway flyway(String target) { + var configuration = + Flyway.configure().dataSource(dataSource).locations("classpath:db/migration/postgresql"); + return (target == null ? configuration : configuration.target(target)).load(); + } + + void migrateToLatest() { + flyway(null).migrate(); + } + + JdbcTemplate jdbc() { + return jdbc; + } + + /** + * Appends a canonical row through the JPA store and returns its event id. Each row occurs one + * second after the previous one, so "the earliest copy" is the first one appended. + */ + String append(String aggregateId, long sequence) { + String eventId = UUID.randomUUID().toString(); + Instant occurredAt = OCCURRED.plusSeconds(appended++); + JpaOutboxStore store = context.getBean(JpaOutboxStore.class); + context + .getBean(SpringTransaction.class) + .inWrite( + () -> store.append(OutboxEvents.event(eventId, aggregateId, sequence, occurredAt))); + return eventId; + } + + void mark(String eventId, String status) { + jdbc.update("UPDATE outbox_event SET status = ? WHERE event_id = ?", status, eventId); + } + + List eventIdsOf(String aggregateId) { + return jdbc.queryForList( + "SELECT event_id FROM outbox_event WHERE aggregate_id = ? ORDER BY event_id", + String.class, + aggregateId); + } + + boolean tableExists(String table) { + return Boolean.TRUE.equals( + jdbc.queryForObject("SELECT to_regclass(?) IS NOT NULL", Boolean.class, table)); + } + + boolean indexExists(String index) { + return Boolean.TRUE.equals( + jdbc.queryForObject( + "SELECT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = ?)", + Boolean.class, + index)); + } + + @Override + public void close() { + context.close(); + dataSource.close(); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java index f3ffc6fc..312bd9be 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java @@ -151,6 +151,28 @@ final class PostgreSqlReadinessSupport implements AutoCloseable { return DriverManager.getConnection(jdbcUrl, properties); } + /** + * Creates another database on this server and returns a small pool on it, for a test that needs + * several schemas at different migration versions. The caller closes the pool. + */ + HikariDataSource createDatabase(String name) throws SQLException { + execute("CREATE DATABASE " + name); + HikariConfig config = new HikariConfig(); + config.setJdbcUrl( + "jdbc:postgresql://" + + container.getHost() + + ":" + + container.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT) + + "/" + + name); + config.setUsername(container.getUsername()); + config.setPassword(container.getPassword()); + config.setMaximumPoolSize(3); + config.setMinimumIdle(1); + config.setConnectionTimeout(1_000); + return new HikariDataSource(config); + } + void execute(String sql) throws SQLException { try (Connection connection = connection(); Statement statement = connection.createStatement()) { diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecipientLeaseFencingIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecipientLeaseFencingIntegrationTest.java index 638b6df3..55442488 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecipientLeaseFencingIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecipientLeaseFencingIntegrationTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientLeaseStore; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientDeliveryJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; import dev.caskeleton.application.notification.platform.dispatch.RecipientLease; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java new file mode 100644 index 00000000..2e30f995 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java @@ -0,0 +1,100 @@ +package dev.caskeleton.adapter.outbound.persistence.transaction; + +import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.TransactionPortContract; +import dev.caskeleton.application.transaction.testkit.TransactionProbe; +import jakarta.persistence.EntityManagerFactory; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * The shipped {@link SpringTransaction} over the transaction manager the leaf composes ({@link + * JpaTransactionManager}), against real PostgreSQL, held to the same contract as the in-memory port + * use-case tests run over. + * + *

        The probe is a table written with {@link JdbcTemplate}, which joins the JPA transaction's + * connection the way the leaf's JDBC adapters (outbox, idempotency) do. What a recording fake + * cannot show and this does: a rollback really removes the row, a failed joined boundary really + * dooms its caller's commit, and a read-only transaction really refuses an insert. + */ +@Tag("jpa-contract") +class SpringTransactionContractTest extends TransactionPortContract { + + private static JpaPlatformContractSupport support; + private static LocalContainerEntityManagerFactoryBean entityManagerFactory; + private static JdbcTemplate jdbc; + private static SpringTransaction transactions; + + @BeforeAll + static void start() { + support = JpaPlatformContractSupport.start(); + entityManagerFactory = new LocalContainerEntityManagerFactoryBean(); + entityManagerFactory.setDataSource(support.dataSource()); + // No entity: the contract is about the transaction, and the probe writes through JDBC. + entityManagerFactory.setPackagesToScan(SpringTransactionContractTest.class.getPackageName()); + entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + entityManagerFactory.setJpaPropertyMap( + Map.of( + "hibernate.hbm2ddl.auto", "none", + "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect")); + entityManagerFactory.afterPropertiesSet(); + EntityManagerFactory factory = entityManagerFactory.getObject(); + JpaTransactionManager transactionManager = new JpaTransactionManager(factory); + transactionManager.afterPropertiesSet(); + jdbc = new JdbcTemplate(support.dataSource()); + jdbc.execute( + "create table if not exists transaction_contract_probe (mark varchar(64) primary key)"); + transactions = new SpringTransaction(transactionManager); + } + + @AfterAll + static void stop() { + if (entityManagerFactory != null) { + entityManagerFactory.destroy(); + } + if (support != null) { + support.close(); + } + } + + @BeforeEach + void empty() { + jdbc.execute("truncate transaction_contract_probe"); + } + + @Override + protected TransactionPort transactions() { + return transactions; + } + + @Override + protected TransactionProbe probe() { + return new TransactionProbe() { + @Override + public void write(String mark) { + jdbc.update("insert into transaction_contract_probe (mark) values (?)", mark); + } + + @Override + public List committed() { + return jdbc.queryForList( + "select mark from transaction_contract_probe order by mark", String.class); + } + + @Override + public boolean inTransaction() { + return TransactionSynchronizationManager.isActualTransactionActive(); + } + }; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java index 4f3051a2..cb7afea5 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java @@ -35,12 +35,20 @@ class AppliedMigrationImmutabilityTest { *

        The fileserver stream ({@code db/migration/jpa/fileserver}, in {@code * adapter:outbound:persistence-fileserver}) runs against the same database through the same * Flyway history and was never pinned at all; it is checked here on the same terms. + * + *

        The messaging platform's tree ({@code db/migration/messaging}, in {@code + * messaging-reliability-jdbc-postgresql}) runs against it too once the consume side is selected: + * {@code adapter:inbound:messaging} applies its inbox range (V11xx). The tree is pinned whole — + * the platform outbox range ships from the same location to deployments that use it, and an + * edited migration stops those just the same. */ private static final List MIGRATION_ROOTS = List.of( Path.of("src/main/resources/db/migration"), Path.of("../persistence-notification/src/main/resources/db/migration"), - Path.of("../persistence-fileserver/src/main/resources/db/migration")); + Path.of("../persistence-fileserver/src/main/resources/db/migration"), + Path.of( + "../../../messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration")); private static final Path MANIFEST = Path.of("src/test/resources/db/applied-migrations.sha256"); diff --git a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 index e44b6dd0..ca048746 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 +++ b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 @@ -13,6 +13,7 @@ 4379872989af0c97b937ff48527c788a2ba0216218d4df9435eba8c6e053ad8d jpa/notification-platform/V10__variables_payload_envelope_guard.sql fb1eee652330995e2f761dd0c0cb9ca137b1c50dd99253aa9958c3ec130cf74b jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql a4c3b56e74bdeaa32be2e716e377aa920bc327b4517bf3d6c6c753cdbcf5c745 jpa/notification-platform/V12__notification_suppression_target_unique.sql +11bd6a456f2d0eb10c89a6f675a7a3af43f2ae1abda061a6f793f9d5a252f144 jpa/notification-platform/V13__notification_request_acceptance.sql 1ac7cc1c2509868eb0ce202e1917bb36846f98f17ad4922abe3fac0ef128199b jpa/notification-platform/V1__notification_platform_core.sql 0add67aa23580e51712f84fabe9b09e08401ef708cfa1b3292b120fdb5c12fa2 jpa/notification-platform/V2__notification_platform_contact_template_policy.sql f5b98598a59cc4376f5d233b410f8a5ae9f3cd94156291ebdf2d0da5a66f34ef jpa/notification-platform/V3__notification_platform_inbox_admin.sql @@ -22,6 +23,12 @@ db82463d7718ecd3378a63d04685766a5f8a83c806bc82b4d9b2f04fb961d26d jpa/notificati b44e4e8612295b425c58223313611f762ac2fe0b3abb6dc79c94133b704aabd5 jpa/notification-platform/V7__notification_collapse.sql c5f9c638c6d5b7768e803a23b3f16e9e0a5e09918c0838ed9c81cb6d9524ec9c jpa/notification-platform/V8__notification_admin_claim.sql 5fb1b1f8086249491b5fca40051a9ec60442e8226fe45f7c5a0f0056c8c5c07c jpa/notification-platform/V9__notification_evidence_certainty.sql +06b2e3cc1621247717d94914caa2704f3f3a1117e187cc53c034fe9d25af0331 messaging/V1001__messaging_outbox.sql +5f8b3981b581fa1ef7df822e988bac63ab35daa0161a7d376fa980627b1b7661 messaging/V1002__messaging_outbox_lease_fencing.sql +205b776ad62acc4405b3ae404d099c9934a1d87be9b641428d39253417ea7583 messaging/V1003__messaging_admin_operation_journal.sql +ea28c0633a791cbe296e16720ee08fca8f4371e841f02bf15d707e4258be04ae messaging/V1004__messaging_outbox_canonical_metadata.sql +c20f1803c6afe84ac323a9fac9007f9a1676ed5ed253b72286c8fc1dee7c21d1 messaging/V1005__messaging_outbox_ordering_key_index.sql +442e5eee5a3f99b4f32a4c7904f3a4aa9b7aa79ba1d0f3b7fbe7d19db38c5cfb messaging/V1101__messaging_inbox.sql 1f90005a2afb7eab905bba56e99c72698cf37a4b7e8b270d392c838e8226161d postgresql/V10__idempotency_request_hash_varchar.sql 74458691063ba3b5b6c1f8616ae255e99bd768218c9e8e3e7f0dc31e26983b20 postgresql/V11__durable_operation.sql 047108ca9163e704c50694a43b420b0e469f9b03fcca61a0efeac2bcfc96ccba postgresql/V12__live_event_log.sql diff --git a/src/adapter/outbound/persistence-mongo/CLAUDE.md b/src/adapter/outbound/persistence-mongo/CLAUDE.md index 3534ef10..03320813 100644 --- a/src/adapter/outbound/persistence-mongo/CLAUDE.md +++ b/src/adapter/outbound/persistence-mongo/CLAUDE.md @@ -49,8 +49,11 @@ design package's assumed module layout onto this leaf lives in ## Allowed -- One project dependency: `application-core`, for `SecretSourcePort` only. The registry entry's - `allowed_dependencies` is `["application-core"]`, matching what the build actually uses; the +- Two project dependencies. `shared-contract` for the `Sha256` and `HmacSha256` helpers (tenant + observable key, admin command digest, credential fingerprint, keyset cursor tag — review + 2026-11-01 01-11; `MongoDigestOutputTest` pins the outputs). `application-core`, for + `SecretSourcePort` only. The registry entry's `allowed_dependencies` is + `["application-core", "shared-contract"]`, matching what the build actually uses; the bridge in `MongoProfileClientSettingsAutoConfiguration` resolves a typed profile's `uri-secret` through the deployment's configured secret backend. `verifyCleanArchitectureDependencies` only checks that resolved edges are a subset of the declared ones, so an unused permission passes every diff --git a/src/adapter/outbound/persistence-mongo/build.gradle b/src/adapter/outbound/persistence-mongo/build.gradle index f5d0cef9..e32912e3 100644 --- a/src/adapter/outbound/persistence-mongo/build.gradle +++ b/src/adapter/outbound/persistence-mongo/build.gradle @@ -29,6 +29,9 @@ dependencies { // configured secret backend (MongoProfileClientSettingsAutoConfiguration). Without this edge the // leaf could not see the port, and a typed profile had no resolver unless a fork wrote one. implementation project(':application-core') + // Sha256 and HmacSha256 for tenant keys, admin command and credential digests and the keyset + // cursor tag (review 2026-11-01 01-11). + implementation project(':shared-contract') // D1/D2 imperative execution path and the mapping subsystem. implementation 'org.springframework.boot:spring-boot-starter-data-mongodb' // The starter package registers auto-configuration and binds typed properties. diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/shared/MongoTenantContext.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/shared/MongoTenantContext.java index 68457ed1..1490e75b 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/shared/MongoTenantContext.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/shared/MongoTenantContext.java @@ -1,9 +1,6 @@ package dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.shared; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; +import dev.caskeleton.shared.digest.Sha256; import java.util.Objects; /** @@ -24,14 +21,7 @@ public record MongoTenantContext(String opaqueTenantKey) { /** A short, stable hash suitable for correlation without naming the tenant. */ public String observableKey() { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - return HexFormat.of() - .formatHex(digest.digest(opaqueTenantKey.getBytes(StandardCharsets.UTF_8))) - .substring(0, 12); - } catch (NoSuchAlgorithmException unavailable) { - throw new IllegalStateException("SHA-256 is required to derive an observable tenant key"); - } + return Sha256.ofUtf8(opaqueTenantKey).hex().substring(0, 12); } /** Describes the tenant without naming it. */ diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java index 8b718792..28c46f66 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java @@ -6,7 +6,7 @@ import com.mongodb.event.ClusterListener; import dev.caskeleton.adapter.outbound.mongo.autoconfigure.MongoPlatformSettings; import dev.caskeleton.adapter.outbound.mongo.autoconfigure.MongoTopologyProbe; import dev.caskeleton.adapter.outbound.mongo.security.MongoCredentialResolver; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import java.util.Objects; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/query/pagination/MongoKeysetCursorCodec.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/query/pagination/MongoKeysetCursorCodec.java index 06d538f2..1ec539ff 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/query/pagination/MongoKeysetCursorCodec.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/query/pagination/MongoKeysetCursorCodec.java @@ -1,15 +1,13 @@ package dev.caskeleton.adapter.outbound.mongo.query.pagination; import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; +import dev.caskeleton.shared.digest.HmacSha256; import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.util.Base64; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; /** * Encodes and verifies keyset cursors (design §19.1). @@ -32,8 +30,6 @@ import javax.crypto.spec.SecretKeySpec; */ public final class MongoKeysetCursorCodec { - private static final String HMAC_ALGORITHM = "HmacSHA256"; - private static final char PAYLOAD_SEPARATOR = '.'; /** Longest token this codec will look at, in characters. */ @@ -45,7 +41,7 @@ public final class MongoKeysetCursorCodec { /** HMAC-SHA256 needs a key at least as long as its output to offer its full strength. */ private static final int MINIMUM_KEY_BYTES = 32; - private final SecretKeySpec key; + private final byte[] key; public MongoKeysetCursorCodec(byte[] secret) { Objects.requireNonNull(secret, "secret"); @@ -53,7 +49,7 @@ public final class MongoKeysetCursorCodec { throw new IllegalArgumentException( "a cursor signing key needs at least " + MINIMUM_KEY_BYTES + " bytes"); } - this.key = new SecretKeySpec(secret.clone(), HMAC_ALGORITHM); + this.key = secret.clone(); } /** @@ -156,15 +152,7 @@ public final class MongoKeysetCursorCodec { } private String sign(String payload) { - try { - Mac mac = Mac.getInstance(HMAC_ALGORITHM); - mac.init(key); - return Base64.getUrlEncoder() - .withoutPadding() - .encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8))); - } catch (GeneralSecurityException unavailable) { - throw new IllegalStateException("HmacSHA256 is required to sign keyset cursors"); - } + return Base64.getUrlEncoder().withoutPadding().encodeToString(HmacSha256.sign(key, payload)); } /** diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/security/MongoCredentialReference.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/security/MongoCredentialReference.java index 1eefc125..f1c7e901 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/security/MongoCredentialReference.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/security/MongoCredentialReference.java @@ -1,9 +1,6 @@ package dev.caskeleton.adapter.outbound.mongo.security; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; +import dev.caskeleton.shared.digest.Sha256; import java.util.Objects; /** @@ -53,13 +50,7 @@ public record MongoCredentialReference(String secretReference, MongoPrincipalRol * the other left the security check answering neither. */ public String fingerprint() { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] hash = digest.digest(secretReference.getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(hash).substring(0, 16); - } catch (NoSuchAlgorithmException unavailable) { - throw new IllegalStateException("SHA-256 is required to fingerprint credentials"); - } + return Sha256.ofUtf8(secretReference).hex().substring(0, 16); } /** True when two references point at the same credential, whatever role each is used under. */ diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/security/admin/MongoAdminCommand.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/security/admin/MongoAdminCommand.java index b0e6c231..357c2753 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/security/admin/MongoAdminCommand.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/security/admin/MongoAdminCommand.java @@ -1,10 +1,7 @@ package dev.caskeleton.adapter.outbound.mongo.security.admin; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import dev.caskeleton.shared.digest.Sha256; import java.time.Instant; -import java.util.HexFormat; import java.util.Objects; /** @@ -92,12 +89,6 @@ public record MongoAdminCommand( /** SHA-256, hex. */ public static String digestOf(String value) { Objects.requireNonNull(value, "value"); - try { - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException unavailable) { - throw new IllegalStateException("SHA-256 is required to digest an admin command"); - } + return Sha256.ofUtf8(value).hex(); } } diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java index d7c83a7d..b32f3a11 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java @@ -13,7 +13,7 @@ import dev.caskeleton.adapter.outbound.mongo.autoconfigure.MongoTopologyProbe; import dev.caskeleton.adapter.outbound.mongo.security.MongoCredentialReference; import dev.caskeleton.adapter.outbound.mongo.security.MongoCredentialResolver; import dev.caskeleton.adapter.outbound.mongo.security.MongoPrincipalRole; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/digest/MongoDigestOutputTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/digest/MongoDigestOutputTest.java new file mode 100644 index 00000000..2112e043 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/digest/MongoDigestOutputTest.java @@ -0,0 +1,90 @@ +package dev.caskeleton.adapter.outbound.mongo.digest; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.shared.MongoTenantContext; +import dev.caskeleton.adapter.outbound.mongo.query.pagination.MongoKeysetCursor; +import dev.caskeleton.adapter.outbound.mongo.query.pagination.MongoKeysetCursorCodec; +import dev.caskeleton.adapter.outbound.mongo.security.MongoCredentialReference; +import dev.caskeleton.adapter.outbound.mongo.security.MongoPrincipalRole; +import dev.caskeleton.adapter.outbound.mongo.security.admin.MongoAdminCommand; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Map; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Every digest this leaf renders is a stored or exchanged value — a correlation key in logs, an + * admin command's recorded digest, a credential identity, a page cursor a client holds between + * requests. These pin the outputs against vectors computed outside the JVM (Python {@code hashlib} + * / {@code hmac}), so moving the computation onto shared-contract's {@code Sha256} and {@code + * HmacSha256} (review 2026-11-01 01-11) cannot change any of them. + */ +class MongoDigestOutputTest { + + @Test + @DisplayName("tenant 관찰 키는 tenant 키 SHA-256 hex의 앞 12자로 이전 출력과 같다") + void theObservableTenantKeyIsTheFirstTwelveHexOfItsSha256() { + // given + MongoTenantContext tenant = new MongoTenantContext("tenant-a"); + + // when + String observable = tenant.observableKey(); + + // then + assertThat(observable).isEqualTo("80a707af7dc7"); + } + + @Test + @DisplayName("관리 명령 digest는 명령 문자열 SHA-256 hex로 이전 출력과 같다") + void theAdminCommandDigestIsTheHexSha256OfTheCommand() { + // when + String digest = MongoAdminCommand.digestOf("{\"drop\":\"orders\"}"); + + // then + assertThat(digest) + .isEqualTo("07e3ff0b3679f38c1e493312dec94d1ba025fc267dc943494582bb751835b915"); + } + + @Test + @DisplayName("자격 증명 지문은 secret 참조 SHA-256 hex의 앞 16자로 이전 출력과 같다") + void theCredentialFingerprintIsTheFirstSixteenHexOfTheReferencesSha256() { + // given + MongoCredentialReference reference = + new MongoCredentialReference("secret://mongo/runtime", MongoPrincipalRole.APP_READ); + + // when + String fingerprint = reference.fingerprint(); + + // then + assertThat(fingerprint).isEqualTo("4190f6d22517f609"); + } + + @Test + @DisplayName("cursor 태그는 payload의 HMAC-SHA256을 패딩 없는 base64url로 쓴 값이다") + void theCursorTagIsTheUnpaddedBase64UrlHmacOfThePayload() throws Exception { + // given + byte[] secret = new byte[32]; + for (int i = 0; i < secret.length; i++) { + secret[i] = (byte) i; + } + MongoKeysetCursorCodec codec = new MongoKeysetCursorCodec(secret); + + // when + String token = codec.encode(MongoKeysetCursor.unsigned(1, Map.of("createdAt", "2026-11-03"))); + + // then + int separator = token.lastIndexOf('.'); + byte[] payload = Base64.getUrlDecoder().decode(token.substring(0, separator)); + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(secret, "HmacSHA256")); + String expectedTag = + Base64.getUrlEncoder().withoutPadding().encodeToString(mac.doFinal(payload)); + assertThat(token.substring(separator + 1)).isEqualTo(expectedTag); + assertThat(new String(payload, StandardCharsets.UTF_8)).contains("createdAt"); + assertThat(codec.decode(token).authenticationTag()).isEqualTo(expectedTag); + } +} diff --git a/src/adapter/outbound/persistence-notification/CLAUDE.md b/src/adapter/outbound/persistence-notification/CLAUDE.md index 630842ef..e7b25f5c 100644 --- a/src/adapter/outbound/persistence-notification/CLAUDE.md +++ b/src/adapter/outbound/persistence-notification/CLAUDE.md @@ -5,8 +5,16 @@ - Module ID: `adapter-outbound-persistence-notification`; Gradle path and allowed edges are in `src/config/architecture/modules.json`. - Focused test: `./gradlew :adapter:outbound:persistence-notification:test --console=plain`. -- Package root: `dev.caskeleton.adapter.outbound.persistence.notification`. Entities, Spring Data - repositories, stores and SQL constants are in `platform` (inbox in `platform.inbox`). +- Package root: `dev.caskeleton.adapter.outbound.persistence.notification`. The package rule is + the one `persistence-fileserver` uses, so both capability leaves read the same way (review 04-16): + - `platform.entity` — JPA rows only. + - `platform.repository` — Spring Data interfaces and the SQL text they run (`RecipientClaimSql`). + - `platform` — the store adapters (`Jpa*`, `Jdbc*`, the inbox's `JpaNotificationInbox` and its + outbox helpers), `NotificationRecordMapper` and the payload codec. + - `configuration` — the auto-configuration facade that registers the stores as beans; the leaf + root holds the scan configuration and the schema stream. + Entity accessors are public because the stores read them from another package; an entity never + leaves the leaf (the ports carry records). ## Where the tests are @@ -14,11 +22,14 @@ |---|---|---| | Unit and wiring tests | this leaf, `src/test` | `:adapter:outbound:persistence-notification:test` | | Real PostgreSQL tests of these stores | `persistence-jpa`, `src/postgresqlIntegrationTest/.../persistence/notification` (that lane owns the container and Flyway wiring) | `:adapter:outbound:persistence-jpa:postgresqlIntegrationTest --tests ''` | -| Port contracts the stores must pass | `application-notification` testFixtures, `*.testkit.*StoreContract` | the in-memory fake and the PostgreSQL test both extend the contract | +| Port contracts the stores must pass | `application-notification` testFixtures, `*.testkit.*Contract` (preference, suppression, deduplication, request, reconciliation job, admin operation, template registry, recipient lease, recipient delivery, delivery attempt, attempt resolver, delivery projection, provider event ledger, contact point, and the side effect over the contact point and suppression stores) | the in-memory fake (`application-notification` test) and the `PostgreSql*ContractTest` in `persistence-jpa` both extend the contract; `jpaPlatformContractTest` runs the PostgreSQL side | | Migration pins | `persistence-jpa/src/test/resources/db/applied-migrations.sha256` | `AppliedMigrationImmutabilityTest` in `:adapter:outbound:persistence-jpa:test` | A store whose port has a contract in `application-notification` testFixtures is tested by a -PostgreSQL subclass of that contract, not by a separate hand-written PostgreSQL test. +PostgreSQL subclass of that contract, not by a separate hand-written PostgreSQL test. A case that is +about the vendor (a CHECK constraint, `@Version` on a bulk update) stays in the subclass. The ports +without a contract (the serving-state read model, consent, inbox), and why, are listed in +`docs/testing/TESTING_STRATEGY.md` §9.2. ## Rules diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java index 0a44244e..26e0eb13 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java @@ -2,16 +2,12 @@ package dev.caskeleton.adapter.outbound.persistence.notification.configuration; import dev.caskeleton.adapter.outbound.persistence.notification.NotificationJpaPersistenceConfig; import dev.caskeleton.adapter.outbound.persistence.notification.NotificationSchemaActivation; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.AdminAuditJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.ConsentJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.ContactPointJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.DeduplicationClaimJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.DeliveryAttemptJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.InboxCommitEventPublisher; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaAdminOperationStore; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaContactPointStore; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaDeliveryAttemptStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationInbox; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationRequestStore; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaNotificationSideEffect; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaPolicyStores; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaProviderEventLedger; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientDeliveryStore; @@ -19,19 +15,21 @@ import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaReci import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaSuppressionStore; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaTemplateRegistry; import dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationRecordMapper; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationRequestJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.PreferenceJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.ProviderEventJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientDeliveryJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.SuppressionJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.TemplateVersionJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxCommitEventPublisher; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxItemJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.JpaNotificationInbox; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.AdminAuditJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ConsentJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ContactPointJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.DeduplicationClaimJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.DeliveryAttemptJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.InboxItemJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.PreferenceJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ProviderEventJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.SuppressionJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.TemplateVersionJpaRepository; import dev.caskeleton.application.notification.platform.admin.AdminOperationStorePort; import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort; import dev.caskeleton.application.notification.platform.callback.DeliveryProjectionStorePort; -import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort; import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; @@ -235,13 +233,6 @@ public class NotificationJpaPersistenceFacade { return new JpaSuppressionStore(suppressions, ids, clock); } - /** Contact-point and suppression side effects of a projected event. */ - @Bean - public NotificationSideEffectPort notificationSideEffectPort( - ContactPointStorePort contactPoints, SuppressionStorePort suppressions, Clock clock) { - return new JpaNotificationSideEffect(contactPoints, suppressions, clock); - } - /** Preference persistence. */ @Bean public PreferenceStorePort preferenceStore( diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxCommitEventPublisher.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/InboxCommitEventPublisher.java similarity index 99% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxCommitEventPublisher.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/InboxCommitEventPublisher.java index aab7f17b..636b46c4 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxCommitEventPublisher.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/InboxCommitEventPublisher.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox; +package dev.caskeleton.adapter.outbound.persistence.notification.platform; import dev.caskeleton.application.notification.platform.inbox.InboxItemCreated; import dev.caskeleton.application.notification.platform.inbox.NotificationInboxSignalPort; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxOutboxRecordFactory.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/InboxOutboxRecordFactory.java similarity index 98% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxOutboxRecordFactory.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/InboxOutboxRecordFactory.java index f3410688..43fd2ed6 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxOutboxRecordFactory.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/InboxOutboxRecordFactory.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox; +package dev.caskeleton.adapter.outbound.persistence.notification.platform; import dev.caskeleton.application.notification.platform.inbox.InboxItemCreated; import java.util.LinkedHashMap; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaAdminOperationStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaAdminOperationStore.java index 610ae925..74728e9e 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaAdminOperationStore.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaAdminOperationStore.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.AdminAuditJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.admin.AdminActor; import dev.caskeleton.application.notification.platform.admin.AdminOperationResult; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaContactPointStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaContactPointStore.java index 11e92bdf..a33908d9 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaContactPointStore.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaContactPointStore.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.ContactPointEntity; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ContactPointJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.api.ContactPointId; import dev.caskeleton.application.notification.platform.api.TenantId; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaDeliveryAttemptStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaDeliveryAttemptStore.java index 52b29819..a9acff12 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaDeliveryAttemptStore.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaDeliveryAttemptStore.java @@ -1,5 +1,8 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.DeliveryAttemptEntity; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.DeliveryAttemptJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.api.ContactPointId; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/JpaNotificationInbox.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationInbox.java similarity index 97% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/JpaNotificationInbox.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationInbox.java index 2c10ec71..c3985c89 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/JpaNotificationInbox.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationInbox.java @@ -1,5 +1,7 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox; +package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.InboxItemEntity; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.InboxItemJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.api.TenantId; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationRequestStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationRequestStore.java index cd13ac5f..e777e3f2 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationRequestStore.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationRequestStore.java @@ -1,5 +1,8 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.NotificationRequestEntity; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.api.RequestStatus; @@ -70,7 +73,12 @@ public final class JpaNotificationRequestStore implements NotificationRequestSto request.scheduleAt().orElse(null), request.notBefore().orElse(null), request.expiresAt().orElse(null), + // These columns were missing from the insert, so the stored request lost the + // caller's collapse (review 05-10) and a deduplication drop read back as accepted. + request.collapse().map(collapse -> collapse.key()).orElse(null), + request.collapse().map(collapse -> collapse.scope().name()).orElse(null), request.status().name(), + request.acceptance().name(), request.correlationId().value(), mapper.metadataJson(request.metadata()), request.createdAt(), diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java index f5bba6de..1c5e43a1 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaPolicyStores.java @@ -1,5 +1,10 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.ConsentEntity; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.PreferenceEntity; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ConsentJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.DeduplicationClaimJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.PreferenceJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.api.TenantId; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaProviderEventLedger.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaProviderEventLedger.java index c65353ef..b71d93d8 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaProviderEventLedger.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaProviderEventLedger.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.ProviderEventEntity; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ProviderEventJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.NormalizedEventType; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientDeliveryStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientDeliveryStore.java index e84ba26d..23fdb2dc 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientDeliveryStore.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientDeliveryStore.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.RecipientDeliveryEntity; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientLeaseStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientLeaseStore.java index 3bce0236..65784bac 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientLeaseStore.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaRecipientLeaseStore.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; import dev.caskeleton.application.notification.platform.dispatch.RecipientLease; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java index f16ff271..de75cd0c 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaSuppressionStore.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.SuppressionEntity; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.SuppressionJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaTemplateRegistry.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaTemplateRegistry.java index dcff476a..03a0c8d3 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaTemplateRegistry.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaTemplateRegistry.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.TemplateVersionEntity; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.TemplateVersionJpaRepository; import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.api.TemplateSelection; import dev.caskeleton.application.notification.platform.api.TenantId; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRecordMapper.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRecordMapper.java index ff323e12..3699b636 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRecordMapper.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRecordMapper.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.NotificationRequestEntity; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.RecipientDeliveryEntity; import dev.caskeleton.application.notification.platform.api.CorrelationId; import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; @@ -88,7 +90,9 @@ public final class NotificationRecordMapper { new CorrelationId(entity.correlationId() == null ? "unspecified" : entity.correlationId()), decodeMetadata(entity.metadataJson()), entity.createdAt(), - entity.updatedAt()); + entity.updatedAt(), + dev.caskeleton.application.notification.platform.api.NotificationAcceptance.valueOf( + entity.acceptance())); } /** Map a stored recipient job. */ @@ -185,7 +189,8 @@ public final class NotificationRecordMapper { record.correlationId().value(), encodeMetadata(record.metadata()), record.createdAt(), - record.updatedAt()); + record.updatedAt(), + record.acceptance().name()); } /** Build a new recipient entity. */ diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/AdminAuditEntity.java similarity index 93% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/AdminAuditEntity.java index 9be7c616..d068485d 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/AdminAuditEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -56,7 +56,7 @@ public class AdminAuditEntity { // JPA } - AdminAuditEntity( + public AdminAuditEntity( UUID id, String operationId, String action, @@ -77,19 +77,19 @@ public class AdminAuditEntity { this.occurredAt = occurredAt; } - String operationId() { + public String operationId() { return operationId; } - String action() { + public String action() { return action; } - String attributes() { + public String attributes() { return attributes; } - boolean dryRun() { + public boolean dryRun() { return dryRun; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/ConsentEntity.java similarity index 88% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/ConsentEntity.java index b958eeb3..f223a891 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/ConsentEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -49,7 +49,7 @@ public class ConsentEntity { // JPA } - ConsentEntity( + public ConsentEntity( UUID id, String tenantId, String recipientRef, @@ -68,35 +68,35 @@ public class ConsentEntity { this.evidenceRef = evidenceRef; } - UUID id() { + public UUID id() { return id; } - String tenantId() { + public String tenantId() { return tenantId; } - String recipientRef() { + public String recipientRef() { return recipientRef; } - String consentType() { + public String consentType() { return consentType; } - boolean granted() { + public boolean granted() { return granted; } - Instant recordedAt() { + public Instant recordedAt() { return recordedAt; } - Instant revokedAt() { + public Instant revokedAt() { return revokedAt; } - String evidenceRef() { + public String evidenceRef() { return evidenceRef; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/ContactPointEntity.java similarity index 84% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/ContactPointEntity.java index 699c2f95..0eeab58a 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/ContactPointEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -87,7 +87,7 @@ public class ContactPointEntity { // JPA } - ContactPointEntity( + public ContactPointEntity( UUID id, String tenantId, String ownerRef, @@ -129,7 +129,7 @@ public class ContactPointEntity { } /** Change the lifecycle state, recording why and when. */ - void changeStatus(String status, String reasonCode, Instant at) { + public void changeStatus(String status, String reasonCode, Instant at) { this.status = status; this.invalidationReason = reasonCode; this.invalidatedAt = "ACTIVE".equals(status) ? null : at; @@ -137,7 +137,8 @@ public class ContactPointEntity { } /** Re-encrypt in place after a key rotation. */ - void reprotect(byte[] ciphertext, byte[] nonce, String keyId, String lookupHmac, Instant at) { + public void reprotect( + byte[] ciphertext, byte[] nonce, String keyId, String lookupHmac, Instant at) { this.ciphertext = ciphertext.clone(); this.nonce = nonce.clone(); this.keyId = keyId; @@ -145,79 +146,79 @@ public class ContactPointEntity { this.updatedAt = at; } - UUID id() { + public UUID id() { return id; } - String tenantId() { + public String tenantId() { return tenantId; } - String ownerRef() { + public String ownerRef() { return ownerRef; } - String type() { + public String type() { return type; } - String provider() { + public String provider() { return provider; } - String applicationId() { + public String applicationId() { return applicationId; } - String environment() { + public String environment() { return environment; } - byte[] ciphertext() { + public byte[] ciphertext() { return ciphertext.clone(); } - byte[] nonce() { + public byte[] nonce() { return nonce.clone(); } - String lookupHmac() { + public String lookupHmac() { return lookupHmac; } - String keyId() { + public String keyId() { return keyId; } - String status() { + public String status() { return status; } - boolean verified() { + public boolean verified() { return verified; } - Instant lastConfirmedAt() { + public Instant lastConfirmedAt() { return lastConfirmedAt; } - Instant lastSuccessfulDeliveryAt() { + public Instant lastSuccessfulDeliveryAt() { return lastSuccessfulDeliveryAt; } - Instant invalidatedAt() { + public Instant invalidatedAt() { return invalidatedAt; } - String invalidationReason() { + public String invalidationReason() { return invalidationReason; } - Instant createdAt() { + public Instant createdAt() { return createdAt; } - Instant updatedAt() { + public Instant updatedAt() { return updatedAt; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/DeduplicationClaimEntity.java similarity index 95% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/DeduplicationClaimEntity.java index eb220707..5b282e92 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/DeduplicationClaimEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -45,7 +45,7 @@ public class DeduplicationClaimEntity { // JPA } - DeduplicationClaimEntity( + public DeduplicationClaimEntity( UUID id, String tenantId, String recipientRef, @@ -64,7 +64,7 @@ public class DeduplicationClaimEntity { this.createdAt = createdAt; } - UUID notificationId() { + public UUID notificationId() { return notificationId; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/DeliveryAttemptEntity.java similarity index 88% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/DeliveryAttemptEntity.java index 2740a35d..b504994b 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/DeliveryAttemptEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -130,7 +130,7 @@ public class DeliveryAttemptEntity { // JPA } - DeliveryAttemptEntity( + public DeliveryAttemptEntity( UUID id, UUID recipientDeliveryId, UUID contactPointId, @@ -196,7 +196,7 @@ public class DeliveryAttemptEntity { } /** Record the completed provider outcome. */ - void completeWith( + public void completeWith( String providerRequestIdHash, boolean requestStarted, boolean requestBodyCommitted, @@ -247,7 +247,7 @@ public class DeliveryAttemptEntity { * for both — and the projector's rule that a hard bounce makes a later "delivered" meaningless * silently stopped applying after a restart. */ - void applyProjection( + public void applyProjection( String deliveryOutcome, String evidenceLevel, boolean opened, @@ -285,7 +285,7 @@ public class DeliveryAttemptEntity { * * @return true when this call is the one that may run it */ - boolean claimSuppressionSideEffect() { + public boolean claimSuppressionSideEffect() { if (suppressionSideEffectApplied) { return false; } @@ -293,43 +293,43 @@ public class DeliveryAttemptEntity { return true; } - boolean engagementOpened() { + public boolean engagementOpened() { return engagementOpened; } - boolean engagementClicked() { + public boolean engagementClicked() { return engagementClicked; } - boolean engagementRead() { + public boolean engagementRead() { return engagementRead; } - Instant engagementLastAt() { + public Instant engagementLastAt() { return engagementLastAt; } - boolean suppressionHardBounced() { + public boolean suppressionHardBounced() { return suppressionHardBounced; } - boolean suppressionComplained() { + public boolean suppressionComplained() { return suppressionComplained; } - boolean suppressionProviderSuppressed() { + public boolean suppressionProviderSuppressed() { return suppressionProviderSuppressed; } - boolean suppressionUserOptedOut() { + public boolean suppressionUserOptedOut() { return suppressionUserOptedOut; } - boolean suppressionInvalidTarget() { + public boolean suppressionInvalidTarget() { return suppressionInvalidTarget; } - long projectionVersion() { + public long projectionVersion() { return projectionVersion; } @@ -366,127 +366,127 @@ public class DeliveryAttemptEntity { @Column(name = "projection_version", nullable = false) private long projectionVersion; - UUID id() { + public UUID id() { return id; } - UUID recipientDeliveryId() { + public UUID recipientDeliveryId() { return recipientDeliveryId; } - UUID contactPointId() { + public UUID contactPointId() { return contactPointId; } - int attemptNo() { + public int attemptNo() { return attemptNo; } - String channel() { + public String channel() { return channel; } - String providerId() { + public String providerId() { return providerId; } - String providerProfileId() { + public String providerProfileId() { return providerProfileId; } - String providerRequestIdHash() { + public String providerRequestIdHash() { return providerRequestIdHash; } - boolean requestStarted() { + public boolean requestStarted() { return requestStarted; } - boolean requestBodyCommitted() { + public boolean requestBodyCommitted() { return requestBodyCommitted; } - boolean providerResponseReceived() { + public boolean providerResponseReceived() { return providerResponseReceived; } - String requestStartedCertainty() { + public String requestStartedCertainty() { return requestStartedCertainty; } - String requestBodyCommittedCertainty() { + public String requestBodyCommittedCertainty() { return requestBodyCommittedCertainty; } - String providerResponseReceivedCertainty() { + public String providerResponseReceivedCertainty() { return providerResponseReceivedCertainty; } - boolean providerAcceptance() { + public boolean providerAcceptance() { return providerAcceptance; } - String providerAcceptanceCertainty() { + public String providerAcceptanceCertainty() { return providerAcceptanceCertainty; } - String submissionOutcome() { + public String submissionOutcome() { return submissionOutcome; } - String deliveryOutcome() { + public String deliveryOutcome() { return deliveryOutcome; } - String confirmation() { + public String confirmation() { return confirmation; } - String evidenceLevel() { + public String evidenceLevel() { return evidenceLevel; } - String failureCategory() { + public String failureCategory() { return failureCategory; } - String failureCode() { + public String failureCode() { return failureCode; } - String nativeStatus() { + public String nativeStatus() { return nativeStatus; } - Instant providerOccurredAt() { + public Instant providerOccurredAt() { return providerOccurredAt; } - Instant startedAt() { + public Instant startedAt() { return startedAt; } - Instant completedAt() { + public Instant completedAt() { return completedAt; } - Long elapsedMillis() { + public Long elapsedMillis() { return elapsedMillis; } - long credentialGeneration() { + public long credentialGeneration() { return credentialGeneration; } - String renderedContentDigest() { + public String renderedContentDigest() { return renderedContentDigest; } - Instant createdAt() { + public Instant createdAt() { return createdAt; } - Instant updatedAt() { + public Instant updatedAt() { return updatedAt; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/InboxItemEntity.java similarity index 89% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/InboxItemEntity.java index f437aaa2..5a3e72d2 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/InboxItemEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -77,7 +77,7 @@ public class InboxItemEntity { // JPA } - InboxItemEntity( + public InboxItemEntity( UUID id, String tenantId, String ownerRef, @@ -104,7 +104,7 @@ public class InboxItemEntity { *

        A no-op once read, because read already implies seen and a late seen event must not look * like the item went backwards. */ - boolean markSeen(Instant at) { + public boolean markSeen(Instant at) { if (seenAt != null || readAt != null || leftTheInbox()) { return false; } @@ -114,7 +114,7 @@ public class InboxItemEntity { } /** Mark read; also fills in seen so the database check constraint stays satisfied. */ - boolean markRead(Instant at) { + public boolean markRead(Instant at) { if (readAt != null || leftTheInbox()) { return false; } @@ -142,7 +142,7 @@ public class InboxItemEntity { * Archive; idempotent. Expired and deleted are terminal: archiving them would move the item back * to a state the owner can still list, so both are left alone. */ - boolean archive(Instant at) { + public boolean archive(Instant at) { if (archivedAt != null || "EXPIRED".equals(state) || "DELETED".equals(state)) { return false; } @@ -151,51 +151,51 @@ public class InboxItemEntity { return true; } - UUID id() { + public UUID id() { return id; } - String tenantId() { + public String tenantId() { return tenantId; } - String ownerRef() { + public String ownerRef() { return ownerRef; } - UUID notificationId() { + public UUID notificationId() { return notificationId; } - String category() { + public String category() { return category; } - String contentJson() { + public String contentJson() { return contentJson; } - String state() { + public String state() { return state; } - Instant createdAt() { + public Instant createdAt() { return createdAt; } - Instant seenAt() { + public Instant seenAt() { return seenAt; } - Instant readAt() { + public Instant readAt() { return readAt; } - Instant archivedAt() { + public Instant archivedAt() { return archivedAt; } - Instant expiresAt() { + public Instant expiresAt() { return expiresAt; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/NotificationRequestEntity.java similarity index 82% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/NotificationRequestEntity.java index a7035828..149a8421 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/NotificationRequestEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -73,6 +73,10 @@ public class NotificationRequestEntity { @Column(name = "correlation_id", length = 160) private String correlationId; + /** ACCEPTED, or DROPPED_AS_DUPLICATE for a submission a deduplication window dropped (V13). */ + @Column(name = "acceptance", nullable = false, length = 40) + private String acceptance; + /** * Declared as JSON, because the column is {@code jsonb} and the field is a {@code String}. * @@ -99,7 +103,7 @@ public class NotificationRequestEntity { // JPA } - NotificationRequestEntity( + public NotificationRequestEntity( UUID id, String tenantId, String idempotencyKey, @@ -119,7 +123,8 @@ public class NotificationRequestEntity { String correlationId, String metadataJson, Instant createdAt, - Instant updatedAt) { + Instant updatedAt, + String acceptance) { this.id = id; this.tenantId = tenantId; this.idempotencyKey = idempotencyKey; @@ -140,91 +145,96 @@ public class NotificationRequestEntity { this.metadataJson = metadataJson; this.createdAt = createdAt; this.updatedAt = updatedAt; + this.acceptance = acceptance; } /** Move the projected request status. */ - void applyStatus(String status, Instant at) { + public void applyStatus(String status, Instant at) { this.requestStatus = status; this.updatedAt = at; } - UUID id() { + public UUID id() { return id; } - String tenantId() { + public String tenantId() { return tenantId; } - String idempotencyKey() { + public String idempotencyKey() { return idempotencyKey; } - String requestFingerprint() { + public String requestFingerprint() { return requestFingerprint; } - String category() { + public String category() { return category; } - String templateId() { + public String templateId() { return templateId; } - long templateVersion() { + public long templateVersion() { return templateVersion; } - String templateLocale() { + public String templateLocale() { return templateLocale; } - String strategyType() { + public String strategyType() { return strategyType; } - String variablesPayload() { + public String variablesPayload() { return variablesPayload; } - Instant scheduleAt() { + public Instant scheduleAt() { return scheduleAt; } - Instant notBefore() { + public Instant notBefore() { return notBefore; } - Instant expiresAt() { + public Instant expiresAt() { return expiresAt; } - String collapseKey() { + public String collapseKey() { return collapseKey; } - String collapseScope() { + public String collapseScope() { return collapseScope; } - String requestStatus() { + public String requestStatus() { return requestStatus; } - String correlationId() { + public String acceptance() { + return acceptance; + } + + public String correlationId() { return correlationId; } - String metadataJson() { + public String metadataJson() { return metadataJson; } - Instant createdAt() { + public Instant createdAt() { return createdAt; } - Instant updatedAt() { + public Instant updatedAt() { return updatedAt; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/PreferenceEntity.java similarity index 88% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/PreferenceEntity.java index b7c6c31c..09138699 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/PreferenceEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -49,7 +49,7 @@ public class PreferenceEntity { // JPA } - PreferenceEntity( + public PreferenceEntity( UUID id, String tenantId, String recipientRef, @@ -64,33 +64,33 @@ public class PreferenceEntity { this.updatedAt = updatedAt; } - void update(String preferredOrder, String mutedChannels, Instant updatedAt) { + public void update(String preferredOrder, String mutedChannels, Instant updatedAt) { this.preferredOrder = preferredOrder; this.mutedChannels = mutedChannels; this.updatedAt = updatedAt; } - UUID id() { + public UUID id() { return id; } - String tenantId() { + public String tenantId() { return tenantId; } - String recipientRef() { + public String recipientRef() { return recipientRef; } - String preferredOrder() { + public String preferredOrder() { return preferredOrder; } - String mutedChannels() { + public String mutedChannels() { return mutedChannels; } - Instant updatedAt() { + public Instant updatedAt() { return updatedAt; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/ProviderEventEntity.java similarity index 88% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/ProviderEventEntity.java index 920977fb..56abc02b 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/ProviderEventEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -96,7 +96,7 @@ public class ProviderEventEntity { // JPA } - ProviderEventEntity( + public ProviderEventEntity( UUID id, String providerProfileId, String providerEventId, @@ -134,82 +134,82 @@ public class ProviderEventEntity { } /** Move the projection status; the event itself is never rewritten. */ - void markProjection(String projectionStatus, String projectionErrorCode) { + public void markProjection(String projectionStatus, String projectionErrorCode) { this.projectionStatus = projectionStatus; this.projectionErrorCode = projectionErrorCode; } /** Bind a late-resolved attempt without touching anything else. */ - void bindAttempt(UUID attemptId) { + public void bindAttempt(UUID attemptId) { this.attemptId = attemptId; } - UUID id() { + public UUID id() { return id; } - String providerProfileId() { + public String providerProfileId() { return providerProfileId; } - String providerEventId() { + public String providerEventId() { return providerEventId; } - String eventFingerprint() { + public String eventFingerprint() { return eventFingerprint; } - String providerRequestIdHash() { + public String providerRequestIdHash() { return providerRequestIdHash; } - UUID attemptId() { + public UUID attemptId() { return attemptId; } - String eventType() { + public String eventType() { return eventType; } - String providerNativeType() { + public String providerNativeType() { return providerNativeType; } - String eventSource() { + public String eventSource() { return eventSource; } - Instant providerOccurredAt() { + public Instant providerOccurredAt() { return providerOccurredAt; } - Instant receivedAt() { + public Instant receivedAt() { return receivedAt; } - boolean signatureVerified() { + public boolean signatureVerified() { return signatureVerified; } /** The ciphertext, defensively copied; {@code null} when the payload was not retained. */ - byte[] rawPayloadCiphertext() { + public byte[] rawPayloadCiphertext() { return rawPayloadCiphertext == null ? null : rawPayloadCiphertext.clone(); } - String rawPayloadDigest() { + public String rawPayloadDigest() { return rawPayloadDigest; } - String normalizedPayloadJson() { + public String normalizedPayloadJson() { return normalizedPayloadJson; } - String projectionStatus() { + public String projectionStatus() { return projectionStatus; } - String projectionErrorCode() { + public String projectionErrorCode() { return projectionErrorCode; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/RecipientDeliveryEntity.java similarity index 88% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/RecipientDeliveryEntity.java index 05ef213c..fca3b4a5 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/RecipientDeliveryEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -108,7 +108,7 @@ public class RecipientDeliveryEntity { // JPA } - RecipientDeliveryEntity( + public RecipientDeliveryEntity( UUID id, UUID notificationId, String tenantId, @@ -156,7 +156,7 @@ public class RecipientDeliveryEntity { } /** Apply a projection update produced by the dispatcher or a projector. */ - void applyProjection( + public void applyProjection( String deliveryState, String submissionOutcome, String deliveryOutcome, @@ -182,97 +182,97 @@ public class RecipientDeliveryEntity { } /** Move to a lifecycle state, optionally rescheduling. */ - void transition(String deliveryState, Instant nextDispatchAt, Instant at) { + public void transition(String deliveryState, Instant nextDispatchAt, Instant at) { this.deliveryState = deliveryState; this.nextDispatchAt = nextDispatchAt; this.updatedAt = at; } - Instant expiresAt() { + public Instant expiresAt() { return expiresAt; } - UUID id() { + public UUID id() { return id; } - UUID notificationId() { + public UUID notificationId() { return notificationId; } - String tenantId() { + public String tenantId() { return tenantId; } - String recipientRef() { + public String recipientRef() { return recipientRef; } - String locale() { + public String locale() { return locale; } - String timeZone() { + public String timeZone() { return timeZone; } - String routingPlanJson() { + public String routingPlanJson() { return routingPlanJson; } - int routeCursor() { + public int routeCursor() { return routeCursor; } - String deliveryState() { + public String deliveryState() { return deliveryState; } - String submissionOutcome() { + public String submissionOutcome() { return submissionOutcome; } - String deliveryOutcome() { + public String deliveryOutcome() { return deliveryOutcome; } - String evidenceLevel() { + public String evidenceLevel() { return evidenceLevel; } - boolean ambiguousAttemptExists() { + public boolean ambiguousAttemptExists() { return ambiguousAttemptExists; } - boolean duplicateRisk() { + public boolean duplicateRisk() { return duplicateRisk; } - Instant nextDispatchAt() { + public Instant nextDispatchAt() { return nextDispatchAt; } - String leaseOwner() { + public String leaseOwner() { return leaseOwner; } - Instant leaseUntil() { + public Instant leaseUntil() { return leaseUntil; } - int attemptCount() { + public int attemptCount() { return attemptCount; } - String lastFailureCategory() { + public String lastFailureCategory() { return lastFailureCategory; } - Instant createdAt() { + public Instant createdAt() { return createdAt; } - Instant updatedAt() { + public Instant updatedAt() { return updatedAt; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/SuppressionEntity.java similarity index 85% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/SuppressionEntity.java index 3ad5d15a..4f1f4995 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/SuppressionEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -50,7 +50,7 @@ public class SuppressionEntity { // JPA } - SuppressionEntity( + public SuppressionEntity( UUID id, String tenantId, String scope, @@ -74,50 +74,50 @@ public class SuppressionEntity { } /** Refresh the window of an existing entry. */ - void refresh(String reason, Instant effectiveAt, Instant expiresAt, String source) { + public void refresh(String reason, Instant effectiveAt, Instant expiresAt, String source) { this.reason = reason; this.effectiveAt = effectiveAt; this.expiresAt = expiresAt; this.source = source; } - UUID id() { + public UUID id() { return id; } - String tenantId() { + public String tenantId() { return tenantId; } - String scope() { + public String scope() { return scope; } - String reason() { + public String reason() { return reason; } - String normalizedTargetHmac() { + public String normalizedTargetHmac() { return normalizedTargetHmac; } - String notificationCategory() { + public String notificationCategory() { return notificationCategory; } - Instant effectiveAt() { + public Instant effectiveAt() { return effectiveAt; } - Instant expiresAt() { + public Instant expiresAt() { return expiresAt; } - String source() { + public String source() { return source; } - Instant createdAt() { + public Instant createdAt() { return createdAt; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionEntity.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/TemplateVersionEntity.java similarity index 90% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionEntity.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/TemplateVersionEntity.java index bdc95c7f..9877b7dd 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionEntity.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/TemplateVersionEntity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -73,7 +73,7 @@ public class TemplateVersionEntity { // JPA } - TemplateVersionEntity( + public TemplateVersionEntity( UUID id, String tenantId, String templateId, @@ -103,44 +103,44 @@ public class TemplateVersionEntity { } /** Disable without deleting, so retry and redrive can still render. */ - void disable(Instant at) { + public void disable(Instant at) { this.status = "DISABLED"; this.updatedAt = at; } - String templateId() { + public String templateId() { return templateId; } - long version() { + public long version() { return version; } - String channel() { + public String channel() { return channel; } - String locale() { + public String locale() { return locale; } - String fallbackLocale() { + public String fallbackLocale() { return fallbackLocale; } - String variableSchema() { + public String variableSchema() { return variableSchema; } - String contentJson() { + public String contentJson() { return contentJson; } - String status() { + public String status() { return status; } - String contentDigest() { + public String contentDigest() { return contentDigest; } } diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/AdminAuditJpaRepository.java similarity index 97% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/AdminAuditJpaRepository.java index 9429560f..2603e7f9 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminAuditJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/AdminAuditJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.AdminAuditEntity; import java.util.Optional; import java.util.UUID; import org.springframework.data.repository.Repository; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/ConsentJpaRepository.java similarity index 90% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/ConsentJpaRepository.java index 1c42bace..b3f9126b 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ConsentJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/ConsentJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.ConsentEntity; import java.util.List; import java.util.UUID; import org.springframework.data.repository.Repository; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/ContactPointJpaRepository.java similarity index 86% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/ContactPointJpaRepository.java index f12aab2d..bb63185e 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ContactPointJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/ContactPointJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.ContactPointEntity; import java.util.Optional; import java.util.UUID; import org.springframework.data.repository.Repository; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/DeduplicationClaimJpaRepository.java similarity index 95% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/DeduplicationClaimJpaRepository.java index cf526136..501b9ddb 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeduplicationClaimJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/DeduplicationClaimJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.DeduplicationClaimEntity; import java.util.Optional; import java.util.UUID; import org.springframework.data.jpa.repository.Modifying; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/DeliveryAttemptJpaRepository.java similarity index 91% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/DeliveryAttemptJpaRepository.java index 5ca095bb..61ed8c06 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/DeliveryAttemptJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/DeliveryAttemptJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.DeliveryAttemptEntity; import java.util.List; import java.util.Optional; import java.util.UUID; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/InboxItemJpaRepository.java similarity index 97% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/InboxItemJpaRepository.java index 7585154d..15428027 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/InboxItemJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.InboxItemEntity; import java.time.Instant; import java.util.List; import java.util.Optional; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/NotificationRequestJpaRepository.java similarity index 85% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/NotificationRequestJpaRepository.java index deacdae6..dee2cf88 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRequestJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/NotificationRequestJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.NotificationRequestEntity; import java.time.Instant; import java.util.Optional; import java.util.UUID; @@ -50,12 +51,14 @@ public interface NotificationRequestJpaRepository "INSERT INTO notification_request (" + " id, tenant_id, idempotency_key, request_fingerprint, category, template_id," + " template_version, template_locale, strategy_type, variables_payload," - + " schedule_at, not_before, expires_at, request_status, correlation_id," - + " metadata_json, created_at, updated_at, version" + + " schedule_at, not_before, expires_at, collapse_key, collapse_scope," + + " request_status, acceptance, correlation_id, metadata_json, created_at," + + " updated_at, version" + ") VALUES (" + " :id, :tenantId, :idempotencyKey, :requestFingerprint, :category, :templateId," + " :templateVersion, :templateLocale, :strategyType, :variablesPayload," - + " :scheduleAt, :notBefore, :expiresAt, :requestStatus, :correlationId," + + " :scheduleAt, :notBefore, :expiresAt, :collapseKey, :collapseScope," + + " :requestStatus, :acceptance, :correlationId," + " CAST(:metadataJson AS jsonb), :createdAt, :updatedAt, 0" + ") ON CONFLICT (tenant_id, idempotency_key) DO NOTHING", nativeQuery = true) @@ -73,7 +76,10 @@ public interface NotificationRequestJpaRepository @Param("scheduleAt") Instant scheduleAt, @Param("notBefore") Instant notBefore, @Param("expiresAt") Instant expiresAt, + @Param("collapseKey") String collapseKey, + @Param("collapseScope") String collapseScope, @Param("requestStatus") String requestStatus, + @Param("acceptance") String acceptance, @Param("correlationId") String correlationId, @Param("metadataJson") String metadataJson, @Param("createdAt") Instant createdAt, diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/PreferenceJpaRepository.java similarity index 95% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/PreferenceJpaRepository.java index f8922ec0..af659cad 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/PreferenceJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/PreferenceJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.PreferenceEntity; import java.time.Instant; import java.util.Optional; import java.util.UUID; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/ProviderEventJpaRepository.java similarity index 98% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/ProviderEventJpaRepository.java index f73e1ef4..96e46b5d 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/ProviderEventJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/ProviderEventJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.ProviderEventEntity; import java.util.List; import java.util.Optional; import java.util.UUID; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientClaimSql.java similarity index 91% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientClaimSql.java index 2b7b757d..6d11bbb5 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSql.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientClaimSql.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; /** * The durable-queue claim, as one statement, in one place. @@ -8,8 +8,12 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform; * author and the adapter author agreed about the query, which is not the property anybody needs; * the property is that this statement, against a real PostgreSQL, claims what it should. * + *

        The lease store contract ({@code RecipientLeaseStoreContract}, run on PostgreSQL by {@code + * PostgreSqlRecipientLeaseStoreContractTest}) now drives this statement through the repository and + * the store, so no test retypes it or runs it beside the adapter (review 2026-11-01 04-14). + * *

        The named parameters are Spring Data's. {@link #positional(String)} rewrites them to JDBC - * placeholders so a test with a bare {@code Connection} can run the identical text. + * placeholders for a caller with a bare {@code Connection}. */ public final class RecipientClaimSql { diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientDeliveryJpaRepository.java similarity index 98% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientDeliveryJpaRepository.java index a3beab48..b5f1ee18 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientDeliveryJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientDeliveryJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.RecipientDeliveryEntity; import java.time.Instant; import java.util.List; import java.util.UUID; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/SuppressionJpaRepository.java similarity index 96% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/SuppressionJpaRepository.java index 631f91ce..479b17a8 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/SuppressionJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/SuppressionJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.SuppressionEntity; import java.time.Instant; import java.util.List; import java.util.Optional; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionJpaRepository.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/TemplateVersionJpaRepository.java similarity index 95% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionJpaRepository.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/TemplateVersionJpaRepository.java index 1c3f1cf9..b1443df5 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TemplateVersionJpaRepository.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/TemplateVersionJpaRepository.java @@ -1,5 +1,6 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.entity.TemplateVersionEntity; import java.util.List; import java.util.Optional; import java.util.UUID; diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TenantBoundRepositoryGuard.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/TenantBoundRepositoryGuard.java similarity index 98% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TenantBoundRepositoryGuard.java rename to src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/TenantBoundRepositoryGuard.java index 0a3f81bd..be6fc4a4 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/TenantBoundRepositoryGuard.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/TenantBoundRepositoryGuard.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; import dev.caskeleton.application.notification.platform.api.TenantId; import java.util.Objects; diff --git a/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V13__notification_request_acceptance.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V13__notification_request_acceptance.sql new file mode 100644 index 00000000..9c251db8 --- /dev/null +++ b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V13__notification_request_acceptance.sql @@ -0,0 +1,21 @@ +-- 05-23c — a submission dropped by a deduplication window was never stored. +-- +-- The receipt named a fresh id that no row held, and a retry with the same idempotency key ran +-- deduplication again: inside the window it was dropped under yet another id, after the window it +-- was accepted and sent. The answer to an idempotency key has to be the same every time it is asked, +-- so the drop is now stored like any other request — CANCELED, with no recipient jobs — and this +-- column records why, so the stored receipt says "dropped" rather than "accepted". +-- +-- Existing rows were all accepted submissions; the default records exactly that. + +ALTER TABLE notification_request + ADD COLUMN IF NOT EXISTS acceptance varchar(40) NOT NULL DEFAULT 'ACCEPTED'; + +ALTER TABLE notification_request + ADD CONSTRAINT ck_notification_request_acceptance + CHECK (acceptance IN ('ACCEPTED', 'DROPPED_AS_DUPLICATE')); + +COMMENT ON COLUMN notification_request.acceptance IS + 'ACCEPTED for a request that will be sent; DROPPED_AS_DUPLICATE for a submission a ' + 'deduplication window suppressed, kept so a retry with the same idempotency key gets the same ' + 'receipt.'; diff --git a/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntityTest.java b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/InboxItemEntityTest.java similarity index 99% rename from src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntityTest.java rename to src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/InboxItemEntityTest.java index 4a51b0a8..d277ae00 100644 --- a/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/inbox/InboxItemEntityTest.java +++ b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/entity/InboxItemEntityTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.entity; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositoryDiscoveryTest.java b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/NotificationRepositoryDiscoveryTest.java similarity index 99% rename from src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositoryDiscoveryTest.java rename to src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/NotificationRepositoryDiscoveryTest.java index de8da4e5..bb6400f0 100644 --- a/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositoryDiscoveryTest.java +++ b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/NotificationRepositoryDiscoveryTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositorySurfaceTest.java b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/NotificationRepositorySurfaceTest.java similarity index 96% rename from src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositorySurfaceTest.java rename to src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/NotificationRepositorySurfaceTest.java index 5dac9f8a..759a2724 100644 --- a/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/NotificationRepositorySurfaceTest.java +++ b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/NotificationRepositorySurfaceTest.java @@ -1,8 +1,7 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxItemJpaRepository; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; diff --git a/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSqlTest.java b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientClaimSqlTest.java similarity index 94% rename from src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSqlTest.java rename to src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientClaimSqlTest.java index 7ca8e802..a1d52969 100644 --- a/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/RecipientClaimSqlTest.java +++ b/src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientClaimSqlTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.adapter.outbound.persistence.notification.platform.repository; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/adapter/outbound/redis-sdk/README.md b/src/adapter/outbound/redis-sdk/README.md index 4aa8050e..1b26037f 100644 --- a/src/adapter/outbound/redis-sdk/README.md +++ b/src/adapter/outbound/redis-sdk/README.md @@ -18,7 +18,9 @@ implementation project(':adapter:outbound:redis-sdk') `redis-runtime` comes with it: the SDK's public types extend and return runtime types (`SemanticRedisCommands`, `RedisLaneContribution`, …), so the SDK declares the runtime as `api`. -Register both edges in that leaf's `allowed_dependencies` in +The SDK itself also uses `shared-contract` (`HmacSha256` for permit signatures, review 2026-11-01 +01-11) as an `implementation` edge; a consumer does not see it. Register both edges in that leaf's +`allowed_dependencies` in `src/config/architecture/modules.json` (HARD-STOP 5). Put the adapter behind an application-core port, as for any other outbound capability. diff --git a/src/adapter/outbound/redis-sdk/build.gradle b/src/adapter/outbound/redis-sdk/build.gradle index b30b8558..5d834b1f 100644 --- a/src/adapter/outbound/redis-sdk/build.gradle +++ b/src/adapter/outbound/redis-sdk/build.gradle @@ -11,6 +11,8 @@ description = 'Optional typed Redis SDK library: guarded typed operations, admin dependencies { api project(':adapter:outbound:redis-runtime') + // HmacSha256 for the permit signature (review 2026-11-01 01-11). + implementation project(':shared-contract') implementation 'org.springframework:spring-core' implementation 'io.lettuce:lettuce-core' implementation 'io.projectreactor:reactor-core' diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/ConfiguredRedisPolicyAuthority.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/ConfiguredRedisPolicyAuthority.java index 08397249..94f586a6 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/ConfiguredRedisPolicyAuthority.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/ConfiguredRedisPolicyAuthority.java @@ -4,6 +4,8 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.AdvancedOpera import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.MultiKeyPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.PersistentKeyPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.RedisPolicyAuthority; +import dev.caskeleton.shared.digest.HmacSha256; +import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Collection; @@ -11,8 +13,6 @@ import java.util.HexFormat; import java.util.Objects; import java.util.Set; import java.util.UUID; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; /** * Issues permits for the policy names this deployment enabled. @@ -24,13 +24,11 @@ import javax.crypto.spec.SecretKeySpec; */ public final class ConfiguredRedisPolicyAuthority implements RedisPolicyAuthority { - private static final String ALGORITHM = "HmacSHA256"; - private static final SecureRandom SECURE_RANDOM = new SecureRandom(); private final Set enabledPolicies; private final String issuerId; - private final SecretKeySpec signingKey; + private final byte[] signingKey; /** * Creates an authority. @@ -44,7 +42,7 @@ public final class ConfiguredRedisPolicyAuthority implements RedisPolicyAuthorit this.issuerId = UUID.randomUUID().toString(); byte[] secret = new byte[32]; SECURE_RANDOM.nextBytes(secret); - this.signingKey = new SecretKeySpec(secret, ALGORITHM); + this.signingKey = secret; } @Override @@ -81,18 +79,21 @@ public final class ConfiguredRedisPolicyAuthority implements RedisPolicyAuthorit * @return the hexadecimal signature */ String sign(String kind, String policyName) { - try { - Mac mac = Mac.getInstance(ALGORITHM); - mac.init(signingKey); - mac.update(kind.getBytes(StandardCharsets.UTF_8)); - mac.update((byte) 0); - mac.update(issuerId.getBytes(StandardCharsets.UTF_8)); - mac.update((byte) 0); - mac.update(policyName.getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(mac.doFinal()); - } catch (java.security.GeneralSecurityException exception) { - throw new IllegalStateException("Cannot sign a Redis capability permit", exception); - } + return signature(signingKey, kind, issuerId, policyName); + } + + /** + * The permit signature: HMAC-SHA256 under {@code key} over {@code kind}, {@code issuerId} and + * {@code policyName}, each UTF-8 and separated by one zero byte, as lowercase hex. + */ + static String signature(byte[] key, String kind, String issuerId, String policyName) { + ByteArrayOutputStream message = new ByteArrayOutputStream(); + message.writeBytes(kind.getBytes(StandardCharsets.UTF_8)); + message.write(0); + message.writeBytes(issuerId.getBytes(StandardCharsets.UTF_8)); + message.write(0); + message.writeBytes(policyName.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(HmacSha256.sign(key, message.toByteArray())); } private String require(String policyName) { diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitSignatureVectorTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitSignatureVectorTest.java new file mode 100644 index 00000000..58b1ceca --- /dev/null +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitSignatureVectorTest.java @@ -0,0 +1,33 @@ +package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Pins the permit signature against a vector computed outside the JVM (Python {@code hmac.new(key, + * b"advanced\\0issuer-1\\0orders-scan", sha256).hexdigest()}), so moving the computation onto + * shared-contract's {@code HmacSha256} (review 2026-11-01 01-11) cannot change what a permit + * carries. + */ +class RedisPermitSignatureVectorTest { + + @Test + @DisplayName("permit 서명은 kind·issuer·policy를 0 바이트로 이은 HMAC-SHA256 hex다") + void thePermitSignatureIsTheHexHmacOfTheZeroSeparatedFields() { + // given + byte[] key = new byte[32]; + for (int i = 0; i < key.length; i++) { + key[i] = (byte) i; + } + + // when + String signature = + ConfiguredRedisPolicyAuthority.signature(key, "advanced", "issuer-1", "orders-scan"); + + // then + assertThat(signature) + .isEqualTo("a65c1f779d49e1b34b30c56b688658dd0284fe43782313883a4ca0720914081f"); + } +} diff --git a/src/adapter/outbound/support/CLAUDE.md b/src/adapter/outbound/support/CLAUDE.md index 150f45d9..3e8f0d3d 100644 --- a/src/adapter/outbound/support/CLAUDE.md +++ b/src/adapter/outbound/support/CLAUDE.md @@ -25,6 +25,11 @@ Package roots: `dev.caskeleton.adapter.outbound` and descriptor at a time with `NOFOLLOW_LINKS`, refusing symbolic components and escapes with typed `IOException`s. A storage capability translates those into its own failure vocabulary (the Fileserver's `LocalStorageFailures`); nothing here knows an error code. +- Own `StrictSettingsBinder`, the one strict settings binding. It is also the only support class an + inbound leaf may use: `adapter:inbound:web` binds `app.security` with it (registry edge and a + class-named ArchUnit exemption, review 2026-11-01 07-10). An empty value for a setting the type + has (`APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT=`) binds as unset; an empty value under a name + the type does not have is still refused (review 15절, r3-I). - Keep feature-specific clients and routing policies in their owning leaf. ## Boundaries diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSource.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSource.java index 3d28233e..4cdc7aac 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSource.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSource.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.support; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import java.util.Objects; import java.util.Optional; import org.springframework.core.env.Environment; diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinder.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinder.java index 3b696435..9d89ca4e 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinder.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinder.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.support; +import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; @@ -14,13 +15,16 @@ import org.springframework.boot.context.properties.bind.BindContext; import org.springframework.boot.context.properties.bind.BindHandler; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.context.properties.bind.PlaceholdersResolver; import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver; +import org.springframework.boot.context.properties.bind.UnboundConfigurationPropertiesException; import org.springframework.boot.context.properties.bind.handler.NoUnboundElementsBindHandler; import org.springframework.boot.context.properties.source.ConfigurationProperty; import org.springframework.boot.context.properties.source.ConfigurationPropertyName; import org.springframework.boot.context.properties.source.ConfigurationPropertyName.Form; import org.springframework.boot.context.properties.source.ConfigurationPropertySource; import org.springframework.boot.context.properties.source.ConfigurationPropertySources; +import org.springframework.boot.context.properties.source.ConfigurationPropertyState; import org.springframework.boot.context.properties.source.IterableConfigurationPropertySource; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; @@ -42,10 +46,13 @@ import org.springframework.core.env.SystemEnvironmentPropertySource; * the default limit while its configuration file says otherwise, and discovering that from a * production incident is the whole failure mode this prevents. * - *

        Two surfaces, two checks

        + *

        Two surfaces, three checks

        * *

        Property sources that enumerate their keys in property form — YAML, properties files, test - * overrides, system properties — are checked by {@link NoUnboundElementsBindHandler}. The system + * overrides, system properties — are checked by {@link NoUnboundElementsBindHandler}, and below a + * list element by this class as well (see {@link UnboundListElementHandler}): Spring's handler + * stops at the first level of a list element, so {@code clients[0].timeout.conect} — or a key a + * module removed — bound nothing and failed nothing (review 2026-11-01 05-15). The system * environment cannot be: Spring enumerates {@code APP_OUTBOX_POLL_INTERVAL} as {@code * app.outbox.poll.interval} while binding it as {@code app.outbox.poll-interval}, so the handler * would reject every correctly spelled hyphenated variable and still say nothing useful about a @@ -61,6 +68,18 @@ import org.springframework.core.env.SystemEnvironmentPropertySource; * *

        This replaced the HTTP client's own reflective variant (S3-lead-2), which derived the accepted * names from its record tree and so worked for that one settings type only. + * + *

        An empty value is "not set"

        + * + *

        An optional setting — a quota limit, a TTL override — is left empty to mean "none": the + * shipped {@code .env.example} carries {@code APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT=} and + * the module default reads it as {@code ${APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT:}}. Spring + * converts the empty string to {@code null} for a number, size or duration and then never reports + * the name as bound, so both checks above called a correctly spelt, deliberately empty setting + * unknown, and a deployment that copied the example failed to start (review 2026-11-01 15절, r3-I). + * A property the binder looked for, found, and found empty now counts as present and unset. Only a + * name the settings type has can be looked for, so an empty value under a misspelt name is refused + * exactly as before. */ public final class StrictSettingsBinder { @@ -120,15 +139,16 @@ public final class StrictSettingsBinder { ? source : source.filter(name -> !ownedBy(foreign, name))) .toList(); - RecordingBindHandler recorded = new RecordingBindHandler(); - BindHandler strict = - new NoUnboundElementsBindHandler(recorded, source -> !isSystemEnvironment(source)); + PlaceholdersResolver placeholders = new PropertySourcesPlaceholdersResolver(environment); + UnboundListElementHandler strict = + new UnboundListElementHandler( + new NoUnboundElementsBindHandler( + BindHandler.DEFAULT, source -> !isSystemEnvironment(source)), + placeholders); // bindOrCreate: a prefix nobody configured is the type's defaults, the same as a scanned // @ConfigurationProperties class, and the compact constructor still validates them. - T settings = - new Binder(sources, new PropertySourcesPlaceholdersResolver(environment)) - .bindOrCreate(prefix, Bindable.of(type), strict); - rejectUnrecognisedEnvironment(environment, root, foreign, recorded.bound); + T settings = new Binder(sources, placeholders).bindOrCreate(prefix, Bindable.of(type), strict); + rejectUnrecognisedEnvironment(environment, root, foreign, strict.bound); return settings; } @@ -240,10 +260,33 @@ public final class StrictSettingsBinder { return source.getUnderlyingSource() instanceof SystemEnvironmentPropertySource; } - /** Remembers every property the binding actually bound, so its variable is not called a typo. */ - private static final class RecordingBindHandler extends AbstractBindHandler { + /** + * Remembers every property the binding bound, and refuses a key below a list element that bound + * nothing. + * + *

        The second half closes a gap in {@link NoUnboundElementsBindHandler}. Spring binds a list + * whole from the first property source that has it, so another source's elements of the same list + * are legitimately left unbound, and the handler excuses them as "overridden collection + * elements". Its test for that is loose: a key under {@code clients[n]} is excused once {@code + * clients[0]} was bound and {@code clients[0].} was attempted — which every + * correctly configured element satisfies. So every key from the second level down was excused, + * typos and removed settings included, in every source. + * + *

        This handler asks the question the excuse is meant to answer: did the key come from the + * source the list was bound from? Only that source's elements were bound, element by element and + * from that source alone, so a key of it that bound nothing names no setting. Keys of a source + * the list was not taken from stay excused, exactly as before. Keys outside any list are left to + * Spring's handler, which judges them correctly. + */ + private static final class UnboundListElementHandler extends AbstractBindHandler { private final Set bound = new LinkedHashSet<>(); + private final PlaceholdersResolver placeholders; + + UnboundListElementHandler(BindHandler parent, PlaceholdersResolver placeholders) { + super(parent); + this.placeholders = placeholders; + } @Override public Object onSuccess( @@ -251,5 +294,97 @@ public final class StrictSettingsBinder { bound.add(name); return super.onSuccess(name, target, context, result); } + + @Override + public void onFinish( + ConfigurationPropertyName name, Bindable target, BindContext context, Object result) + throws Exception { + if (result == null && suppliedEmpty(name, context)) { + // Present and deliberately unset. Spring's handler learns what was bound only through + // onSuccess, which a value converted to null never reaches, so it is told here — before + // the root's onFinish runs its check. The environment check reads the same set. + bound.add(name); + super.onSuccess(name, target, context, ""); + } + super.onFinish(name, target, context, result); + if (context.getDepth() == 0) { + refuseUnboundListElementKeys(name, context); + } + } + + private void refuseUnboundListElementKeys(ConfigurationPropertyName root, BindContext context) { + List sources = new ArrayList<>(); + context.getSources().forEach(sources::add); + Set unbound = new TreeSet<>(); + for (ConfigurationPropertySource source : sources) { + if (isSystemEnvironment(source) + || !(source instanceof IterableConfigurationPropertySource iterable)) { + continue; + } + for (ConfigurationPropertyName name : iterable) { + if (!root.isAncestorOf(name) || bound.contains(name)) { + continue; + } + int index = firstListIndex(root, name); + if (index >= 0 && listSource(name.chop(index), sources) == source) { + ConfigurationProperty property = iterable.getConfigurationProperty(name); + if (property != null) { + unbound.add(property); + } + } + } + } + if (!unbound.isEmpty()) { + throw new UnboundConfigurationPropertiesException(unbound); + } + } + + /** + * Whether the source the binder read {@code name} from holds an empty value for it. + * + *

        The first source that has the property, in priority order, is the one the binder took it + * from; its value is resolved the way the binder resolved it, so an empty placeholder default + * counts as empty too. + */ + private boolean suppliedEmpty(ConfigurationPropertyName name, BindContext context) { + for (ConfigurationPropertySource source : context.getSources()) { + ConfigurationProperty property = source.getConfigurationProperty(name); + if (property != null) { + return placeholders.resolvePlaceholders(property.getValue()) instanceof String text + && text.isEmpty(); + } + } + return false; + } + + /** The position of the first list index below the root, or -1 when the name has none. */ + private static int firstListIndex( + ConfigurationPropertyName root, ConfigurationPropertyName name) { + for (int element = root.getNumberOfElements(); + element < name.getNumberOfElements(); + element++) { + if (name.isNumericIndex(element)) { + return element; + } + } + return -1; + } + + /** + * The source Spring binds the list from: the first, in priority order, that holds the list as + * one value or holds its element {@code [0]} (elements bind from index 0 until one is missing). + */ + private static ConfigurationPropertySource listSource( + ConfigurationPropertyName list, List sources) { + ConfigurationPropertyName first = list.append("[0]"); + for (ConfigurationPropertySource source : sources) { + if (source.getConfigurationProperty(list) != null + || source.getConfigurationProperty(first) != null + || source.containsDescendantOf(first) == ConfigurationPropertyState.PRESENT) { + return source; + } + } + return null; + } } } diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSourceContractTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSourceContractTest.java new file mode 100644 index 00000000..f7b6c976 --- /dev/null +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSourceContractTest.java @@ -0,0 +1,21 @@ +package dev.caskeleton.adapter.outbound.support; + +import dev.caskeleton.application.secret.SecretSourcePort; +import dev.caskeleton.application.secret.testkit.SecretSourceContract; +import java.util.HashMap; +import java.util.Map; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.StandardEnvironment; + +/** The Spring Environment backend keeps the secret source contract the fake keeps. */ +class EnvironmentSecretSourceContractTest extends SecretSourceContract { + + @Override + protected SecretSourcePort sourceWith(Map secrets) { + StandardEnvironment environment = new StandardEnvironment(); + environment + .getPropertySources() + .addFirst(new MapPropertySource("contract", new HashMap(secrets))); + return new EnvironmentSecretSource(environment); + } +} diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSourceTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSourceTest.java index 897c5e51..e37f790b 100644 --- a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSourceTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/EnvironmentSecretSourceTest.java @@ -2,7 +2,7 @@ package dev.caskeleton.adapter.outbound.support; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinderTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinderTest.java index 1b592f1b..3eba3b4b 100644 --- a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinderTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/StrictSettingsBinderTest.java @@ -9,7 +9,10 @@ import java.util.Map; import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.context.properties.bind.BindException; +import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.env.SystemEnvironmentPropertySource; import org.springframework.mock.env.MockEnvironment; @@ -160,6 +163,158 @@ class StrictSettingsBinderTest { assertThat(settings.allowedHosts()).containsExactly("payment.test"); } + /** A list of groups, the shape whose deeper keys Spring's own unbound-key check skips. */ + public record ClientListSettings(List clients) {} + + /** One list element with a nested group two levels down. */ + public record Client(String name, Timeout timeout, Retry retry) {} + + /** The element's first-level group. */ + public record Timeout(Duration connect) {} + + /** A first-level group with a second-level group under it. */ + public record Retry(Integer maxAttempts, Backoff backoff) {} + + /** The second-level group. */ + public record Backoff(Duration initial) {} + + @ParameterizedTest + @ValueSource( + strings = { + "clients[0].timeout.conect", + "clients[1].timeout.request-write-idle", + "clients[0].retry.backoff.intial" + }) + @DisplayName("list 원소 아래 둘째 단계 이하의 오타·없는 키도 그 이름으로 거부된다") + void aKeyBelowTheFirstLevelOfAListElementThatNamesNoSettingIsRefusedByName(String key) { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty(PREFIX + ".clients[0].name", "payment") + .withProperty(PREFIX + ".clients[0].timeout.connect", "1s") + .withProperty(PREFIX + ".clients[0].retry.backoff.initial", "100ms") + .withProperty(PREFIX + ".clients[1].name", "webhook") + .withProperty(PREFIX + ".clients[1].timeout.connect", "2s") + .withProperty(PREFIX + "." + key, "1s"); + + // when + Throwable thrown = + catchThrowable( + () -> StrictSettingsBinder.bind(environment, PREFIX, ClientListSettings.class)); + + // then + assertThat(thrown) + .isInstanceOf(BindException.class) + .hasStackTraceContaining(PREFIX + "." + key); + } + + @Test + @DisplayName("우선순위가 높은 출처가 list를 통째로 정하면 낮은 출처의 list 원소는 오타로 보지 않는다") + void aListElementALowerPrioritySourceOverridesWhollyIsNotCalledATypo() { + // given + MockEnvironment environment = + new MockEnvironment().withProperty(PREFIX + ".clients[0].name", "payment"); + environment + .getPropertySources() + .addLast( + new MapPropertySource( + "module-defaults", + Map.of( + PREFIX + ".clients[0].name", "default", + PREFIX + ".clients[0].timeout.connect", "5s", + PREFIX + ".clients[1].retry.backoff.initial", "1s"))); + + // when + ClientListSettings settings = + StrictSettingsBinder.bind(environment, PREFIX, ClientListSettings.class); + + // then + assertThat(settings.clients()).containsExactly(new Client("payment", null, null)); + } + + /** Settings with an optional size: absent means "no limit", the shape of a quota setting. */ + public record LimitSettings(Duration lease, org.springframework.util.unit.DataSize limit) {} + + @Test + @DisplayName("모듈 기본값의 빈 placeholder로 온 선택 숫자 설정은 미설정으로 바인딩된다") + void anOptionalSettingWhosePlaceholderResolvesEmptyBindsAsUnset() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty(PREFIX + ".lease", "30s") + .withProperty(PREFIX + ".limit", "${SAMPLE_SHARED_LIMIT:}"); + + // when + LimitSettings settings = StrictSettingsBinder.bind(environment, PREFIX, LimitSettings.class); + + // then + assertThat(settings).isEqualTo(new LimitSettings(Duration.ofSeconds(30), null)); + } + + @Test + @DisplayName(".env.example처럼 빈 값으로 온 선택 숫자 env는 미설정으로 바인딩된다") + void anOptionalSettingWhoseEnvironmentVariableIsEmptyBindsAsUnset() { + // given + MockEnvironment environment = + withSystemEnvironment(Map.of("SAMPLE_SHARED_LIMIT", "")) + .withProperty(PREFIX + ".lease", "30s") + .withProperty(PREFIX + ".limit", "${SAMPLE_SHARED_LIMIT:}"); + + // when + LimitSettings settings = StrictSettingsBinder.bind(environment, PREFIX, LimitSettings.class); + + // then + assertThat(settings.limit()).isNull(); + } + + @Test + @DisplayName("다른 출처에 선언이 없어도 빈 값의 올바른 env 이름은 오타가 아니다") + void anEmptyCorrectlySpelledVariableIsNotATypoEvenWhenNothingElseDeclaresIt() { + // given + MockEnvironment environment = withSystemEnvironment(Map.of("SAMPLE_SHARED_LIMIT", "")); + + // when + LimitSettings settings = StrictSettingsBinder.bind(environment, PREFIX, LimitSettings.class); + + // then + assertThat(settings.limit()).isNull(); + } + + @Test + @DisplayName("값이 비어 있어도 설정 이름이 아닌 키는 그대로 거부된다") + void aMisspeltKeyIsStillRefusedWhenItsValueIsEmpty() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty(PREFIX + ".lease", "30s") + .withProperty(PREFIX + ".limt", ""); + + // when + Throwable thrown = + catchThrowable(() -> StrictSettingsBinder.bind(environment, PREFIX, LimitSettings.class)); + + // then + assertThat(thrown).isInstanceOf(BindException.class).hasStackTraceContaining("limt"); + } + + @Test + @DisplayName("값이 비어 있어도 prefix 아래 오타 env는 그 이름으로 거부된다") + void aMisspeltEnvironmentVariableIsStillRefusedWhenItsValueIsEmpty() { + // given + MockEnvironment environment = + withSystemEnvironment(Map.of("SAMPLE_SHARED_LIMT", "")) + .withProperty(PREFIX + ".lease", "30s"); + + // when + Throwable thrown = + catchThrowable(() -> StrictSettingsBinder.bind(environment, PREFIX, LimitSettings.class)); + + // then + assertThat(thrown) + .isInstanceOf(CapabilityStartupValidationException.class) + .hasMessageContaining("SAMPLE_SHARED_LIMT"); + } + private static MockEnvironment withSystemEnvironment(Map variables) { MockEnvironment environment = new MockEnvironment(); environment diff --git a/src/app-bootstrap/README.md b/src/app-bootstrap/README.md index 8962338a..56902f31 100644 --- a/src/app-bootstrap/README.md +++ b/src/app-bootstrap/README.md @@ -59,7 +59,9 @@ WebSocket, gRPC, 파일 서버, 알림)는 `build.gradle`에 주석 처리된 `r ### AuthenticationModeCompositionConfig -`app.security.auth-mode`의 기본값은 `jwt`이며 `jwt|redis-session` 중 정확히 하나만 허용한다. +`app.security.auth-mode`의 기본값은 `jwt`이며 `jwt|redis-session` 중 정확히 하나만 허용한다. 모드는 +web leaf의 `SecuritySettings`(`app.security` 전체의 유일한 소유자, strict 바인딩)에서 읽는다. 예전에는 +bootstrap의 `AuthenticationModeSettings`가 같은 prefix를 관대하게 한 번 더 바인딩했다(리뷰 07-10). JWT mode는 `jwtDecoder`가 있어야 하고 Redis session repository/filter가 있으면 기동을 거부한다. Redis session mode는 반대로 `jwtDecoder`를 거부하고 `redisVersionedSessionRepository`와 `springSessionRepositoryFilter`가 모두 있어야 한다. 이 검증은 bean name만 확인하므로 bootstrap이 diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java index 8a252743..10371835 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java @@ -72,22 +72,35 @@ class AdapterBoundaryArchitectureTest { + "declares transaction mode, repository access and outbound permission") .allowEmptyShould(true); + /** + * The one class an inbound adapter may take from {@code adapter:outbound:support}: the strict + * settings binder (registry edge {@code adapter-inbound-web -> adapter-outbound-support}, review + * 2026-11-01 07-10). It reads configuration and talks to no external system, so it is not an + * outbound adapter in the sense the rules below forbid, and the web leaf binding {@code + * app.security} through a copy of it would be a second binder to keep in step. Named by class so + * nothing else in that leaf comes with it. + */ + private static final DescribedPredicate THE_STRICT_SETTINGS_BINDER = + JavaClass.Predicates.equivalentTo( + dev.caskeleton.adapter.outbound.support.StrictSettingsBinder.class); + @ArchTest static final ArchRule WEB_ADAPTER_DOES_NOT_DEPEND_ON_PERSISTENCE_OR_OUTBOUND_ADAPTERS = noClasses() .that() .resideInAPackage("..adapter.inbound.web..") .should() - .dependOnClassesThat() - .resideInAnyPackage( - "..adapter.outbound.persistence..", - "..adapter.outbound..", - "..adapter.outbound.identifier..", - "org.springframework.data.repository..", - "org.springframework.data.jpa.repository..", - "jakarta.persistence..", - "javax.persistence..", - "org.hibernate.."); + .dependOnClassesThat( + JavaClass.Predicates.resideInAnyPackage( + "..adapter.outbound.persistence..", + "..adapter.outbound..", + "..adapter.outbound.identifier..", + "org.springframework.data.repository..", + "org.springframework.data.jpa.repository..", + "jakarta.persistence..", + "javax.persistence..", + "org.hibernate..") + .and(DescribedPredicate.not(THE_STRICT_SETTINGS_BINDER))); @ArchTest static final ArchRule PERSISTENCE_ADAPTER_DOES_NOT_DEPEND_ON_WEB_OR_OUTBOUND_ADAPTERS = @@ -349,13 +362,15 @@ class AdapterBoundaryArchitectureTest { .that() .resideInAPackage("..adapter.inbound..") .should() - .dependOnClassesThat() - .resideInAPackage("..adapter.outbound..") + .dependOnClassesThat( + JavaClass.Predicates.resideInAPackage("..adapter.outbound..") + .and(DescribedPredicate.not(THE_STRICT_SETTINGS_BINDER))) .as( "inbound (driving) adapters must not depend on outbound (driven) adapters — an " + "inbound adapter drives the application through its inbound ports and reaches " + "persistence / messaging / cache / http only via application outbound ports, " - + "never by touching an outbound adapter directly (Task 7 adapter topology)"); + + "never by touching an outbound adapter directly (Task 7 adapter topology); the " + + "strict settings binder is the one support class allowed (07-10)"); @ArchTest static final ArchRule OUTBOUND_ADAPTERS_DO_NOT_DEPEND_ON_INBOUND_ADAPTERS = 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 fe3d5cc8..916d9945 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 @@ -110,6 +110,7 @@ class ArchRuleDiscoveryContractTest { // package and passed for having nothing to look at — the removal is recorded here // rather than made by deleting a field, which is what BOOT-012 asks. "EXTERNAL_OUTBOUND_CALLS_REQUIRE_EXTERNAL_OUTBOUND_ALLOWED_CAPABILITY", + "FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES", "IDENTIFIER_ADAPTER_DOES_NOT_DEPEND_ON_OTHER_ADAPTERS_OR_BOOTSTRAP", "INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES", "INBOUND_ADAPTERS_DO_NOT_DEPEND_ON_OUTBOUND_ADAPTERS", @@ -162,6 +163,7 @@ class ArchRuleDiscoveryContractTest { "SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES", "STARTUP_FAILURES_ARE_RAISED_THROUGH_THE_TYPED_FACTORY", "SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION", + "TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES", "THROWABLES_ARE_NAMED_EXCEPTION", "USE_CASE_CAPABILITY_MATCHES_TRANSACTION_PORT_BOUNDARY", "USE_CASE_PORTS_CARRY_ONE_OPERATION", diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java index 920353db..a0d58794 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java @@ -1,6 +1,7 @@ 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.junit.AnalyzeClasses; import com.tngtech.archunit.junit.ArchTest; @@ -12,10 +13,10 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * src/application-core/CLAUDE.md} ("Naming convention"), which is the rule book. * *

        This test enforces only the rules that ArchUnit can decide reliably (N6 configuration binding, - * I5 throwables). The rest of that table — repository vs store port, id factories, use case suffix - * exceptions — is a review rule, and the review checks it against that table. (The previous rule - * book, {@code .agents/plugins/ca-superpowers/rules/code-conventions.md}, is not in the - * repository.) + * I5 throwables, and the two package-ownership rules beside that table). The rest of that table — + * repository vs store port, id factories, use case suffix exceptions — is a review rule, and the + * review checks it against that table. (The previous rule book, {@code + * .agents/plugins/ca-superpowers/rules/code-conventions.md}, is not in the repository.) */ @AnalyzeClasses(packages = "dev.caskeleton", importOptions = ProductionClassImportOption.class) class NamingConventionTest { @@ -51,4 +52,51 @@ class NamingConventionTest { .haveSimpleNameEndingWith("Exception") .as("code-conventions I5: dev.caskeleton throwable types end with 'Exception'") .allowEmptyShould(true); + + // Package ownership — a business feature package does not take a template package's name. The + // template's own packages are listed in TemplatePackageOwnership (machine copy of the "Package + // ownership" table in src/application-core/CLAUDE.md); everything else under the two roots is a + // feature, so a derived service adds features without editing the list. A feature always has a + // domain package (docs/manual/03-placement.md ①), which is where a feature named after an + // application template package — `operation`, `lock`, `cache` — shows up. + @ArchTest + static final ArchRule FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES = + featurePackagesDoNotReuseTemplatePackageNames(TemplatePackageOwnership.PRODUCTION); + + // Package ownership — template code never knows a feature. This is the half the name rule cannot + // see: business code written straight into a template package (a locker feature in `lock`) keeps + // the package name and is caught by what it imports. + @ArchTest + static final ArchRule TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES = + templatePackagesDoNotDependOnFeaturePackages(TemplatePackageOwnership.PRODUCTION); + + static ArchRule featurePackagesDoNotReuseTemplatePackageNames( + TemplatePackageOwnership ownership) { + return classes() + .that(ownership.featurePackage()) + .should(ownership.useANameNoTemplatePackageUses()) + .as( + "package ownership: a business feature package under " + + ownership.applicationRoot() + + " or " + + ownership.domainRoot() + + " does not take a template package name " + + TemplatePackageOwnership.templateNames()) + .allowEmptyShould(true); + } + + static ArchRule templatePackagesDoNotDependOnFeaturePackages(TemplatePackageOwnership ownership) { + return noClasses() + .that(ownership.templatePackage()) + .should() + .dependOnClassesThat(ownership.featurePackage()) + .as( + "package ownership: template-owned packages under " + + ownership.applicationRoot() + + " and " + + ownership.domainRoot() + + " do not depend on a business feature package — template code never knows a" + + " feature, so a feature class put into a template package is caught here") + .allowEmptyShould(true); + } } diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnership.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnership.java new file mode 100644 index 00000000..da3c1362 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnership.java @@ -0,0 +1,129 @@ +package dev.caskeleton.bootstrap.architecture; + +import com.tngtech.archunit.base.DescribedPredicate; +import com.tngtech.archunit.core.domain.JavaClass; +import com.tngtech.archunit.lang.ArchCondition; +import com.tngtech.archunit.lang.ConditionEvents; +import com.tngtech.archunit.lang.SimpleConditionEvent; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; + +/** + * Which top-level packages under the application and domain roots the template owns, and which are + * a service's business features. + * + *

        This is the machine copy of the "Package ownership" table in {@code + * src/application-core/CLAUDE.md}, which is the rule book. A template change that adds, renames or + * removes one of these packages changes the table and this class together; {@code + * TemplatePackageOwnershipRuleTest} fails when a name here no longer exists, so a rename cannot + * leave the old name behind. + * + *

        Everything under the two roots that is not listed is a business feature package, which is what + * lets a derived service add {@code dev.caskeleton.application.invoice} without touching this list. + * The roots are parameters so the rules can be proven on fixture packages; production uses {@link + * #PRODUCTION}. + */ +record TemplatePackageOwnership(String applicationRoot, String domainRoot) { + + /** Template-owned {@code dev.caskeleton.application.} packages, across every leaf. */ + static final Set APPLICATION_PACKAGES = + Set.of( + // application-core: the use case kernel + "usecase", + "command", + "query", + "capability", + "transaction", + "security", + "tenant", + "observability", + "secret", + // application-core: platform features + "messaging", + "outbox", + "idempotency", + "operation", + "lease", + "lock", + "cache", + "realtime", + // capability leaves that share the application root + "notification", + "fileserver", + "objectstorage"); + + /** Template-owned {@code dev.caskeleton.domain.} packages. */ + static final Set DOMAIN_PACKAGES = Set.of("identifier", "stereotype"); + + static final TemplatePackageOwnership PRODUCTION = + new TemplatePackageOwnership("dev.caskeleton.application", "dev.caskeleton.domain"); + + /** Every name a business feature package may not take, sorted for messages. */ + static Set templateNames() { + Set names = new TreeSet<>(APPLICATION_PACKAGES); + names.addAll(DOMAIN_PACKAGES); + return names; + } + + DescribedPredicate templatePackage() { + return DescribedPredicate.describe( + "reside in a template-owned package", type -> isTemplate(type.getPackageName())); + } + + DescribedPredicate featurePackage() { + return DescribedPredicate.describe( + "reside in a business feature package", type -> isFeature(type.getPackageName())); + } + + /** A feature package's name is its first segment below its root, and no template uses it. */ + ArchCondition useANameNoTemplatePackageUses() { + return new ArchCondition<>("use a package name no template package uses") { + @Override + public void check(JavaClass item, ConditionEvents events) { + Optional name = featureName(item.getPackageName()); + if (name.isPresent() && templateNames().contains(name.get())) { + events.add( + SimpleConditionEvent.violated( + item, + item.getName() + + " is in business feature package '" + + name.get() + + "', a name the template already uses. A feature beside a template package" + + " of the same name merges into the same tree on every upstream update." + + " Rename the feature (template packages: src/application-core/CLAUDE.md" + + " \"Package ownership\").")); + } + } + }; + } + + private boolean isTemplate(String packageName) { + return segment(packageName, applicationRoot).map(APPLICATION_PACKAGES::contains).orElse(false) + || segment(packageName, domainRoot).map(DOMAIN_PACKAGES::contains).orElse(false); + } + + private boolean isFeature(String packageName) { + return featureName(packageName).isPresent(); + } + + private Optional featureName(String packageName) { + Optional application = + segment(packageName, applicationRoot).filter(name -> !APPLICATION_PACKAGES.contains(name)); + if (application.isPresent()) { + return application; + } + return segment(packageName, domainRoot).filter(name -> !DOMAIN_PACKAGES.contains(name)); + } + + /** The first package segment strictly below {@code root}, if the package is below it. */ + private static Optional segment(String packageName, String root) { + String prefix = root + "."; + if (!packageName.startsWith(prefix)) { + return Optional.empty(); + } + String rest = packageName.substring(prefix.length()); + int dot = rest.indexOf('.'); + return Optional.of(dot < 0 ? rest : rest.substring(0, dot)); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipRuleTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipRuleTest.java new file mode 100644 index 00000000..94c279e8 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/TemplatePackageOwnershipRuleTest.java @@ -0,0 +1,128 @@ +package dev.caskeleton.bootstrap.architecture; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.tngtech.archunit.core.domain.JavaClass; +import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.importer.ClassFileImporter; +import com.tngtech.archunit.lang.EvaluationResult; +import dev.caskeleton.bootstrap.architecture.fixtures.packageownership.application.invoice.LockInvoiceForPayment; +import dev.caskeleton.bootstrap.architecture.fixtures.packageownership.application.lock.LockHandle; +import dev.caskeleton.bootstrap.architecture.fixtures.packageownership.application.lock.LockerRental; +import dev.caskeleton.bootstrap.architecture.fixtures.packageownership.domain.invoice.Invoice; +import dev.caskeleton.bootstrap.architecture.fixtures.packageownership.domain.locker.Locker; +import dev.caskeleton.bootstrap.architecture.fixtures.packageownership.domain.operation.Operation; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The package-ownership rules in {@link NamingConventionTest} catch what they claim and nothing a + * derived service legitimately does, and their template list names only packages that exist. + * + *

        The fixtures stand in for the two roots ({@code fixtures.packageownership.application} and + * {@code .domain}); each case is imported in isolation so one fixture cannot satisfy another's + * expectation. + */ +class TemplatePackageOwnershipRuleTest { + + private static final String FIXTURE_ROOT = + "dev.caskeleton.bootstrap.architecture.fixtures.packageownership"; + + private static final TemplatePackageOwnership FIXTURE_OWNERSHIP = + new TemplatePackageOwnership(FIXTURE_ROOT + ".application", FIXTURE_ROOT + ".domain"); + + @Test + @DisplayName("업무 기능 domain 패키지가 템플릿 패키지 이름(operation)을 쓰면 규칙이 잡는다") + void aFeatureNamedAfterATemplatePackageIsReported() { + // given + JavaClasses featureNamedOperation = new ClassFileImporter().importClasses(Operation.class); + + // when + EvaluationResult result = + NamingConventionTest.featurePackagesDoNotReuseTemplatePackageNames(FIXTURE_OWNERSHIP) + .evaluate(featureNamedOperation); + + // then + assertThat(result.hasViolation()).isTrue(); + assertThat(result.getFailureReport().getDetails()) + .anySatisfy(detail -> assertThat(detail).contains("'operation'")); + } + + @Test + @DisplayName("템플릿 패키지(lock)에 넣은 업무 코드는 업무 기능을 import해서 규칙에 잡힌다") + void businessCodeInsideATemplatePackageIsReported() { + // given + JavaClasses lockerRentalInLock = + new ClassFileImporter().importClasses(LockerRental.class, Locker.class); + + // when + EvaluationResult result = + NamingConventionTest.templatePackagesDoNotDependOnFeaturePackages(FIXTURE_OWNERSHIP) + .evaluate(lockerRentalInLock); + + // then + assertThat(result.hasViolation()).isTrue(); + assertThat(result.getFailureReport().getDetails()) + .anySatisfy(detail -> assertThat(detail).contains(LockerRental.class.getName())); + } + + @Test + @DisplayName("템플릿과 다른 이름의 업무 기능이 템플릿 패키지를 쓰는 것은 두 규칙 모두 허용한다") + void aFeatureWithItsOwnNameUsingATemplatePackageIsAllowed() { + // given + JavaClasses derivedServiceShape = + new ClassFileImporter() + .importClasses( + LockInvoiceForPayment.class, LockHandle.class, Invoice.class, Locker.class); + + // when + boolean anyViolation = + NamingConventionTest.featurePackagesDoNotReuseTemplatePackageNames(FIXTURE_OWNERSHIP) + .evaluate(derivedServiceShape) + .hasViolation() + || NamingConventionTest.templatePackagesDoNotDependOnFeaturePackages(FIXTURE_OWNERSHIP) + .evaluate(derivedServiceShape) + .hasViolation(); + + // then + assertThat(anyViolation).isFalse(); + } + + @Test + @DisplayName("템플릿 패키지 목록의 이름은 모두 production 코드에 실제로 있는 패키지다") + void theTemplateListNamesOnlyPackagesThatExist() { + // given + TemplatePackageOwnership production = TemplatePackageOwnership.PRODUCTION; + + // when + JavaClasses imported = + new ClassFileImporter() + .withImportOption(new ProductionClassImportOption()) + .importPackages(production.applicationRoot(), production.domainRoot()); + + // then + Set application = topLevelPackages(imported, production.applicationRoot()); + Set domain = topLevelPackages(imported, production.domainRoot()); + assertThat(application) + .as( + "a name in TemplatePackageOwnership.APPLICATION_PACKAGES that no longer exists was" + + " renamed or removed without the list (and the table in" + + " src/application-core/CLAUDE.md) following it") + .containsAll(TemplatePackageOwnership.APPLICATION_PACKAGES); + assertThat(domain) + .as("TemplatePackageOwnership.DOMAIN_PACKAGES names a package that no longer exists") + .containsAll(TemplatePackageOwnership.DOMAIN_PACKAGES); + } + + private static Set topLevelPackages(JavaClasses classes, String root) { + String prefix = root + "."; + return classes.stream() + .map(JavaClass::getPackageName) + .filter(name -> name.startsWith(prefix)) + .map(name -> name.substring(prefix.length()).split("\\.", 2)[0]) + .collect(Collectors.toCollection(TreeSet::new)); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/invoice/LockInvoiceForPayment.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/invoice/LockInvoiceForPayment.java new file mode 100644 index 00000000..c128b723 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/invoice/LockInvoiceForPayment.java @@ -0,0 +1,7 @@ +package dev.caskeleton.bootstrap.architecture.fixtures.packageownership.application.invoice; + +import dev.caskeleton.bootstrap.architecture.fixtures.packageownership.application.lock.LockHandle; +import dev.caskeleton.bootstrap.architecture.fixtures.packageownership.domain.invoice.Invoice; + +/** A feature using a template package — the direction the rules allow. */ +public record LockInvoiceForPayment(Invoice invoice, LockHandle lock) {} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/lock/LockHandle.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/lock/LockHandle.java new file mode 100644 index 00000000..2d4ccb05 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/lock/LockHandle.java @@ -0,0 +1,4 @@ +package dev.caskeleton.bootstrap.architecture.fixtures.packageownership.application.lock; + +/** Template code in the template's {@code lock} package: it knows no feature. */ +public record LockHandle(String name) {} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/lock/LockerRental.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/lock/LockerRental.java new file mode 100644 index 00000000..b6f5f012 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/application/lock/LockerRental.java @@ -0,0 +1,17 @@ +package dev.caskeleton.bootstrap.architecture.fixtures.packageownership.application.lock; + +import dev.caskeleton.bootstrap.architecture.fixtures.packageownership.domain.locker.Locker; + +/** Business code written into the template's {@code lock} package: it imports a feature. */ +public final class LockerRental { + + private final Locker locker; + + public LockerRental(Locker locker) { + this.locker = locker; + } + + public Locker locker() { + return locker; + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/invoice/Invoice.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/invoice/Invoice.java new file mode 100644 index 00000000..85a67c2f --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/invoice/Invoice.java @@ -0,0 +1,4 @@ +package dev.caskeleton.bootstrap.architecture.fixtures.packageownership.domain.invoice; + +/** A business feature with a name no template package uses. */ +public record Invoice(String id) {} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/locker/Locker.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/locker/Locker.java new file mode 100644 index 00000000..786eefde --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/locker/Locker.java @@ -0,0 +1,4 @@ +package dev.caskeleton.bootstrap.architecture.fixtures.packageownership.domain.locker; + +/** A business feature with a name no template package uses. */ +public record Locker(String id) {} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/operation/Operation.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/operation/Operation.java new file mode 100644 index 00000000..d925c7bc --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/domain/operation/Operation.java @@ -0,0 +1,7 @@ +package dev.caskeleton.bootstrap.architecture.fixtures.packageownership.domain.operation; + +/** + * A business feature named after the template's {@code operation} package. Its application half + * would land in that package. + */ +public record Operation(String id) {} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/package-info.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/package-info.java new file mode 100644 index 00000000..4f162f00 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/fixtures/packageownership/package-info.java @@ -0,0 +1,7 @@ +/** + * Fixture roots for the package-ownership rules ({@code NamingConventionTest}). {@code application} + * and {@code domain} below stand in for {@code dev.caskeleton.application} and {@code + * dev.caskeleton.domain}: {@code lock} is a template package there, {@code operation} is a template + * application package name, and {@code invoice} and {@code locker} are business features. + */ +package dev.caskeleton.bootstrap.architecture.fixtures.packageownership; 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 23a1f01b..b1bf6204 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 @@ -3,6 +3,7 @@ package dev.caskeleton.bootstrap.integration.objectstorage; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageCapabilityConfig; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; import dev.caskeleton.application.objectstorage.identity.ObjectOperationEpoch; @@ -22,7 +23,6 @@ import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPor import dev.caskeleton.application.objectstorage.port.ObjectTransferPort; import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; import dev.caskeleton.application.objectstorage.request.ObjectReadRequest; -import dev.caskeleton.application.outbound.CallBudget; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java index 8778fcc6..ce5faf80 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java @@ -1,7 +1,7 @@ package dev.caskeleton.bootstrap.runtime; import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import org.springframework.beans.factory.ObjectProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceFactory.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceFactory.java index 38bd68b8..2e57bb8d 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceFactory.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceFactory.java @@ -1,7 +1,7 @@ package dev.caskeleton.bootstrap.runtime; import dev.caskeleton.adapter.outbound.support.EnvironmentSecretSource; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import org.springframework.core.env.Environment; /** diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java index a8b01557..807cda18 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java @@ -4,7 +4,7 @@ import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets; import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; import dev.caskeleton.adapter.outbound.support.startup.StartupRule; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; @@ -27,7 +27,7 @@ import org.springframework.core.env.PropertySource; * singleton is created. It builds the secret backend from the environment itself rather than taking * the {@code SecretSourcePort} bean, so running early pulls no other bean forward. */ -public class SecretSourceValidator implements StartupRule { +public final class SecretSourceValidator implements StartupRule { /** Prefix marking a dev/local fake credential; forbidden to reach the prod profile. */ static final String LOCAL_DEV_SENTINEL_PREFIX = "__LOCAL_DEV_"; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java index 79fe8729..b1f6f1c6 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java @@ -18,7 +18,7 @@ import org.springframework.core.env.Environment; * bean of that name and type declared? — is answered by the bean definitions, which are complete * before any singleton is created, so asking it then creates nothing. */ -public class StartupSafetyValidator implements StartupRule { +public final class StartupSafetyValidator implements StartupRule { /** Shipped cross-instance lock provider selected by multi-instance mode. */ static final String DISTRIBUTED_LOCK_PROVIDER_BEAN = "distributedLockProvider"; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfig.java index 9e35b47d..7be90f50 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfig.java @@ -1,34 +1,75 @@ package dev.caskeleton.bootstrap.security; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings.AuthenticationMode; import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; +import java.util.Set; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.SmartInitializingSingleton; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -/** Fails startup when JWT and Redis Session infrastructure are both present or both absent. */ +/** + * Fails startup when JWT and Redis Session infrastructure are both present or both absent. + * + *

        The mode is the web leaf's: {@link SecuritySettings} owns {@code app.security} whole and binds + * it strictly. This configuration used to bind the same prefix a second time, leniently, into a + * settings record of its own with an enum of its own — two owners of one key, and a typo under the + * prefix that neither refused (review 2026-11-01 07-10). + */ @Configuration(proxyBeanMethods = false) -@EnableConfigurationProperties(AuthenticationModeSettings.class) public class AuthenticationModeCompositionConfig { @Bean SmartInitializingSingleton authenticationModeCompositionValidator( - AuthenticationModeSettings settings, ListableBeanFactory beans) { + SecuritySettings settings, ListableBeanFactory beans) { return () -> validate(settings.authMode(), beans); } - static void validate( - AuthenticationModeSettings.AuthenticationMode mode, ListableBeanFactory beans) { + static void validate(AuthenticationMode mode, ListableBeanFactory beans) { + BeanShape shape = BeanShape.of(mode); StartupValidationContext contradictions = StartupValidationContext.forPhase(StartupPhase.ENV_VALIDATION); - for (String required : mode.requiredBeans()) { + for (String required : shape.required()) { contradictions.require(beans.containsBean(required), required + " is absent"); } - for (String forbidden : mode.forbiddenBeans()) { + for (String forbidden : shape.forbidden()) { contradictions.require(!beans.containsBean(forbidden), forbidden + " is active"); } contradictions.failIfViolated("Authentication mode composition is not exclusive for " + mode); } + + /** + * The beans a mode requires and the beans it forbids. + * + *

        The guard once decided this with an {@code if (mode == JWT) … else …}, so a third mode would + * have been validated as though it were Redis Session — a wrong answer rather than a refusal + * (BOOT-010). The switch below has no default: a third constant does not compile until it names + * its two sets. + * + *

        Bean names rather than types, because that is what the guard can ask a {@code + * ListableBeanFactory} without instantiating anything: the point is to check the shape of the + * graph, not to build it. + * + * @param required beans that must exist for the mode to authenticate a request + * @param forbidden beans that must not exist, because they would authenticate it the other way + */ + record BeanShape(Set required, Set forbidden) { + + static BeanShape of(AuthenticationMode mode) { + return switch (mode) { + // Stateless bearer tokens: a decoder, and no session infrastructure at all. + case JWT -> + new BeanShape( + Set.of("jwtDecoder"), + Set.of("redisVersionedSessionRepository", "springSessionRepositoryFilter")); + // Server-side sessions in Redis: the repository and its filter, and no decoder. + case REDIS_SESSION -> + new BeanShape( + Set.of("redisVersionedSessionRepository", "springSessionRepositoryFilter"), + Set.of("jwtDecoder")); + }; + } + } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeSettings.java deleted file mode 100644 index c02ea829..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeSettings.java +++ /dev/null @@ -1,68 +0,0 @@ -package dev.caskeleton.bootstrap.security; - -import java.util.Set; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.bind.ConstructorBinding; - -/** Composition-root authority for the exclusive application authentication mode. */ -@ConfigurationProperties(prefix = "app.security") -public record AuthenticationModeSettings(AuthenticationMode authMode) { - - @ConstructorBinding - public AuthenticationModeSettings(AuthenticationMode authMode) { - this.authMode = authMode == null ? AuthenticationMode.JWT : authMode; - } - - /** - * The exclusive authentication modes, each carrying the beans it requires and forbids. - * - *

        The composition guard used to decide this with an {@code if (mode == JWT) … else …}, so a - * third mode would have taken the {@code else} branch and been validated as though it were Redis - * Session — a wrong answer rather than a refusal (BOOT-010). Declaring the two bean sets on the - * constant means a third mode cannot be added without naming them: the abstract methods below - * make the compiler ask. - * - *

        Constant bodies rather than constructor arguments, and that is not a style preference. Error - * Prone's {@code ImmutableEnumChecker} rejects a {@code Set} field in an enum even when it holds - * {@code Set.copyOf(...)}, because it reasons about the declared type. A method has no field to - * object to, and it keeps each constant's answer next to the constant. - * - *

        Bean names rather than types, because that is what the guard can ask a {@code - * ListableBeanFactory} without instantiating anything: the point is to check the shape of the - * graph, not to build it. - */ - public enum AuthenticationMode { - - /** Stateless bearer tokens: a decoder, and no session infrastructure at all. */ - JWT { - @Override - public Set requiredBeans() { - return Set.of("jwtDecoder"); - } - - @Override - public Set forbiddenBeans() { - return Set.of("redisVersionedSessionRepository", "springSessionRepositoryFilter"); - } - }, - - /** Server-side sessions in Redis: the repository and its filter, and no decoder. */ - REDIS_SESSION { - @Override - public Set requiredBeans() { - return Set.of("redisVersionedSessionRepository", "springSessionRepositoryFilter"); - } - - @Override - public Set forbiddenBeans() { - return Set.of("jwtDecoder"); - } - }; - - /** Beans that must exist for this mode to be able to authenticate a request. */ - public abstract Set requiredBeans(); - - /** Beans that must not exist, because they would authenticate a request the other way. */ - public abstract Set forbiddenBeans(); - } -} diff --git a/src/app-bootstrap/src/main/resources/application-dev.yml b/src/app-bootstrap/src/main/resources/application-dev.yml index 3f1268e5..c3f546e2 100644 --- a/src/app-bootstrap/src/main/resources/application-dev.yml +++ b/src/app-bootstrap/src/main/resources/application-dev.yml @@ -1,22 +1,19 @@ # ============================================================================= -# dev profile — PostgreSQL, Flyway-migrated. +# dev profile — the shared non-production deployment. # -# Deliberately thin. The datasource, pool, and every other operational value stay env-driven in -# application.yml and src/.env, because a shared dev database is an operator-supplied address, not -# a value this file can know. What belongs here is the shape dev must have whatever the operator -# sets: the vendor and the schema owner. +# Deliberately empty. Every operational value stays env-driven (application.yml and src/.env), +# because a shared dev deployment's addresses and credentials are operator-supplied, not values +# this file can know. # -# Both keys below restate the repository default rather than change it, so adding this file moves -# no behaviour. That is the point — the moment dev and prod diverge from local, the difference has -# a declared home instead of being implied by whatever the environment happened to inject. +# It used to pin the JPA vendor selector to postgresql and `spring.flyway.enabled` to true. Both are +# the JPA capability module's keys, and both now ship with that module, in its +# config/module-defaults file, for every profile. Pinned here they survived the +# module's removal — a reader took them as a sign the default composition runs a database — and the +# Flyway pin outranked APP_FLYWAY_ENABLED, so the variable the env registry documents was read by +# local alone (07-08, 07-10). ProfileSeparationContractTest refuses a key here that a module outside +# the default composition ships. +# +# The file stays so the profile has a declared home: the moment dev must differ from the defaults, +# the difference goes here, in review, rather than being implied by whatever the environment +# injected. # ============================================================================= - -spring: - flyway: - # Flyway owns the schema from dev onward. Stated rather than inherited so switching a profile - # to H2 cannot silently carry a migration expectation with it. - enabled: true - -app: - persistence: - vendor: postgresql diff --git a/src/app-bootstrap/src/main/resources/application-local.yml b/src/app-bootstrap/src/main/resources/application-local.yml index f19af5bc..6520a0c5 100644 --- a/src/app-bootstrap/src/main/resources/application-local.yml +++ b/src/app-bootstrap/src/main/resources/application-local.yml @@ -16,9 +16,8 @@ # ProfileSeparationContractTest#localProfileAnswersEveryRequiredPlaceholder fails the build when # application.yml grows a required placeholder this file does not cover. # -# What local verifies: wiring, request/response behaviour, application logic. -# What it does not: migrations and vendor behaviour — the schema here comes from the JPA entities, -# and the dev/prod path is the one Flyway proves. +# What local verifies: wiring, request/response behaviour, application logic, and — with JPA +# selected — the same Flyway-owned PostgreSQL schema dev and prod run. # ============================================================================= spring: @@ -63,23 +62,14 @@ spring: connection-timeout: 30000 idle-timeout: 600000 max-lifetime: 1800000 - flyway: - # On, because the default vendor is now the same PostgreSQL dev and prod run. Flyway owns the - # schema from local onward; that is what makes a migration that disagrees with a mapping a local - # failure instead of a production one. - # - # The H2 developer task turns it off, and must: the migration tree is PostgreSQL DDL — DO $$ - # blocks and all — with nothing for Flyway to apply against H2, and with Flyway on and no vendor - # location override it falls back to classpath:db/migration and walks the PostgreSQL tree. - enabled: ${APP_FLYWAY_ENABLED:true} + # Flyway on, ddl-auto validate and the PostgreSQL vendor are not restated here: the JPA module + # ships all three for every profile (its config/module-defaults file), so local cannot mean a + # different schema owner from dev and prod (JPA-INT-003). They were here as copies of those + # defaults, and a copy is a place to disagree. The H2 developer task still turns them to H2, + # Flyway off and create-drop through APP_PERSISTENCE_VENDOR, APP_FLYWAY_ENABLED and + # APP_DATASOURCE_DDL_AUTO: the migration tree is PostgreSQL DDL, and create-drop is only safe on a + # database that dies with the process. jpa: - hibernate: - # validate, like dev and prod: Flyway owns the schema and Hibernate checks that the mapping - # agrees with it. create-drop was the H2 default and is what hid two mapping/migration - # disagreements this wave — a vendor that generates the schema from the entities cannot report - # a mismatch with them. The H2 developer task restores create-drop, which is only safe there - # because that database dies with the process. - ddl-auto: ${APP_DATASOURCE_DDL_AUTO:validate} show-sql: false open-in-view: false properties: @@ -150,11 +140,6 @@ logging: org.hibernate.SQL: WARN app: - persistence: - # PostgreSQL, like dev and prod. The claim SQL, SQLState rows and timeout guards differ per - # vendor even though the ports do not, so a local run on H2 exercised different code from the one - # that ships. The H2 developer task selects H2PersistenceConfig explicitly. - vendor: ${APP_PERSISTENCE_VENDOR:postgresql} bootstrap: app-name: ca-skeleton presentation: diff --git a/src/app-bootstrap/src/main/resources/application-prod.yml b/src/app-bootstrap/src/main/resources/application-prod.yml index 5a670b56..9401bdaa 100644 --- a/src/app-bootstrap/src/main/resources/application-prod.yml +++ b/src/app-bootstrap/src/main/resources/application-prod.yml @@ -1,32 +1,20 @@ # ============================================================================= -# prod profile — PostgreSQL, Flyway-migrated. +# prod profile. # # As thin as the dev profile, and for the same reason: production values are operator-supplied and -# live in the environment, not in a committed file. Only the shape is pinned here. +# live in the environment, not in a committed file. # -# The prod safety rules are NOT restated in this file. They are startup validators, because a -# forbidden value has to fail whether it arrives from this file, an env var, or a container -# override — a YAML default only wins against the sources that are quieter than it: +# The prod safety rules are NOT restated in this file. They are startup rules, because a forbidden +# value has to fail whether it arrives from this file, an env var, or a container override — a YAML +# default only wins against the sources that are quieter than it. The composition root's own is # -# JpaDangerousConfigurationGuard ddl-auto must be none|validate (persistence-jpa) -# FlywayProdSafetyValidator baseline-on-migrate / out-of-order / clean stay disarmed # ErrorDetailExposureSafetyValidator spring.web.error.include-* stay never/false (exit 71) -# PostgreSqlTransportSecurityValidator pgJDBC sslmode=verify-full -# PersistenceVendorProdSafetyValidator neither the vendor selector nor the URL may be H2 # -# The vendor pin below is therefore the readable statement of intent, not the enforcement: an env -# var outranks this file, so overriding it to h2 fails at startup rather than booting an in-memory -# database that loses every write on restart. +# and each capability ships its own beside its build line, so they leave together. The vendor and +# Flyway pins that stood here belong to such a module and moved into it (07-08); see the dev +# profile's header. # ============================================================================= -spring: - flyway: - enabled: true - -app: - persistence: - vendor: postgresql - # The API description and its browser are off under prod, and not by way of a placeholder: an # environment variable that could turn them back on is the same as not having decided. A prod # deployment that genuinely wants them changes this file, visibly, in review. diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStorageOverlayContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStorageOverlayContractTest.java new file mode 100644 index 00000000..62d45bdd --- /dev/null +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStorageOverlayContractTest.java @@ -0,0 +1,198 @@ +package dev.caskeleton.bootstrap.contract; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Pattern; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; + +/** + * The default image and the default Compose file carry no optional capability, and the one + * capability that keeps files on disk brings its volume in its own overlay (07-08, capability + * criterion 7: the only place that knows a module is the module). + * + *

        The default image used to create the fileserver storage directory and declare it a {@code + * VOLUME}, and {@code docker-compose.yml} mounted a {@code fileserver-data} volume into every + * container — in a composition that has no fileserver module at all. A reader took the volume as a + * sign the capability was on, and every plain {@code docker run} created an anonymous volume nobody + * wrote to. The volume now lives in {@code infra/fileserver/compose/docker-compose.fileserver.yml}, + * beside the rest of the capability's infrastructure, which a lane or a developer adds with the + * capability. Its ownership is set by a one-shot that runs as root in the application's own image, + * so a fresh volume, a reused one and a bind mount all end up owned by the account the application + * runs as. + */ +@Tag("repository-contract") +class CapabilityStorageOverlayContractTest { + + private static final Path REPOSITORY_ROOT = + RepositoryContractResources.fromSystemProperty().repositoryRoot(); + + private static final String OVERLAY = "infra/fileserver/compose/docker-compose.fileserver.yml"; + private static final String OVERLAY_KEY = "fileserver"; + private static final String STORAGE_INIT = "fileserver-storage-init"; + private static final String STORAGE_ROOT = "/var/lib/backend/files"; + private static final String VOLUME = "fileserver-data"; + + /** The capability names 07-08's completion criterion greps for. */ + private static final Pattern CAPABILITY_NAME = + Pattern.compile("fileserver|notification|operation|persistence"); + + @Test + @DisplayName("기본 Dockerfile과 기본 compose는 선택 capability 이름을 담지 않는다") + void theDefaultImageAndComposeNameNoOptionalCapability() throws IOException { + // given + List defaultContainerFiles = List.of("src/Dockerfile", "docker-compose.yml"); + + // when + List mentions = new ArrayList<>(); + for (String file : defaultContainerFiles) { + List lines = read(file).lines().toList(); + for (int index = 0; index < lines.size(); index++) { + if (CAPABILITY_NAME.matcher(lines.get(index).toLowerCase(Locale.ROOT)).find()) { + mentions.add(file + ":" + (index + 1) + ": " + lines.get(index).strip()); + } + } + } + + // then + assertThat(mentions).isEmpty(); + } + + @Test + @DisplayName("기본 이미지는 VOLUME을 선언하지 않는다 — 선언하면 모든 컨테이너가 익명 볼륨을 만든다") + void theDefaultImageDeclaresNoVolume() throws IOException { + // when + List volumes = + read("src/Dockerfile").lines().filter(line -> line.startsWith("VOLUME")).toList(); + + // then + assertThat(volumes).isEmpty(); + } + + @Test + void theFileserverOverlayMountsItsVolumeAtTheModulesDefaultStorageRoot() throws IOException { + // given + Map overlay = yaml(read(OVERLAY)); + + // when + Map app = map(map(overlay, "services"), "app"); + + // then + assertThat(list(app, "volumes")).containsExactly(VOLUME + ":" + STORAGE_ROOT); + assertThat(map(app, "environment").get("APP_FILESERVER_PLATFORM_STORAGE_ROOT")) + .as("the mount and the root the module writes to must name one path") + .isEqualTo(STORAGE_ROOT); + assertThat(keys(map(overlay, "volumes"))).contains(VOLUME); + assertThat( + read( + "src/composition/fileserver-platform/src/main/resources/" + + "config/module-defaults/fileserver.yml")) + .as("the overlay mounts where the module writes when nobody overrides the root") + .contains("${APP_FILESERVER_PLATFORM_STORAGE_ROOT:" + STORAGE_ROOT + "}"); + } + + /** + * Docker seeds a fresh named volume from the image directory at the mount point, but only when + * that directory exists in the image — and the default image no longer has it. A reused volume or + * a bind mount keeps whatever owner it had. Either way the application, which runs as a non-root + * account, would be refused every write; the module's storage probe then stops startup with + * "storage root is not writable". The one-shot fixes the owner each time, as root, in the + * application's own image, naming the account rather than a number the image could change. + */ + @Test + @DisplayName("fileserver 볼륨 소유자는 앱 이미지 안에서 root로 도는 one-shot이 앱 계정으로 맞춘다") + void theFileserverVolumeIsHandedToTheApplicationAccountBeforeTheApplicationStarts() + throws IOException { + // given + Map base = yaml(read("docker-compose.yml")); + Map overlay = yaml(read(OVERLAY)); + + // when + Map init = map(map(overlay, "services"), STORAGE_INIT); + + // then + assertThat(init.get("image")) + .as("the application's own image, so the account it chowns to is the one the app runs as") + .isEqualTo(map(map(base, "services"), "app").get("image")); + assertThat(init.get("pull_policy")) + .as("the image is built by the app service, never pulled") + .isEqualTo("never"); + assertThat(init.get("user")).isEqualTo("0:0"); + assertThat(String.join(" ", list(init, "entrypoint"))) + .contains("chown app:app " + STORAGE_ROOT) + .contains("chmod 0750 " + STORAGE_ROOT); + assertThat(list(init, "volumes")).containsExactly(VOLUME + ":" + STORAGE_ROOT); + assertThat( + map(map(map(map(overlay, "services"), "app"), "depends_on"), STORAGE_INIT) + .get("condition")) + .isEqualTo("service_completed_successfully"); + } + + @Test + @DisplayName("fileserver를 켜는 lane만, 그리고 모두 fileserver overlay와 소유권 one-shot을 쓴다") + void exactlyTheLanesThatSwitchTheFileserverOnBringItsOverlay() throws IOException { + // given + Map contracts = yaml(read("src/config/runtime/compose-profile-contracts.json")); + + // when + List mismatched = new ArrayList<>(); + for (Object item : (List) contracts.get("lanes")) { + Map lane = (Map) item; + boolean switchedOn = + "true".equals(map(lane, "activationEnv").get("APP_FILESERVER_PLATFORM_ENABLED")); + boolean overlaid = list(lane, "files").contains(OVERLAY_KEY); + boolean initialised = + lane.get("preStartServices") instanceof List preStart + && preStart.contains(STORAGE_INIT) + && list(lane, "services").contains(STORAGE_INIT); + if (switchedOn != overlaid || switchedOn != initialised) { + mismatched.add(lane.get("id") + " (on=" + switchedOn + ", overlay=" + overlaid + ")"); + } + } + + // then + assertThat(map(contracts, "composeFiles").get(OVERLAY_KEY)).isEqualTo(OVERLAY); + assertThat(list(contracts, "preStartServices")).contains(STORAGE_INIT); + assertThat(mismatched).isEmpty(); + } + + private static String read(String relative) throws IOException { + return Files.readString(REPOSITORY_ROOT.resolve(relative)); + } + + private static Map yaml(String source) { + LoaderOptions options = new LoaderOptions(); + options.setAllowDuplicateKeys(false); + Object loaded = new Yaml(new SafeConstructor(options)).load(source); + assertThat(loaded).isInstanceOf(Map.class); + return (Map) loaded; + } + + private static Map map(Map owner, String key) { + Object value = owner.get(key); + assertThat(value).as("%s must be a mapping", key).isInstanceOf(Map.class); + return (Map) value; + } + + private static List keys(Map owner) { + return owner.keySet().stream().map(String::valueOf).toList(); + } + + private static List list(Map owner, String key) { + Object value = owner.get(key); + assertThat(value).as("%s must be a list", key).isInstanceOf(List.class); + return ((List) value).stream().map(String::valueOf).toList(); + } +} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java index 3280dc8f..3296ca77 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java @@ -16,11 +16,19 @@ import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Stream; import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.EnumerablePropertySource; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.mock.env.MockEnvironment; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; @@ -45,7 +53,8 @@ import org.yaml.snakeyaml.constructor.SafeConstructor; class ProfileSeparationContractTest { private static final Path REPOSITORY_ROOT = repositoryRoot(); - private static final String VENDOR_KEY = "vendor"; + private static final String VENDOR_PROPERTY = "app.persistence.vendor"; + private static final String FLYWAY_ENABLED_PROPERTY = "spring.flyway.enabled"; /** * local defaults to an in-memory database, and defaults is now the operative word. @@ -67,17 +76,45 @@ class ProfileSeparationContractTest { */ @Test void localDefaultsToTheShippedVendorRatherThanAnEntityGeneratedSchema() throws IOException { - Map local = profile("local"); + // given + MockEnvironment local = resolved("local", Map.of()); - assertThat(vendorOf(local)) - .as("the same vendor dev and prod run, and a default rather than a pin") - .isEqualTo("${APP_PERSISTENCE_VENDOR:postgresql}"); - assertThat(datasourceUrlOf(local)) + // when + String vendor = local.getProperty(VENDOR_PROPERTY); + + // then + assertThat(vendor).as("the same vendor dev and prod run").isEqualTo("postgresql"); + assertThat(local.getProperty(FLYWAY_ENABLED_PROPERTY)) + .as("Flyway owns the schema from local onward, which is what makes a disagreement local") + .isEqualTo("true"); + assertThat(datasourceUrlOf(profile("local"))) .as("the Compose PostgreSQL, on its published port") .startsWith("${APP_DATASOURCE_URL:jdbc:postgresql://"); - assertThat(rawFlywayEnabledOf(local)) - .as("Flyway owns the schema from local onward, which is what makes a disagreement local") - .isEqualTo("${APP_FLYWAY_ENABLED:true}"); + } + + /** + * local no longer restates the vendor, the Flyway switch or ddl-auto; it takes all three from the + * JPA module's defaults. The H2 developer task reaches them through the same three variables it + * always set, which is what this pins: a default that stopped reading its variable would put the + * task back on PostgreSQL with Flyway walking a tree H2 cannot run. + */ + @Test + @DisplayName("bootRunH2가 주는 세 변수는 local에서 모듈 기본값을 거쳐 H2·Flyway 끔·create-drop이 된다") + void theH2DeveloperTaskStillSelectsH2ThroughTheModuleDefaults() throws IOException { + // given + Map h2Task = + Map.of( + "APP_PERSISTENCE_VENDOR", "h2", + "APP_FLYWAY_ENABLED", "false", + "APP_DATASOURCE_DDL_AUTO", "create-drop"); + + // when + MockEnvironment local = resolved("local", h2Task); + + // then + assertThat(local.getProperty(VENDOR_PROPERTY)).isEqualTo("h2"); + assertThat(local.getProperty(FLYWAY_ENABLED_PROPERTY)).isEqualTo("false"); + assertThat(local.getProperty("spring.jpa.hibernate.ddl-auto")).isEqualTo("create-drop"); } @Test @@ -93,13 +130,72 @@ class ProfileSeparationContractTest { .contains("DB_CLOSE_DELAY=-1"); } + /** + * dev and prod still run PostgreSQL with Flyway owning the schema. What changed is who says so: + * the persistence-jpa module's own defaults, which arrive with its build line and leave with it, + * rather than a pin in the composition root's profile files that outlived the module (07-08). + */ @ParameterizedTest @ValueSource(strings = {"dev", "prod"}) void deployedProfilesRunPostgreSqlWithFlyway(String profile) throws IOException { - Map configuration = profile(profile); + // given + MockEnvironment configuration = resolved(profile, Map.of()); - assertThat(vendorOf(configuration)).isEqualTo("postgresql"); - assertThat(flywayEnabledOf(configuration)).isEqualTo(true); + // when + String vendor = configuration.getProperty(VENDOR_PROPERTY); + + // then + assertThat(vendor).isEqualTo("postgresql"); + assertThat(configuration.getProperty(FLYWAY_ENABLED_PROPERTY)).isEqualTo("true"); + } + + /** + * The env-key registry promises that {@code APP_FLYWAY_ENABLED} sets {@code + * spring.flyway.enabled}. dev and prod pinned the literal {@code true} over it, so the variable + * the Compose lanes inject for those runtimes was read by nothing, and an operator who set it + * believed a value that was never applied (07-10). One placeholder in the module that owns the + * key now answers it in every profile. + */ + @ParameterizedTest + @ValueSource(strings = {"local", "dev", "prod"}) + @DisplayName("APP_FLYWAY_ENABLED는 모든 프로필에서 spring.flyway.enabled를 정한다") + void theFlywaySwitchReachesEveryProfile(String profile) throws IOException { + // given + MockEnvironment configuration = resolved(profile, Map.of("APP_FLYWAY_ENABLED", "false")); + + // when + String flywayEnabled = configuration.getProperty(FLYWAY_ENABLED_PROPERTY); + + // then + assertThat(flywayEnabled).isEqualTo("false"); + } + + /** + * The composition root ships no capability (capability criterion 7: only the module knows + * itself). A key that a module outside the default composition ships, restated in dev or prod, + * survives the module's removal and tells the reader that the capability is on (07-08). The + * modules are the ones {@code capabilityProjects} in app-bootstrap's build script names; their + * keys are whatever their {@code config/**} files ship. + */ + @ParameterizedTest + @ValueSource(strings = {"dev", "prod"}) + @DisplayName("dev·prod 프로필 파일은 기본 조립에 없는 capability가 싣는 키를 다시 쓰지 않는다") + void deployedProfilesRestateNoKeyAnUnselectedCapabilityShips(String profile) throws IOException { + // given + Map capabilityKeys = keysShippedByUnselectedCapabilities(); + + // when + List restated = + propertyNames("application-" + profile + ".yml").stream() + .filter(capabilityKeys::containsKey) + .map(key -> key + " (shipped by " + capabilityKeys.get(key) + ")") + .toList(); + + // then + assertThat(capabilityKeys) + .as("a scan that found no capability key proves nothing") + .isNotEmpty(); + assertThat(restated).isEmpty(); } @ParameterizedTest @@ -127,7 +223,7 @@ class ProfileSeparationContractTest { private static String vendorOf(Map configuration) { Map persistence = child(child(configuration, "app"), "persistence"); - Object vendor = persistence == null ? null : persistence.get(VENDOR_KEY); + Object vendor = persistence == null ? null : persistence.get("vendor"); return vendor == null ? null : vendor.toString(); } @@ -137,27 +233,6 @@ class ProfileSeparationContractTest { return url == null ? null : url.toString(); } - /** - * The raw {@code spring.flyway.enabled} value, placeholder or literal. - * - *

        {@link #flywayEnabledOf} answers null for a placeholder, which reads as "absent" and is not - * the same claim as "declared as an overridable default". - * - * @param configuration the parsed profile document - * @return the value as written, or null when the key is absent - */ - private static String rawFlywayEnabledOf(Map configuration) { - Map flyway = child(child(configuration, "spring"), "flyway"); - Object enabled = flyway == null ? null : flyway.get("enabled"); - return enabled == null ? null : enabled.toString(); - } - - private static Boolean flywayEnabledOf(Map configuration) { - Map flyway = child(child(configuration, "spring"), "flyway"); - Object enabled = flyway == null ? null : flyway.get("enabled"); - return enabled instanceof Boolean value ? value : null; - } - private static Map child(Map owner, String key) { if (owner == null) { return null; @@ -166,6 +241,93 @@ class ProfileSeparationContractTest { return value instanceof Map map ? map : null; } + /** + * A profile as Spring resolves it: the shipped configuration (application.yml, its imports and + * the module defaults on this classpath, which carries persistence-jpa) at the bottom, the + * profile file above it, and the given environment variables on top. + */ + private static MockEnvironment resolved(String profile, Map variables) + throws IOException { + MockEnvironment environment = new MockEnvironment(); + ShippedConfiguration.propertySources().forEach(environment.getPropertySources()::addLast); + for (PropertySource source : profileSources("application-" + profile + ".yml")) { + environment.getPropertySources().addFirst(source); + } + environment.getPropertySources().addFirst(new MapPropertySource("variables", variables)); + return environment; + } + + private static List> profileSources(String resource) throws IOException { + Path file = REPOSITORY_ROOT.resolve("src/app-bootstrap/src/main/resources").resolve(resource); + return new YamlPropertySourceLoader().load(resource, new FileSystemResource(file)); + } + + private static List propertyNames(String resource) throws IOException { + List names = new ArrayList<>(); + for (PropertySource source : profileSources(resource)) { + if (source instanceof EnumerablePropertySource enumerable) { + names.addAll(List.of(enumerable.getPropertyNames())); + } + } + return names; + } + + /** Key → the file that ships it, for every module {@code capabilityProjects} names. */ + private static Map keysShippedByUnselectedCapabilities() throws IOException { + String buildScript = + Files.readString(REPOSITORY_ROOT.resolve("src/app-bootstrap/build.gradle")); + Matcher block = + Pattern.compile("def capabilityProjects = \\[(.*?)]", Pattern.DOTALL).matcher(buildScript); + assertThat(block.find()) + .as("app-bootstrap/build.gradle must keep its capabilityProjects list") + .isTrue(); + List gradlePaths = + Pattern.compile("'(:[^']+)'") + .matcher(block.group(1)) + .results() + .map(m -> m.group(1)) + .toList(); + + Map sourcePathByGradlePath = new LinkedHashMap<>(); + Map registry = + (Map) + new Yaml(new SafeConstructor(new LoaderOptions())) + .load( + Files.readString( + REPOSITORY_ROOT.resolve("src/config/architecture/modules.json"))); + for (Object module : (List) registry.get("modules")) { + Map entry = (Map) module; + sourcePathByGradlePath.put( + String.valueOf(entry.get("gradle_path")), String.valueOf(entry.get("source_path"))); + } + + Map owner = new LinkedHashMap<>(); + for (String gradlePath : gradlePaths) { + String sourcePath = sourcePathByGradlePath.get(gradlePath); + assertThat(sourcePath).as("%s must be a registered leaf", gradlePath).isNotNull(); + Path config = REPOSITORY_ROOT.resolve(sourcePath).resolve("src/main/resources/config"); + if (!Files.isDirectory(config)) { + continue; + } + List files; + try (Stream walk = Files.walk(config)) { + files = walk.filter(path -> path.toString().endsWith(".yml")).sorted().toList(); + } + for (Path file : files) { + String name = REPOSITORY_ROOT.relativize(file).toString(); + for (PropertySource source : + new YamlPropertySourceLoader().load(name, new FileSystemResource(file))) { + if (source instanceof EnumerablePropertySource enumerable) { + for (String key : enumerable.getPropertyNames()) { + owner.putIfAbsent(key, name); + } + } + } + } + } + return owner; + } + private static Map yaml(String resource) throws IOException { String source = Files.readString( @@ -174,6 +336,10 @@ class ProfileSeparationContractTest { options.setAllowDuplicateKeys(false); // The base file is placeholder-driven; resolving is Spring's job, parsing is all this needs. Object loaded = new Yaml(new SafeConstructor(options)).load(source); + if (loaded == null) { + // A profile file holding only its header, as dev does: Spring reads it as no properties. + return Map.of(); + } assertThat(loaded).as("%s must parse as a YAML mapping", resource).isInstanceOf(Map.class); return (Map) loaded; } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceTest.java index 13978e18..45cf178c 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.bootstrap.runtime; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.support.EnvironmentSecretSource; -import dev.caskeleton.application.outbound.SecretSourcePort; +import dev.caskeleton.application.secret.SecretSourcePort; import org.junit.jupiter.api.Test; import org.springframework.mock.env.MockEnvironment; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfigTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfigTest.java index bba492f7..afdaabb5 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfigTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfigTest.java @@ -2,9 +2,17 @@ package dev.caskeleton.bootstrap.security; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings.AuthenticationMode; +import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +/** + * The composition root's exclusivity check reads the mode from the web leaf's {@link + * SecuritySettings}, the one owner of {@code app.security}. + */ class AuthenticationModeCompositionConfigTest { private final ApplicationContextRunner runner = @@ -12,48 +20,91 @@ class AuthenticationModeCompositionConfigTest { .withUserConfiguration(AuthenticationModeCompositionConfig.class); @Test - void jwtModeRequiresOnlyJwtInfrastructure() { - runner - .withBean("jwtDecoder", Object.class, Object::new) - .withPropertyValues("app.security.auth-mode=jwt") - .run(context -> assertThat(context).hasNotFailed()); + @DisplayName("JWT 모드는 jwtDecoder만 있으면 기동한다") + void aJwtModeWithOnlyTheDecoderStarts() { + // given + var jwtOnly = + runner + .withBean(SecuritySettings.class, () -> settings(AuthenticationMode.JWT)) + .withBean("jwtDecoder", Object.class, Object::new); - runner - .withBean("jwtDecoder", Object.class, Object::new) - .withBean("redisVersionedSessionRepository", Object.class, Object::new) - .withPropertyValues("app.security.auth-mode=jwt") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasMessage( - // Names the bean, not a phrase: an operator can grep the composition for - // "redisVersionedSessionRepository" and find what registered it. - "Authentication mode composition is not exclusive for JWT: " - + "redisVersionedSessionRepository is active"); - }); + // when + jwtOnly.run( + context -> + // then + assertThat(context).hasNotFailed()); } @Test - void redisSessionModeRequiresCompleteSessionInfrastructureAndNoJwtDecoder() { - runner - .withBean("redisVersionedSessionRepository", Object.class, Object::new) - .withBean("springSessionRepositoryFilter", Object.class, Object::new) - .withPropertyValues("app.security.auth-mode=redis-session") - .run(context -> assertThat(context).hasNotFailed()); + @DisplayName("JWT 모드에 Redis session 저장소가 함께 있으면 그 bean 이름을 담아 기동을 거부한다") + void aJwtModeWithASessionRepositoryFailsStartupNamingIt() { + // given + var mixed = + runner + .withBean(SecuritySettings.class, () -> settings(AuthenticationMode.JWT)) + .withBean("jwtDecoder", Object.class, Object::new) + .withBean("redisVersionedSessionRepository", Object.class, Object::new); - runner - .withBean("jwtDecoder", Object.class, Object::new) - .withBean("redisVersionedSessionRepository", Object.class, Object::new) - .withPropertyValues("app.security.auth-mode=redis-session") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasMessage( - "Authentication mode composition is not exclusive for REDIS_SESSION: " - + "springSessionRepositoryFilter is absent; " - + "jwtDecoder is active"); - }); + // when + mixed.run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasMessage( + // Names the bean, not a phrase: an operator can grep the composition for + // "redisVersionedSessionRepository" and find what registered it. + "Authentication mode composition is not exclusive for JWT: " + + "redisVersionedSessionRepository is active"); + }); + } + + @Test + @DisplayName("Redis session 모드는 저장소와 필터가 모두 있고 jwtDecoder가 없으면 기동한다") + void aRedisSessionModeWithTheCompleteSessionInfrastructureStarts() { + // given + var sessions = + runner + .withBean(SecuritySettings.class, () -> settings(AuthenticationMode.REDIS_SESSION)) + .withBean("redisVersionedSessionRepository", Object.class, Object::new) + .withBean("springSessionRepositoryFilter", Object.class, Object::new); + + // when + sessions.run( + context -> + // then + assertThat(context).hasNotFailed()); + } + + @Test + @DisplayName("Redis session 모드에 필터가 없고 jwtDecoder가 있으면 둘 다 담아 기동을 거부한다") + void aRedisSessionModeMissingTheFilterWithADecoderFailsStartupNamingBoth() { + // given + var mixed = + runner + .withBean(SecuritySettings.class, () -> settings(AuthenticationMode.REDIS_SESSION)) + .withBean("jwtDecoder", Object.class, Object::new) + .withBean("redisVersionedSessionRepository", Object.class, Object::new); + + // when + mixed.run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasMessage( + "Authentication mode composition is not exclusive for REDIS_SESSION: " + + "springSessionRepositoryFilter is absent; " + + "jwtDecoder is active"); + }); + } + + private static SecuritySettings settings(AuthenticationMode mode) { + return new SecuritySettings( + mode, + "http://localhost:8081/realms/ca-skeleton", + List.of("ca-skeleton-api"), + List.of(), + null); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/BootstrapRolePermissionOwnershipTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/BootstrapRolePermissionOwnershipTest.java new file mode 100644 index 00000000..95eb1bec --- /dev/null +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/security/BootstrapRolePermissionOwnershipTest.java @@ -0,0 +1,61 @@ +package dev.caskeleton.bootstrap.security; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.EnumerablePropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.ClassPathResource; + +/** + * The bootstrap does not know a capability's permission names (review 05-19). + * + *

        Notification and fileserver role mappings used to live in this module's {@code + * config/security.yml}, so removing a capability's build line left its permissions mapped and + * adding one meant editing the bootstrap. Each capability now ships its {@code + * app.authz.role-permissions} entries in its own {@code config/module-defaults} file (asserted in + * that module's tests); this holds the other half: no file the bootstrap ships maps a role to a + * permission. + */ +class BootstrapRolePermissionOwnershipTest { + + private static final String ROLE_PERMISSIONS = "app.authz.role-permissions"; + + private static final List BOOTSTRAP_CONFIGURATION = + List.of( + "application.yml", + "application-local.yml", + "application-dev.yml", + "application-prod.yml", + "config/observability.yml", + "config/runtime.yml", + "config/security.yml", + "config/server.yml"); + + @Test + @DisplayName("bootstrap이 싣는 설정 파일 어디에도 역할→권한 매핑이 없다") + void noBootstrapConfigurationFileMapsARoleToAPermission() throws IOException { + // given + List mapped = new ArrayList<>(); + + // when + for (String resource : BOOTSTRAP_CONFIGURATION) { + for (PropertySource source : + new YamlPropertySourceLoader().load(resource, new ClassPathResource(resource))) { + Arrays.stream(((EnumerablePropertySource) source).getPropertyNames()) + .filter(name -> name.startsWith(ROLE_PERMISSIONS)) + .map(name -> resource + ": " + name) + .forEach(mapped::add); + } + } + + // then + assertThat(mapped).isEmpty(); + } +} diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index 50b3353e..917d0a4b 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -61,7 +61,7 @@ Package root: `dev.caskeleton.application`. | `command.Command` | Marker for write intents. Plain immutable types built from domain values. | | `query.Query` | Marker for read intents. Plain immutable types built from domain values. | | `transaction.TransactionPort` | Outbound port for join-capable write/read, physical root-only write, and independent write boundaries. Implemented by `adapter-persistence`. | -| `outbound.SecretSourcePort` | Framework-free outbound secret-resolution seam. Deployment selects a backend in app-bootstrap; concrete environment/cloud/vault readers belong to outbound adapter leaves. | +| `secret.SecretSourcePort` | Framework-free outbound secret-resolution seam. Deployment selects a backend in app-bootstrap; concrete environment/cloud/vault readers belong to outbound adapter leaves. | | `transaction.NestedRootTransactionRejectedException` | Fail-fast signal raised before action/provider side effects when `inRootWrite` detects an actual ambient transaction. | | `transaction.TransactionMode` | `WRITE` / `READ_ONLY` / `REQUIRES_NEW`. `NESTED` and `NEVER` are intentionally absent. | | `transaction.Isolation` | `READ_COMMITTED` (pinned default) / `REPEATABLE_READ` / `SERIALIZABLE`. `READ_UNCOMMITTED` is forbidden (not declared); the vendor default is never used (engine defaults differ — PostgreSQL READ COMMITTED vs MySQL InnoDB REPEATABLE READ). Routing the stricter levels through `TransactionPort` is a `planned` joint change with `feature-application-port-usecase-contract`; the shipped call path pins `READ_COMMITTED`. | @@ -105,6 +105,66 @@ The one-line rule for stores: **if the domain would recognise the thing it store `Repository` in the domain; if it is plumbing the application needs, it is a `StorePort` in the application.** +## Package ownership + +This section is the rule book for **which packages the template owns** and where a business feature +goes. `docs/manual/03-placement.md` points here. + +- A business feature is `dev.caskeleton.application.` (and `dev.caskeleton.domain.`, + `...adapter.inbound.web.`, `...bootstrap.autoconfigure.`): one package per feature + directly under each root, no `command`/`usecase`/`port` sub-packages. +- `` is **not** one of the template package names below. A feature beside a template + package of the same name lands in the same package tree, and every upstream template update merges + into it. +- Template packages never import a feature package. Business code does not go into a template + package, even when the name fits. +- Everything under the two roots that is not listed here is a feature. A derived service adds + features without editing this list; the template edits it when it adds, renames or removes one of + its own packages. + +| Package (`dev.caskeleton.application.*`) | Owning leaf | Holds | +|---|---|---| +| `usecase`, `command`, `query` | application-core | inbound port base types and the command/query markers | +| `capability` | application-core | `@UseCaseCapability` and its enums | +| `transaction` | application-core | `TransactionPort` and its modes | +| `security` | application-core | authorization port, `@RequiresPermission`, `@SystemInvoked`, `ObjectAccessPolicy` | +| `tenant` | application-core | `TenantId` | +| `observability` | application-core | `CorrelationIdPort`, `UserPrincipalPseudonymizerPort` | +| `secret` | application-core | `SecretSourcePort`, `SecretReference` | +| `messaging` | application-core | the integration-event semantic contract | +| `outbox` | application-core | transactional outbox append and relay | +| `idempotency` | application-core | keyed idempotency executor and store port | +| `operation` | application-core | durable (long-running) operations | +| `lease`, `lock` | application-core | distributed lease and lock ports | +| `cache` | application-core | cache region port | +| `realtime` | application-core | live event replay port | +| `notification` | application-notification | notification capability | +| `fileserver` | application-fileserver | file server capability | +| `objectstorage` | application-objectstorage | object storage capability (its `content.CallBudget` is the call deadline it carries) | + +| Package (`dev.caskeleton.domain.*`) | Owning leaf | Holds | +|---|---|---| +| `identifier` | domain-core | `ResourceId`, `IdFactory` | +| `stereotype` | domain-core | `@AggregateRoot`, `@DomainEvent`, `@ValueObject` | + +Enforcement: + +- `scripts/new-feature.sh` refuses a feature name that is already a package under any of the five + roots, in any leaf — every template package included. +- `NamingConventionTest.FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`: a feature package + under either root does not take a name from these tables. Every feature has a domain package, so a + feature named `operation` is caught at `dev.caskeleton.domain.operation`. +- `NamingConventionTest.TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`: a feature class written + into a template package keeps the template's name but imports its own domain, and that import is + what fails. +- The machine copy of these tables is `TemplatePackageOwnership` (app-bootstrap `architectureTest`). + `TemplatePackageOwnershipRuleTest` fails when it names a package that no longer exists; a new + template package joins both the tables and that class in the same change. +- Rejected alternatives: allowing only the listed top-level packages (every derived feature would + have to edit the template's list — a merge conflict per feature), and a separate + `application-platform` leaf for the platform packages (review 2026-11-01 01-10 (b): clearer + boundary, but more registry edges than a naming rule needs). + ## Canonical use case shape ```java diff --git a/src/application-core/README.md b/src/application-core/README.md index 43580f40..a11b353b 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -600,3 +600,15 @@ R1 오케스트레이션 타입(`dev.caskeleton.application.notification` 직속 유일 인덱스가 append 시점에 거부한다. - aggregate가 자체 version 열(낙관적 락)을 가지면 그 값을 써도 된다. 이 포트는 counter가 없는 aggregate를 위한 것이다. + +--- + +## 비밀 값 해석 (secret) + +- `SecretSourcePort`와 `SecretReference`(`secret:///` 한 가지 표기)를 둔다. 예전에는 + `CallBudget`과 함께 `outbound` 패키지에 묶여 있었다. 세 타입은 서로 관계가 없고 `outbound`는 + 내용이 아니라 방향을 말하는 이름이라, 2026-11-01 리뷰 01-10에서 내용별로 흩었다. +- `CallBudget`은 쓰는 곳이 object storage 계약(요청 record와 content 콜백 context)뿐이라 + `application-objectstorage`의 `objectstorage.content`로, 항상 함께 다니는 `CancellationView` 옆에 + 옮겼다. 다른 전송(HTTP client·gRPC·GraphQL)은 각자의 deadline 타입을 쓴다. +- 포트 계약 `secret.testkit.SecretSourceContract`, fake `InMemorySecretSource`(testFixtures). diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java index 0b7f5f9b..cb7060e0 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java @@ -40,7 +40,7 @@ import java.util.function.Supplier; idempotency = Idempotency.IDEMPOTENT, repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, externalOutboundAllowed = true) -public class PublishPendingOutboxEventsUseCase +public final class PublishPendingOutboxEventsUseCase implements CommandUseCase { private final OutboxStorePort store; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbound/SecretReference.java b/src/application-core/src/main/java/dev/caskeleton/application/secret/SecretReference.java similarity index 97% rename from src/application-core/src/main/java/dev/caskeleton/application/outbound/SecretReference.java rename to src/application-core/src/main/java/dev/caskeleton/application/secret/SecretReference.java index e95cc83b..e030a25b 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbound/SecretReference.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/secret/SecretReference.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.outbound; +package dev.caskeleton.application.secret; import java.util.Objects; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbound/SecretSourcePort.java b/src/application-core/src/main/java/dev/caskeleton/application/secret/SecretSourcePort.java similarity index 93% rename from src/application-core/src/main/java/dev/caskeleton/application/outbound/SecretSourcePort.java rename to src/application-core/src/main/java/dev/caskeleton/application/secret/SecretSourcePort.java index 151d19d0..fbd52462 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbound/SecretSourcePort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/secret/SecretSourcePort.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.outbound; +package dev.caskeleton.application.secret; import java.util.Optional; diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisherContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisherContractTest.java new file mode 100644 index 00000000..2945ac69 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisherContractTest.java @@ -0,0 +1,26 @@ +package dev.caskeleton.application.messaging.event.testkit; + +import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import java.util.List; + +class FakeIntegrationEventPublisherContractTest extends IntegrationEventPublishContract { + + private FakeIntegrationEventPublisher fake; + + @Override + protected IntegrationEventPublishPort publisherOverABrokerThat(BrokerAnswer answer) { + fake = + new FakeIntegrationEventPublisher() + .answering(FakeIntegrationEventPublisher.outcomeOf(answer)); + return fake; + } + + @Override + protected List eventIdsTheBrokerReceived() { + return fake.published().stream() + .map(ValidatedIntegrationEvent::eventId) + .map(id -> id.value()) + .toList(); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/observability/testkit/FixedCorrelationIdContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/observability/testkit/FixedCorrelationIdContractTest.java new file mode 100644 index 00000000..b9d27ad5 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/observability/testkit/FixedCorrelationIdContractTest.java @@ -0,0 +1,12 @@ +package dev.caskeleton.application.observability.testkit; + +import dev.caskeleton.application.observability.CorrelationIdPort; + +/** The in-memory fake keeps the correlation id contract. */ +class FixedCorrelationIdContractTest extends CorrelationIdContract { + + @Override + protected CorrelationIdPort portCarrying(String correlationId) { + return FixedCorrelationId.of(correlationId); + } +} 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 30a4f32d..d26132f1 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 @@ -7,17 +7,15 @@ import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore; -import dev.caskeleton.application.outbox.OutboxAppendPort; -import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import dev.caskeleton.application.usecase.CommandUseCase; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; -import java.util.ArrayList; import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Supplier; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -34,11 +32,13 @@ class SubmitDurableOperationUseCaseTest { private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); private static final DurableOperationId ID = new DurableOperationId("op-1"); - private final InMemoryDurableOperationStore operations = new InMemoryDurableOperationStore(); - private final AtomicBoolean insideTransaction = new AtomicBoolean(); - private final RecordingOutbox outbox = new RecordingOutbox(insideTransaction); - private final RollbackAwareTransactions transactions = - new RollbackAwareTransactions(operations, outbox, insideTransaction); + // Both stores join the in-memory port's transactions and undo their writes when one rolls back, + // as the database does. A port that simply ran the action would let rollbackLeavesNothing pass + // for an implementation with no transaction at all — the exact defect that test is looking for. + private final DirectTransactionPort transactions = new DirectTransactionPort(); + private final InMemoryDurableOperationStore operations = + new InMemoryDurableOperationStore(transactions); + private final FailingOutbox outbox = new FailingOutbox(transactions); private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder(new DurableOperationSubmittedContract()); private final CommandUseCase useCase = @@ -64,7 +64,7 @@ class SubmitDurableOperationUseCaseTest { assertThat(acceptance.operationId()).isEqualTo(ID); assertThat(acceptance.alreadyAccepted()).isFalse(); assertThat(operations.size()).isEqualTo(1); - assertThat(outbox.appended).hasSize(1); + assertThat(outbox.appended()).hasSize(1); } @Test @@ -73,10 +73,11 @@ class SubmitDurableOperationUseCaseTest { 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. - assertThat(outbox.appendedOutsideTransaction).isEmpty(); - assertThat(transactions.independentCommits).isEmpty(); - assertThat(transactions.writeTransactions).isEqualTo(1); + // independently, and every failure mode this use case exists to prevent comes back. The + // outbox refuses an append outside a write transaction, so reaching here means it had one; + // exactly one boundary committed, and it was not an independent (inNew) one. + assertThat(transactions.committed()).containsExactly(Boundary.WRITE); + assertThat(outbox.appended()).hasSize(1); } @Test @@ -88,7 +89,7 @@ class SubmitDurableOperationUseCaseTest { .isInstanceOf(IllegalStateException.class); assertThat(operations.size()).isZero(); - assertThat(outbox.appended).isEmpty(); + assertThat(outbox.appended()).isEmpty(); } @Test @@ -104,7 +105,7 @@ class SubmitDurableOperationUseCaseTest { assertThat(repeat.operationId()).isEqualTo(ID); assertThat(repeat.alreadyAccepted()).isTrue(); assertThat(operations.size()).isEqualTo(1); - assertThat(outbox.appended).hasSize(1); + assertThat(outbox.appended()).hasSize(1); } @Test @@ -116,7 +117,7 @@ class SubmitDurableOperationUseCaseTest { OperationAcceptance retry = useCase.handle(command(ID, "a".repeat(64))); // then - assertThat(List.of(retry.alreadyAccepted(), outbox.appended.size())).containsExactly(true, 1); + assertThat(List.of(retry.alreadyAccepted(), outbox.appended().size())).containsExactly(true, 1); } @Test @@ -129,7 +130,7 @@ class SubmitDurableOperationUseCaseTest { assertThat(second.alreadyAccepted()).isFalse(); assertThat(operations.size()).isEqualTo(2); - assertThat(outbox.appended).hasSize(2); + assertThat(outbox.appended()).hasSize(2); } @Test @@ -138,7 +139,7 @@ class SubmitDurableOperationUseCaseTest { useCase.handle(command(ID, "a".repeat(64))); // when - ValidatedIntegrationEvent event = outbox.appended.get(0); + ValidatedIntegrationEvent event = outbox.appended().get(0); // then // A worker that receives the message twice — which the relay's at-least-once delivery makes @@ -182,89 +183,22 @@ class SubmitDurableOperationUseCaseTest { .containsOnly(identity); } - private static final class RecordingOutbox implements OutboxAppendPort { + /** The in-memory outbox, failing its next append when told to. */ + private static final class FailingOutbox extends InMemoryOutboxStore { - private final List appended = new ArrayList<>(); - private final List appendedOutsideTransaction = new ArrayList<>(); - private final AtomicBoolean insideTransaction; private boolean failNext; - private RecordingOutbox(AtomicBoolean insideTransaction) { - this.insideTransaction = insideTransaction; + private FailingOutbox(DirectTransactionPort transactions) { + super(transactions); } @Override public void append(ValidatedIntegrationEvent event) { - if (!insideTransaction.get()) { - // The port's own contract: appending outside the caller's write transaction is silent - // event loss, and it is invisible to any assertion about what ended up in the list. - appendedOutsideTransaction.add(event.eventId().value()); - } if (failNext) { failNext = false; throw new IllegalStateException("the outbox write failed"); } - appended.add(event); - } - } - - /** - * A transaction port that actually rolls back. - * - *

        A port that simply runs the action would let {@link #rollbackLeavesNothing} pass for an - * implementation with no transaction at all — the exact defect the test is looking for. - */ - private static final class RollbackAwareTransactions implements TransactionPort { - - private final InMemoryDurableOperationStore operations; - private final RecordingOutbox outbox; - private final AtomicBoolean insideTransaction; - private final List independentCommits = new ArrayList<>(); - private int writeTransactions; - - private RollbackAwareTransactions( - InMemoryDurableOperationStore operations, - RecordingOutbox outbox, - AtomicBoolean insideTransaction) { - this.operations = operations; - this.outbox = outbox; - this.insideTransaction = insideTransaction; - } - - @Override - public T inWrite(Supplier action) { - writeTransactions++; - insideTransaction.set(true); - int outboxMark = outbox.appended.size(); - try { - return action.get(); - } catch (RuntimeException rollback) { - operations.clear(); - while (outbox.appended.size() > outboxMark) { - outbox.appended.remove(outbox.appended.size() - 1); - } - throw rollback; - } finally { - insideTransaction.set(false); - } - } - - @Override - public T inRootWrite(Supplier action) { - return inWrite(action); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - // Deliberately not delegating to inWrite: a REQUIRES_NEW transaction commits independently, - // which is the one thing this submission must never do. - independentCommits.add("inNew"); - return action.get(); + super.append(event); } } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java index e883549e..f5668d0f 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java @@ -2,16 +2,16 @@ package dev.caskeleton.application.outbox; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.application.outbox.testkit.FakeOutboxMessagePublisher; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.application.outbox.testkit.OutboxEvents; -import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; -import java.util.function.Supplier; import java.util.random.RandomGenerator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -38,19 +38,19 @@ class OutcomeAwareRelayTest { private PublishPendingOutboxEventsUseCase useCase; - private OutcomePort publishPort; + private FakeOutboxMessagePublisher publishPort; @BeforeEach void setUp() { store = new InMemoryOutboxStore(); reporter = new OutcomeReporter(); - publishPort = new OutcomePort(); + publishPort = new FakeOutboxMessagePublisher(); useCase = new PublishPendingOutboxEventsUseCase( store, publishPort, reporter, - new DirectTransactions(), + new DirectTransactionPort(), new OutboxBackoffPolicy(new NoJitter()), Clock.fixed(NOW, ZoneOffset.UTC), 10, @@ -59,13 +59,16 @@ class OutcomeAwareRelayTest { } @Test - @DisplayName("a confirmed publish still marks the row published") + @DisplayName("확인된 발행은 행을 PUBLISHED로 바꾼다") void aConfirmedPublishMarksTheRowPublished() { + // given store.addClaimable(event("evt-1", 1)); - publishPort.answer = OutboxPublishOutcome.CONFIRMED; + publishPort.answering(OutboxPublishOutcome.CONFIRMED); + // when OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); + // then assertThat(result.outcomes()) .extracting(OutboxRelayResult.EventOutcome::outcome) .containsExactly(OutboxRelayResult.Outcome.PUBLISHED); @@ -73,13 +76,16 @@ class OutcomeAwareRelayTest { } @Test - @DisplayName("an ambiguous publish stays claimable rather than being treated as a definite loss") + @DisplayName("확인 여부를 모르는 발행은 확실한 유실로 보지 않고 다시 claim할 수 있게 남긴다") void anAmbiguousPublishStaysClaimable() { + // given store.addClaimable(event("evt-2", 1)); - publishPort.answer = OutboxPublishOutcome.AMBIGUOUS; + publishPort.answering(OutboxPublishOutcome.AMBIGUOUS); + // when OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); + // then assertThat(result.outcomes()) .extracting(OutboxRelayResult.EventOutcome::outcome) .containsExactly(OutboxRelayResult.Outcome.FAILED); @@ -97,13 +103,16 @@ class OutcomeAwareRelayTest { } @Test - @DisplayName("a refusal before transmission is dead-lettered without spending the retry budget") + @DisplayName("보내기 전 거부는 재시도 예산을 쓰지 않고 바로 DEAD가 된다") void aRefusalBeforeTransmissionIsDeadLettered() { + // given store.addClaimable(event("evt-3", 1)); - publishPort.answer = OutboxPublishOutcome.REJECTED_BEFORE_SEND; + publishPort.answering(OutboxPublishOutcome.REJECTED_BEFORE_SEND); + // when OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); + // then assertThat(result.outcomes()) .extracting(OutboxRelayResult.EventOutcome::outcome) .as("the same payload will be refused the same way on every attempt") @@ -119,13 +128,16 @@ class OutcomeAwareRelayTest { } @Test - @DisplayName("a broker-side refusal is also definite, and says which side refused") + @DisplayName("broker 쪽 거부도 확정 거부라 DEAD가 되고, 어느 쪽이 거부했는지 남긴다") void aBrokerSideRefusalIsAlsoDefinite() { + // given store.addClaimable(event("evt-4", 1)); - publishPort.answer = OutboxPublishOutcome.REJECTED_AFTER_BROKER; + publishPort.answering(OutboxPublishOutcome.REJECTED_AFTER_BROKER); + // when useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); + // then assertThat(store.dead()).containsExactly("evt-4"); assertThat(reporter.reports.get(0).causeType()) .isEqualTo(OutboxPublishRefusedException.class.getName()); @@ -136,13 +148,16 @@ class OutcomeAwareRelayTest { } @Test - @DisplayName("an adapter that only throws keeps the behaviour it always had") + @DisplayName("예외만 던지는 adapter의 실패는 예전처럼 FAILED로 남는다") void aThrowingAdapterIsUnchanged() { + // given store.addClaimable(event("evt-5", 1)); - publishPort.failure = new IllegalStateException("the broker connection dropped"); + publishPort.throwing(new IllegalStateException("the broker connection dropped")); + // when OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); + // then assertThat(result.outcomes()) .extracting(OutboxRelayResult.EventOutcome::outcome) .containsExactly(OutboxRelayResult.Outcome.FAILED); @@ -153,29 +168,6 @@ class OutcomeAwareRelayTest { return OutboxEvents.claimed(eventId, NOW.minusSeconds(60), attemptCount); } - /** A port that answers with an outcome, or throws when the test asks it to. */ - private static final class OutcomePort implements OutboxMessagePublishPort { - - private OutboxPublishOutcome answer = OutboxPublishOutcome.CONFIRMED; - - private RuntimeException failure; - - @Override - public void publish(ClaimedOutboxEvent event) { - if (failure != null) { - throw failure; - } - } - - @Override - public OutboxPublishOutcome publishForOutcome(ClaimedOutboxEvent event) { - if (failure != null) { - throw failure; - } - return answer; - } - } - private static final class OutcomeReporter implements OutboxRelayFailureReportPort { private final List reports = new ArrayList<>(); @@ -186,29 +178,6 @@ class OutcomeAwareRelayTest { } } - private static final class DirectTransactions implements TransactionPort { - - @Override - public T inWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRootWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } - /** Deterministic backoff: the window is not what these cases are about. */ private static final class NoJitter implements RandomGenerator { diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java index db890f8c..5c664c0d 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java @@ -3,19 +3,17 @@ package dev.caskeleton.application.outbox; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.application.outbox.testkit.FakeOutboxMessagePublisher; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.application.outbox.testkit.OutboxEvents; -import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; -import java.util.function.Supplier; import java.util.random.RandomGenerator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,9 +38,9 @@ class PublishPendingOutboxEventsUseCaseTest { private static final int BATCH_SIZE = 10; private FakeOutboxStorePort store; - private FakeOutboxMessagePublishPort publishPort; + private FakeOutboxMessagePublisher publishPort; private RecordingFailureReporter reporter; - private FakeTransactionPort tx; + private DirectTransactionPort tx; private OutboxBackoffPolicy backoffPolicy; private Clock clock; private PublishPendingOutboxEventsUseCase useCase; @@ -50,9 +48,9 @@ class PublishPendingOutboxEventsUseCaseTest { @BeforeEach void setUp() { store = new FakeOutboxStorePort(); - publishPort = new FakeOutboxMessagePublishPort(); + publishPort = new FakeOutboxMessagePublisher(); reporter = new RecordingFailureReporter(); - tx = new FakeTransactionPort(); + tx = new DirectTransactionPort(); clock = Clock.fixed(NOW, ZoneOffset.UTC); // Use fixed random for determinism: always returns 0.0 jitter (nextDouble() = 0.0) backoffPolicy = new OutboxBackoffPolicy(new ZeroRandom()); @@ -72,18 +70,21 @@ class PublishPendingOutboxEventsUseCaseTest { // ---- success path ---- @Test - void legacyVoidPublisherNormalReturnTransitionsEventToPublishedCharacterization() { + void aConfirmedPublishTransitionsEventToPublishedCharacterization() { + // given ClaimedOutboxEvent event = makeEvent("evt-1", "agg-1", NOW.minusSeconds(60), 1); store.addClaimable(event); + // when OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); + // then assertThat(result.claimedCount()).isEqualTo(1); assertThat(result.outcomes()).hasSize(1); assertThat(result.outcomes().getFirst().outcome()) .isEqualTo(OutboxRelayResult.Outcome.PUBLISHED); assertThat(store.published()).containsExactly("evt-1"); - assertThat(publishPort.publishedEvents).containsExactly("evt-1"); + assertThat(publishPort.publishedEventIds()).containsExactly("evt-1"); assertThat(reporter.reports).isEmpty(); } @@ -98,7 +99,7 @@ class PublishPendingOutboxEventsUseCaseTest { useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); // The publish port must receive events in occurredAt order (early before late) - assertThat(publishPort.publishedEvents).containsExactly("evt-early", "evt-late"); + assertThat(publishPort.publishedEventIds()).containsExactly("evt-early", "evt-late"); } // ---- transient failure path ---- @@ -107,7 +108,8 @@ class PublishPendingOutboxEventsUseCaseTest { void senderExceptionTransitionsEventToFailedWithBackoffCharacterization() { ClaimedOutboxEvent event = makeEvent("evt-fail", "agg-1", NOW.minusSeconds(60), 1); store.addClaimable(event); - publishPort.failOn("evt-fail", new RuntimeException("broker down")); + RuntimeException brokerDown = new RuntimeException("broker down"); + publishPort.throwing("evt-fail", brokerDown); OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -129,7 +131,7 @@ class PublishPendingOutboxEventsUseCaseTest { "correlation-evt-fail", 1, nextAttemptAt, - publishPort.failureOn("evt-fail"))); + brokerDown)); } @Test @@ -137,7 +139,8 @@ class PublishPendingOutboxEventsUseCaseTest { // attemptCount=3 means this is the 3rd attempt — next failure should DEAD ClaimedOutboxEvent event = makeEvent("evt-dead", "agg-1", NOW.minusSeconds(60), 3); store.addClaimable(event); - publishPort.failOn("evt-dead", new RuntimeException("persistent broker down")); + RuntimeException brokerDown = new RuntimeException("persistent broker down"); + publishPort.throwing("evt-dead", brokerDown); OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -152,7 +155,7 @@ class PublishPendingOutboxEventsUseCaseTest { "agg-1", "correlation-evt-dead", 3, - publishPort.failureOn("evt-dead"))); + brokerDown)); } // ---- failure NOT swallowed ---- @@ -164,7 +167,7 @@ class PublishPendingOutboxEventsUseCaseTest { ClaimedOutboxEvent ok = makeEvent("evt-ok", "agg-1", NOW.minusSeconds(60), 1); store.addClaimable(fail); store.addClaimable(ok); - publishPort.failOn("evt-fail", new RuntimeException("transient")); + publishPort.throwing("evt-fail", new RuntimeException("transient")); OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -193,7 +196,7 @@ class PublishPendingOutboxEventsUseCaseTest { void failureOnSecondAttemptTransitionsToFailedNotDead() { ClaimedOutboxEvent event = makeEvent("evt-2nd", "agg-1", NOW.minusSeconds(60), 2); store.addClaimable(event); - publishPort.failOn("evt-2nd", new RuntimeException("2nd attempt failure")); + publishPort.throwing("evt-2nd", new RuntimeException("2nd attempt failure")); OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -213,10 +216,10 @@ class PublishPendingOutboxEventsUseCaseTest { // ---- markPublished failure — spec §엣지·실패·의존 semantics ---- /** - * When {@code store.markPublished} throws after a normal void publisher return, the exception - * must propagate out of {@code handle()} rather than being caught and misclassified as a publish - * failure (which would trigger FAILED/DEAD state machine and potentially dead-letter a - * successfully-delivered event). + * When {@code store.markPublished} throws after a confirmed publish, the exception must propagate + * out of {@code handle()} rather than being caught and misclassified as a publish failure (which + * would trigger FAILED/DEAD state machine and potentially dead-letter a successfully-delivered + * event). * *

        Contract (spec §엣지·실패·의존): * @@ -224,14 +227,15 @@ class PublishPendingOutboxEventsUseCaseTest { *

      2. The exception propagates — it is NOT swallowed inside {@code publishOne}. *
      3. {@code markFailed} is NOT called for the event (no misclassification). *
      4. {@code markDead} is NOT called for the event (no misclassification). - *
      5. {@code publishPort.publish} is not called again before the in-flight timeout. + *
      6. The publish port is not called again before the in-flight timeout. *
      7. The row remains IN_FLIGHT and can be recovered via the orphan visibility-timeout reclaim - * path on a later tick. Because the prior void publisher return is not broker - * acknowledgement evidence, a later publish can be a duplicate. + * path on a later tick. The confirmed publish left no PUBLISHED row behind, so the later + * publish is a duplicate. * */ @Test - void legacyMarkPublishedFailureLeavesInFlightAndDuplicatePossibleCharacterization() { + void + markPublishedFailureAfterAConfirmedPublishLeavesInFlightAndDuplicatePossibleCharacterization() { ClaimedOutboxEvent event = makeEvent("evt-store-fail", "agg-1", NOW.minusSeconds(60), 1); MutableClock mutableClock = new MutableClock(NOW, ZoneOffset.UTC); @@ -257,8 +261,8 @@ class PublishPendingOutboxEventsUseCaseTest { .isInstanceOf(RuntimeException.class) .hasMessage("DB down on markPublished"); - // A normal void return records only that the legacy publisher call completed. - assertThat(publishPort.publishedEvents).containsExactly("evt-store-fail"); + // The broker confirmed the publish; only the PUBLISHED transition failed to persist. + assertThat(publishPort.publishedEventIds()).containsExactly("evt-store-fail"); assertThat(throwingStore.currentStatus()).isEqualTo(OutboxEventStatus.IN_FLIGHT); assertThat(throwingStore.attemptCount()).isEqualTo(1); assertThat(throwingStore.nextAttemptAt()).isEqualTo(NOW.plus(IN_FLIGHT_TIMEOUT)); @@ -272,11 +276,11 @@ class PublishPendingOutboxEventsUseCaseTest { OutboxRelayResult beforeTimeout = useCaseWithThrowingStore.handle(PublishPendingOutboxEventsCommand.INSTANCE); assertThat(beforeTimeout.claimedCount()).isZero(); - assertThat(publishPort.publishedEvents).containsExactly("evt-store-fail"); + assertThat(publishPort.publishedEventIds()).containsExactly("evt-store-fail"); assertThat(throwingStore.attemptCount()).isEqualTo(1); // Move strictly past the timeout. The orphan becomes eligible and the same event is sent again - // because no PUBLISHED transition was persisted after the first normal void return. + // because no PUBLISHED transition was persisted after the first confirmed publish. mutableClock.advance(Duration.ofNanos(2)); assertThatThrownBy( () -> useCaseWithThrowingStore.handle(PublishPendingOutboxEventsCommand.INSTANCE)) @@ -284,7 +288,7 @@ class PublishPendingOutboxEventsUseCaseTest { .hasMessage("DB down on markPublished"); assertThat(throwingStore.currentStatus()).isEqualTo(OutboxEventStatus.IN_FLIGHT); assertThat(throwingStore.attemptCount()).isEqualTo(2); - assertThat(publishPort.publishedEvents) + assertThat(publishPort.publishedEventIds()) .as("mark failure leaves a duplicate-possible retry window") .containsExactly("evt-store-fail", "evt-store-fail"); } @@ -327,7 +331,7 @@ class PublishPendingOutboxEventsUseCaseTest { // First event (earlier occurredAt) must have been published to the broker, // and the second event must NOT have been published (no partial-batch silent swallow). - assertThat(publishPort.publishedEvents).containsExactly("evt-first"); + assertThat(publishPort.publishedEventIds()).containsExactly("evt-first"); // No FAILED or DEAD misclassification for the first event. assertThat(throwingStore.failed()).doesNotContainKey("evt-first"); @@ -345,7 +349,7 @@ class PublishPendingOutboxEventsUseCaseTest { ThrowingTransitionStorePort throwingStore = new ThrowingTransitionStorePort(new RuntimeException("markFailed failed"), null); throwingStore.addClaimable(event); - publishPort.failOn("evt-fail", new RuntimeException("broker down")); + publishPort.throwing("evt-fail", new RuntimeException("broker down")); PublishPendingOutboxEventsUseCase throwingUseCase = new PublishPendingOutboxEventsUseCase( throwingStore, @@ -369,7 +373,7 @@ class PublishPendingOutboxEventsUseCaseTest { ThrowingTransitionStorePort throwingStore = new ThrowingTransitionStorePort(null, new RuntimeException("markDead failed")); throwingStore.addClaimable(event); - publishPort.failOn("evt-dead", new RuntimeException("broker down")); + publishPort.throwing("evt-dead", new RuntimeException("broker down")); PublishPendingOutboxEventsUseCase throwingUseCase = new PublishPendingOutboxEventsUseCase( throwingStore, @@ -393,7 +397,7 @@ class PublishPendingOutboxEventsUseCaseTest { ClaimedOutboxEvent succeeded = makeEvent("evt-ok", "agg-1", NOW.minusSeconds(60), 1); store.addClaimable(failed); store.addClaimable(succeeded); - publishPort.failOn("evt-fail", new RuntimeException("broker down")); + publishPort.throwing("evt-fail", new RuntimeException("broker down")); OutboxRelayFailureReportPort throwingReporter = ignored -> { throw new RuntimeException("reporter failed"); @@ -531,27 +535,6 @@ class PublishPendingOutboxEventsUseCaseTest { } } - static final class FakeOutboxMessagePublishPort implements OutboxMessagePublishPort { - final List publishedEvents = new ArrayList<>(); - private final Map failureMap = new LinkedHashMap<>(); - - void failOn(String eventId, RuntimeException ex) { - failureMap.put(eventId, ex); - } - - RuntimeException failureOn(String eventId) { - return failureMap.get(eventId); - } - - @Override - public void publish(ClaimedOutboxEvent event) { - if (failureMap.containsKey(event.eventId())) { - throw failureMap.get(event.eventId()); - } - publishedEvents.add(event.eventId()); - } - } - static final class RecordingFailureReporter implements OutboxRelayFailureReportPort { final List reports = new ArrayList<>(); @@ -561,28 +544,6 @@ class PublishPendingOutboxEventsUseCaseTest { } } - static final class FakeTransactionPort implements TransactionPort { - @Override - public T inWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRootWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } - static final class MutableClock extends Clock { private Instant current; private final ZoneId zone; diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/StoppingRelayReleasesItsClaimsTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/StoppingRelayReleasesItsClaimsTest.java index 52d80c92..91b3e858 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/StoppingRelayReleasesItsClaimsTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/StoppingRelayReleasesItsClaimsTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.application.outbox; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCaseTest.ZeroRandom; +import dev.caskeleton.application.outbox.testkit.FakeOutboxMessagePublisher; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.application.outbox.testkit.OutboxEvents; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; @@ -10,7 +11,6 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; -import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.DisplayName; @@ -37,12 +37,8 @@ class StoppingRelayReleasesItsClaimsTest { store.append(OutboxEvents.event(second, NOW.minusSeconds(2))); store.append(OutboxEvents.event(third, NOW.minusSeconds(1))); AtomicBoolean stopRequested = new AtomicBoolean(); - List sent = new ArrayList<>(); - OutboxMessagePublishPort port = - event -> { - sent.add(event.eventId()); - stopRequested.set(true); - }; + FakeOutboxMessagePublisher port = + new FakeOutboxMessagePublisher().whenPublishing(event -> stopRequested.set(true)); PublishPendingOutboxEventsUseCase relay = relay(store, port); // when @@ -50,7 +46,7 @@ class StoppingRelayReleasesItsClaimsTest { relay.handle(new PublishPendingOutboxEventsCommand(stopRequested::get)); // then - assertThat(sent).containsExactly(first); + assertThat(port.publishedEventIds()).containsExactly(first); assertThat(result.outcomes()) .extracting(OutboxRelayResult.EventOutcome::outcome) .containsExactly( @@ -70,7 +66,7 @@ class StoppingRelayReleasesItsClaimsTest { InMemoryOutboxStore store = new InMemoryOutboxStore(); store.append(OutboxEvents.event("0193a000-0000-7000-8000-000000000011", NOW.minusSeconds(2))); store.append(OutboxEvents.event("0193a000-0000-7000-8000-000000000012", NOW.minusSeconds(1))); - PublishPendingOutboxEventsUseCase relay = relay(store, event -> {}); + PublishPendingOutboxEventsUseCase relay = relay(store, new FakeOutboxMessagePublisher()); // when OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java index 3ef7dc71..04fbc520 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCaseTest.MutableClock; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCaseTest.ZeroRandom; +import dev.caskeleton.application.outbox.testkit.FakeOutboxMessagePublisher; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.application.outbox.testkit.OutboxEvents; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; @@ -11,9 +12,7 @@ import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -39,7 +38,7 @@ class TransientPublishFailureRelayTest { private MutableClock clock; - private ScriptedPort port; + private FakeOutboxMessagePublisher port; private List reports; @@ -49,7 +48,7 @@ class TransientPublishFailureRelayTest { void setUp() { store = new InMemoryOutboxStore(); clock = new MutableClock(START, ZoneOffset.UTC); - port = new ScriptedPort(); + port = new FakeOutboxMessagePublisher(); reports = new ArrayList<>(); relay = new PublishPendingOutboxEventsUseCase( @@ -69,7 +68,7 @@ class TransientPublishFailureRelayTest { void aRetryableRefusalIsScheduledForRetryInsteadOfDeadLettered() { // given: the platform refused the publish because it is shutting down store.addClaimable(OutboxEvents.claimed("evt-shutdown", START.minusSeconds(1), 1)); - port.answer = OutboxPublishOutcome.REJECTED_RETRYABLE; + port.answering(OutboxPublishOutcome.REJECTED_RETRYABLE); // when OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -95,8 +94,8 @@ class TransientPublishFailureRelayTest { OutboxEvents.claimed("evt-refused", START.minusSeconds(2), lastBudgetedAttempt)); store.addClaimable( OutboxEvents.claimed("evt-ambiguous", START.minusSeconds(1), lastBudgetedAttempt)); - port.script("evt-refused", OutboxPublishOutcome.REJECTED_RETRYABLE); - port.script("evt-ambiguous", OutboxPublishOutcome.AMBIGUOUS); + port.answering("evt-refused", OutboxPublishOutcome.REJECTED_RETRYABLE); + port.answering("evt-ambiguous", OutboxPublishOutcome.AMBIGUOUS); // when relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -112,8 +111,7 @@ class TransientPublishFailureRelayTest { // given: each publish against the stopped broker takes the whole deadline store.addClaimable(OutboxEvents.claimed("evt-first", START.minusSeconds(3), 1)); store.addClaimable(OutboxEvents.claimed("evt-last", START.minusSeconds(2), 1)); - port.answer = OutboxPublishOutcome.AMBIGUOUS; - port.costPerPublish = PUBLISH_DEADLINE; + port.answering(OutboxPublishOutcome.AMBIGUOUS).whenPublishing(event -> spend(PUBLISH_DEADLINE)); // when relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -134,8 +132,14 @@ class TransientPublishFailureRelayTest { store.addClaimable(OutboxEvents.claimed("evt-" + i, START.minusSeconds(60 - i), 1)); } Instant brokerBack = START.plus(Duration.ofMinutes(10)); - port.answerUntil(brokerBack, OutboxPublishOutcome.AMBIGUOUS); - port.costPerPublish = PUBLISH_DEADLINE; + port.answering(OutboxPublishOutcome.AMBIGUOUS) + .whenPublishing( + event -> { + if (!clock.instant().isBefore(brokerBack)) { + port.answering(OutboxPublishOutcome.CONFIRMED); + } + spend(PUBLISH_DEADLINE); + }); // when: the scheduler keeps polling every five seconds for half an hour runRelayEvery(Duration.ofSeconds(5), START.plus(Duration.ofMinutes(30))); @@ -150,7 +154,7 @@ class TransientPublishFailureRelayTest { void repeatedTransientFailuresBackOffUpToTheCeiling() { // given: a row that has already been tried many times during a long outage store.addClaimable(OutboxEvents.claimed("evt-long-outage", START.minusSeconds(1), 12)); - port.answer = OutboxPublishOutcome.AMBIGUOUS; + port.answering(OutboxPublishOutcome.AMBIGUOUS); // when relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -166,12 +170,12 @@ class TransientPublishFailureRelayTest { void aRowThatWaitedOutAnOutageIsNotDeadLetteredByItsFirstUnclassifiedFailure() { // given: a row that went through more transient refusals than the whole attempt budget store.addClaimable(OutboxEvents.claimed("evt-after-outage", START.minusSeconds(1), 1)); - port.answer = OutboxPublishOutcome.REJECTED_RETRYABLE; + port.answering(OutboxPublishOutcome.REJECTED_RETRYABLE); for (int i = 0; i <= OutboxBackoffPolicy.MAX_ATTEMPTS; i++) { relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); clock.advance(OutboxBackoffPolicy.MAX_DELAY.plus(OutboxBackoffPolicy.BASE_DELAY)); } - port.thrown = new IllegalStateException("a failure the adapter could not classify"); + port.throwing(new IllegalStateException("a failure the adapter could not classify")); // when OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -188,15 +192,16 @@ class TransientPublishFailureRelayTest { void unclassifiedFailuresStillExhaustTheBudgetBetweenTransientOnes() { // given: transient refusals interleaved with failures the adapter could not classify store.addClaimable(OutboxEvents.claimed("evt-poison", START.minusSeconds(1), 1)); - port.thrown = new IllegalStateException("payload the adapter cannot classify"); + IllegalStateException unclassified = + new IllegalStateException("payload the adapter cannot classify"); + port.throwing(unclassified); for (int i = 1; i < OutboxBackoffPolicy.MAX_ATTEMPTS; i++) { relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); clock.advance(OutboxBackoffPolicy.MAX_DELAY.plus(OutboxBackoffPolicy.BASE_DELAY)); - port.thrown = null; - port.answer = OutboxPublishOutcome.REJECTED_RETRYABLE; + port.answering(OutboxPublishOutcome.REJECTED_RETRYABLE); relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); clock.advance(OutboxBackoffPolicy.MAX_DELAY.plus(OutboxBackoffPolicy.BASE_DELAY)); - port.thrown = new IllegalStateException("payload the adapter cannot classify"); + port.throwing(unclassified); } // when @@ -215,46 +220,8 @@ class TransientPublishFailureRelayTest { } } - /** Answers per event, or until a moment on the relay's clock, and spends time doing it. */ - private final class ScriptedPort implements OutboxMessagePublishPort { - - private final Map scripted = new HashMap<>(); - - private OutboxPublishOutcome answer = OutboxPublishOutcome.CONFIRMED; - - private Instant answerUntil = Instant.MAX; - - private Duration costPerPublish = Duration.ZERO; - - /** When set, every publish throws it instead of answering. */ - private RuntimeException thrown; - - void script(String eventId, OutboxPublishOutcome outcome) { - scripted.put(eventId, outcome); - } - - void answerUntil(Instant until, OutboxPublishOutcome outcome) { - this.answer = outcome; - this.answerUntil = until; - } - - @Override - public void publish(ClaimedOutboxEvent event) { - throw new UnsupportedOperationException("the relay asks for an outcome"); - } - - @Override - public OutboxPublishOutcome publishForOutcome(ClaimedOutboxEvent event) { - Instant calledAt = clock.instant(); - clock.advance(costPerPublish); - if (thrown != null) { - throw thrown; - } - OutboxPublishOutcome outcome = scripted.get(event.eventId()); - if (outcome != null) { - return outcome; - } - return calledAt.isBefore(answerUntil) ? answer : OutboxPublishOutcome.CONFIRMED; - } + /** What one publish against a stopped broker spends before it answers. */ + private void spend(Duration cost) { + clock.advance(cost); } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisherContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisherContractTest.java new file mode 100644 index 00000000..96ff3a23 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisherContractTest.java @@ -0,0 +1,76 @@ +package dev.caskeleton.application.outbox.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.messaging.event.testkit.BrokerAnswer; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventPublisher; +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.application.outbox.OutboxPublishOutcome; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class FakeOutboxMessagePublisherContractTest extends OutboxMessagePublishContract { + + private FakeOutboxMessagePublisher fake; + + @Override + protected OutboxMessagePublishPort publisherOverABrokerThat(BrokerAnswer answer) { + fake = + new FakeOutboxMessagePublisher().answering(FakeIntegrationEventPublisher.outcomeOf(answer)); + return fake; + } + + @Override + protected List eventIdsTheBrokerReceived() { + return fake.published().stream().map(claim -> claim.event().eventId().value()).toList(); + } + + @Test + @DisplayName("event 하나에 정한 답은 모든 발행에 정한 답보다 먼저 쓰인다") + void anAnswerScriptedForOneEventWinsOverTheSharedAnswer() { + // given + FakeOutboxMessagePublisher publisher = + new FakeOutboxMessagePublisher() + .answering(OutboxPublishOutcome.AMBIGUOUS) + .answering(CLAIMED_EVENT_ID, OutboxPublishOutcome.REJECTED_BEFORE_SEND); + + // when + OutboxPublishOutcome outcome = publisher.publishForOutcome(claimedRow()); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND); + } + + @Test + @DisplayName("던지도록 정한 예외는 답 대신 그대로 던지고, 그 발행도 받은 것으로 기록한다") + void aScriptedFailureIsThrownAsIsAndTheEventIsStillRecorded() { + // given + IllegalStateException dropped = new IllegalStateException("connection dropped"); + FakeOutboxMessagePublisher publisher = new FakeOutboxMessagePublisher().throwing(dropped); + + // when + Throwable thrown = catchThrowable(() -> publisher.publishForOutcome(claimedRow())); + + // then + assertThat(List.of(thrown, publisher.publishedEventIds())) + .containsExactly(dropped, List.of(CLAIMED_EVENT_ID)); + } + + @Test + @DisplayName("모든 발행에 답을 다시 정하면 앞서 정한 예외는 더 던지지 않는다") + void answeringAgainStopsAPreviouslyScriptedFailure() { + // given + FakeOutboxMessagePublisher publisher = + new FakeOutboxMessagePublisher() + .throwing(new IllegalStateException("connection dropped")) + .answering(OutboxPublishOutcome.REJECTED_RETRYABLE); + + // when + OutboxPublishOutcome outcome = publisher.publishForOutcome(claimedRow()); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_RETRYABLE); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreAppendContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreAppendContractTest.java new file mode 100644 index 00000000..90d85885 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreAppendContractTest.java @@ -0,0 +1,27 @@ +package dev.caskeleton.application.outbox.testkit; + +import dev.caskeleton.application.outbox.OutboxAppendPort; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; + +/** The in-memory store, over the in-memory transaction port, keeps the outbox append contract. */ +class InMemoryOutboxStoreAppendContractTest extends OutboxAppendContract { + + private final DirectTransactionPort transactions = new DirectTransactionPort(); + private final InMemoryOutboxStore store = new InMemoryOutboxStore(transactions); + + @Override + protected TransactionPort transactions() { + return transactions; + } + + @Override + protected OutboxAppendPort append() { + return store; + } + + @Override + protected boolean committed(String eventId) { + return store.appended().stream().anyMatch(event -> event.eventId().value().equals(eventId)); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/realtime/testkit/InMemoryLiveEventReplayContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/realtime/testkit/InMemoryLiveEventReplayContractTest.java new file mode 100644 index 00000000..75963702 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/realtime/testkit/InMemoryLiveEventReplayContractTest.java @@ -0,0 +1,27 @@ +package dev.caskeleton.application.realtime.testkit; + +import dev.caskeleton.application.realtime.LiveEventReplayPort; +import java.time.Duration; + +/** The in-memory history keeps the replay contract the transport tests run over. */ +class InMemoryLiveEventReplayContractTest extends LiveEventReplayContract { + + private static final Duration RETENTION = Duration.ofHours(1); + + private final InMemoryLiveEventReplay replay = new InMemoryLiveEventReplay(clock(), RETENTION); + + @Override + protected LiveEventReplayPort replay() { + return replay; + } + + @Override + protected long append(String streamId, String payload) { + return replay.append(streamId, payload); + } + + @Override + protected Duration retention() { + return RETENTION; + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbound/SecretReferenceTest.java b/src/application-core/src/test/java/dev/caskeleton/application/secret/SecretReferenceTest.java similarity index 97% rename from src/application-core/src/test/java/dev/caskeleton/application/outbound/SecretReferenceTest.java rename to src/application-core/src/test/java/dev/caskeleton/application/secret/SecretReferenceTest.java index 2d2c6b91..d5c63d96 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbound/SecretReferenceTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/secret/SecretReferenceTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.outbound; +package dev.caskeleton.application.secret; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; diff --git a/src/application-core/src/test/java/dev/caskeleton/application/secret/testkit/InMemorySecretSourceContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/secret/testkit/InMemorySecretSourceContractTest.java new file mode 100644 index 00000000..627454a1 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/secret/testkit/InMemorySecretSourceContractTest.java @@ -0,0 +1,13 @@ +package dev.caskeleton.application.secret.testkit; + +import dev.caskeleton.application.secret.SecretSourcePort; +import java.util.Map; + +/** The in-memory fake keeps the secret source contract. */ +class InMemorySecretSourceContractTest extends SecretSourceContract { + + @Override + protected SecretSourcePort sourceWith(Map secrets) { + return new InMemorySecretSource(secrets); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/security/testkit/InMemoryAuthorizationContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/security/testkit/InMemoryAuthorizationContractTest.java new file mode 100644 index 00000000..909530ac --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/security/testkit/InMemoryAuthorizationContractTest.java @@ -0,0 +1,15 @@ +package dev.caskeleton.application.security.testkit; + +import dev.caskeleton.application.security.AuthorizationPort; +import dev.caskeleton.shared.security.Permission; +import java.util.Map; +import java.util.Set; + +/** The in-memory fake keeps the authorization contract. */ +class InMemoryAuthorizationContractTest extends AuthorizationContract { + + @Override + protected AuthorizationPort portGranting(Map> rolePermissions) { + return new InMemoryAuthorization(rolePermissions); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/transaction/TransactionPortTest.java b/src/application-core/src/test/java/dev/caskeleton/application/transaction/TransactionPortTest.java index ba276967..60383cc5 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/transaction/TransactionPortTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/transaction/TransactionPortTest.java @@ -2,103 +2,98 @@ package dev.caskeleton.application.transaction; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import java.util.ArrayList; import java.util.List; -import java.util.function.Supplier; import org.junit.jupiter.api.Test; +/** + * The {@link Runnable} default methods open the boundary their {@link java.util.function.Supplier} + * counterpart opens. The port under test is the in-memory one, which does not override them, so + * what runs here is the interface's own default code. + */ class TransactionPortTest { @Test void runnableInWriteDelegatesToSupplierInWrite() { - RecordingTransactionPort port = new RecordingTransactionPort(); + // given + DirectTransactionPort port = new DirectTransactionPort(); List sideEffect = new ArrayList<>(); + // when port.inWrite(() -> sideEffect.add("ran")); - assertThat(port.invocations).containsExactly(TransactionMode.WRITE); + // then + assertThat(port.committed()).containsExactly(Boundary.WRITE); assertThat(sideEffect).containsExactly("ran"); } @Test void runnableInRootWriteDelegatesToSupplierInRootWrite() { - RecordingTransactionPort port = new RecordingTransactionPort(); + // given + DirectTransactionPort port = new DirectTransactionPort(); List sideEffect = new ArrayList<>(); + // when port.inRootWrite(() -> sideEffect.add("ran")); - assertThat(port.invocations).containsExactly(TransactionMode.WRITE); + // then + assertThat(port.committed()).containsExactly(Boundary.ROOT_WRITE); assertThat(sideEffect).containsExactly("ran"); } @Test void runnableInReadDelegatesToSupplierInRead() { - RecordingTransactionPort port = new RecordingTransactionPort(); + // given + DirectTransactionPort port = new DirectTransactionPort(); List sideEffect = new ArrayList<>(); + // when port.inRead(() -> sideEffect.add("ran")); - assertThat(port.invocations).containsExactly(TransactionMode.READ_ONLY); + // then + assertThat(port.committed()).containsExactly(Boundary.READ); assertThat(sideEffect).containsExactly("ran"); } @Test void runnableInNewDelegatesToSupplierInNew() { - RecordingTransactionPort port = new RecordingTransactionPort(); + // given + DirectTransactionPort port = new DirectTransactionPort(); List sideEffect = new ArrayList<>(); + // when port.inNew(() -> sideEffect.add("ran")); - assertThat(port.invocations).containsExactly(TransactionMode.REQUIRES_NEW); + // then + assertThat(port.committed()).containsExactly(Boundary.NEW); assertThat(sideEffect).containsExactly("ran"); } @Test void supplierInWriteReturnsActionValue() { - RecordingTransactionPort port = new RecordingTransactionPort(); + // given + DirectTransactionPort port = new DirectTransactionPort(); + // when String result = port.inWrite(() -> "v"); + // then assertThat(result).isEqualTo("v"); - assertThat(port.invocations).containsExactly(TransactionMode.WRITE); + assertThat(port.committed()).containsExactly(Boundary.WRITE); } @Test void supplierInRootWriteReturnsActionValue() { - RecordingTransactionPort port = new RecordingTransactionPort(); + // given + DirectTransactionPort port = new DirectTransactionPort(); + // when String result = port.inRootWrite(() -> "v"); + // then assertThat(result).isEqualTo("v"); - assertThat(port.invocations).containsExactly(TransactionMode.WRITE); - } - - private static final class RecordingTransactionPort implements TransactionPort { - - private final List invocations = new ArrayList<>(); - - @Override - public T inWrite(Supplier action) { - invocations.add(TransactionMode.WRITE); - return action.get(); - } - - @Override - public T inRootWrite(Supplier action) { - invocations.add(TransactionMode.WRITE); - return action.get(); - } - - @Override - public T inRead(Supplier action) { - invocations.add(TransactionMode.READ_ONLY); - return action.get(); - } - - @Override - public T inNew(Supplier action) { - invocations.add(TransactionMode.REQUIRES_NEW); - return action.get(); - } + assertThat(port.committed()).containsExactly(Boundary.ROOT_WRITE); } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPortContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPortContractTest.java new file mode 100644 index 00000000..49a09433 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPortContractTest.java @@ -0,0 +1,47 @@ +package dev.caskeleton.application.transaction.testkit; + +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.ArrayList; +import java.util.List; + +/** + * The in-memory port keeps the transaction contract the use-case tests run over. + * + *

        The probe is written the way a fake store uses the port: it refuses a write outside a + * transaction or inside a read-only one, and registers the undo of every write it accepts. + */ +class DirectTransactionPortContractTest extends TransactionPortContract { + + private final DirectTransactionPort transactions = new DirectTransactionPort(); + + @Override + protected TransactionPort transactions() { + return transactions; + } + + @Override + protected TransactionProbe probe() { + return new TransactionProbe() { + private final List marks = new ArrayList<>(); + + @Override + public void write(String mark) { + if (!transactions.active() || transactions.readOnly()) { + throw new IllegalStateException("no write transaction is active for " + mark); + } + marks.add(mark); + transactions.onRollback(() -> marks.remove(mark)); + } + + @Override + public List committed() { + return marks.stream().sorted().toList(); + } + + @Override + public boolean inTransaction() { + return transactions.active(); + } + }; + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java index c5e2a5d7..297ce65f 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java @@ -8,6 +8,9 @@ import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; import dev.caskeleton.application.idempotency.IdempotencyCompleteOutcome; import dev.caskeleton.application.idempotency.IdempotencyFailOutcome; import dev.caskeleton.application.idempotency.IdempotencyFailureDisposition; +import dev.caskeleton.application.idempotency.IdempotencyInspection; +import dev.caskeleton.application.idempotency.IdempotencyInspectionRequest; +import dev.caskeleton.application.idempotency.IdempotencyMutationResult; import dev.caskeleton.application.idempotency.IdempotencyOwner; import dev.caskeleton.application.idempotency.IdempotencyReleaseOutcome; import dev.caskeleton.application.idempotency.IdempotencyRenewOutcome; @@ -18,16 +21,23 @@ import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.idempotency.StoredResponse; import dev.caskeleton.application.transaction.OperationId; import java.time.Duration; +import java.util.function.Supplier; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * The owner-safe state machine every {@link IdempotencyStorePort} owes its callers, run unchanged - * against the in-memory fake and every store. + * against the in-memory fake and every store: the fake, the Redis store over the command fake and + * over a real server, and the PostgreSQL store over a real database. * - *

        Time-free on purpose: lease expiry and take-over depend on whose clock the store trusts, and - * those cases stay with each store's own tests. What is here is what a caller of the port relies on - * whichever store is composed. + *

        Mostly time-free: expiry and take-over of an abandoned lease depend on whose clock the store + * trusts, and those cases stay with each store's own tests. The one timed case is the one a caller + * relies on whichever store is composed — {@code renew} really extends the lease (review 05-02: the + * Redis store answered a renew as already applied and let the lease run out). A store reaches time + * through {@link #elapse(Duration)}; the in-memory fake has no expiry and leaves it a no-op. + * + *

        Every call goes through {@link #inTransaction(Supplier)}, the way the store's callers make it: + * the PostgreSQL store refuses to run outside an application-owned write transaction. */ public abstract class IdempotencyStoreContract { @@ -50,10 +60,47 @@ public abstract class IdempotencyStoreContract { */ protected abstract IdempotencyStorePort store(); + /** + * Runs one store call the way the store's callers do. The default runs it directly; a store that + * requires a transaction around every call opens one here. + * + * @param work one call on the store + * @return what the call returned + */ + protected T inTransaction(Supplier work) { + return work.get(); + } + + /** + * The processing lease the timed case claims with; long enough for the store's round trips. + * + * @return the lease + */ + protected Duration processingLease() { + return Duration.ofSeconds(30); + } + + /** + * Lets {@code duration} pass on the clock the store trusts. A store without lease expiry keeps + * the default no-op. + * + * @param duration how long to let pass + */ + protected void elapse(Duration duration) {} + + private IdempotencyStorePort subject() { + return new EachCallInTransaction(store()); + } + private static IdempotencyClaimRequest claim( IdempotencyClaimAttempt attempt, RequestFingerprint fingerprint) { + return claim(attempt, fingerprint, Duration.ofSeconds(30)); + } + + private static IdempotencyClaimRequest claim( + IdempotencyClaimAttempt attempt, RequestFingerprint fingerprint, Duration processingLease) { return new IdempotencyClaimRequest( - SCOPE, fingerprint, attempt, Duration.ofSeconds(30), Duration.ofHours(24), "json-v2", 1); + SCOPE, fingerprint, attempt, processingLease, Duration.ofHours(24), "json-v2", 1); } private static IdempotencyOwner acquire(IdempotencyStorePort store) { @@ -62,6 +109,14 @@ public abstract class IdempotencyStoreContract { .owner(); } + private static IdempotencyOwner ownerOf(IdempotencyClaimOutcome outcome) { + return switch (outcome) { + case IdempotencyClaimOutcome.Acquired acquired -> acquired.owner(); + case IdempotencyClaimOutcome.TakenOverClaimed takenOver -> takenOver.owner(); + default -> throw new AssertionError("the claim did not take ownership: " + outcome); + }; + } + private static IdempotencyOwner executing(IdempotencyStorePort store) { return store.markExecutionStarted(acquire(store), OPERATION).owner().orElseThrow(); } @@ -70,7 +125,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("먼저 claim한 쪽이 얻고 다른 요청은 진행 중으로 막힌다") void aFirstClaimExcludesTheSecond() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); acquire(store); // when @@ -85,7 +140,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("같은 attempt로 다시 claim하면 새로 얻지 않고 재생한다") void theSameAttemptReplaysItsAcquire() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); store.claim(claim(attempt, FINGERPRINT)); @@ -100,7 +155,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("같은 scope의 다른 요청 본문은 재생이 아니라 fingerprint 불일치다") void aDifferentRequestUnderTheSameScopeIsAMismatch() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); acquire(store); // when @@ -115,7 +170,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("완료한 결과는 다음 claim에서 그대로 재생된다") void aCompletedResultReplays() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); store.complete( executing(store), new StoredResponse("{\"ok\":true}"), Duration.ofHours(1), OPERATION); @@ -133,7 +188,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("전이 전에 받은 오래된 owner 핸들로는 complete할 수 없다") void aStaleHandleCannotComplete() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); IdempotencyOwner stale = acquire(store); store.markExecutionStarted(stale, OPERATION); @@ -149,7 +204,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("renew는 RENEWED와 더 새 revision의 핸들을 돌려주고 그 핸들로 complete할 수 있다") void renewReturnsANewerHandleThatCanComplete() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); IdempotencyOwner executing = executing(store); // when @@ -167,7 +222,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("실행을 시작하기 전 claim은 renew할 수 없다") void aClaimNotYetExecutingCannotBeRenewed() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); IdempotencyOwner claimed = acquire(store); // when @@ -182,7 +237,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("재시도 가능한 실패는 다음 claim이 attempt 2로 넘겨받게 한다") void aRetryableFailureLetsTheNextClaimTakeOver() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); store.markFailed( executing(store), IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, @@ -202,7 +257,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("효과가 불명인 채 포기한 작업은 다시 돌리지 않고 복구를 요구한다") void anAbandonedOperationRequiresRecovery() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); IdempotencyFailOutcome marked = store.markFailed( executing(store), @@ -223,7 +278,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("실행 전 release는 scope를 비우고 실행 뒤 release는 거부된다") void releaseFreesTheScopeOnlyBeforeExecution() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); IdempotencyOwner claimed = acquire(store); // when @@ -231,8 +286,17 @@ public abstract class IdempotencyStoreContract { // then assertThat(released).isEqualTo(IdempotencyReleaseOutcome.RELEASED_BEFORE_EXECUTION); - IdempotencyOwner executing = executing(store); - assertThat(store.releaseBeforeExecution(executing, OPERATION)) + // The next claim owns the scope. Whether the store forgets the released record (Acquired) or + // keeps it and counts the claim as a further attempt (TakenOverClaimed) is the store's own + // choice; the executor runs both the same way. + IdempotencyClaimOutcome next = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT)); + assertThat(next) + .isInstanceOfAny( + IdempotencyClaimOutcome.Acquired.class, IdempotencyClaimOutcome.TakenOverClaimed.class); + IdempotencyOwner executing = + store.markExecutionStarted(ownerOf(next), OTHER_OPERATION).owner().orElseThrow(); + assertThat(store.releaseBeforeExecution(executing, OTHER_OPERATION)) .isEqualTo(IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED); } @@ -240,7 +304,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("같은 결과로 두 번 complete하면 멱등이고 다른 결과면 충돌이다") void completingTwiceIsIdempotentOnlyForTheSameResult() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); IdempotencyOwner executing = executing(store); store.complete(executing, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION); @@ -260,7 +324,7 @@ public abstract class IdempotencyStoreContract { @DisplayName("STARTED 전이는 새 revision의 핸들을 돌려준다") void startingAdvancesTheRevision() { // given - IdempotencyStorePort store = store(); + IdempotencyStorePort store = subject(); IdempotencyOwner claimed = acquire(store); // when @@ -271,4 +335,89 @@ public abstract class IdempotencyStoreContract { assertThat(started.owner().orElseThrow().stateRevision()) .isGreaterThan(claimed.stateRevision()); } + + @Test + @DisplayName("renew한 처리 lease는 처음 만료 시각이 지나도 다른 요청에 넘어가지 않는다") + void aRenewedLeaseOutlivesItsFirstExpiry() { + // given + IdempotencyStorePort store = subject(); + Duration lease = processingLease(); + IdempotencyOwner claimed = + ((IdempotencyClaimOutcome.Acquired) + store.claim(claim(store.newClaimAttempt(OPERATION), FINGERPRINT, lease))) + .owner(); + IdempotencyOwner executing = + store.markExecutionStarted(claimed, OPERATION).owner().orElseThrow(); + elapse(lease.multipliedBy(3).dividedBy(5)); + store.renew(executing, lease, OPERATION); + elapse(lease.multipliedBy(3).dividedBy(5)); + + // when + IdempotencyClaimOutcome other = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT, lease)); + + // then + assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class); + } + + /** Routes every call of the store through {@link #inTransaction(Supplier)}. */ + private final class EachCallInTransaction implements IdempotencyStorePort { + + private final IdempotencyStorePort store; + + private EachCallInTransaction(IdempotencyStorePort store) { + this.store = store; + } + + @Override + public IdempotencyClaimAttempt newClaimAttempt(OperationId operationId) { + return inTransaction(() -> store.newClaimAttempt(operationId)); + } + + @Override + public IdempotencyClaimOutcome claim(IdempotencyClaimRequest request) { + return inTransaction(() -> store.claim(request)); + } + + @Override + public IdempotencyMutationResult markExecutionStarted( + IdempotencyOwner owner, OperationId operationId) { + return inTransaction(() -> store.markExecutionStarted(owner, operationId)); + } + + @Override + public IdempotencyMutationResult renew( + IdempotencyOwner owner, Duration processingLeaseTtl, OperationId operationId) { + return inTransaction(() -> store.renew(owner, processingLeaseTtl, operationId)); + } + + @Override + public IdempotencyCompleteOutcome complete( + IdempotencyOwner owner, + StoredResponse response, + Duration replayTtl, + OperationId operationId) { + return inTransaction(() -> store.complete(owner, response, replayTtl, operationId)); + } + + @Override + public IdempotencyFailOutcome markFailed( + IdempotencyOwner owner, + IdempotencyFailureDisposition disposition, + Duration retention, + OperationId operationId) { + return inTransaction(() -> store.markFailed(owner, disposition, retention, operationId)); + } + + @Override + public IdempotencyReleaseOutcome releaseBeforeExecution( + IdempotencyOwner owner, OperationId operationId) { + return inTransaction(() -> store.releaseBeforeExecution(owner, operationId)); + } + + @Override + public IdempotencyInspection inspect(IdempotencyInspectionRequest request) { + return inTransaction(() -> store.inspect(request)); + } + } } diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/BrokerAnswer.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/BrokerAnswer.java new file mode 100644 index 00000000..585a41b2 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/BrokerAnswer.java @@ -0,0 +1,23 @@ +package dev.caskeleton.application.messaging.event.testkit; + +/** + * What the broker behind a publish port does with a message, as the publish contracts script it. + * + *

        Named after the broker's behaviour, not after the application's outcome: the contracts check + * that each implementation translates the first into the second, so the scenario cannot already be + * written in the answer's vocabulary. + */ +public enum BrokerAnswer { + /** Stores the message and acknowledges it. */ + CONFIRMS, + /** Received the message, and no acknowledgement ever arrived. */ + NEVER_CONFIRMS, + /** + * Refuses it for a reason of the moment: shutting down, permits exhausted, credentials rotating. + */ + REFUSES_FOR_NOW, + /** Refuses it before anything was transmitted: routing, an unknown destination. */ + REFUSES_BEFORE_SENDING, + /** Receives it and refuses it: quota, ACL, size. */ + REFUSES_AFTER_RECEIVING +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisher.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisher.java new file mode 100644 index 00000000..4d2a5ad4 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisher.java @@ -0,0 +1,60 @@ +package dev.caskeleton.application.messaging.event.testkit; + +import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.OutboxPublishOutcome; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; + +/** + * The {@link IntegrationEventPublishPort} fake: records every event it is handed and answers with + * the outcome a test scripted, {@code CONFIRMED} unless told otherwise. Held to {@link + * IntegrationEventPublishContract} like the platform bridge. + */ +public final class FakeIntegrationEventPublisher implements IntegrationEventPublishPort { + + private final List published = new ArrayList<>(); + private OutboxPublishOutcome answer = OutboxPublishOutcome.CONFIRMED; + + /** + * Answers every later publish with {@code outcome}. + * + * @param outcome the outcome to report + * @return this fake + */ + public FakeIntegrationEventPublisher answering(OutboxPublishOutcome outcome) { + this.answer = Objects.requireNonNull(outcome, "outcome"); + return this; + } + + @Override + public CompletionStage publish(ValidatedIntegrationEvent event) { + published.add(Objects.requireNonNull(event, "event must not be null")); + return CompletableFuture.completedFuture(answer); + } + + /** Every event handed to this fake, in order. */ + public List published() { + return List.copyOf(published); + } + + /** + * The outcome a broker answering {@code answer} produces, for a test that scripts this fake by + * broker behaviour. + * + * @param answer what the broker does + * @return the outcome the application reads + */ + public static OutboxPublishOutcome outcomeOf(BrokerAnswer answer) { + return switch (answer) { + case CONFIRMS -> OutboxPublishOutcome.CONFIRMED; + case NEVER_CONFIRMS -> OutboxPublishOutcome.AMBIGUOUS; + case REFUSES_FOR_NOW -> OutboxPublishOutcome.REJECTED_RETRYABLE; + case REFUSES_BEFORE_SENDING -> OutboxPublishOutcome.REJECTED_BEFORE_SEND; + case REFUSES_AFTER_RECEIVING -> OutboxPublishOutcome.REJECTED_AFTER_BROKER; + }; + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventPublishContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventPublishContract.java new file mode 100644 index 00000000..7863777b --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventPublishContract.java @@ -0,0 +1,118 @@ +package dev.caskeleton.application.messaging.event.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; +import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.OutboxPublishOutcome; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import java.time.Instant; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link IntegrationEventPublishPort} promises, run by the platform bridge's test and + * the fake's test alike (review 2026-11-01 TEST-F-1). + * + *

        The relay acts on the outcome alone: it marks a row published, retries it, or parks it. So the + * promise is the translation — each thing a broker can do with a message arrives as the one outcome + * that leads the relay to the right action. A bridge that reported a refusal of the moment as a + * definite rejection parked a committed event and its aggregate behind it (06-01); the bridge's own + * test caught it, the fake every use-case test ran on did not have to. + * + *

        The event id is a canonical UUIDv7, the only spelling the platform carries. + */ +public abstract class IntegrationEventPublishContract { + + /** A canonical lower-case UUIDv7, the event's id. */ + protected static final String CONTRACT_EVENT_ID = "01994e11-4d88-7000-8000-00000000c0de"; + + /** A port over a broker that gives {@code answer} to every publish. */ + protected abstract IntegrationEventPublishPort publisherOverABrokerThat(BrokerAnswer answer); + + /** The event ids the broker behind the last port received, in the order it received them. */ + protected abstract List eventIdsTheBrokerReceived(); + + @Test + @DisplayName("broker가 저장하고 확인한 메시지는 CONFIRMED로 알리고, broker는 그 event를 자기 id로 한 번 받는다") + void aMessageTheBrokerStoredIsReportedConfirmedAndReachesItOnceUnderItsOwnId() { + // given + IntegrationEventPublishPort port = publisherOverABrokerThat(BrokerAnswer.CONFIRMS); + + // when + OutboxPublishOutcome outcome = publish(port); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.CONFIRMED); + assertThat(eventIdsTheBrokerReceived()).containsExactly(CONTRACT_EVENT_ID); + } + + @Test + @DisplayName("broker가 받고 확인을 주지 않은 메시지는 다시 시도할 수 있는 AMBIGUOUS로 알린다") + void aMessageTheBrokerNeverAcknowledgedIsReportedAmbiguous() { + // given + IntegrationEventPublishPort port = publisherOverABrokerThat(BrokerAnswer.NEVER_CONFIRMS); + + // when + OutboxPublishOutcome outcome = publish(port); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.AMBIGUOUS); + assertThat(outcome.retryable()).isTrue(); + } + + @Test + @DisplayName("그 순간의 이유로 거부된 메시지는 확정 거부가 아니라 다시 시도할 거부로 알린다") + void aRefusalOfTheMomentIsReportedRetryableNotDefinite() { + // given + IntegrationEventPublishPort port = publisherOverABrokerThat(BrokerAnswer.REFUSES_FOR_NOW); + + // when + OutboxPublishOutcome outcome = publish(port); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_RETRYABLE); + assertThat(outcome.retryable()).isTrue(); + } + + @Test + @DisplayName("아무것도 보내기 전에 거부된 메시지는 전송되지 않은 확정 거부로 알린다") + void aRefusalBeforeAnythingWasSentIsReportedAsNothingTransmitted() { + // given + IntegrationEventPublishPort port = + publisherOverABrokerThat(BrokerAnswer.REFUSES_BEFORE_SENDING); + + // when + OutboxPublishOutcome outcome = publish(port); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND); + assertThat(outcome.nothingTransmitted()).isTrue(); + } + + @Test + @DisplayName("broker가 받은 뒤 거부한 메시지는 broker 쪽 확정 거부로 알린다") + void aRefusalByTheBrokerIsReportedAsRejectedAfterTheBroker() { + // given + IntegrationEventPublishPort port = + publisherOverABrokerThat(BrokerAnswer.REFUSES_AFTER_RECEIVING); + + // when + OutboxPublishOutcome outcome = publish(port); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_AFTER_BROKER); + assertThat(outcome.retryable()).isFalse(); + } + + /** The contract's event, published and waited for. */ + private static OutboxPublishOutcome publish(IntegrationEventPublishPort port) { + return port.publish(contractEvent()).toCompletableFuture().join(); + } + + /** The event every scenario publishes. */ + protected static ValidatedIntegrationEvent contractEvent() { + return OutboxEvents.event(CONTRACT_EVENT_ID, Instant.parse("2026-11-03T00:00:00Z")); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/observability/testkit/CorrelationIdContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/observability/testkit/CorrelationIdContract.java new file mode 100644 index 00000000..7c9d8c83 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/observability/testkit/CorrelationIdContract.java @@ -0,0 +1,64 @@ +package dev.caskeleton.application.observability.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.observability.CorrelationIdPort; +import java.util.Optional; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link CorrelationIdPort} promises: the invocation's correlation identifier when it + * has a non-blank one, and empty otherwise. A blank value is absent, so a use case that stamps the + * identifier on an event never writes an empty correlation. Run against the in-memory fake and the + * web MDC adapter. + */ +public abstract class CorrelationIdContract { + + /** + * A port whose current invocation carries {@code correlationId}. + * + * @param correlationId the raw stored value; {@code null} for none + * @return the port under test + */ + protected abstract CorrelationIdPort portCarrying(String correlationId); + + @Test + @DisplayName("현재 호출의 correlation id를 그대로 돌려준다") + void theCurrentCorrelationIdIsReturned() { + // given + CorrelationIdPort port = portCarrying("corr-123"); + + // when + Optional current = port.currentCorrelationId(); + + // then + assertThat(current).contains("corr-123"); + } + + @Test + @DisplayName("correlation id가 없으면 비어 있다") + void noCorrelationIdIsEmpty() { + // given + CorrelationIdPort port = portCarrying(null); + + // when + Optional current = port.currentCorrelationId(); + + // then + assertThat(current).isEmpty(); + } + + @Test + @DisplayName("공백뿐인 correlation id는 없는 것으로 본다") + void aBlankCorrelationIdIsEmpty() { + // given + CorrelationIdPort port = portCarrying(" "); + + // when + Optional current = port.currentCorrelationId(); + + // then + assertThat(current).isEmpty(); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/observability/testkit/FixedCorrelationId.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/observability/testkit/FixedCorrelationId.java new file mode 100644 index 00000000..01c93ba1 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/observability/testkit/FixedCorrelationId.java @@ -0,0 +1,38 @@ +package dev.caskeleton.application.observability.testkit; + +import dev.caskeleton.application.observability.CorrelationIdPort; +import java.util.Optional; + +/** + * In-memory {@link CorrelationIdPort} carrying one fixed value, with the port's rule that a blank + * value is absent. {@link CorrelationIdContract} holds it and the web MDC adapter to the same + * cases. + */ +public final class FixedCorrelationId implements CorrelationIdPort { + + private final String correlationId; + + private FixedCorrelationId(String correlationId) { + this.correlationId = correlationId; + } + + /** + * A port whose every invocation carries {@code correlationId}. + * + * @param correlationId the raw value; {@code null} for none + * @return the port + */ + public static FixedCorrelationId of(String correlationId) { + return new FixedCorrelationId(correlationId); + } + + /** A port with no correlation identifier. */ + public static FixedCorrelationId none() { + return new FixedCorrelationId(null); + } + + @Override + public Optional currentCorrelationId() { + return Optional.ofNullable(correlationId).filter(value -> !value.isBlank()); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/operation/testkit/InMemoryDurableOperationStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/operation/testkit/InMemoryDurableOperationStore.java index 077db829..019193c3 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/operation/testkit/InMemoryDurableOperationStore.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/operation/testkit/InMemoryDurableOperationStore.java @@ -9,12 +9,14 @@ import dev.caskeleton.application.operation.DurableOperationSubmitResult; import dev.caskeleton.application.operation.OperationFailure; import dev.caskeleton.application.operation.OperationLease; import dev.caskeleton.application.operation.OperationProgressSnapshot; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @@ -26,6 +28,10 @@ import java.util.concurrent.ConcurrentHashMap; * terminal operation is never reopened. A fake that was laxer than the adapter would let the use * case tests certify behaviour the real store refuses. {@link DurableOperationStoreContract} holds * this fake and the adapter to the same cases. + * + *

        Built over a {@link DirectTransactionPort}, every write made inside one of its transactions is + * undone when that transaction rolls back, as the database undoes it; built without one, writes + * stay as they are made. */ public final class InMemoryDurableOperationStore implements DurableOperationStorePort { @@ -35,6 +41,21 @@ public final class InMemoryDurableOperationStore implements DurableOperationStor private final Map byScope = new ConcurrentHashMap<>(); private final Map submissions = new ConcurrentHashMap<>(); + private final DirectTransactionPort transactions; + + /** A store whose writes stay as they are made. */ + public InMemoryDurableOperationStore() { + this.transactions = null; + } + + /** + * A store whose writes inside a transaction of {@code transactions} roll back with it. + * + * @param transactions the port the use case under test opens its transactions through + */ + public InMemoryDurableOperationStore(DirectTransactionPort transactions) { + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } @Override public DurableOperationSubmitResult submit(DurableOperationSubmission submission) { @@ -63,8 +84,13 @@ public final class InMemoryDurableOperationStore implements DurableOperationStor Optional.empty(), Optional.empty(), submission.expiresAt()); - byId.put(submission.operationId(), operation); + write(submission.operationId(), operation); submissions.put(submission.operationId(), submission); + onRollback( + () -> { + byScope.remove(scope); + submissions.remove(submission.operationId()); + }); return new DurableOperationSubmitResult(operation, true); } @@ -99,7 +125,7 @@ public final class InMemoryDurableOperationStore implements DurableOperationStor operation.resultReference(), Optional.empty(), Optional.of(new OperationLease(workerId, now, now.plus(leaseDuration)))); - byId.put(claimed.operationId(), claimed); + write(claimed.operationId(), claimed); return submissions.get(claimed.operationId()); }); } @@ -111,7 +137,7 @@ public final class InMemoryDurableOperationStore implements DurableOperationStor if (!holdsLease(operation, workerId, now)) { return false; } - byId.put( + write( operationId, replace( operation, @@ -132,7 +158,7 @@ public final class InMemoryDurableOperationStore implements DurableOperationStor if (operation == null || !ownedBy(operation, workerId)) { return false; } - byId.put( + write( operationId, replace( operation, @@ -156,7 +182,7 @@ public final class InMemoryDurableOperationStore implements DurableOperationStor if (operation == null || !ownedBy(operation, workerId)) { return false; } - byId.put( + write( operationId, replace( operation, @@ -180,7 +206,7 @@ public final class InMemoryDurableOperationStore implements DurableOperationStor if (operation == null || !ownedBy(operation, workerId)) { return false; } - byId.put( + write( operationId, replace( operation, @@ -202,7 +228,7 @@ public final class InMemoryDurableOperationStore implements DurableOperationStor || !operation.state().cancellable()) { return false; } - byId.put( + write( operationId, replace( operation, @@ -222,7 +248,7 @@ public final class InMemoryDurableOperationStore implements DurableOperationStor byId.forEach( (id, operation) -> { if (operation.state() == DurableOperationState.RUNNING && operation.leaseExpiredAt(now)) { - byId.put( + write( id, replace( operation, @@ -245,7 +271,7 @@ public final class InMemoryDurableOperationStore implements DurableOperationStor byId.forEach( (id, operation) -> { if (!operation.state().terminal() && !now.isBefore(operation.expiresAt())) { - byId.put( + write( id, replace( operation, @@ -262,6 +288,24 @@ public final class InMemoryDurableOperationStore implements DurableOperationStor return List.copyOf(expired); } + private void write(DurableOperationId operationId, DurableOperation operation) { + DurableOperation previous = byId.put(operationId, operation); + onRollback( + () -> { + if (previous == null) { + byId.remove(operationId); + } else { + byId.put(operationId, previous); + } + }); + } + + private void onRollback(Runnable undo) { + if (transactions != null && transactions.active()) { + transactions.onRollback(undo); + } + } + /** How many operations exist. */ public int size() { return byId.size(); diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisher.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisher.java new file mode 100644 index 00000000..e3ddc929 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisher.java @@ -0,0 +1,137 @@ +package dev.caskeleton.application.outbox.testkit; + +import dev.caskeleton.application.outbox.ClaimedOutboxEvent; +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.application.outbox.OutboxPublishAmbiguousException; +import dev.caskeleton.application.outbox.OutboxPublishOutcome; +import dev.caskeleton.application.outbox.OutboxPublishRefusedException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Consumer; + +/** + * The {@link OutboxMessagePublishPort} fake: records every claimed row it is handed and answers + * with the outcome a test scripted, {@code CONFIRMED} unless told otherwise. The throwing method + * fails closed the way the messaging bridge does. Held to {@link OutboxMessagePublishContract} like + * it. + * + *

        The relay's tests script it four ways: one outcome for every publish ({@link + * #answering(OutboxPublishOutcome)}), one outcome for one event ({@link #answering(String, + * OutboxPublishOutcome)}), an exception the broker client raised instead of answering ({@link + * #throwing}), and something that happens while the broker call is in progress ({@link + * #whenPublishing}) — a clock that moves, a stop request that arrives. A per-event script wins over + * the shared answer, and a thrown exception wins over both. + */ +public final class FakeOutboxMessagePublisher implements OutboxMessagePublishPort { + + private final List published = new ArrayList<>(); + private final Map answerPerEvent = new HashMap<>(); + private final Map failurePerEvent = new HashMap<>(); + private OutboxPublishOutcome answer = OutboxPublishOutcome.CONFIRMED; + private RuntimeException failure; + private Consumer duringPublish = event -> {}; + + /** + * Answers every later publish with {@code outcome}, and stops throwing a failure set by {@link + * #throwing(RuntimeException)}. + * + * @param outcome the outcome to report + * @return this fake + */ + public FakeOutboxMessagePublisher answering(OutboxPublishOutcome outcome) { + this.answer = Objects.requireNonNull(outcome, "outcome"); + this.failure = null; + return this; + } + + /** + * Answers every later publish of {@code eventId} with {@code outcome}, whatever the shared answer + * is. + * + * @param eventId the event id the script applies to + * @param outcome the outcome to report for it + * @return this fake + */ + public FakeOutboxMessagePublisher answering(String eventId, OutboxPublishOutcome outcome) { + answerPerEvent.put( + Objects.requireNonNull(eventId, "eventId"), Objects.requireNonNull(outcome, "outcome")); + return this; + } + + /** + * Throws {@code thrown} from every later publish instead of answering — an adapter whose broker + * client failed in a way it could not classify. {@link #answering(OutboxPublishOutcome)} stops + * it. + * + * @param thrown the exception the publish raises + * @return this fake + */ + public FakeOutboxMessagePublisher throwing(RuntimeException thrown) { + this.failure = Objects.requireNonNull(thrown, "thrown"); + return this; + } + + /** + * Throws {@code thrown} from every later publish of {@code eventId} instead of answering. + * + * @param eventId the event id the failure applies to + * @param thrown the exception the publish raises + * @return this fake + */ + public FakeOutboxMessagePublisher throwing(String eventId, RuntimeException thrown) { + failurePerEvent.put( + Objects.requireNonNull(eventId, "eventId"), Objects.requireNonNull(thrown, "thrown")); + return this; + } + + /** + * Runs {@code sideEffect} on every later publish after the event is recorded and before the fake + * answers, for a broker call that takes time or that coincides with something else. + * + * @param sideEffect what happens while the broker call is in progress + * @return this fake + */ + public FakeOutboxMessagePublisher whenPublishing(Consumer sideEffect) { + this.duringPublish = Objects.requireNonNull(sideEffect, "sideEffect"); + return this; + } + + @Override + public void publish(ClaimedOutboxEvent event) { + OutboxPublishOutcome outcome = publishForOutcome(event); + if (outcome == OutboxPublishOutcome.CONFIRMED) { + return; + } + if (outcome == OutboxPublishOutcome.AMBIGUOUS) { + throw new OutboxPublishAmbiguousException(); + } + throw new OutboxPublishRefusedException(outcome); + } + + @Override + public OutboxPublishOutcome publishForOutcome(ClaimedOutboxEvent event) { + published.add(Objects.requireNonNull(event, "event must not be null")); + // The answer is read after the side effect: a side effect that moves a clock past an outage or + // re-scripts the fake decides what this very call reports, as a broker that came back would. + duringPublish.accept(event); + String eventId = event.eventId(); + RuntimeException thrown = failurePerEvent.getOrDefault(eventId, failure); + if (thrown != null) { + throw thrown; + } + return answerPerEvent.getOrDefault(eventId, answer); + } + + /** Every claimed row handed to this fake, in order, whatever it answered. */ + public List published() { + return List.copyOf(published); + } + + /** The event ids of {@link #published()}, in the same order. */ + public List publishedEventIds() { + return published.stream().map(ClaimedOutboxEvent::eventId).toList(); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java index 7ccdbc9b..a9442c84 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java @@ -7,6 +7,7 @@ import dev.caskeleton.application.outbox.OutboxCompletion; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; import dev.caskeleton.application.outbox.OutboxStorePort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; @@ -16,6 +17,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; /** @@ -25,6 +27,11 @@ import java.util.Set; * It does not model the per-aggregate FIFO gate; that lives in the claim SQL and is covered against * PostgreSQL. * + *

        Built over a {@link DirectTransactionPort}, {@link #append} behaves as the SQL store's does + * under a real transaction: it is refused outside a write transaction and undone when that + * transaction rolls back ({@link OutboxAppendContract} holds both stores to it). Built without one, + * append writes at once; that form is for relay tests that seed rows directly. + * *

        Not final so a test can override one operation to inject a storage failure. */ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { @@ -37,10 +44,32 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { private final Map failed = new LinkedHashMap<>(); private final List dead = new ArrayList<>(); private final List released = new ArrayList<>(); + private final DirectTransactionPort transactions; + + /** A store tests seed directly: append writes at once, with or without a transaction. */ + public InMemoryOutboxStore() { + this.transactions = null; + } + + /** + * A store whose append joins {@code transactions} as the SQL store's joins the caller's. + * + * @param transactions the port the use case under test opens its transactions through + */ + public InMemoryOutboxStore(DirectTransactionPort transactions) { + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } @Override public void append(ValidatedIntegrationEvent event) { + if (transactions != null && (!transactions.active() || transactions.readOnly())) { + throw new IllegalStateException("outbox append requires an active write transaction"); + } add(event, 0); + if (transactions != null) { + String eventId = event.eventId().value(); + transactions.onRollback(() -> rows.remove(eventId)); + } } /** diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAppendContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAppendContract.java index df8488cc..fffdbaf6 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAppendContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAppendContract.java @@ -1,88 +1,140 @@ package dev.caskeleton.application.outbox.testkit; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; -import java.util.Objects; +import java.time.Instant; import java.util.UUID; -import java.util.function.Predicate; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; /** - * Provider-neutral contract kit for the outbox append boundary: an append belongs to the caller's - * write transaction, so it commits and rolls back with it. + * What every {@link OutboxAppendPort} promises: an append belongs to the caller's write + * transaction, so it commits and rolls back with it, and an append that no write transaction would + * carry is refused rather than written on its own (the dual write the outbox exists to prevent). * - *

        The contract is expressed only in application-owned types. A persistence adapter supplies its - * transaction port, append port, and a probe that can observe whether the event became durable. No - * Spring, JPA, SQL, or provider type is part of this fixture. + *

        Run unchanged against the in-memory store over {@link + * dev.caskeleton.application.transaction.testkit.DirectTransactionPort} and the JPA store over a + * Spring transaction on real PostgreSQL. The contract is expressed only in application-owned types: + * an implementation supplies its transaction port, its append port and a way to see whether an + * event became durable. */ -public final class OutboxAppendContract { - - private OutboxAppendContract() {} +public abstract class OutboxAppendContract { /** - * Verifies that an append performed inside a caller-owned write transaction disappears when that - * same transaction rolls back. + * The transaction port the append joins; the same instance for the whole test. + * + * @return the caller's transaction port */ - public static void verifyRollbackRemovesEvent( - TransactionPort transactions, - OutboxAppendPort append, - Predicate eventExists, - Clock clock) { - requireInputs(transactions, append, eventExists, clock); - String eventId = "outbox-contract-rollback-" + UUID.randomUUID(); + protected abstract TransactionPort transactions(); - try { - transactions.inWrite( - () -> { - append.append(OutboxEvents.event(eventId, clock.instant())); - throw new ExpectedRollback(); - }); - throw new AssertionError("write transaction swallowed the contract rollback signal"); - } catch (ExpectedRollback expected) { - // The signal exists only to force the caller-owned transaction to roll back. - } + /** + * The append port under test; the same instance for the whole test. + * + * @return the append port + */ + protected abstract OutboxAppendPort append(); - if (eventExists.test(eventId)) { - throw new AssertionError( - "outbox append survived caller transaction rollback for event " + eventId); - } + /** + * Whether {@code eventId} is durable — visible to a reader outside any transaction. + * + * @param eventId the event looked for + * @return true when the event has committed + */ + protected abstract boolean committed(String eventId); + + private static String newEventId(String purpose) { + return "outbox-contract-" + purpose + "-" + UUID.randomUUID(); } - /** Verifies that an append becomes durable when the caller-owned write transaction commits. */ - public static void verifyCommitPersistsEvent( - TransactionPort transactions, - OutboxAppendPort append, - Predicate eventExists, - Clock clock) { - requireInputs(transactions, append, eventExists, clock); - String eventId = "outbox-contract-commit-" + UUID.randomUUID(); - - transactions.inWrite( - () -> { - append.append(OutboxEvents.event(eventId, clock.instant())); - return null; - }); - - if (!eventExists.test(eventId)) { - throw new AssertionError( - "outbox append was not durable after caller transaction commit for event " + eventId); - } + private static Instant now() { + return Clock.systemUTC().instant(); } - private static void requireInputs( - TransactionPort transactions, - OutboxAppendPort append, - Predicate eventExists, - Clock clock) { - Objects.requireNonNull(transactions, "transactions"); - Objects.requireNonNull(append, "append"); - Objects.requireNonNull(eventExists, "eventExists"); - Objects.requireNonNull(clock, "clock"); + @Test + @DisplayName("호출자 쓰기 트랜잭션이 커밋되면 append한 이벤트가 남는다") + void anAppendCommitsWithItsCaller() { + // given + String eventId = newEventId("commit"); + + // when + transactions().inWrite(() -> append().append(OutboxEvents.event(eventId, now()))); + + // then + assertThat(committed(eventId)).isTrue(); } - private static final class ExpectedRollback extends RuntimeException { - private ExpectedRollback() { - super("expected contract rollback", null, false, false); - } + @Test + @DisplayName("호출자 쓰기 트랜잭션이 롤백되면 append한 이벤트도 사라진다") + void anAppendRollsBackWithItsCaller() { + // given + String eventId = newEventId("rollback"); + IllegalStateException rollback = new IllegalStateException("the business write failed"); + + // when + Throwable thrown = + catchThrowable( + () -> + transactions() + .inWrite( + () -> { + append().append(OutboxEvents.event(eventId, now())); + throw rollback; + })); + + // then + assertThat(thrown).isSameAs(rollback); + assertThat(committed(eventId)).isFalse(); + } + + @Test + @DisplayName("트랜잭션 밖의 append는 거부되고 아무것도 남지 않는다") + void anAppendOutsideATransactionIsRefused() { + // given + String eventId = newEventId("outside"); + + // when + Throwable thrown = catchThrowable(() -> append().append(OutboxEvents.event(eventId, now()))); + + // then + assertThat(thrown).isInstanceOf(IllegalStateException.class); + assertThat(committed(eventId)).isFalse(); + } + + @Test + @DisplayName("읽기 전용 트랜잭션 안의 append는 거부되고 아무것도 남지 않는다") + void anAppendInsideAReadOnlyTransactionIsRefused() { + // given + String eventId = newEventId("read-only"); + + // when + Throwable thrown = + catchThrowable( + () -> transactions().inRead(() -> append().append(OutboxEvents.event(eventId, now())))); + + // then + assertThat(thrown).isInstanceOf(RuntimeException.class); + assertThat(committed(eventId)).isFalse(); + } + + @Test + @DisplayName("같은 eventId를 다시 append한 트랜잭션은 실패하고 처음 이벤트는 남는다") + void aDuplicateEventIdFailsItsTransactionAndKeepsTheFirst() { + // given + String eventId = newEventId("duplicate"); + transactions().inWrite(() -> append().append(OutboxEvents.event(eventId, now()))); + + // when + Throwable thrown = + catchThrowable( + () -> + transactions().inWrite(() -> append().append(OutboxEvents.event(eventId, now())))); + + // then + assertThat(thrown).isInstanceOf(RuntimeException.class); + assertThat(committed(eventId)).isTrue(); } } diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxMessagePublishContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxMessagePublishContract.java new file mode 100644 index 00000000..3f7d39cf --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxMessagePublishContract.java @@ -0,0 +1,132 @@ +package dev.caskeleton.application.outbox.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.messaging.event.testkit.BrokerAnswer; +import dev.caskeleton.application.outbox.ClaimedOutboxEvent; +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.application.outbox.OutboxPublishOutcome; +import java.time.Instant; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link OutboxMessagePublishPort} promises, run by the messaging bridge's test and the + * fake's test alike (review 2026-11-01 TEST-F-1). + * + *

        Two methods, two promises. {@link OutboxMessagePublishPort#publishForOutcome} reports what the + * broker did, so the relay can tell a possibly-stored message from a refused one. {@link + * OutboxMessagePublishPort#publish} is fail-closed: it returns only when the broker confirmed, and + * anything else — an ambiguous publish included — is an exception, so a caller that ignores the + * outcome can never mark an unconfirmed row published. + */ +public abstract class OutboxMessagePublishContract { + + /** A canonical lower-case UUIDv7, the claimed row's event id. */ + protected static final String CLAIMED_EVENT_ID = "01994e11-4d88-7000-8000-00000000ba5e"; + + /** A port over a broker that gives {@code answer} to every publish. */ + protected abstract OutboxMessagePublishPort publisherOverABrokerThat(BrokerAnswer answer); + + /** The event ids the broker behind the last port received, in the order it received them. */ + protected abstract List eventIdsTheBrokerReceived(); + + @Test + @DisplayName("claim한 행은 그 행이 담은 event 그대로 broker에 가고, 확인되면 CONFIRMED로 알린다") + void aClaimedRowReachesTheBrokerAsTheEventItCarriesAndIsReportedConfirmed() { + // given + OutboxMessagePublishPort port = publisherOverABrokerThat(BrokerAnswer.CONFIRMS); + + // when + OutboxPublishOutcome outcome = port.publishForOutcome(claimedRow()); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.CONFIRMED); + assertThat(eventIdsTheBrokerReceived()).containsExactly(CLAIMED_EVENT_ID); + } + + @Test + @DisplayName("확인을 받지 못한 발행은 결과 조회에서 AMBIGUOUS로 알린다") + void anUnacknowledgedPublishIsReportedAmbiguous() { + // given + OutboxMessagePublishPort port = publisherOverABrokerThat(BrokerAnswer.NEVER_CONFIRMS); + + // when + OutboxPublishOutcome outcome = port.publishForOutcome(claimedRow()); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.AMBIGUOUS); + } + + @Test + @DisplayName("broker의 거부는 결과 조회에서 그 거부의 종류 그대로 알린다") + void aBrokerRefusalIsReportedAsThatKindOfRefusal() { + // given + OutboxMessagePublishPort port = publisherOverABrokerThat(BrokerAnswer.REFUSES_AFTER_RECEIVING); + + // when + OutboxPublishOutcome outcome = port.publishForOutcome(claimedRow()); + + // then + assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_AFTER_BROKER); + } + + @Test + @DisplayName("예외로 알리는 발행은 broker가 확인했을 때만 정상 반환한다") + void theThrowingPublishReturnsWhenTheBrokerConfirmed() { + // given + OutboxMessagePublishPort port = publisherOverABrokerThat(BrokerAnswer.CONFIRMS); + + // when + Throwable thrown = catchThrowable(() -> port.publish(claimedRow())); + + // then + assertThat(thrown).isNull(); + } + + @Test + @DisplayName("예외로 알리는 발행은 확인을 받지 못하면 예외를 던진다") + void theThrowingPublishThrowsWhenNoAcknowledgementArrived() { + // given + OutboxMessagePublishPort port = publisherOverABrokerThat(BrokerAnswer.NEVER_CONFIRMS); + + // when + Throwable thrown = catchThrowable(() -> port.publish(claimedRow())); + + // then + assertThat(thrown).isInstanceOf(RuntimeException.class); + } + + @Test + @DisplayName("예외로 알리는 발행은 그 순간의 이유로 거부돼도 예외를 던진다") + void theThrowingPublishThrowsOnARefusalOfTheMoment() { + // given + OutboxMessagePublishPort port = publisherOverABrokerThat(BrokerAnswer.REFUSES_FOR_NOW); + + // when + Throwable thrown = catchThrowable(() -> port.publish(claimedRow())); + + // then + assertThat(thrown).isInstanceOf(RuntimeException.class); + } + + @Test + @DisplayName("예외로 알리는 발행은 보내기 전에 거부돼도 예외를 던진다") + void theThrowingPublishThrowsOnARefusalBeforeSending() { + // given + OutboxMessagePublishPort port = publisherOverABrokerThat(BrokerAnswer.REFUSES_BEFORE_SENDING); + + // when + Throwable thrown = catchThrowable(() -> port.publish(claimedRow())); + + // then + assertThat(thrown).isInstanceOf(RuntimeException.class); + } + + /** The row every scenario publishes, claimed once. */ + protected static ClaimedOutboxEvent claimedRow() { + return OutboxEvents.claimed(CLAIMED_EVENT_ID, Instant.parse("2026-11-03T00:00:00Z"), 1); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/realtime/testkit/InMemoryLiveEventReplay.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/realtime/testkit/InMemoryLiveEventReplay.java new file mode 100644 index 00000000..f6dc06d2 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/realtime/testkit/InMemoryLiveEventReplay.java @@ -0,0 +1,103 @@ +package dev.caskeleton.application.realtime.testkit; + +import dev.caskeleton.application.realtime.LiveEventReplayPort; +import dev.caskeleton.application.realtime.ReplayCursorUnavailableException; +import dev.caskeleton.application.realtime.ReplayWindow; +import dev.caskeleton.application.realtime.ReplayedEvent; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** + * In-memory {@link LiveEventReplayPort} with the rules of the JPA history: positions per stream + * from 1 and never reused, an event replayable until {@code appendedAt + retention} on the given + * clock, a cursor older than what is retained refused with {@link + * ReplayCursorUnavailableException}. {@link LiveEventReplayContract} holds it and the JPA store to + * the same cases. + * + *

        Single-threaded: one instance per test. + */ +public final class InMemoryLiveEventReplay implements LiveEventReplayPort { + + private record Stored(ReplayedEvent event, Instant retainedUntil) {} + + private final Clock clock; + private final Duration retention; + private final Map> streams = new HashMap<>(); + private final Map lastPositions = new HashMap<>(); + + /** + * A history measured on {@code clock}. + * + * @param clock the clock retention is measured against + * @param retention how long an appended event stays replayable + */ + public InMemoryLiveEventReplay(Clock clock, Duration retention) { + this.clock = Objects.requireNonNull(clock, "clock"); + this.retention = Objects.requireNonNull(retention, "retention"); + if (retention.isNegative() || retention.isZero()) { + throw new IllegalArgumentException("retention must be positive"); + } + } + + /** + * Appends an event, as the store's writer does. + * + * @return the position it was given + */ + public long append(String streamId, String payload) { + Objects.requireNonNull(streamId, "streamId"); + Objects.requireNonNull(payload, "payload"); + Instant now = clock.instant(); + long position = lastPositions.merge(streamId, 1L, Long::sum); + streams + .computeIfAbsent(streamId, ignored -> new ArrayList<>()) + .add(new Stored(new ReplayedEvent(streamId, position, payload, now), now.plus(retention))); + return position; + } + + @Override + public ReplayWindow window(String streamId) { + Objects.requireNonNull(streamId, "streamId"); + List retained = retained(streamId); + if (retained.isEmpty()) { + return ReplayWindow.empty(streamId); + } + return new ReplayWindow( + streamId, + Optional.of(retained.get(0).event().position()), + Optional.of(retained.get(retained.size() - 1).event().position())); + } + + @Override + public List replayAfter(String streamId, long afterPosition, int limit) { + Objects.requireNonNull(streamId, "streamId"); + if (afterPosition < 0) { + throw new IllegalArgumentException("a cursor cannot be negative"); + } + if (limit < 1) { + throw new IllegalArgumentException("a replay of nothing is not a replay"); + } + if (!window(streamId).canResumeAfter(afterPosition)) { + throw new ReplayCursorUnavailableException(streamId, afterPosition); + } + return retained(streamId).stream() + .map(Stored::event) + .filter(event -> event.position() > afterPosition) + .limit(limit) + .toList(); + } + + private List retained(String streamId) { + Instant now = clock.instant(); + return streams.getOrDefault(streamId, List.of()).stream() + .filter(stored -> stored.retainedUntil().isAfter(now)) + .toList(); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/realtime/testkit/LiveEventReplayContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/realtime/testkit/LiveEventReplayContract.java new file mode 100644 index 00000000..4c7e5b1f --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/realtime/testkit/LiveEventReplayContract.java @@ -0,0 +1,213 @@ +package dev.caskeleton.application.realtime.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.realtime.LiveEventReplayPort; +import dev.caskeleton.application.realtime.ReplayCursorUnavailableException; +import dev.caskeleton.application.realtime.ReplayWindow; +import dev.caskeleton.application.realtime.ReplayedEvent; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link LiveEventReplayPort} promises a reconnecting client, run against the in-memory + * fake and the JPA history on real PostgreSQL. + * + *

        Writing history is not on the port (a transport reads it and never writes it), so each + * implementation supplies its own {@link #append}. Retention is measured on {@link #clock()}, which + * the implementation is built with and the contract moves. + */ +public abstract class LiveEventReplayContract { + + private final ContractClock clock = new ContractClock(Instant.parse("2026-11-03T00:00:00Z")); + + /** + * The clock the implementation must measure retention against; the contract moves it. + * + * @return the clock + */ + protected final Clock clock() { + return clock; + } + + /** + * The port under test; the same instance for the whole test. + * + * @return the port + */ + protected abstract LiveEventReplayPort replay(); + + /** + * Appends an event the way the store's writer does. + * + * @param streamId which stream + * @param payload the encoded event + * @return the position the event was given + */ + protected abstract long append(String streamId, String payload); + + /** + * How long an appended event stays replayable in this store. + * + * @return the retention + */ + protected abstract Duration retention(); + + private void elapse(Duration duration) { + clock.now = clock.now.plus(duration); + } + + private static String newStream() { + return "contract-" + UUID.randomUUID(); + } + + @Test + @DisplayName("빈 stream은 보존 범위가 없고 처음부터 replay해도 빈 목록이다") + void anEmptyStreamHasNoWindowAndReplaysNothing() { + // given + String stream = newStream(); + + // when + List replayed = replay().replayAfter(stream, 0, 10); + + // then + assertThat(replayed).isEmpty(); + assertThat(replay().window(stream)).isEqualTo(ReplayWindow.empty(stream)); + } + + @Test + @DisplayName("위치는 stream마다 1부터 붙고 replay는 cursor 다음부터 위치 오름차순이다") + void replayReturnsWhatFollowsTheCursorInPositionOrder() { + // given + String stream = newStream(); + long first = append(stream, "a"); + append(stream, "b"); + append(stream, "c"); + + // when + List replayed = replay().replayAfter(stream, first, 10); + + // then + assertThat(first).isEqualTo(1); + assertThat(replayed).extracting(ReplayedEvent::position).containsExactly(2L, 3L); + assertThat(replayed).extracting(ReplayedEvent::payload).containsExactly("b", "c"); + } + + @Test + @DisplayName("replay는 limit보다 많이 돌려주지 않는다") + void replayReturnsAtMostTheLimit() { + // given + String stream = newStream(); + append(stream, "a"); + append(stream, "b"); + append(stream, "c"); + + // when + List replayed = replay().replayAfter(stream, 0, 2); + + // then + assertThat(replayed).extracting(ReplayedEvent::payload).containsExactly("a", "b"); + } + + @Test + @DisplayName("다른 stream의 이벤트는 섞이지 않고 위치도 따로 센다") + void streamsDoNotMix() { + // given + String stream = newStream(); + String other = newStream(); + append(stream, "mine"); + long otherPosition = append(other, "theirs"); + + // when + List replayed = replay().replayAfter(stream, 0, 10); + + // then + assertThat(otherPosition).isEqualTo(1); + assertThat(replayed).extracting(ReplayedEvent::payload).containsExactly("mine"); + } + + @Test + @DisplayName("window는 보존 중인 가장 이른 위치와 가장 늦은 위치를 알려준다") + void theWindowSpansWhatIsRetained() { + // given + String stream = newStream(); + append(stream, "a"); + append(stream, "b"); + + // when + ReplayWindow window = replay().window(stream); + + // then + assertThat(window.earliestRetained()).contains(1L); + assertThat(window.latestRetained()).contains(2L); + } + + @Test + @DisplayName("보존 기간이 지난 이벤트는 replay되지 않고 그보다 앞선 cursor는 재스냅샷을 요구한다") + void anExpiredEventIsNotReplayedAndAnOlderCursorIsUnavailable() { + // given + String stream = newStream(); + append(stream, "expires"); + elapse(retention().dividedBy(2)); + append(stream, "survives"); + elapse(retention().dividedBy(2).plusSeconds(1)); + + // when + Throwable tooOld = catchThrowable(() -> replay().replayAfter(stream, 0, 10)); + + // then + assertThat(tooOld).isInstanceOf(ReplayCursorUnavailableException.class); + assertThat(replay().replayAfter(stream, 1, 10)) + .extracting(ReplayedEvent::payload) + .containsExactly("survives"); + assertThat(replay().window(stream).earliestRetained()).contains(2L); + } + + @Test + @DisplayName("모두 만료된 뒤에도 위치는 다시 쓰이지 않는다") + void positionsAreNotReusedAfterEverythingExpired() { + // given + String stream = newStream(); + append(stream, "old"); + elapse(retention().plusSeconds(1)); + + // when + long next = append(stream, "new"); + + // then + assertThat(next).isEqualTo(2); + } + + /** A clock only the contract moves. */ + private static final class ContractClock extends Clock { + + private Instant now; + + private ContractClock(Instant now) { + this.now = now; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + throw new UnsupportedOperationException("the contract clock is UTC only"); + } + + @Override + public Instant instant() { + return now; + } + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/secret/testkit/InMemorySecretSource.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/secret/testkit/InMemorySecretSource.java new file mode 100644 index 00000000..3539b889 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/secret/testkit/InMemorySecretSource.java @@ -0,0 +1,28 @@ +package dev.caskeleton.application.secret.testkit; + +import dev.caskeleton.application.secret.SecretSourcePort; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** + * In-memory {@link SecretSourcePort} for use-case and composition tests. + * + *

        Keeps the port's one rule — a blank value is absent — so a presence check tested over it + * behaves as it will over a real backend. {@link SecretSourceContract} holds it and the backends to + * the same cases. + */ +public final class InMemorySecretSource implements SecretSourcePort { + + private final Map secrets; + + public InMemorySecretSource(Map secrets) { + this.secrets = Map.copyOf(Objects.requireNonNull(secrets, "secrets")); + } + + @Override + public Optional resolve(String key) { + String value = secrets.get(Objects.requireNonNull(key, "key")); + return value == null || value.isBlank() ? Optional.empty() : Optional.of(value); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/secret/testkit/SecretSourceContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/secret/testkit/SecretSourceContract.java new file mode 100644 index 00000000..cae2a54b --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/secret/testkit/SecretSourceContract.java @@ -0,0 +1,68 @@ +package dev.caskeleton.application.secret.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.secret.SecretSourcePort; +import java.util.Map; +import java.util.Optional; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link SecretSourcePort} promises, run against the in-memory fake and every backend. + * + *

        The rule that matters is the port's own: a blank value is absent. A presence check written + * against a fake that hands back {@code ""} passes in a test and lets an empty secret through in + * production, which is the bypass the port exists to close. + */ +public abstract class SecretSourceContract { + + /** + * A source holding exactly {@code secrets}; called once per test. + * + * @param secrets key to raw value, blank values included + * @return the source under test + */ + protected abstract SecretSourcePort sourceWith(Map secrets); + + @Test + @DisplayName("설정된 값은 그대로 돌려준다") + void aConfiguredValueResolvesToItself() { + // given + SecretSourcePort source = sourceWith(Map.of("app.contract.secret", "s3cr3t-value")); + + // when + Optional resolved = source.resolve("app.contract.secret"); + + // then + assertThat(resolved).contains("s3cr3t-value"); + } + + @Test + @DisplayName("없는 키는 비어 있다") + void anUnknownKeyIsAbsent() { + // given + SecretSourcePort source = sourceWith(Map.of("app.contract.secret", "s3cr3t-value")); + + // when + Optional resolved = source.resolve("app.contract.missing"); + + // then + assertThat(resolved).isEmpty(); + } + + @Test + @DisplayName("빈 값과 공백뿐인 값은 없는 것으로 본다") + void aBlankValueIsAbsent() { + // given + SecretSourcePort source = + sourceWith(Map.of("app.contract.empty", "", "app.contract.blank", " \t")); + + // when + Optional empty = source.resolve("app.contract.empty"); + + // then + assertThat(empty).isEmpty(); + assertThat(source.resolve("app.contract.blank")).isEmpty(); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/security/testkit/AuthorizationContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/security/testkit/AuthorizationContract.java new file mode 100644 index 00000000..604903a0 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/security/testkit/AuthorizationContract.java @@ -0,0 +1,123 @@ +package dev.caskeleton.application.security.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.security.AuthorizationDeniedException; +import dev.caskeleton.application.security.AuthorizationPort; +import dev.caskeleton.application.security.AuthorizationPrincipal; +import dev.caskeleton.shared.security.Permission; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link AuthorizationPort} promises a guarded use case: it returns only when one of the + * caller's roles grants the required permission, and otherwise fails closed with {@link + * AuthorizationDeniedException} naming the caller and the permission. Run against the in-memory + * fake and the web adapter's role registry. + */ +public abstract class AuthorizationContract { + + private static final Permission READ = new Permission("worklog", "read"); + private static final Permission WRITE = new Permission("worklog", "write"); + private static final Permission CLOSE = new Permission("worklog", "close"); + + /** + * A port where each role grants exactly the given permissions. + * + * @param rolePermissions role name to the permissions it grants + * @return the port under test + */ + protected abstract AuthorizationPort portGranting(Map> rolePermissions); + + private AuthorizationPort port() { + return portGranting(Map.of("user", Set.of(READ, WRITE), "closer", Set.of(CLOSE))); + } + + @Test + @DisplayName("역할이 준 권한이면 통과한다") + void aPermissionTheRoleGrantsPasses() { + // given + AuthorizationPort port = port(); + + // when + Throwable thrown = + catchThrowable( + () -> + port.requirePermission(new AuthorizationPrincipal("alice", Set.of("user")), WRITE)); + + // then + assertThat(thrown).isNull(); + } + + @Test + @DisplayName("역할이 주지 않은 권한은 호출자와 권한을 담아 거부한다") + void aPermissionTheRoleDoesNotGrantIsDeniedNamingCallerAndPermission() { + // given + AuthorizationPort port = port(); + + // when + Throwable thrown = + catchThrowable( + () -> + port.requirePermission(new AuthorizationPrincipal("alice", Set.of("user")), CLOSE)); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + AuthorizationDeniedException.class, + denied -> { + assertThat(denied.subject()).isEqualTo("alice"); + assertThat(denied.requiredPermission()).isEqualTo(CLOSE); + }); + } + + @Test + @DisplayName("역할이 없는 호출자는 거부된다") + void aCallerWithoutRolesIsDenied() { + // given + AuthorizationPort port = port(); + + // when + Throwable thrown = + catchThrowable( + () -> port.requirePermission(new AuthorizationPrincipal("bob", Set.of()), READ)); + + // then + assertThat(thrown).isInstanceOf(AuthorizationDeniedException.class); + } + + @Test + @DisplayName("모르는 역할은 아무 권한도 주지 않는다") + void anUnknownRoleGrantsNothing() { + // given + AuthorizationPort port = port(); + + // when + Throwable thrown = + catchThrowable( + () -> port.requirePermission(new AuthorizationPrincipal("bob", Set.of("guest")), READ)); + + // then + assertThat(thrown).isInstanceOf(AuthorizationDeniedException.class); + } + + @Test + @DisplayName("여러 역할의 권한은 합쳐진다") + void permissionsOfSeveralRolesCombine() { + // given + AuthorizationPort port = port(); + + // when + Throwable thrown = + catchThrowable( + () -> + port.requirePermission( + new AuthorizationPrincipal("carol", Set.of("user", "closer")), CLOSE)); + + // then + assertThat(thrown).isNull(); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/security/testkit/InMemoryAuthorization.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/security/testkit/InMemoryAuthorization.java new file mode 100644 index 00000000..89a45cfc --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/security/testkit/InMemoryAuthorization.java @@ -0,0 +1,39 @@ +package dev.caskeleton.application.security.testkit; + +import dev.caskeleton.application.security.AuthorizationDeniedException; +import dev.caskeleton.application.security.AuthorizationPort; +import dev.caskeleton.application.security.AuthorizationPrincipal; +import dev.caskeleton.shared.security.Permission; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * In-memory {@link AuthorizationPort}: each role grants exactly the permissions it is given, an + * unknown role grants none, and a missing permission fails closed with {@link + * AuthorizationDeniedException}. {@link AuthorizationContract} holds it and the web adapter to the + * same cases. + */ +public final class InMemoryAuthorization implements AuthorizationPort { + + private final Map> rolePermissions; + + /** + * A port granting {@code rolePermissions}. + * + * @param rolePermissions role name to the permissions it grants + */ + public InMemoryAuthorization(Map> rolePermissions) { + this.rolePermissions = Map.copyOf(Objects.requireNonNull(rolePermissions, "rolePermissions")); + } + + @Override + public void requirePermission(AuthorizationPrincipal principal, Permission required) { + boolean granted = + principal.roles().stream() + .anyMatch(role -> rolePermissions.getOrDefault(role, Set.of()).contains(required)); + if (!granted) { + throw new AuthorizationDeniedException(principal.subject(), required); + } + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java index d83e1eb4..fd0e237b 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java @@ -7,20 +7,30 @@ import java.util.List; import java.util.function.Supplier; /** - * Runs every action in place, for tests over fakes that have no transaction to open, and records - * which boundaries ran so a test can assert them. + * Runs every action in place, for tests over fakes that have no transaction to open, records which + * boundaries committed, and keeps the commit and rollback rules of the real port. * *

          - *
        • {@link #committed()} lists the boundaries whose action returned, in completion order; an - * action that throws is rolled back and not listed. + *
        • {@link #committed()} lists the boundaries whose work committed, in completion order. A + * boundary that throws is rolled back and not listed; a boundary that joined its caller is + * listed only once the caller commits. *
        • {@link #active()} is true while an action runs, so a fake can record whether it was called - * inside a transaction. - *
        • {@link #inRootWrite} rejects an active transaction, as the real port does. + * inside a transaction; {@link #readOnly()} says whether that transaction came from {@link + * #inRead}. + *
        • {@code inWrite} and {@code inRead} join an active transaction, as {@code REQUIRED} does; + * {@code inNew} always runs in a transaction of its own; {@link #inRootWrite} rejects an + * active transaction before running its action. + *
        • A joined boundary that throws dooms the transaction it joined: the caller may catch the + * exception, but its own commit then fails with {@link IllegalStateException} and nothing in + * that transaction commits — what Spring reports as {@code UnexpectedRollbackException}. + *
        • {@link #onRollback(Runnable)} lets a fake undo what it wrote when the active transaction + * rolls back, so a test over fakes sees the same state the database would leave. *
        • {@link #rejectingNesting()} also fails any boundary opened inside another, for use cases * that must commit each step on its own. *
        * - *

        Single-threaded: one instance per test. + *

        {@link TransactionPortContract} holds it to the same cases as the Spring adapter on a real + * database. Single-threaded: one instance per test. */ public final class DirectTransactionPort implements TransactionPort { @@ -34,7 +44,7 @@ public final class DirectTransactionPort implements TransactionPort { private final boolean rejectNesting; private final List committed = new ArrayList<>(); - private boolean active; + private Transaction current; public DirectTransactionPort() { this(false); @@ -49,14 +59,31 @@ public final class DirectTransactionPort implements TransactionPort { return new DirectTransactionPort(true); } - /** Boundaries whose action returned, in completion order. */ + /** Boundaries whose work committed, in completion order. */ public List committed() { return List.copyOf(committed); } /** Whether an action is running right now. */ public boolean active() { - return active; + return current != null; + } + + /** Whether the transaction running right now is a read-only one, opened by {@link #inRead}. */ + public boolean readOnly() { + return current != null && current.readOnly; + } + + /** + * Runs {@code undo} if the transaction active now rolls back; undo actions run newest first. + * + * @throws IllegalStateException when no transaction is active + */ + public void onRollback(Runnable undo) { + if (current == null) { + throw new IllegalStateException("no transaction is active to roll back"); + } + current.undo.add(undo); } @Override @@ -66,7 +93,7 @@ public final class DirectTransactionPort implements TransactionPort { @Override public T inRootWrite(Supplier action) { - if (active) { + if (current != null) { throw new NestedRootTransactionRejectedException(); } return run(Boundary.ROOT_WRITE, action); @@ -83,17 +110,64 @@ public final class DirectTransactionPort implements TransactionPort { } private T run(Boundary boundary, Supplier action) { - if (active && rejectNesting) { + if (current != null && rejectNesting) { throw new IllegalStateException(boundary + " transaction opened inside another"); } - boolean outer = active; - active = true; + if (current != null && boundary != Boundary.NEW) { + return join(boundary, action); + } + Transaction suspended = current; + Transaction transaction = new Transaction(boundary == Boundary.READ); + current = transaction; try { - T result = action.get(); + T result; + try { + result = action.get(); + } catch (RuntimeException | Error failure) { + transaction.rollBack(); + throw failure; + } + if (transaction.doomed) { + transaction.rollBack(); + throw new IllegalStateException( + boundary + " transaction rolled back: a boundary that joined it failed"); + } + committed.addAll(transaction.joined); committed.add(boundary); return result; } finally { - active = outer; + current = suspended; + } + } + + private T join(Boundary boundary, Supplier action) { + Transaction joined = current; + try { + T result = action.get(); + joined.joined.add(boundary); + return result; + } catch (RuntimeException | Error failure) { + joined.doomed = true; + throw failure; + } + } + + /** One physical transaction: what joined it, whether it is doomed, and how to undo it. */ + private static final class Transaction { + + private final boolean readOnly; + private final List joined = new ArrayList<>(); + private final List undo = new ArrayList<>(); + private boolean doomed; + + private Transaction(boolean readOnly) { + this.readOnly = readOnly; + } + + private void rollBack() { + for (int i = undo.size() - 1; i >= 0; i--) { + undo.get(i).run(); + } } } } diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionPortContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionPortContract.java new file mode 100644 index 00000000..69b7d2d8 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionPortContract.java @@ -0,0 +1,311 @@ +package dev.caskeleton.application.transaction.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.transaction.NestedRootTransactionRejectedException; +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link TransactionPort} promises a use case, run unchanged against the in-memory port + * ({@link DirectTransactionPort}) and the Spring adapter on a real database. + * + *

        A use-case test runs over the in-memory port and the service runs over the Spring one. If the + * two disagree about what rolls back, the use-case test is green for a unit of work that commits + * half its writes in production (review 2026-11-01 01-05). The cases are the ones a caller builds + * on: an action's write commits when it returns and disappears when it throws, a joined boundary + * shares its caller's fate, {@code inNew} does not, {@code inRootWrite} refuses to run inside + * another transaction, and a read transaction does not write. + * + *

        The contract sees commits through a {@link TransactionProbe} the implementation supplies. + */ +public abstract class TransactionPortContract { + + /** + * The port under test; called once per test. + * + * @return a port whose transactions govern {@link #probe()} + */ + protected abstract TransactionPort transactions(); + + /** + * A fresh, empty probe the port's transactions govern; called once per test. + * + * @return the probe + */ + protected abstract TransactionProbe probe(); + + @Test + @DisplayName("네 경계 모두 action을 트랜잭션 안에서 돌린다") + void everyBoundaryRunsItsActionInsideATransaction() { + // given + TransactionPort transactions = transactions(); + TransactionProbe probe = probe(); + + // when + List inside = + List.of( + transactions.inWrite(probe::inTransaction), + transactions.inRootWrite(probe::inTransaction), + transactions.inRead(probe::inTransaction), + transactions.inNew(probe::inTransaction)); + + // then + assertThat(inside).containsExactly(true, true, true, true); + assertThat(probe.inTransaction()).isFalse(); + } + + @Test + @DisplayName("inWrite는 action의 값을 돌려주고 그 쓰기를 커밋한다") + void aWriteReturnsTheActionsValueAndCommitsItsWrite() { + // given + TransactionPort transactions = transactions(); + TransactionProbe probe = probe(); + + // when + String value = transactions.inWrite(written(probe, "write", "value")); + + // then + assertThat(value).isEqualTo("value"); + assertThat(probe.committed()).containsExactly("write"); + } + + @Test + @DisplayName("action이 던진 예외는 같은 인스턴스로 전파되고 그 쓰기는 커밋되지 않는다") + void aThrowingActionPropagatesItsExceptionAndCommitsNothing() { + // given + TransactionPort transactions = transactions(); + TransactionProbe probe = probe(); + IllegalStateException failure = new IllegalStateException("the action failed"); + + // when + Throwable thrown = + catchThrowable( + () -> + transactions.inWrite( + () -> { + probe.write("rolled-back"); + throw failure; + })); + + // then + assertThat(thrown).isSameAs(failure); + assertThat(probe.committed()).isEmpty(); + } + + @Test + @DisplayName("최상위 inRootWrite는 action의 값을 돌려주고 그 쓰기를 커밋한다") + void aTopLevelRootWriteCommits() { + // given + TransactionPort transactions = transactions(); + TransactionProbe probe = probe(); + + // when + String value = transactions.inRootWrite(written(probe, "root", "value")); + + // then + assertThat(value).isEqualTo("value"); + assertThat(probe.committed()).containsExactly("root"); + } + + @Test + @DisplayName("inWrite 안의 inRootWrite는 action을 부르지 않고 거부된다") + void aRootWriteInsideAWriteIsRejectedBeforeItsActionRuns() { + // given + TransactionPort transactions = transactions(); + AtomicBoolean rootActionRan = new AtomicBoolean(); + + // when + Throwable rejected = + transactions.inWrite(() -> catchThrowable(() -> rootWrite(transactions, rootActionRan))); + + // then + assertThat(rejected).isInstanceOf(NestedRootTransactionRejectedException.class); + assertThat(rootActionRan).isFalse(); + } + + @Test + @DisplayName("inNew 안의 inRootWrite도 action을 부르지 않고 거부된다") + void aRootWriteInsideANewTransactionIsRejectedBeforeItsActionRuns() { + // given + TransactionPort transactions = transactions(); + AtomicBoolean rootActionRan = new AtomicBoolean(); + + // when + Throwable rejected = + transactions.inNew(() -> catchThrowable(() -> rootWrite(transactions, rootActionRan))); + + // then + assertThat(rejected).isInstanceOf(NestedRootTransactionRejectedException.class); + assertThat(rootActionRan).isFalse(); + } + + @Test + @DisplayName("inRead 안의 inRootWrite도 action을 부르지 않고 거부된다") + void aRootWriteInsideAReadIsRejectedBeforeItsActionRuns() { + // given + TransactionPort transactions = transactions(); + AtomicBoolean rootActionRan = new AtomicBoolean(); + + // when + Throwable rejected = + transactions.inRead(() -> catchThrowable(() -> rootWrite(transactions, rootActionRan))); + + // then + assertThat(rejected).isInstanceOf(NestedRootTransactionRejectedException.class); + assertThat(rootActionRan).isFalse(); + } + + @Test + @DisplayName("안쪽 inWrite는 바깥 트랜잭션에 참여해 바깥이 롤백되면 함께 사라진다") + void aJoinedWriteRollsBackWithItsCaller() { + // given + TransactionPort transactions = transactions(); + TransactionProbe probe = probe(); + + // when + Throwable thrown = + catchThrowable( + () -> + transactions.inWrite( + () -> { + probe.write("outer"); + transactions.inWrite(() -> probe.write("joined")); + throw new IllegalStateException("the caller rolls back"); + })); + + // then + assertThat(thrown).hasMessage("the caller rolls back"); + assertThat(probe.committed()).isEmpty(); + } + + @Test + @DisplayName("참여한 안쪽 경계가 실패하면 바깥이 그 예외를 삼켜도 바깥 쓰기는 커밋되지 않는다") + void aFailedJoinedBoundaryDoomsItsCallerEvenWhenTheCallerSwallowsTheFailure() { + // given + TransactionPort transactions = transactions(); + TransactionProbe probe = probe(); + IllegalStateException joinedFailure = new IllegalStateException("the joined boundary failed"); + + // when + Throwable thrown = + catchThrowable( + () -> + transactions.inWrite( + () -> { + probe.write("outer"); + Throwable swallowed = + catchThrowable( + () -> + transactions.inWrite( + () -> { + probe.write("joined"); + throw joinedFailure; + })); + return swallowed; + })); + + // then + assertThat(thrown).isInstanceOf(RuntimeException.class).isNotSameAs(joinedFailure); + assertThat(probe.committed()).isEmpty(); + } + + @Test + @DisplayName("inNew의 쓰기는 바깥 트랜잭션이 롤백돼도 따로 커밋된다") + void aNewTransactionCommitsEvenWhenItsCallerRollsBack() { + // given + TransactionPort transactions = transactions(); + TransactionProbe probe = probe(); + + // when + Throwable thrown = + catchThrowable( + () -> + transactions.inWrite( + () -> { + probe.write("outer"); + transactions.inNew(() -> probe.write("independent")); + throw new IllegalStateException("the caller rolls back"); + })); + + // then + assertThat(thrown).hasMessage("the caller rolls back"); + assertThat(probe.committed()).containsExactly("independent"); + } + + @Test + @DisplayName("inNew가 실패해도 바깥 트랜잭션의 쓰기는 커밋된다") + void aFailedNewTransactionLeavesItsCallerCommittable() { + // given + TransactionPort transactions = transactions(); + TransactionProbe probe = probe(); + + // when + transactions.inWrite( + () -> { + probe.write("outer"); + return catchThrowable( + () -> + transactions.inNew( + () -> { + probe.write("independent"); + throw new IllegalStateException("the independent write failed"); + })); + }); + + // then + assertThat(probe.committed()).containsExactly("outer"); + } + + @Test + @DisplayName("inRead 안의 쓰기는 거부되고 아무것도 커밋되지 않는다") + void aReadTransactionRefusesWrites() { + // given + TransactionPort transactions = transactions(); + TransactionProbe probe = probe(); + + // when + Throwable thrown = catchThrowable(() -> transactions.inRead(() -> probe.write("read"))); + + // then + assertThat(thrown).isInstanceOf(RuntimeException.class); + assertThat(probe.committed()).isEmpty(); + } + + @Test + @DisplayName("Runnable 오버로드도 Supplier 경계처럼 쓰기를 커밋한다") + void theRunnableOverloadsCommitLikeTheSupplierOnes() { + // given + TransactionPort transactions = transactions(); + TransactionProbe probe = probe(); + + // when + transactions.inWrite((Runnable) () -> probe.write("runnable-write")); + transactions.inRootWrite((Runnable) () -> probe.write("runnable-root")); + transactions.inNew((Runnable) () -> probe.write("runnable-new")); + + // then + assertThat(probe.committed()) + .containsExactly("runnable-new", "runnable-root", "runnable-write"); + } + + private static Supplier written(TransactionProbe probe, String mark, T value) { + return () -> { + probe.write(mark); + return value; + }; + } + + private static Object rootWrite(TransactionPort transactions, AtomicBoolean actionRan) { + return transactions.inRootWrite( + () -> { + actionRan.set(true); + return null; + }); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionProbe.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionProbe.java new file mode 100644 index 00000000..d98e633c --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionProbe.java @@ -0,0 +1,27 @@ +package dev.caskeleton.application.transaction.testkit; + +import java.util.List; + +/** + * A transactional resource the {@link TransactionPortContract} writes through, so that the contract + * can see what a boundary committed and what it rolled back. + * + *

        Each implementation of the contract supplies the probe its transactions actually govern: a + * table on the database a Spring transaction runs against, or a list the in-memory port undoes on + * rollback. The contract only ever asks the three questions below. + */ +public interface TransactionProbe { + + /** + * Writes {@code mark} through the transaction active on this thread. + * + * @throws RuntimeException when the active transaction refuses writes (a read-only one) + */ + void write(String mark); + + /** The marks a reader outside any transaction sees — what has committed — in ascending order. */ + List committed(); + + /** Whether a transaction is active on this thread right now. */ + boolean inTransaction(); +} diff --git a/src/application-fileserver/build.gradle b/src/application-fileserver/build.gradle index 43f7cc40..41282aad 100644 --- a/src/application-fileserver/build.gradle +++ b/src/application-fileserver/build.gradle @@ -9,10 +9,16 @@ dependencies { implementation project(':application-core') implementation project(':shared-contract') - // Port contracts (`*Contract`) are abstract JUnit classes that the in-memory fakes here and the - // JPA adapters in persistence-fileserver both extend, so a use-case test that passes against a - // fake is passing against the behaviour the real store is held to (AGENTS.md test rule 6). - // FileserverException's error code is a shared-contract type; the contracts assert on it. + // The port owner's test fixtures: one hand-rolled fake per port, and the abstract port + // contracts (`*Contract`) that a fake and the real adapter both extend (AGENTS.md test rule 6, + // capability criterion 5). A use-case test that passes against a fake is passing against the + // behaviour the JPA adapters in persistence-fileserver are held to. Adapters reach them with + // `testImplementation testFixtures(...)`. FileserverException's error code is a shared-contract + // type; the contracts assert on it. + testFixturesImplementation project(':application-core') + // DirectTransactions records and injects faults around application-core's shared fake rather + // than being a second transaction port of its own. + testFixturesImplementation testFixtures(project(':application-core')) testFixturesImplementation project(':shared-contract') testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' testFixturesImplementation 'org.assertj:assertj-core' diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/content/CreateContentCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/content/CreateContentCommand.java index d30d99b3..fb91f851 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/content/CreateContentCommand.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/content/CreateContentCommand.java @@ -22,8 +22,9 @@ public record CreateContentCommand( Objects.requireNonNull(uploadId, "uploadId"); Objects.requireNonNull(namespace, "namespace"); Objects.requireNonNull(expectedLength, "expectedLength"); - if (maximumLength <= 0) { - throw new IllegalArgumentException("maximumLength must be positive"); + // 0 is a real ceiling: a declared empty upload must refuse its first byte. + if (maximumLength < 0) { + throw new IllegalArgumentException("maximumLength must not be negative"); } if (expectedLength.isPresent() && expectedLength.getAsLong() < 0) { throw new IllegalArgumentException("expectedLength must not be negative"); diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileQuotaPort.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileQuotaPort.java index 72a51057..8aa1b726 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileQuotaPort.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileQuotaPort.java @@ -17,4 +17,12 @@ public interface FileQuotaPort { void commit(QuotaReservation reservation, long actualBytes); void release(QuotaReservation reservation); + + /** + * Bytes the scope holds now: live reservations plus committed usage. + * + *

        What a configured namespace limit is compared against; an expired or released reservation no + * longer counts. + */ + long usedBytes(QuotaScope scope); } diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java index db60ce18..0c1a1c2a 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java @@ -38,8 +38,9 @@ import java.util.Optional; * Copies a readable file into a new file the caller owns. * *

        A copy writes new bytes, so it passes the same capacity checks an upload does: {@link - * TransferAdmissionController} refuses it at the hard high-water mark, and the target namespace's - * quota is reserved before the bytes move and committed with the record's publication. + * TransferAdmissionController} refuses it at the hard high-water mark, the target namespace must be + * one {@link TargetNamespacePolicy} opens to copies, and the target namespace's quota is checked + * against its limit, reserved before the bytes move and committed with the record's publication. */ @RequiresPermission("file:copy") @UseCaseCapability( @@ -58,6 +59,7 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase { private final FileAccessPolicyPort accessPolicy; private final OriginalFilenamePolicy filenamePolicy; private final UploadPolicy uploadPolicy; + private final TargetNamespacePolicy targetNamespaces; private final UploadIdentifierPort identifierFactory; private final TransactionPort transactions; private final Clock clock; @@ -66,6 +68,7 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase { FileMetadataPort metadataStore, CopyContentPort copyGateway, UploadPolicies policies, + TargetNamespacePolicy targetNamespaces, FileQuotaPort quotaService, TransferAdmissionController admissionController, UploadIdentifierPort identifierFactory, @@ -78,6 +81,7 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase { this.accessPolicy = policies.access(); this.filenamePolicy = policies.filenames(); this.uploadPolicy = policies.upload(); + this.targetNamespaces = Objects.requireNonNull(targetNamespaces, "targetNamespaces"); this.identifierFactory = Objects.requireNonNull(identifierFactory, "identifierFactory"); this.transactions = Objects.requireNonNull(transactions, "transactions"); this.clock = Objects.requireNonNull(clock, "clock"); @@ -89,6 +93,7 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase { FileRecord source = FileRecords.require(metadataStore, command.sourceFileId()); accessPolicy.authorize( FileOperation.COPY, context.subject(), Optional.of(source.toDescriptor())); + targetNamespaces.requireAllowed(command.targetNamespace()); ContentPreconditions.requireDigestMatches(source, command.expectedSha256()); FileRecords.requireReadable(source); @@ -105,18 +110,20 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase { FileId targetId = identifierFactory.newFileId(); CopyTarget target = transactions.inWrite( - () -> - new CopyTarget( - quotaService.reserve(scope, bytes, uploadPolicy.reservationTtl()), - metadataStore.insert( - new FileRecordDraft( - targetId, - command.targetNamespace(), - filename.value(), - source.verifiedMediaType().or(source::claimedMediaType), - source.actualSize(), - // The copy belongs to whoever made it, not to the source's owner. - context.subject().asOwner())))); + () -> { + uploadPolicy.namespaceQuota().requireRoom(quotaService, scope, bytes); + return new CopyTarget( + quotaService.reserve(scope, bytes, uploadPolicy.reservationTtl()), + metadataStore.insert( + new FileRecordDraft( + targetId, + command.targetNamespace(), + filename.value(), + source.verifiedMediaType().or(source::claimedMediaType), + source.actualSize(), + // The copy belongs to whoever made it, not to the source's owner. + context.subject().asOwner()))); + }); StoredContent copied; try { diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java index 59605a19..ba23d23f 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java @@ -18,7 +18,7 @@ import dev.caskeleton.application.transaction.TransactionPort; import java.util.Objects; import java.util.Optional; -/** Moves a readable file to another namespace. */ +/** Moves a readable file to another namespace that {@link TargetNamespacePolicy} opens. */ @RequiresPermission("file:move") @UseCaseCapability( transactionMode = TransactionMode.WRITE, @@ -30,14 +30,17 @@ public class MoveFileApplicationUseCase implements MoveFileUseCase { private final FileMetadataPort metadataStore; private final FileAccessPolicyPort accessPolicy; + private final TargetNamespacePolicy targetNamespaces; private final TransactionPort transactions; public MoveFileApplicationUseCase( FileMetadataPort metadataStore, FileAccessPolicyPort accessPolicy, + TargetNamespacePolicy targetNamespaces, TransactionPort transactions) { this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore"); this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.targetNamespaces = Objects.requireNonNull(targetNamespaces, "targetNamespaces"); this.transactions = Objects.requireNonNull(transactions, "transactions"); } @@ -47,6 +50,7 @@ public class MoveFileApplicationUseCase implements MoveFileUseCase { FileRecord record = FileRecords.require(metadataStore, fileId); accessPolicy.authorize( FileOperation.MOVE, command.context().subject(), Optional.of(record.toDescriptor())); + targetNamespaces.requireAllowed(command.targetNamespace()); ContentPreconditions.requireDigestMatches(record, command.expectedSha256()); FileRecords.requireReadable(record); diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/TargetNamespacePolicy.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/TargetNamespacePolicy.java new file mode 100644 index 00000000..2cafb3b8 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/TargetNamespacePolicy.java @@ -0,0 +1,44 @@ +package dev.caskeleton.application.fileserver.lifecycle; + +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; +import java.util.Objects; +import java.util.Set; + +/** + * The namespaces a copy or a move may write into. + * + *

        The target comes from the request body, and a namespace is also the quota and ownership + * grouping (see {@link StorageNamespace}). Without a list, any caller holding {@code file:copy} or + * {@code file:move} could place files — and charge their bytes — in a namespace it was never meant + * to reach. The default list is the upload default namespace alone; a deployment that wants more + * names them. + * + *

        The refusal is {@code ACCESS_DENIED}: the namespace exists as a name, the caller is just not + * permitted to write there. + */ +public record TargetNamespacePolicy(Set allowed) { + + public TargetNamespacePolicy { + Objects.requireNonNull(allowed, "allowed"); + if (allowed.isEmpty()) { + throw new IllegalArgumentException( + "at least one target namespace is required: an empty list refuses every copy and move"); + } + allowed = Set.copyOf(allowed); + } + + public static TargetNamespacePolicy only(StorageNamespace... allowed) { + return new TargetNamespacePolicy(Set.of(allowed)); + } + + public void requireAllowed(StorageNamespace target) { + if (!allowed.contains(target)) { + throw new FileserverException( + "target namespace is not open to copy or move", + FileserverFailureContext.of(FileserverErrorCode.ACCESS_DENIED, false)); + } + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/NamespaceQuota.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/NamespaceQuota.java new file mode 100644 index 00000000..1e02fb89 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/quota/NamespaceQuota.java @@ -0,0 +1,60 @@ +package dev.caskeleton.application.fileserver.quota; + +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; +import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; +import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; +import java.util.Objects; +import java.util.OptionalLong; + +/** + * The most bytes one namespace may hold, reserved and committed together. + * + *

        No limit configured means unlimited: whether a template's namespaces are capped is a service's + * policy, and the volume itself is already protected by the transfer admission's hard high-water + * mark. A configured limit is enforced, never merely recorded — a reservation that would take the + * namespace past it is refused with {@code QUOTA_EXCEEDED} before any record or byte exists. + * + *

        Known limit, stated rather than hidden: the check reads usage and then reserves, and two + * reservations in different transactions can both pass the read. The overshoot is bounded by the + * reservations admitted at the same moment (transfer admission caps those per instance), and the + * next reservation after them is refused. Making the check exact needs a per-namespace lock row or + * a vendor-specific advisory lock in the persistence adapter; neither exists yet, and a quota that + * is right up to concurrent admission is what this template promises. + */ +public record NamespaceQuota(OptionalLong limitBytes) { + + public NamespaceQuota { + Objects.requireNonNull(limitBytes, "limitBytes"); + if (limitBytes.isPresent() && limitBytes.getAsLong() <= 0) { + throw new IllegalArgumentException("a namespace quota limit must be positive"); + } + } + + public static NamespaceQuota unlimited() { + return new NamespaceQuota(OptionalLong.empty()); + } + + public static NamespaceQuota ofBytes(long limitBytes) { + return new NamespaceQuota(OptionalLong.of(limitBytes)); + } + + /** + * Refuses {@code requestedBytes} when the scope already holds too much to take them. + * + *

        Run inside the boundary that reserves, immediately before the reservation. Without a limit + * it reads nothing, so an unlimited deployment pays no usage query per upload. + */ + public void requireRoom(FileQuotaPort quota, QuotaScope scope, long requestedBytes) { + if (limitBytes.isEmpty()) { + return; + } + long used = quota.usedBytes(scope); + if (used + requestedBytes > limitBytes.getAsLong()) { + throw new FileserverException( + "namespace quota would be exceeded", + FileserverFailureContext.of(FileserverErrorCode.QUOTA_EXCEEDED, false)); + } + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java index bf5a15aa..82ac7a21 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java @@ -140,7 +140,11 @@ public class AppendUploadApplicationUseCase implements AppendUploadUseCase { Duration.between(startedAt, clock.instant()), appended.appendedBytes()); return new AppendUploadResult( - committed.committedOffset(), appended.appendedBytes(), appended.sha256()); + committed.committedOffset(), + appended.appendedBytes(), + appended.sha256(), + committed.expectedLength(), + committed.expiresAt()); } catch (UploadOffsetMismatchException mismatch) { metrics.recordOffsetMismatch(session.mode(), "client"); throw mismatch; diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadResult.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadResult.java index d5f710dc..dd4e9385 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadResult.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadResult.java @@ -1,19 +1,39 @@ package dev.caskeleton.application.fileserver.upload; +import java.time.Instant; import java.util.Objects; +import java.util.OptionalLong; /** * Outcome of one append. * *

        {@code committedOffset} is the value the client must resume from; it only ever reflects bytes * proven durable. + * + *

        {@code expectedLength} and {@code expiresAt} are the session's own facts at the moment the + * offset committed. A protocol adapter needs them to answer the append (tus {@code Upload-Expires}, + * and whether the upload just reached its declared length), and reading them back through the + * status query would demand {@code file:read} from a caller that was only ever granted {@code + * file:upload} — after its bytes were already committed (review 05-12). */ -public record AppendUploadResult(long committedOffset, long appendedBytes, String sha256Snapshot) { +public record AppendUploadResult( + long committedOffset, + long appendedBytes, + String sha256Snapshot, + OptionalLong expectedLength, + Instant expiresAt) { public AppendUploadResult { Objects.requireNonNull(sha256Snapshot, "sha256Snapshot"); + Objects.requireNonNull(expectedLength, "expectedLength"); + Objects.requireNonNull(expiresAt, "expiresAt"); if (committedOffset < 0 || appendedBytes < 0) { throw new IllegalArgumentException("offsets must not be negative"); } } + + /** Whether this append brought the upload to its declared length; never for a deferred one. */ + public boolean reachedDeclaredLength() { + return expectedLength.isPresent() && expectedLength.getAsLong() == committedOffset; + } } diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java index 7bc88f21..481f0475 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java @@ -113,6 +113,7 @@ public class CreateUploadApplicationUseCase implements CreateUploadUseCase { CreatedUpload created = transactions.inWrite( () -> { + uploadPolicy.namespaceQuota().requireRoom(quotaService, scope, reservationBytes); QuotaReservation reservation = quotaService.reserve(scope, reservationBytes, uploadPolicy.reservationTtl()); FileRecord record = diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCase.java index 64520ca5..7c78d98d 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCase.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCase.java @@ -20,6 +20,7 @@ import dev.caskeleton.application.fileserver.api.metadata.FileRecord; import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; import dev.caskeleton.application.fileserver.api.metadata.UploadSession; import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.metadata.WriterLease; import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; import dev.caskeleton.application.fileserver.api.security.FileOperation; import dev.caskeleton.application.fileserver.api.security.RequestContext; @@ -30,6 +31,7 @@ import dev.caskeleton.application.fileserver.api.security.VerificationVerdict; import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; import dev.caskeleton.application.fileserver.cleanup.CleanupType; +import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator; import dev.caskeleton.application.fileserver.port.in.FinalizeUploadCommand; import dev.caskeleton.application.fileserver.port.in.FinalizeUploadUseCase; import dev.caskeleton.application.fileserver.recovery.RecoveryQueuePort; @@ -50,6 +52,14 @@ import java.util.OptionalLong; * transition, and quota is committed only after READY. If the metadata commit fails after * the physical publish, the caller gets an ambiguous completion and the file goes to the recovery * queue — never a READY answer the store cannot back. + * + *

        Finalize holds the writer lease an append holds, for the whole hash-verify-publish-commit + * sequence (review 05-22). Hashing and moving the staged bytes while an append — a Draft-12 client + * that defers its length, or a retried PATCH — still writes them would publish one set of bytes + * under another's digest. The lease is taken through the same {@link WriterLeaseCoordinator} the + * append uses, renewed (which re-proves the holder) right before the irreversible publish, and + * released by its token: a release keyed on the node's instance id would also have freed another + * writer's lease on the same node. */ @RequiresPermission("file:upload") @UseCaseCapability( @@ -69,6 +79,7 @@ public class FinalizeUploadApplicationUseCase implements FinalizeUploadUseCase { private final CleanupQueuePort cleanupQueue; private final RecoveryQueuePort recoveryQueue; private final FileAccessPolicyPort accessPolicy; + private final WriterLeaseCoordinator leaseCoordinator; private final PublishMode publishMode; private final TransactionPort transactions; private final Clock clock; @@ -82,6 +93,7 @@ public class FinalizeUploadApplicationUseCase implements FinalizeUploadUseCase { CleanupQueuePort cleanupQueue, RecoveryQueuePort recoveryQueue, FileAccessPolicyPort accessPolicy, + WriterLeaseCoordinator leaseCoordinator, PublishMode publishMode, TransactionPort transactions, Clock clock) { @@ -93,6 +105,7 @@ public class FinalizeUploadApplicationUseCase implements FinalizeUploadUseCase { this.cleanupQueue = cleanupQueue; this.recoveryQueue = recoveryQueue; this.accessPolicy = accessPolicy; + this.leaseCoordinator = leaseCoordinator; this.publishMode = publishMode; this.transactions = transactions; this.clock = clock; @@ -120,7 +133,24 @@ public class FinalizeUploadApplicationUseCase implements FinalizeUploadUseCase { accessPolicy.authorize( FileOperation.FINALIZE, context.subject(), Optional.of(record.toDescriptor())); requireDeclaredLengthReached(session); + UploadSessions.requireActive(sessionStore, session.uploadId(), clock.instant()); + WriterLease lease = leaseCoordinator.acquire(session.uploadId(), context.instanceId()); + try { + return finalizeUnderLease(session, record, request, lease); + } finally { + leaseCoordinator.release(lease); + } + } + + /** + * The sequence itself, run while this call holds the writer lease. + * + *

        The lease taken here is the one released by the caller, by token. Renewal before the publish + * proves the holder without changing the token, so that release still matches. + */ + private FileView finalizeUnderLease( + UploadSession session, FileRecord record, FinalizeUploadRequest request, WriterLease lease) { UploadHandle handle = contentGateway.reattach(session); String serverDigest = contentGateway.stagedDigest(handle, session.committedOffset()); requireClientDigestMatches(record, request, serverDigest); @@ -133,6 +163,8 @@ public class FinalizeUploadApplicationUseCase implements FinalizeUploadUseCase { return applyNonAcceptVerdict(verifying, session, verdict); } + // Last point before an irreversible move: refuse it if another writer took the lease over. + leaseCoordinator.renew(lease); StoredContent published; try { published = publish(handle, session, serverDigest, verifying.contentKey()); @@ -142,7 +174,7 @@ public class FinalizeUploadApplicationUseCase implements FinalizeUploadUseCase { enqueueRecovery(verifying, "PUBLISH_UNCONFIRMED", ambiguous); throw ambiguous; } - return commitReady(verifying, session, published, verdict, context); + return commitReady(verifying, session, published, verdict); } private FileRecord requireRecord(UploadSession session) { @@ -352,8 +384,7 @@ public class FinalizeUploadApplicationUseCase implements FinalizeUploadUseCase { FileRecord verifying, UploadSession session, StoredContent published, - VerificationResult verdict, - RequestContext context) { + VerificationResult verdict) { Instant publishedAt = clock.instant(); FileRecord ready; try { @@ -389,10 +420,6 @@ public class FinalizeUploadApplicationUseCase implements FinalizeUploadUseCase { .ambiguousRequiringReconciliation()); } - transactions.inWrite( - () -> { - contentGateway.releaseLease(session, context); - }); return FileView.of(ready.toDescriptor()); } diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadContentPort.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadContentPort.java index e663bf1d..4be5ae9d 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadContentPort.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadContentPort.java @@ -5,7 +5,6 @@ import dev.caskeleton.application.fileserver.api.content.FinalizeContentCommand; import dev.caskeleton.application.fileserver.api.content.StoredContent; import dev.caskeleton.application.fileserver.api.content.UploadHandle; import dev.caskeleton.application.fileserver.api.metadata.UploadSession; -import dev.caskeleton.application.fileserver.api.security.RequestContext; /** * Narrow view of the content store used by finalization. @@ -34,7 +33,4 @@ public interface UploadContentPort { ContentKey newContentKey(); StoredContent finalizeUpload(UploadHandle handle, FinalizeContentCommand command); - - /** Releases the writer lease this node holds for the session. */ - void releaseLease(UploadSession session, RequestContext context); } diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadPolicy.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadPolicy.java index 1edec731..dd128077 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadPolicy.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadPolicy.java @@ -1,6 +1,7 @@ package dev.caskeleton.application.fileserver.upload; import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.quota.NamespaceQuota; import java.time.Duration; import java.time.Instant; import java.util.Objects; @@ -22,7 +23,8 @@ public record UploadPolicy( Duration reservationTtl, Duration leaseDuration, StorageNamespace defaultNamespace, - Duration sessionTtl) { + Duration sessionTtl, + NamespaceQuota namespaceQuota) { public UploadPolicy { if (maximumFileSize <= 0 || initialReservationBytes <= 0) { @@ -38,11 +40,12 @@ public record UploadPolicy( if (sessionTtl.isNegative() || sessionTtl.isZero()) { throw new IllegalArgumentException("sessionTtl must be positive"); } + Objects.requireNonNull(namespaceQuota, "namespaceQuota"); } /** * Design standard profile: 100 MiB maximum, 8 MiB initial reservation, 24 h reservation TTL, 30 s - * lease, 1 h upload session. + * lease, 1 h upload session, no namespace quota limit. */ public static UploadPolicy standard(StorageNamespace defaultNamespace) { return new UploadPolicy( @@ -51,7 +54,20 @@ public record UploadPolicy( Duration.ofHours(24), Duration.ofSeconds(30), defaultNamespace, - Duration.ofHours(1)); + Duration.ofHours(1), + NamespaceQuota.unlimited()); + } + + /** The same policy with a namespace quota limit. */ + public UploadPolicy withNamespaceQuota(NamespaceQuota quota) { + return new UploadPolicy( + maximumFileSize, + initialReservationBytes, + reservationTtl, + leaseDuration, + defaultNamespace, + sessionTtl, + quota); } /** When a session opened at {@code now} stops accepting bytes. */ diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java index 9133db82..ef13282c 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java @@ -50,9 +50,15 @@ final class UploadSessions { return session; } + /** + * The staging ceiling: the declared length when there is one, 0 included. + * + *

        A declared 0-byte upload used to be raised to a 1-byte ceiling, which let it accept a byte + * it could then never finalize (the declared length no longer matched) until the session expired. + */ static long effectiveMaximum(UploadPolicy policy, OptionalLong expectedLength) { return expectedLength.isPresent() - ? Math.min(policy.maximumFileSize(), Math.max(expectedLength.getAsLong(), 1)) + ? Math.min(policy.maximumFileSize(), expectedLength.getAsLong()) : policy.maximumFileSize(); } diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadUseCasesTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadUseCasesTest.java index bea18987..ca699ab3 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadUseCasesTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadUseCasesTest.java @@ -91,6 +91,25 @@ class DownloadUseCasesTest { refused -> assertThat(refused.code()).isEqualTo(FileserverErrorCode.ACCESS_DENIED)); } + @Test + @DisplayName("다른 사용자가 만든 파일은 메타데이터도 읽을 수 없다") + void describingAFileAnotherCallerOwnsIsRefused() { + // given + FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + RequestContext stranger = + new RequestContext(FileAccessSubject.of("user-2", Set.of("uploader")), "trace-2", "node-a"); + + // when + Throwable failure = + catchThrowable(() -> describeFile.handle(new DescribeFileQuery(ready.fileId(), stranger))); + + // then + assertThat(failure) + .isInstanceOfSatisfying( + FileserverException.class, + refused -> assertThat(refused.code()).isEqualTo(FileserverErrorCode.ACCESS_DENIED)); + } + @Test void nonReadyFileIsRejectedAndNeverOpened() { FileRecord verifying = ReadyFileFixture.verifying(metadata, SIZE, DIGEST); diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java index 437435f5..db33316f 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java @@ -23,6 +23,7 @@ import dev.caskeleton.application.fileserver.cleanup.CleanupType; import dev.caskeleton.application.fileserver.port.in.CopyFileCommand; import dev.caskeleton.application.fileserver.port.in.DeleteFileCommand; import dev.caskeleton.application.fileserver.port.in.MoveFileCommand; +import dev.caskeleton.application.fileserver.quota.NamespaceQuota; import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; import dev.caskeleton.application.fileserver.quota.TransferAdmissionProperties; import dev.caskeleton.application.fileserver.testkit.DirectTransactions; @@ -73,23 +74,31 @@ class FileLifecycleUseCasesTest { /** How full the pool reads; the standard profile refuses writes from 0.85. */ private OptionalDouble storageUsed = OptionalDouble.empty(); + /** Copies and moves may write into the upload namespace and {@link #TARGET}, nowhere else. */ + private static final TargetNamespacePolicy TARGETS = + TargetNamespacePolicy.only(FileserverFixtures.NAMESPACE, TARGET); + + private static final StorageNamespace NOT_OPEN = StorageNamespace.of("tenant-c"); + private final CopyFileApplicationUseCase copy = - new CopyFileApplicationUseCase( - metadata, - copyGateway, - new UploadPolicies( - accessPolicy, - OriginalFilenamePolicy.standard(), - UploadPolicy.standard(FileserverFixtures.NAMESPACE)), - quota, - new TransferAdmissionController( - TransferAdmissionProperties.standard(), () -> storageUsed, MAX_FILE), - new SequentialUploadIdentifierFactory(), - transactions, - Clock.fixed(FileserverFixtures.NOW, ZoneOffset.UTC)); + copyUnder(UploadPolicy.standard(FileserverFixtures.NAMESPACE)); private final MoveFileApplicationUseCase move = - new MoveFileApplicationUseCase(metadata, accessPolicy, transactions); + new MoveFileApplicationUseCase(metadata, accessPolicy, TARGETS, transactions); + + private CopyFileApplicationUseCase copyUnder(UploadPolicy policy) { + return new CopyFileApplicationUseCase( + metadata, + copyGateway, + new UploadPolicies(accessPolicy, OriginalFilenamePolicy.standard(), policy), + TARGETS, + quota, + new TransferAdmissionController( + TransferAdmissionProperties.standard(), () -> storageUsed, MAX_FILE), + new SequentialUploadIdentifierFactory(), + transactions, + Clock.fixed(FileserverFixtures.NOW, ZoneOffset.UTC)); + } @Test void logicalDeleteBlocksDownloadBeforePhysicalDeleteCompletes() { @@ -332,6 +341,121 @@ class FileLifecycleUseCasesTest { assertThat(copyGateway.copies()).isEmpty(); } + @Test + @DisplayName("허용 목록에 없는 namespace로의 복사는 ACCESS_DENIED로 거절되고 바이트도 쿼터도 건드리지 않는다") + void copyIntoANamespaceThePolicyDoesNotOpenIsRefusedBeforeAnythingIsWritten() { + // given + FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + copyGateway.copiesContentOf(SIZE, DIGEST); + + // when + Throwable failure = + catchThrowable( + () -> + copy.handle( + new CopyFileCommand( + source.fileId(), + NOT_OPEN, + Optional.empty(), + Optional.empty(), + FileserverFixtures.context()))); + + // then + assertThat(List.of(codeOf(failure), copyGateway.copies(), quota.reservationCount())) + .containsExactly(FileserverErrorCode.ACCESS_DENIED, List.of(), 0); + } + + @Test + @DisplayName("허용 목록에 없는 namespace로의 이동은 ACCESS_DENIED로 거절되고 파일은 제자리에 남는다") + void moveIntoANamespaceThePolicyDoesNotOpenIsRefusedAndTheFileStays() { + // given + FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + + // when + Throwable failure = + catchThrowable( + () -> + move.handle( + new MoveFileCommand( + ready.fileId(), NOT_OPEN, Optional.empty(), FileserverFixtures.context()))); + + // then + assertThat(List.of(codeOf(failure), metadata.find(ready.fileId()).orElseThrow().namespace())) + .containsExactly(FileserverErrorCode.ACCESS_DENIED, ready.namespace()); + } + + @Test + @DisplayName("대상 namespace 쿼터 상한을 넘기는 복사는 QUOTA_EXCEEDED로 거절되고 레코드도 바이트도 만들지 않는다") + void copyThatWouldTakeTheTargetNamespacePastItsQuotaIsRefused() { + // given + FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + copyGateway.copiesContentOf(SIZE, DIGEST); + quota.alreadyHolds(QuotaScope.ofNamespace(TARGET.value()), 15); + CopyFileApplicationUseCase limited = + copyUnder( + UploadPolicy.standard(FileserverFixtures.NAMESPACE) + .withNamespaceQuota(NamespaceQuota.ofBytes(24))); + + // when + Throwable failure = catchThrowable(() -> limited.handle(copyOf(source))); + + // then + assertThat( + List.of( + codeOf(failure), + copyGateway.copies(), + metadata.find(nextCopyId()).isPresent(), + quota.reservationCount())) + .containsExactly(FileserverErrorCode.QUOTA_EXCEEDED, List.of(), false, 0); + } + + @Test + @DisplayName("쿼터 상한을 정확히 채우는 복사는 허용된다") + void copyThatExactlyFillsTheTargetNamespaceQuotaIsAdmitted() { + // given + FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + copyGateway.copiesContentOf(SIZE, DIGEST); + quota.alreadyHolds(QuotaScope.ofNamespace(TARGET.value()), 14); + CopyFileApplicationUseCase limited = + copyUnder( + UploadPolicy.standard(FileserverFixtures.NAMESPACE) + .withNamespaceQuota(NamespaceQuota.ofBytes(24))); + + // when + FileView copied = limited.handle(copyOf(source)); + + // then + assertThat(List.of(copied.state(), quota.usedBytes(QuotaScope.ofNamespace(TARGET.value())))) + .containsExactly(FileState.READY, 24L); + } + + @Test + @DisplayName("다른 사용자가 만든 파일은 file:move 권한이 있어도 옮길 수 없다") + void movingAFileAnotherCallerOwnsIsRefusedAndTheFileStays() { + // given + FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + RequestContext stranger = + new RequestContext(FileAccessSubject.of("user-2", Set.of("uploader")), "trace-2", "node-a"); + + // when + Throwable failure = + catchThrowable( + () -> + move.handle( + new MoveFileCommand(ready.fileId(), TARGET, Optional.empty(), stranger))); + + // then + assertThat(List.of(codeOf(failure), metadata.find(ready.fileId()).orElseThrow().namespace())) + .containsExactly(FileserverErrorCode.ACCESS_DENIED, ready.namespace()); + } + + private static Object codeOf(Throwable failure) { + if (failure == null) { + return "no failure"; + } + return failure instanceof FileserverException refused ? refused.code() : failure; + } + private static CopyFileCommand copyOf(FileRecord source) { return new CopyFileCommand( source.fileId(), TARGET, Optional.empty(), Optional.empty(), FileserverFixtures.context()); diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGatewayContractTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGatewayContractTest.java new file mode 100644 index 00000000..d532890f --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGatewayContractTest.java @@ -0,0 +1,14 @@ +package dev.caskeleton.application.fileserver.testkit; + +import dev.caskeleton.application.fileserver.upload.UploadStoragePort; + +/** The fake every use case test stages bytes in obeys the same rules as the real store. */ +class FakeUploadStorageGatewayContractTest extends UploadStoragePortContract { + + private final FakeUploadStorageGateway storage = new FakeUploadStorageGateway(); + + @Override + protected UploadStoragePort storage() { + return storage; + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCaseTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCaseTest.java index 0e751b9c..48fcd04c 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCaseTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCaseTest.java @@ -14,8 +14,10 @@ import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; import dev.caskeleton.application.fileserver.api.metadata.FileRecord; import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; import dev.caskeleton.application.fileserver.api.metadata.UploadSession; +import dev.caskeleton.application.fileserver.api.metadata.WriterLease; import dev.caskeleton.application.fileserver.api.security.FileOperation; import dev.caskeleton.application.fileserver.api.security.VerificationResult; +import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator; import dev.caskeleton.application.fileserver.port.in.FinalizeUploadCommand; import dev.caskeleton.application.fileserver.testkit.DirectTransactions; import dev.caskeleton.application.fileserver.testkit.FakeFileAccessPolicy; @@ -27,10 +29,13 @@ import dev.caskeleton.application.fileserver.testkit.InMemoryFileMetadataStore; import dev.caskeleton.application.fileserver.testkit.InMemoryRecoveryQueue; import dev.caskeleton.application.fileserver.testkit.InMemoryUploadSessionStore; import java.time.Clock; +import java.time.Duration; import java.time.ZoneOffset; +import java.util.List; import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class FinalizeUploadApplicationUseCaseTest { @@ -59,6 +64,11 @@ class FinalizeUploadApplicationUseCaseTest { cleanup, recovery, accessPolicy, + new WriterLeaseCoordinator( + sessions, + Duration.ofSeconds(30), + transactions, + Clock.fixed(FileserverFixtures.NOW, ZoneOffset.UTC)), PublishMode.ATOMIC_MOVE_PREFERRED, transactions, Clock.fixed(FileserverFixtures.NOW, ZoneOffset.UTC)); @@ -114,7 +124,7 @@ class FinalizeUploadApplicationUseCaseTest { FileserverFixtures.context())); assertThat(quota.committedBytes()).isEqualTo(10); - assertThat(content.leaseReleases()).isEqualTo(1); + assertThat(sessions.find(session.uploadId()).orElseThrow().leaseToken()).isEmpty(); } @Test @@ -315,13 +325,74 @@ class FinalizeUploadApplicationUseCaseTest { assertThat(recovery.reasons()).containsValue("READY_COMMIT_UNCONFIRMED"); assertThat(transactions.openedWrites()) - .as("recovery must survive the failed ambient READY transaction") - .endsWith("new"); + .as( + "recovery must survive the failed ambient READY transaction; the writer-lease release" + + " (05-22) is the one write after it") + .endsWith("new", "write"); assertThat(metadata.find(verifyingRecord.fileId()).orElseThrow().state()) .isNotEqualTo(FileState.READY); assertThat(quota.anyCommitted()).isFalse(); } + /** + * 05-22: finalize hashes and moves the staged bytes, so it must hold the writer lease an append + * holds. Another writer — here one on the same node, which an instance-id check cannot tell apart + * — keeps its lease and the bytes stay unpublished. + */ + @Test + @DisplayName( + "다른 writer가 lease를 잡고 있으면 finalize는 CONCURRENT_MODIFICATION으로 거절되고 그 lease를 건드리지 않는다") + void aFinalizeWhileAnotherWriterHoldsTheLeaseIsRefusedAndLeavesThatLeaseInPlace() { + // given + UploadSession session = uploadedSession(10); + WriterLease otherWriter = + sessions.acquireLease( + session.uploadId(), + FileserverFixtures.context().instanceId(), + FileserverFixtures.NOW, + Duration.ofSeconds(30), + session.version()); + + // when + Throwable failure = + catchThrowable( + () -> + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context()))); + + // then + assertThat( + List.of( + String.valueOf( + failure instanceof FileserverException refused ? refused.code() : failure), + content.publishedCount(), + sessions.find(session.uploadId()).orElseThrow().leaseToken())) + .containsExactly( + FileserverErrorCode.CONCURRENT_MODIFICATION.name(), + 0, + Optional.of(otherWriter.token())); + } + + @Test + @DisplayName("finalize가 끝나면 자기가 잡은 writer lease를 token으로 풀어 세션에 lease가 남지 않는다") + void aCompletedFinalizeLeavesNoWriterLeaseOnTheSession() { + // given + UploadSession session = uploadedSession(10); + + // when + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context())); + + // then + assertThat(sessions.find(session.uploadId()).orElseThrow().leaseToken()).isEmpty(); + } + @Test void aRecordStillCreatedIsWalkedThroughUploadingToReady() { // given diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/ResumableUploadUseCasesTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/ResumableUploadUseCasesTest.java index e3f1423e..42c9422d 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/ResumableUploadUseCasesTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/ResumableUploadUseCasesTest.java @@ -49,6 +49,7 @@ import java.util.Map; import java.util.Optional; import java.util.OptionalLong; import java.util.Set; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class ResumableUploadUseCasesTest { @@ -298,6 +299,29 @@ class ResumableUploadUseCasesTest { .isEqualTo(6); } + /** 05-23a: the staging ceiling is the declared length itself, even when that length is 0. */ + @Test + @DisplayName("0바이트로 선언한 업로드는 첫 1바이트를 FILE_TOO_LARGE로 거절하고 offset을 0에 둔다") + void aZeroByteDeclaredUploadRefusesItsFirstByte() { + // given + UploadSessionView created = service.create(createRequest(0), FileserverFixtures.context()); + + // when + Throwable failure = + catchThrowable( + () -> + service.append( + created.uploadId(), 0, channel("x"), 1, FileserverFixtures.context())); + + // then + assertThat( + List.of( + String.valueOf( + failure instanceof FileserverException refused ? refused.code() : failure), + sessions.find(created.uploadId()).orElseThrow().committedOffset())) + .containsExactly(FileserverErrorCode.FILE_TOO_LARGE.name(), 0L); + } + @Test void anOffsetTheClientGuessedWrongIsRejectedWithoutWriting() { UploadSessionView created = service.create(createRequest(), FileserverFixtures.context()); diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCaseTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCaseTest.java index 531c01e3..32286cc9 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCaseTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCaseTest.java @@ -67,7 +67,14 @@ class UploadFileApplicationUseCaseTest { // given AmbiguousCompletionException ambiguous = AmbiguousCompletionException.forUpload("publish outcome unknown", UPLOAD_ID); - AppendUploadUseCase append = command -> new AppendUploadResult(3, 3, FileserverFixtures.DIGEST); + AppendUploadUseCase append = + command -> + new AppendUploadResult( + 3, + 3, + FileserverFixtures.DIGEST, + java.util.OptionalLong.of(3), + FileserverFixtures.NOW.plusSeconds(3600)); FinalizeUploadUseCase finalizer = command -> { throw ambiguous; diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/DirectTransactions.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/DirectTransactions.java similarity index 51% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/DirectTransactions.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/DirectTransactions.java index 1a893950..8c450460 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/DirectTransactions.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/DirectTransactions.java @@ -1,29 +1,34 @@ package dev.caskeleton.application.fileserver.testkit; import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; /** - * Runs every boundary inline and records that it was opened. + * application-core's {@link DirectTransactionPort}, plus the two things fileserver tests ask of it + * that it does not do: the order boundaries were opened in, and a fault on the next + * independent boundary. * - *

        The fake stores in this package are in-memory maps with no rollback, so this cannot prove that - * a failed unit undoes its writes — that is what the real-PostgreSQL readiness suite is for. What - * it does prove is the part unit tests can: that a service opens a boundary at all, and how many. - * {@link #openedWrites()} lets a test assert that two writes which must commit together were asked - * for inside one boundary rather than two. {@link #failNextNew(RuntimeException)} makes the next - * independent boundary fail, which is how a test reaches a compensation that could not be written. + *

        This was a second hand-written transaction port. Joining, nesting, root-write rejection and + * what counts as committed are now the shared fake's, the one held to the transaction port + * contract; this class only records and injects. The fake stores in this package are in-memory maps + * with no rollback, so this cannot prove that a failed unit undoes its writes — that is what the + * real-PostgreSQL readiness suite is for. {@link #openedWrites()} lets a test assert that two + * writes which must commit together were asked for inside one boundary rather than two. {@link + * #failNextNew(RuntimeException)} makes the next independent boundary fail, which is how a test + * reaches a compensation that could not be written. */ public final class DirectTransactions implements TransactionPort { + private final DirectTransactionPort transactions = new DirectTransactionPort(); private final List opened = new ArrayList<>(); private RuntimeException nextNewFailure; - private int depth; /** True while an action runs inside one of this port's boundaries. */ public boolean active() { - return depth > 0; + return transactions.active(); } /** Makes the next {@link #inNew(Supplier)} fail with {@code failure} instead of running. */ @@ -43,19 +48,19 @@ public final class DirectTransactions implements TransactionPort { @Override public T inWrite(Supplier action) { opened.add("write"); - return run(action); + return transactions.inWrite(action); } @Override public T inRootWrite(Supplier action) { opened.add("root-write"); - return run(action); + return transactions.inRootWrite(action); } @Override public T inRead(Supplier action) { opened.add("read"); - return run(action); + return transactions.inRead(action); } @Override @@ -66,15 +71,6 @@ public final class DirectTransactions implements TransactionPort { nextNewFailure = null; throw failure; } - return run(action); - } - - private T run(Supplier action) { - depth++; - try { - return action.get(); - } finally { - depth--; - } + return transactions.inNew(action); } } diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeAdminPorts.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeAdminPorts.java similarity index 100% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeAdminPorts.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeAdminPorts.java diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeCleanupContentGateway.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeCleanupContentGateway.java similarity index 100% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeCleanupContentGateway.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeCleanupContentGateway.java diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeCopyContentGateway.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeCopyContentGateway.java similarity index 100% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeCopyContentGateway.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeCopyContentGateway.java diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeDownloadContentGateway.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeDownloadContentGateway.java similarity index 100% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeDownloadContentGateway.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeDownloadContentGateway.java diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java similarity index 100% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java similarity index 52% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java index ceaaac82..3e3170db 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java @@ -6,15 +6,31 @@ import dev.caskeleton.application.fileserver.api.metadata.QuotaReservationStatus import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; import java.time.Duration; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.UUID; -/** Hand-rolled quota service recording reservations, commits, and releases. */ +/** + * Hand-rolled quota service recording reservations, commits, and releases. + * + *

        It keeps the ledger the durable adapter keeps: a live reservation counts toward its scope's + * usage until it is committed (then the committed bytes count instead) or released (then nothing + * counts). That is what a configured namespace limit is compared against. + */ public final class FakeFileQuotaService implements FileQuotaPort { private final List reserved = new ArrayList<>(); private final List released = new ArrayList<>(); private final List committed = new ArrayList<>(); + private final Map liveBytes = new HashMap<>(); + private final Map scopes = new HashMap<>(); + private final Map committedUsage = new HashMap<>(); + + /** Books usage the scope already holds, as if earlier uploads had committed it. */ + public void alreadyHolds(QuotaScope scope, long bytes) { + committedUsage.merge(scope, bytes, Long::sum); + } @Override public QuotaReservation reserve(QuotaScope scope, long expectedBytes, Duration ttl) { @@ -28,24 +44,41 @@ public final class FakeFileQuotaService implements FileQuotaPort { QuotaReservationStatus.RESERVED, 0); reserved.add(reservation); + liveBytes.put(reservation.reservationId(), expectedBytes); + scopes.put(reservation.reservationId(), scope); return reservation; } @Override public void extend(QuotaReservation reservation, long additionalBytes) { - // Extension is accounted for by the reservation total in the durable adapter; the fake only - // needs to prove the call happened without changing the recorded reservation identity. + // The recorded reservation identity stays the same; the live total grows as the durable + // adapter's does. reserved.add(reservation); + liveBytes.computeIfPresent(reservation.reservationId(), (id, bytes) -> bytes + additionalBytes); } @Override public void commit(QuotaReservation reservation, long actualBytes) { committed.add(actualBytes); + if (liveBytes.remove(reservation.reservationId()) != null) { + committedUsage.merge(scopes.get(reservation.reservationId()), actualBytes, Long::sum); + } } @Override public void release(QuotaReservation reservation) { released.add(reservation); + liveBytes.remove(reservation.reservationId()); + } + + @Override + public long usedBytes(QuotaScope scope) { + long live = + liveBytes.entrySet().stream() + .filter(entry -> scope.equals(scopes.get(entry.getKey()))) + .mapToLong(Map.Entry::getValue) + .sum(); + return live + committedUsage.getOrDefault(scope, 0L); } public List reservedScopes() { diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeQuotaCommitGateway.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeQuotaCommitGateway.java similarity index 100% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeQuotaCommitGateway.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeQuotaCommitGateway.java diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeReconciliationContentProbe.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeReconciliationContentProbe.java similarity index 100% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeReconciliationContentProbe.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeReconciliationContentProbe.java diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadContentGateway.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeUploadContentGateway.java similarity index 87% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadContentGateway.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeUploadContentGateway.java index d594d8ed..6bad3ea4 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadContentGateway.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeUploadContentGateway.java @@ -7,11 +7,9 @@ import dev.caskeleton.application.fileserver.api.content.FinalizeContentCommand; import dev.caskeleton.application.fileserver.api.content.StoredContent; import dev.caskeleton.application.fileserver.api.content.UploadHandle; import dev.caskeleton.application.fileserver.api.metadata.UploadSession; -import dev.caskeleton.application.fileserver.api.security.RequestContext; import dev.caskeleton.application.fileserver.upload.UploadContentPort; import java.util.LinkedHashMap; import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; /** * Hand-rolled content gateway. @@ -22,7 +20,6 @@ import java.util.concurrent.atomic.AtomicInteger; public final class FakeUploadContentGateway implements UploadContentPort { private final Map published = new LinkedHashMap<>(); - private final AtomicInteger leaseReleases = new AtomicInteger(); private String stagedDigest = "a".repeat(64); private RuntimeException finalizeFailure; private int keyCounter; @@ -61,11 +58,6 @@ public final class FakeUploadContentGateway implements UploadContentPort { return new StoredContent(key, size, command.expectedSha256().orElse(stagedDigest), true); } - @Override - public void releaseLease(UploadSession session, RequestContext context) { - leaseReleases.incrementAndGet(); - } - public boolean contentExists(ContentKey key) { return published.containsKey(key); } @@ -74,10 +66,6 @@ public final class FakeUploadContentGateway implements UploadContentPort { return published.size(); } - public int leaseReleases() { - return leaseReleases.get(); - } - private ContentKey nextKey() { String flat = String.format("%032x", ++keyCounter); return new ContentKey(flat.substring(0, 2) + '/' + flat.substring(2, 4) + '/' + flat); diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGateway.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGateway.java similarity index 84% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGateway.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGateway.java index 26fd40a8..6e5b6c73 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGateway.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGateway.java @@ -8,6 +8,7 @@ import dev.caskeleton.application.fileserver.api.content.WriteFence; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverException; import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; +import dev.caskeleton.application.fileserver.api.error.UploadOffsetMismatchException; import dev.caskeleton.application.fileserver.upload.UploadStoragePort; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -25,6 +26,7 @@ import java.util.Optional; public final class FakeUploadStorageGateway implements UploadStoragePort { private final Map staging = new LinkedHashMap<>(); + private final Map maximumLengths = new LinkedHashMap<>(); private boolean failNextCreate; private long physicalLengthOverride = -1; @@ -51,6 +53,7 @@ public final class FakeUploadStorageGateway implements UploadStoragePort { FileserverFailureContext.of(FileserverErrorCode.STORAGE_UNAVAILABLE, true)); } staging.put(uploadId, new ByteArrayOutputStream()); + maximumLengths.put(uploadId, maximumLength); return new FakeHandle(uploadId, namespace); } @@ -58,6 +61,7 @@ public final class FakeUploadStorageGateway implements UploadStoragePort { public UploadHandle reattachStaging( UploadId uploadId, StorageNamespace namespace, long maximumLength) { staging.computeIfAbsent(uploadId, ignored -> new ByteArrayOutputStream()); + maximumLengths.put(uploadId, maximumLength); return new FakeHandle(uploadId, namespace); } @@ -70,6 +74,10 @@ public final class FakeUploadStorageGateway implements UploadStoragePort { Optional expectedChunkSha256, WriteFence fence) { ByteArrayOutputStream sink = staging.get(handle.uploadId()); + // Same rule as the real store: the offset must be the staged length, checked before writing. + if (expectedOffset != sink.size()) { + throw UploadOffsetMismatchException.of(handle.uploadId(), expectedOffset, sink.size()); + } ByteArrayOutputStream chunk = new ByteArrayOutputStream(); ByteBuffer buffer = ByteBuffer.allocate(8192); try { @@ -89,6 +97,12 @@ public final class FakeUploadStorageGateway implements UploadStoragePort { throw new UncheckedIOException(exception); } byte[] received = chunk.toByteArray(); + // The ceiling the staging was created with, 0 included: nothing past it is ever kept. + if (sink.size() + received.length > maximumLengths.getOrDefault(handle.uploadId(), 0L)) { + throw new FileserverException( + "upload exceeds the configured maximum file size", + FileserverFailureContext.of(FileserverErrorCode.FILE_TOO_LARGE, false)); + } // Same rule as the real store: checked against this call's bytes, before anything is kept. if (expectedChunkSha256.isPresent() && !sha256Hex(received).equalsIgnoreCase(expectedChunkSha256.get())) { @@ -114,6 +128,7 @@ public final class FakeUploadStorageGateway implements UploadStoragePort { @Override public void discardStaging(UploadId uploadId) { staging.remove(uploadId); + maximumLengths.remove(uploadId); } private static String sha256Hex(byte[] payload) { diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FileserverFixtures.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileserverFixtures.java similarity index 87% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FileserverFixtures.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileserverFixtures.java index a4999587..206bfe3d 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FileserverFixtures.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileserverFixtures.java @@ -33,6 +33,10 @@ public final class FileserverFixtures { context().subject().asOwner()); } + /** + * A session as the last append leaves it: the offset committed and the writer lease released, so + * the next writer — a finalize, or another append — can take the lease. + */ public static UploadSession session(FileId fileId, long expectedLength, long committedOffset) { return new UploadSession( UploadId.of(UUID.randomUUID()), @@ -41,9 +45,9 @@ public final class FileserverFixtures { OptionalLong.of(expectedLength), committedOffset, NOW.plusSeconds(3600), - Optional.of("node-a"), - Optional.of(UUID.randomUUID()), - Optional.of(NOW.plusSeconds(30)), + Optional.empty(), + Optional.empty(), + Optional.empty(), false, 0, NOW, diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueue.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueue.java similarity index 100% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueue.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueue.java diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java similarity index 98% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java index c1a3fd33..3a1be230 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java @@ -174,10 +174,11 @@ public final class InMemoryUploadSessionStore return advanced; } + /** Release matches the token, exactly as the JPA statement does: another writer's lease stays. */ @Override public void releaseLease(UploadId uploadId, WriterLease lease) { UploadSession current = sessions.get(uploadId); - if (current == null) { + if (current == null || !current.leaseToken().map(lease.token()::equals).orElse(false)) { return; } sessions.put( diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/ReadyFileFixture.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/ReadyFileFixture.java similarity index 100% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/ReadyFileFixture.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/ReadyFileFixture.java diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/RecordingQuotaReclaimGateway.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/RecordingQuotaReclaimGateway.java similarity index 100% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/RecordingQuotaReclaimGateway.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/RecordingQuotaReclaimGateway.java diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/SequentialUploadIdentifierFactory.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/SequentialUploadIdentifierFactory.java similarity index 100% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/SequentialUploadIdentifierFactory.java rename to src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/SequentialUploadIdentifierFactory.java diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/UploadStoragePortContract.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/UploadStoragePortContract.java new file mode 100644 index 00000000..1aaa534a --- /dev/null +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/UploadStoragePortContract.java @@ -0,0 +1,180 @@ +package dev.caskeleton.application.fileserver.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.content.AppendResult; +import dev.caskeleton.application.fileserver.api.content.UploadHandle; +import dev.caskeleton.application.fileserver.api.content.WriteFence; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.upload.UploadStoragePort; +import java.io.ByteArrayInputStream; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link UploadStoragePort} must do, the fake and the real store alike. + * + *

        The application's offset, checksum and size guarantees rest on these rules. A fake that + * skipped one would let a use case test pass against behaviour no production store has, so the fake + * extends this contract exactly as the adapter does (AGENTS.md test rule 6). + */ +public abstract class UploadStoragePortContract { + + protected static final StorageNamespace NAMESPACE = StorageNamespace.of("tenant-a"); + + /** Generous enough that only the scenarios about the ceiling ever reach it. */ + protected static final long MAX_FILE = 1024L * 1024; + + /** The store under certification, fresh for each test. */ + protected abstract UploadStoragePort storage(); + + @Test + void appendsAccumulateAndTheStagingLengthCountsEveryByte() { + // given + UploadHandle handle = storage().createStaging(newUploadId(), NAMESPACE, MAX_FILE); + storage().append(handle, 0, channel("abc"), 3); + + // when + AppendResult second = storage().append(handle, 3, channel("def"), 3); + + // then + assertThat(List.of(second.committedOffset(), second.sha256(), storage().stagingLength(handle))) + .containsExactly(6L, sha256Hex("abcdef"), 6L); + } + + @Test + void anOffsetThatDisagreesWithTheStagedBytesIsRefusedWithoutWriting() { + // given + UploadHandle handle = storage().createStaging(newUploadId(), NAMESPACE, MAX_FILE); + storage().append(handle, 0, channel("abc"), 3); + + // when + Throwable failure = catchThrowable(() -> storage().append(handle, 0, channel("xyz"), 3)); + + // then + assertThat(List.of(codeOf(failure), storage().stagingLength(handle))) + .containsExactly(FileserverErrorCode.UPLOAD_OFFSET_MISMATCH, 3L); + } + + @Test + void aChunkWhoseChecksumDoesNotMatchIsRefusedAndRolledBack() { + // given + UploadHandle handle = storage().createStaging(newUploadId(), NAMESPACE, MAX_FILE); + storage().append(handle, 0, channel("abc"), 3); + + // when + Throwable failure = + catchThrowable( + () -> + storage() + .append( + handle, + 3, + channel("def"), + 3, + Optional.of(sha256Hex("not-def")), + WriteFence.unfenced())); + + // then + assertThat(List.of(codeOf(failure), storage().stagingLength(handle))) + .containsExactly(FileserverErrorCode.CHECKSUM_MISMATCH, 3L); + } + + @Test + @DisplayName("상한을 넘는 append는 FILE_TOO_LARGE로 거절되고 staging 길이는 그대로다") + void anAppendPastTheMaximumLengthIsRefusedAsTooLarge() { + // given + UploadHandle handle = storage().createStaging(newUploadId(), NAMESPACE, 3); + + // when + Throwable failure = catchThrowable(() -> storage().append(handle, 0, channel("abcd"), 4)); + + // then + assertThat(List.of(codeOf(failure), storage().stagingLength(handle))) + .containsExactly(FileserverErrorCode.FILE_TOO_LARGE, 0L); + } + + /** A declared 0-byte upload must not become a 1-byte one that can never finalize (05-23a). */ + @Test + @DisplayName("0바이트로 만든 staging은 첫 1바이트부터 FILE_TOO_LARGE로 거절한다") + void aStagingCreatedForZeroBytesRefusesTheFirstByte() { + // given + UploadHandle handle = storage().createStaging(newUploadId(), NAMESPACE, 0); + + // when + Throwable failure = catchThrowable(() -> storage().append(handle, 0, channel("x"), 1)); + + // then + assertThat(List.of(codeOf(failure), storage().stagingLength(handle))) + .containsExactly(FileserverErrorCode.FILE_TOO_LARGE, 0L); + } + + @Test + void aReattachedStagingResumesAtTheBytesAlreadyStaged() { + // given + UploadId uploadId = newUploadId(); + UploadHandle first = storage().createStaging(uploadId, NAMESPACE, MAX_FILE); + storage().append(first, 0, channel("abc"), 3); + UploadHandle reattached = storage().reattachStaging(uploadId, NAMESPACE, MAX_FILE); + + // when + AppendResult resumed = storage().append(reattached, 3, channel("def"), 3); + + // then + assertThat(List.of(resumed.committedOffset(), resumed.sha256())) + .containsExactly(6L, sha256Hex("abcdef")); + } + + @Test + void aDiscardedStagingReadsAsZeroLengthRatherThanFailing() { + // given + UploadId uploadId = newUploadId(); + UploadHandle handle = storage().createStaging(uploadId, NAMESPACE, MAX_FILE); + storage().append(handle, 0, channel("abc"), 3); + + // when + storage().discardStaging(uploadId); + + // then + assertThat(storage().stagingLength(handle)).isZero(); + } + + protected static UploadId newUploadId() { + return UploadId.of(UUID.randomUUID()); + } + + protected static ReadableByteChannel channel(String payload) { + return Channels.newChannel(new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8))); + } + + protected static String sha256Hex(String payload) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(payload.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is required by the platform", impossible); + } + } + + private static Object codeOf(Throwable failure) { + if (failure == null) { + return "no failure"; + } + return failure instanceof FileserverException refused ? refused.code() : failure; + } +} diff --git a/src/application-notification/build.gradle b/src/application-notification/build.gradle index 4ac05967..71aaa736 100644 --- a/src/application-notification/build.gradle +++ b/src/application-notification/build.gradle @@ -12,6 +12,12 @@ dependencies { // Port contracts (`*Contract`) are abstract JUnit classes that the in-memory fakes here and the // PostgreSQL adapters (persistence-jpa's postgresqlIntegrationTest lane) both extend, so a use // case test passing on a fake says something about the real store (review 04-14). + // The provider adapter contract (`provider.testkit`) lives here too: the port is this leaf's, + // so a provider adapter in any leaf extends the same contract (capability criterion 5). testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' testFixturesImplementation 'org.assertj:assertj-core' + + // Use-case tests run over application-core's shared transaction fake (DirectTransactionPort), + // the one held to the transaction port contract, not a hand-written port per test class. + testImplementation testFixtures(project(':application-core')) } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchService.java index c852b2ce..b82fe548 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchService.java @@ -1,6 +1,5 @@ package dev.caskeleton.application.notification.platform.dispatch; -import dev.caskeleton.application.notification.platform.api.CollapseSpec; import dev.caskeleton.application.notification.platform.api.NotificationVariable; import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; @@ -18,7 +17,6 @@ import dev.caskeleton.application.notification.platform.policy.RouteCandidate; import dev.caskeleton.application.notification.platform.policy.RoutingContext; import dev.caskeleton.application.notification.platform.policy.RoutingDecision; import dev.caskeleton.application.notification.platform.policy.RoutingDecisionEngine; -import dev.caskeleton.application.notification.platform.provider.ProviderCallNotStartedException; import dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence; import dev.caskeleton.application.notification.platform.provider.ProviderFailure; import dev.caskeleton.application.notification.platform.provider.ProviderProfileSnapshot; @@ -185,6 +183,15 @@ public final class NotificationDispatchService { releaseLease(lease); return; } + if (!collapseHonoured(profile, work)) { + // Checked before the attempt row exists (review 05-10). It used to run while the submission + // was being built, after the insert and outside the try, so the refusal escaped dispatch, + // left the attempt in DISPATCHING and recovery picked the same doomed request up again on + // every lease cycle. The profile will not learn collapsing on the next pass either. + failBeforeAttempt(work, lease, FailureCategory.INVALID_PAYLOAD, now); + releaseLease(lease); + return; + } DeliveryAttemptRecord attempt = transactions.inWrite( @@ -327,8 +334,9 @@ public final class NotificationDispatchService { work.request().expiresAt(), Optional.of(attempt.id().value().toString()), // The frozen collapse, not Optional.empty(). The APNs and FCM mappers can send one and - // the capability model has a flag for it; the value simply never arrived. - requireCollapseSupported(profile, work), + // the capability model has a flag for it; the value simply never arrived. dispatch() + // has already refused a collapse this profile cannot honour. + work.request().collapse(), Map.of(), TraceContext.NONE); try { @@ -339,26 +347,14 @@ public final class NotificationDispatchService { } /** - * The request's collapse specification, refused when the provider cannot honour it. + * Whether the profile can honour the request's collapse specification, if it has one. * *

        Silently dropping it would send a notification the caller believes will replace an earlier - * one and which will not — the user sees two. A typed pre-dispatch failure is the honest answer: - * nothing is transmitted, and the operator learns that this profile cannot do what was asked. + * one and which will not — the user sees two. Refusing is the honest answer: nothing is + * transmitted, and the delivery closes as an invalid payload the operator can see. */ - private static Optional requireCollapseSupported( - ProviderProfileSnapshot profile, Work work) { - var collapse = work.request().collapse(); - if (collapse.isEmpty()) { - return collapse; - } - if (!profile.capabilities().collapse()) { - throw new ProviderCallNotStartedException( - NotificationFailureCode.PROVIDER_CONFIGURATION_INVALID, - FailureCategory.INVALID_PAYLOAD, - false, - "the request asks for collapsing and this provider profile does not support it"); - } - return collapse; + private static boolean collapseHonoured(ProviderProfileSnapshot profile, Work work) { + return work.request().collapse().isEmpty() || profile.capabilities().collapse(); } private RenderedNotificationContent render(Work work, RouteCandidate route) { diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationRequestRecord.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationRequestRecord.java index 1deb2f5a..25de87e9 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationRequestRecord.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationRequestRecord.java @@ -28,9 +28,18 @@ public record NotificationRequestRecord( CorrelationId correlationId, Map metadata, Instant createdAt, - Instant updatedAt) { + Instant updatedAt, + dev.caskeleton.application.notification.platform.api.NotificationAcceptance acceptance) { public NotificationRequestRecord { + Objects.requireNonNull(acceptance, "acceptance"); + if (acceptance + == dev.caskeleton.application.notification.platform.api.NotificationAcceptance + .CONVERGED_ON_EXISTING) { + // A converged submission is answered with the earlier request's id; it never has a row. + throw new IllegalArgumentException( + "a stored request is accepted or dropped, never converged"); + } Objects.requireNonNull(id, "id"); Objects.requireNonNull(collapse, "collapse"); Objects.requireNonNull(tenantId, "tenantId"); @@ -50,10 +59,92 @@ public record NotificationRequestRecord( Objects.requireNonNull(updatedAt, "updatedAt"); } - /** Receipt for this stored request. */ + /** + * A request that will be sent: the ordinary acceptance. + * + *

        Every caller that builds a request to send uses this shape; only a deduplication drop stores + * anything else (see {@link #droppedAsDuplicate}). + */ + public NotificationRequestRecord( + NotificationId id, + TenantId tenantId, + String idempotencyKey, + String requestFingerprint, + String category, + TemplateSelection template, + String strategyType, + String variablesPayload, + Optional scheduleAt, + Optional notBefore, + Optional expiresAt, + Optional collapse, + RequestStatus status, + CorrelationId correlationId, + Map metadata, + Instant createdAt, + Instant updatedAt) { + this( + id, + tenantId, + idempotencyKey, + requestFingerprint, + category, + template, + strategyType, + variablesPayload, + scheduleAt, + notBefore, + expiresAt, + collapse, + status, + correlationId, + metadata, + createdAt, + updatedAt, + dev.caskeleton.application.notification.platform.api.NotificationAcceptance.ACCEPTED); + } + + /** + * Receipt for this stored request. + * + *

        It carries the stored acceptance, so a retry of a dropped submission is told "dropped" again + * rather than "accepted" (review 05-23c). + */ public dev.caskeleton.application.notification.platform.api.NotificationReceipt receipt() { - return dev.caskeleton.application.notification.platform.api.NotificationReceipt.accepted( - id, status, createdAt); + return new dev.caskeleton.application.notification.platform.api.NotificationReceipt( + id, status, createdAt, acceptance); + } + + /** + * This request as a deduplication window dropped it: canceled, with no recipients, and saying so. + * + *

        Stored under the submission's idempotency key so a retry converges on this answer. When the + * drop was only returned, a retry re-ran deduplication with a new id, and once the window had + * passed the same idempotency key was accepted and sent. + * + * @return the record to store in place of an accepted one + */ + public NotificationRequestRecord droppedAsDuplicate() { + return new NotificationRequestRecord( + id, + tenantId, + idempotencyKey, + requestFingerprint, + category, + template, + strategyType, + variablesPayload, + scheduleAt, + notBefore, + expiresAt, + collapse, + RequestStatus.CANCELED, + correlationId, + metadata, + createdAt, + updatedAt, + dev.caskeleton.application.notification.platform.api.NotificationAcceptance + .DROPPED_AS_DUPLICATE); } /** @@ -95,6 +186,7 @@ public record NotificationRequestRecord( correlationId, metadata, createdAt, - updatedAt); + updatedAt, + acceptance); } } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java index a5d00c3b..8c6ec788 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java @@ -205,13 +205,7 @@ public final class NotificationSubmissionService { // earlier notification that covers it. return Optional.of( switch (spec.get().action()) { - case DROP -> - new NotificationReceipt( - request.id(), - dev.caskeleton.application.notification.platform.api.RequestStatus.CANCELED, - now, - dev.caskeleton.application.notification.platform.api.NotificationAcceptance - .DROPPED_AS_DUPLICATE); + case DROP -> storeDrop(request); case RETURN_EXISTING -> requests .findById(plan.tenantId(), result.existingNotificationId().get()) @@ -228,6 +222,20 @@ public final class NotificationSubmissionService { }); } + /** + * Stores the dropped submission under its idempotency key, with no recipients. + * + *

        The receipt has to be the same every time the caller asks with that key. Returned without a + * row, the drop named an id nothing could read, and a retry after the window was accepted. + */ + private NotificationReceipt storeDrop(NotificationRequestRecord request) { + NotificationRequestInsertOutcome outcome = + requests.insert(request.droppedAsDuplicate(), List.of()); + return outcome.inserted() + ? outcome.stored().receipt() + : converge(outcome.stored(), request.requestFingerprint()); + } + private NotificationReceipt converge(NotificationRequestRecord existing, String fingerprint) { if (!existing.requestFingerprint().equals(fingerprint)) { throw new IdempotencyConflictException( diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffect.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/SuppressionSideEffect.java similarity index 63% rename from src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffect.java rename to src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/SuppressionSideEffect.java index 05d4bb62..079dc95f 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JpaNotificationSideEffect.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/SuppressionSideEffect.java @@ -1,11 +1,9 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.platform; +package dev.caskeleton.application.notification.platform.dispatch; -import dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction; import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort; import dev.caskeleton.application.notification.platform.callback.SuppressionFacts; import dev.caskeleton.application.notification.platform.contact.ContactPointStatus; -import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; import dev.caskeleton.application.notification.platform.policy.SuppressionEntry; import dev.caskeleton.application.notification.platform.policy.SuppressionId; import dev.caskeleton.application.notification.platform.policy.SuppressionReason; @@ -15,39 +13,62 @@ import dev.caskeleton.application.notification.platform.policy.SuppressionStoreP import java.time.Clock; import java.util.Objects; import java.util.Optional; -import java.util.UUID; /** - * Applies the consequences of a projected event. + * What a projected event does to the contact point and the suppression list. * *

        A hard bounce and a complaint mean different things: the first says the address is gone, the * second says the person does not want this. Both stop sending, but mapping them to one reason * would make the difference invisible to whoever later asks why an address is suppressed. + * + *

        This was {@code JpaNotificationSideEffect}, in the persistence leaf, although it touches no + * table of its own: it is a rule over two store ports, and a rule belongs to the application + * (review 2026-11-01 04-14, r3-J). Where it lived, a use-case test could only replace it with a + * no-op or with a second copy of the rule. Here it runs as itself over the contact point and + * suppression fakes, and over the JPA stores in the PostgreSQL lane, under one contract ({@code + * NotificationSideEffectContract}). The caller's transaction is the projection's; the two store + * writes refuse to run without one. + * + *

        In {@code dispatch} rather than beside the port in {@code callback}: it writes through {@link + * ContactPointStorePort}, which this package owns, and {@code callback} may not depend on it — the + * package graph is acyclic and registered (NTF-022). */ -public final class JpaNotificationSideEffect implements NotificationSideEffectPort { +public final class SuppressionSideEffect implements NotificationSideEffectPort { private final ContactPointStorePort contactPoints; private final SuppressionStorePort suppressions; + private final NotificationIdGeneratorPort ids; private final Clock clock; - public JpaNotificationSideEffect( - ContactPointStorePort contactPoints, SuppressionStorePort suppressions, Clock clock) { + /** + * The side effect over the two stores it writes. + * + * @param contactPoints where the contact point's status changes + * @param suppressions where the suppression entry is added + * @param ids where a new suppression entry's id comes from + * @param clock when the suppression takes effect + */ + public SuppressionSideEffect( + ContactPointStorePort contactPoints, + SuppressionStorePort suppressions, + NotificationIdGeneratorPort ids, + Clock clock) { this.contactPoints = Objects.requireNonNull(contactPoints, "contactPoints"); this.suppressions = Objects.requireNonNull(suppressions, "suppressions"); + this.ids = Objects.requireNonNull(ids, "ids"); this.clock = Objects.requireNonNull(clock, "clock"); } @Override public void apply(DeliveryAttemptSnapshot attempt, SuppressionFacts facts) { - CallerTransaction.require("notification side effect apply"); Objects.requireNonNull(attempt, "attempt"); Objects.requireNonNull(facts, "facts"); if (!facts.requiresSuppression()) { return; } - Optional - contactPoint = contactPoints.find(attempt.tenantId(), attempt.contactPointId()); + Optional contactPoint = + contactPoints.find(attempt.tenantId(), attempt.contactPointId()); if (contactPoint.isEmpty()) { return; } @@ -66,7 +87,7 @@ public final class JpaNotificationSideEffect implements NotificationSideEffectPo suppressions.upsert( new SuppressionEntry( - new SuppressionId(UUID.randomUUID()), + new SuppressionId(ids.nextId()), attempt.tenantId(), SuppressionScope.CONTACT_POINT, reason, diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminOperationExecutorTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminOperationExecutorTest.java index 9dd1ee1d..80b5960d 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminOperationExecutorTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/AdminOperationExecutorTest.java @@ -1,10 +1,11 @@ package dev.caskeleton.application.notification.platform.admin; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; -import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.notification.platform.admin.testkit.InMemoryAdminOperationStore; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; @@ -16,93 +17,106 @@ class AdminOperationExecutorTest { private static final AdminActor ACTOR = new AdminActor("operator-1", Set.of(), Optional.empty()); private static final String FINGERPRINT = "a".repeat(64); + private static final String OTHER_FINGERPRINT = "b".repeat(64); + + private final InMemoryAdminOperationStore store = new InMemoryAdminOperationStore(); @Test + @DisplayName("처음 claim한 operation만 claim을 쥔 채 한 쓰기 트랜잭션 안에서 부수 효과를 실행한다") void claimedOperationIsTheOnlyOutcomeThatRunsTheSideEffect() { - FakeStore store = new FakeStore(AdminOperationClaim.claimed()); - RecordingTransactions transactions = new RecordingTransactions(); + // given + DirectTransactionPort transactions = new DirectTransactionPort(); AdminOperationExecutor executor = new AdminOperationExecutor(store, transactions); AtomicInteger sideEffects = new AtomicInteger(); + // when AdminOperationResult result = executor.execute( - "op-1", - FINGERPRINT, - ACTOR, - "ADMIN_PROVIDER_STATE", - () -> { - sideEffects.incrementAndGet(); - return result("op-1"); - }); + "op-1", FINGERPRINT, ACTOR, "ADMIN_PROVIDER_STATE", sideEffect(sideEffects)); - assertThat(result.operationId()).isEqualTo("op-1"); - assertThat(sideEffects).hasValue(1); - assertThat(store.claims).isEqualTo(1); - assertThat(transactions.writes).isEqualTo(1); + // then + assertThat( + List.of( + result.operationId(), + sideEffects.get(), + store.claim("op-1", FINGERPRINT, ACTOR, "ADMIN_PROVIDER_STATE"), + transactions.committed())) + .as("the operation saves its own result; until then the id answers in-progress") + .containsExactly( + "op-1", + 1, + AdminOperationClaim.inProgress(), + List.of(DirectTransactionPort.Boundary.WRITE)); } @Test + @DisplayName("이미 끝난 operation은 부수 효과 없이 저장된 결과를 돌려준다") void replayReturnsTheStoredResultWithoutRunningTheSideEffect() { + // given AdminOperationResult previous = result("op-1"); - FakeStore store = new FakeStore(AdminOperationClaim.replay(previous)); + store.claim("op-1", FINGERPRINT, ACTOR, "ADMIN_PROVIDER_STATE"); + store.save(previous, ACTOR, "ADMIN_PROVIDER_STATE"); AdminOperationExecutor executor = - new AdminOperationExecutor(store, new RecordingTransactions()); + new AdminOperationExecutor(store, new DirectTransactionPort()); AtomicInteger sideEffects = new AtomicInteger(); + // when AdminOperationResult replayed = executor.execute( - "op-1", - FINGERPRINT, - ACTOR, - "ADMIN_PROVIDER_STATE", - () -> { - sideEffects.incrementAndGet(); - return result("op-1"); - }); + "op-1", FINGERPRINT, ACTOR, "ADMIN_PROVIDER_STATE", sideEffect(sideEffects)); - assertThat(replayed).isSameAs(previous); - assertThat(sideEffects).hasValue(0); + // then + assertThat(List.of(replayed, sideEffects.get())).containsExactly(previous, 0); } @Test + @DisplayName("다른 호출이 claim해 진행 중인 operation은 부수 효과 전에 멈춘다") void inProgressClaimStopsBeforeTheSideEffect() { - FakeStore store = new FakeStore(AdminOperationClaim.inProgress()); + // given + store.claim("op-1", FINGERPRINT, ACTOR, "ADMIN_REDRIVE"); AdminOperationExecutor executor = - new AdminOperationExecutor(store, new RecordingTransactions()); + new AdminOperationExecutor(store, new DirectTransactionPort()); AtomicInteger sideEffects = new AtomicInteger(); - assertThatThrownBy( + // when + Throwable thrown = + catchThrowable( () -> executor.execute( - "op-1", FINGERPRINT, ACTOR, "ADMIN_REDRIVE", sideEffect(sideEffects))) - .isInstanceOf(AdminOperationInProgressException.class); + "op-1", FINGERPRINT, ACTOR, "ADMIN_REDRIVE", sideEffect(sideEffects))); - assertThat(sideEffects).hasValue(0); + // then + assertThat(List.of(thrown.getClass(), sideEffects.get())) + .containsExactly(AdminOperationInProgressException.class, 0); } @Test + @DisplayName("같은 id를 다른 명령으로 보내면 부수 효과 전에 충돌로 멈춘다") void conflictingCommandStopsBeforeTheSideEffect() { - FakeStore store = new FakeStore(AdminOperationClaim.conflict()); + // given + store.claim("op-1", OTHER_FINGERPRINT, ACTOR, "ADMIN_REDRIVE"); AdminOperationExecutor executor = - new AdminOperationExecutor(store, new RecordingTransactions()); + new AdminOperationExecutor(store, new DirectTransactionPort()); AtomicInteger sideEffects = new AtomicInteger(); - assertThatThrownBy( + // when + Throwable thrown = + catchThrowable( () -> executor.execute( - "op-1", FINGERPRINT, ACTOR, "ADMIN_REDRIVE", sideEffect(sideEffects))) - .isInstanceOf(AdminOperationConflictException.class); + "op-1", FINGERPRINT, ACTOR, "ADMIN_REDRIVE", sideEffect(sideEffects))); - assertThat(sideEffects).hasValue(0); + // then + assertThat(List.of(thrown.getClass(), sideEffects.get())) + .containsExactly(AdminOperationConflictException.class, 0); } @Test @DisplayName("트랜잭션 밖에서 실패한 operation은 claim을 FAILED 결과로 닫는다") void anOperationThatFailsOutsideTheTransactionCompletesItsClaimAsFailed() { // given - FakeStore store = new FakeStore(AdminOperationClaim.claimed()); AdminOperationExecutor executor = - new AdminOperationExecutor(store, new RecordingTransactions()); + new AdminOperationExecutor(store, new DirectTransactionPort()); // when var unused = @@ -118,11 +132,12 @@ class AdminOperationExecutorTest { })); // then - assertThat(store.saved) + assertThat(store.findByOperationId("op-1")) .as( "the claim committed before the operation ran; left CLAIMED, the id answers in-progress") + .get() .extracting(AdminOperationResult::operationId, AdminOperationResult::reasonCodes) - .containsExactly("op-1", java.util.List.of("FAILED")); + .containsExactly("op-1", List.of("FAILED")); } private static Supplier sideEffect(AtomicInteger sideEffects) { @@ -134,66 +149,6 @@ class AdminOperationExecutorTest { private static AdminOperationResult result(String operationId) { return new AdminOperationResult( - operationId, - false, - 1, - Optional.empty(), - Optional.empty(), - Optional.empty(), - java.util.List.of("ok")); - } - - private static final class FakeStore implements AdminOperationStorePort { - private final AdminOperationClaim outcome; - private int claims; - private AdminOperationResult saved; - - FakeStore(AdminOperationClaim outcome) { - this.outcome = outcome; - } - - @Override - public Optional findByOperationId(String operationId) { - return Optional.empty(); - } - - @Override - public AdminOperationResult save(AdminOperationResult result, AdminActor actor, String action) { - saved = result; - return result; - } - - @Override - public AdminOperationClaim claim( - String operationId, String commandFingerprint, AdminActor actor, String action) { - claims++; - assertThat(commandFingerprint).isEqualTo(FINGERPRINT); - return outcome; - } - } - - private static final class RecordingTransactions implements TransactionPort { - private int writes; - - @Override - public T inWrite(Supplier action) { - writes++; - return action.get(); - } - - @Override - public T inRootWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } + operationId, false, 1, Optional.empty(), Optional.empty(), Optional.empty(), List.of("ok")); } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationServiceTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationServiceTest.java index 2aba79d5..2a7e002b 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationServiceTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/NotificationAdminApplicationServiceTest.java @@ -13,13 +13,18 @@ import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; -import dev.caskeleton.application.notification.platform.dispatch.NotificationPlatformNoops; +import dev.caskeleton.application.notification.platform.dispatch.AttemptSnapshots; +import dev.caskeleton.application.notification.platform.dispatch.PlatformCollaborators; import dev.caskeleton.application.notification.platform.dispatch.PlatformFakes; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryRecipientQueue; import dev.caskeleton.application.notification.platform.observation.NotificationAuditEvent; import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; import dev.caskeleton.application.notification.platform.policy.SuppressionEntry; @@ -27,6 +32,7 @@ import dev.caskeleton.application.notification.platform.policy.SuppressionId; import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; import dev.caskeleton.application.notification.platform.provider.ProviderRuntimeState; import dev.caskeleton.application.notification.platform.provider.ReconciliationResult; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; @@ -96,7 +102,8 @@ class NotificationAdminApplicationServiceTest { // given Fixture fixture = new Fixture(); DeliveryAttemptSnapshot foreign = attemptOf(new TenantId("tenant-a")); - fixture.attempts.snapshots.put(foreign.attemptId(), foreign); + AttemptSnapshots.store( + fixture.requests, fixture.attempts, foreign, RecipientDeliveryState.DISPATCHING); AdminActor tenantB = new AdminActor( "operator-b", @@ -162,13 +169,14 @@ class NotificationAdminApplicationServiceTest { @Override public ReconciliationResult reconcile(DeliveryAttemptSnapshot attempt) { - transactionOpenDuringProviderCall.add(holder.get().transactions.inTransaction()); + transactionOpenDuringProviderCall.add(holder.get().transactions.active()); return new ReconciliationResult.Unsupported(); } }); holder.set(fixture); DeliveryAttemptSnapshot attempt = attemptOf(new TenantId("tenant-a")); - fixture.attempts.snapshots.put(attempt.attemptId(), attempt); + AttemptSnapshots.store( + fixture.requests, fixture.attempts, attempt, RecipientDeliveryState.DISPATCHING); AdminActor operator = new AdminActor( "operator-1", Set.of(NotificationAdminAuthority.RECONCILE), Optional.empty()); @@ -208,15 +216,15 @@ class NotificationAdminApplicationServiceTest { } private static final class Fixture { - private final PlatformFakes.AttemptStore attempts = new PlatformFakes.AttemptStore(); - private final PlatformFakes.RequestStore requests = new PlatformFakes.RequestStore(); - private final PlatformFakes.RecipientStore recipients = - new PlatformFakes.RecipientStore(requests); + private final InMemoryNotificationRequestStore requests = + new InMemoryNotificationRequestStore(); + private final InMemoryDeliveryAttemptStore attempts = + new InMemoryDeliveryAttemptStore(requests); + private final InMemoryRecipientQueue recipients = new InMemoryRecipientQueue(requests, CLOCK); private final RecordingRuntime runtime = new RecordingRuntime(); private final RecordingOperations operations = new RecordingOperations(); private final RecordingAudit audit = new RecordingAudit(); - private final PlatformFakes.RecordingTransactions transactions = - new PlatformFakes.RecordingTransactions(); + private final DirectTransactionPort transactions = new DirectTransactionPort(); private final NotificationAdminApplicationService service; private Fixture() { @@ -229,8 +237,8 @@ class NotificationAdminApplicationServiceTest { private Fixture(ReconciliationGatewayPort gateway) { ReconciliationService reconciliation = gateway == null - ? NotificationPlatformNoops.reconciliation(attempts, recipients, CLOCK) - : NotificationPlatformNoops.reconciliation(attempts, recipients, gateway, CLOCK); + ? PlatformCollaborators.reconciliation(attempts, recipients, CLOCK) + : PlatformCollaborators.reconciliation(attempts, recipients, gateway, CLOCK); service = new NotificationAdminApplicationService( new AdminAuthorizationGuard(), diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/testkit/InMemoryAdminOperationStoreTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/testkit/InMemoryAdminOperationStoreTest.java new file mode 100644 index 00000000..cafe1342 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/admin/testkit/InMemoryAdminOperationStoreTest.java @@ -0,0 +1,26 @@ +package dev.caskeleton.application.notification.platform.admin.testkit; + +import dev.caskeleton.application.notification.platform.admin.AdminOperationStorePort; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeEach; + +/** The in-memory fake held to the same contract as the JPA store. */ +class InMemoryAdminOperationStoreTest extends AdminOperationStoreContract { + + private InMemoryAdminOperationStore store; + + @BeforeEach + void freshStore() { + store = new InMemoryAdminOperationStore(); + } + + @Override + protected AdminOperationStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/CallbackIngestionAtomicityTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/CallbackIngestionAtomicityTest.java index 169287a2..b6a574b5 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/CallbackIngestionAtomicityTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/CallbackIngestionAtomicityTest.java @@ -2,22 +2,23 @@ package dev.caskeleton.application.notification.platform.callback; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.NormalizedEventType; import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; import dev.caskeleton.application.notification.platform.api.ProviderId; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.callback.testkit.InMemoryProviderEventLedger; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; import dev.caskeleton.application.notification.platform.port.in.IngestProviderCallbackCommand; -import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; -import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.function.Supplier; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -28,18 +29,21 @@ class CallbackIngestionAtomicityTest { private static final ProviderId SES = new ProviderId("ses"); private static final ProviderProfileId PROFILE = new ProviderProfileId("email-main"); - private final RecordingLedger ledger = new RecordingLedger(); - private final RecordingTransactions transactions = new RecordingTransactions(); + private final InMemoryProviderEventLedger ledger = + new InMemoryProviderEventLedger( + new InMemoryDeliveryAttemptStore(new InMemoryNotificationRequestStore()), + new Sha256ProviderRequestIdHasher()); + private final DirectTransactionPort transactions = new DirectTransactionPort(); @Test @DisplayName("the append runs inside one transaction") void theAppendRunsInsideOneTransaction() { service().handle(callback()); - assertThat(transactions.writes) + assertThat(transactions.committed()) .as("event-at-a-time appends could commit the first and lose the rest") - .isEqualTo(1); - assertThat(ledger.appended).hasSize(1); + .containsExactly(DirectTransactionPort.Boundary.WRITE); + assertThat(ledger.rows()).hasSize(1); } @Test @@ -47,7 +51,7 @@ class CallbackIngestionAtomicityTest { void theEndpointReturnsOnceTheEventIsDurable() { service().handle(callback()); - assertThat(ledger.appended).as("the event is durable when ingestion returns").hasSize(1); + assertThat(ledger.rows()).as("the event is durable when ingestion returns").hasSize(1); assertThat(IngestProviderCallbackApplicationUseCase.class.getDeclaredFields()) .noneMatch(field -> field.getType().equals(ProviderEventProjectionService.class)); } @@ -83,83 +87,6 @@ class CallbackIngestionAtomicityTest { "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8)); } - /** Counts write boundaries, so "one transaction" is a fact rather than a claim. */ - private static final class RecordingTransactions implements TransactionPort { - - private int writes; - - @Override - public T inWrite(Supplier action) { - writes++; - return action.get(); - } - - @Override - public T inRootWrite(Supplier action) { - return inWrite(action); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return inWrite(action); - } - } - - private static final class RecordingLedger implements ProviderEventLedger { - - private final List appended = new ArrayList<>(); - - @Override - public AppendEventResult append(VerifiedProviderEvent event) { - return appendAll(List.of(event)); - } - - @Override - public AppendEventResult appendAll(List events) { - appended.addAll(events); - return new AppendEventResult(List.of(), List.of()); - } - - @Override - public List pendingProjection(int limit) { - return List.of(); - } - - @Override - public void markApplied(ProviderEventRecordId eventId, ProjectionResult result) {} - - @Override - public void markFailed(ProviderEventRecordId eventId, String errorCode) {} - - @Override - public List unmatched(int limit) { - return List.of(); - } - - @Override - public List bindUnmatched( - ProviderProfileId providerProfileId, - String providerRequestId, - DeliveryAttemptId attemptId) { - return List.of(); - } - - @Override - public boolean bindAttempt(ProviderEventRecordId eventId, DeliveryAttemptId attemptId) { - return false; - } - - @Override - public List eventsForAttempt(DeliveryAttemptId attemptId) { - return List.of(); - } - } - private static final class PassThroughProtection implements CallbackPayloadProtectionPort { @Override diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProviderEventLateMatchTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProviderEventLateMatchTest.java index 9a57f838..c52af90f 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProviderEventLateMatchTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/ProviderEventLateMatchTest.java @@ -2,21 +2,28 @@ package dev.caskeleton.application.notification.platform.callback; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.NormalizedEventType; +import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; import dev.caskeleton.application.notification.platform.api.ProviderId; -import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; import dev.caskeleton.application.notification.platform.api.routing.Channel; -import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; -import dev.caskeleton.application.transaction.TransactionPort; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; +import dev.caskeleton.application.notification.platform.callback.testkit.InMemoryProviderEventLedger; +import dev.caskeleton.application.notification.platform.dispatch.AttemptSnapshots; +import dev.caskeleton.application.notification.platform.dispatch.PlatformFakes; +import dev.caskeleton.application.notification.platform.dispatch.SuppressionSideEffect; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryContactPointStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; +import dev.caskeleton.application.notification.platform.policy.testkit.InMemorySuppressionStore; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.ZoneOffset; import java.util.Map; import java.util.Optional; -import java.util.function.Supplier; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -28,208 +35,125 @@ import org.junit.jupiter.api.Test; * — and the pass had nothing to look with. The raw provider request id is never stored, so a * rehydrated event's {@code providerRequestId} is always empty, and an unbound event has no attempt * id either. The sweep therefore looked at the same rows forever and resolved none of them. + * + *

        The ledger, the resolver and the projections are the store fakes, so an event is "stored + * before its attempt" by actually appending it first. */ class ProviderEventLateMatchTest { private static final ProviderId PROVIDER = new ProviderId("twilio"); - - private static final ProviderRequestIdHash HASH = new ProviderRequestIdHash("a".repeat(64)); + private static final Clock CLOCK = Clock.fixed(CallbackFixtures.NOW, ZoneOffset.UTC); private final DeliveryAttemptSnapshot attempt = CallbackFixtures.attempt(Channel.SMS, PROVIDER); - private final RecordingLedger ledger = new RecordingLedger(); - private final RecordingResolver resolver = new RecordingResolver(); - private final InMemoryProjections projections = new InMemoryProjections(); + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final InMemoryDeliveryAttemptStore attempts = + new InMemoryDeliveryAttemptStore(requests, new Sha256ProviderRequestIdHasher(), CLOCK); + private final InMemoryProviderEventLedger ledger = + new InMemoryProviderEventLedger(attempts, new Sha256ProviderRequestIdHasher()); private final ProviderEventProjectionService projection = new ProviderEventProjectionService( ledger, new DeliveredProjector(), - resolver, - projections, - (ignoredAttempt, ignoredFacts) -> {}, - new DirectTransactions(), - new DiscardingMetrics()); + attempts, + attempts, + new SuppressionSideEffect( + new InMemoryContactPointStore(CLOCK), + new InMemorySuppressionStore(), + new PlatformFakes.SequentialIds(), + CLOCK), + new DirectTransactionPort(), + new PlatformFakes.RecordingMetrics()); @Test - @DisplayName("a stored event with only its hash still finds its attempt") + @DisplayName("해시만 가진 저장된 이벤트도 자기 attempt를 찾는다") void aStoredEventWithOnlyItsHashFindsItsAttempt() { - resolver.register(HASH, attempt); + // given + ProviderEventRecord stored = storedBeforeItsAttempt(Optional.of("SM1")); + AttemptSnapshots.store(requests, attempts, attempt, RecipientDeliveryState.DISPATCHING); - Optional result = - projection.project( - CallbackFixtures.event( - NormalizedEventType.DELIVERY_CONFIRMED, - "delivered", - Optional.empty(), - Optional.of(HASH))); + // when + Optional result = projection.project(stored); + // then assertThat(result) .as("the raw request id is not stored, so the hash is the only matcher a sweep has") .isPresent(); - assertThat(projections.saved()).containsKey(attempt.attemptId()); + assertThat(attempts.load(attempt.attemptId()).deliveryOutcome()) + .isEqualTo(DeliveryOutcome.DELIVERED); } @Test - @DisplayName("the match is written back, so the next pass resolves by identity") + @DisplayName("찾은 짝을 원장에 다시 써서 다음 pass는 attempt id로 찾는다") void theMatchIsWrittenBack() { - resolver.register(HASH, attempt); + // given + ProviderEventRecord stored = storedBeforeItsAttempt(Optional.of("SM1")); + AttemptSnapshots.store(requests, attempts, attempt, RecipientDeliveryState.DISPATCHING); - ProviderEventRecord event = - CallbackFixtures.event( - NormalizedEventType.DELIVERY_CONFIRMED, - "delivered", - Optional.empty(), - Optional.of(HASH)); - projection.project(event); + // when + projection.project(stored); - assertThat(ledger.bound()) + // then + assertThat(ledger.eventsForAttempt(attempt.attemptId())) .as("leaving attempt_id null makes every later pass hash its way back to the same attempt") - .containsExactly(Map.entry(event.id(), attempt.attemptId())); + .extracting(ProviderEventRecord::id) + .containsExactly(stored.id()); } @Test - @DisplayName("an event whose hash matches nothing stays unresolved rather than mismatched") + @DisplayName("해시가 아무 attempt와도 맞지 않는 이벤트는 엉뚱하게 묶이지 않고 미매칭으로 남는다") void anEventWhoseHashMatchesNothingStaysUnresolved() { - Optional result = - projection.project( - CallbackFixtures.event( - NormalizedEventType.DELIVERY_CONFIRMED, - "delivered", - Optional.empty(), - Optional.of(HASH))); + // given + ProviderEventRecord stored = storedBeforeItsAttempt(Optional.of("SM1")); + // when + Optional result = projection.project(stored); + + // then assertThat(result).isEmpty(); - assertThat(ledger.bound()).isEmpty(); + assertThat(ledger.unmatched(10)) + .extracting(ProviderEventRecord::id) + .containsExactly(stored.id()); } @Test - @DisplayName("an event with no hash at all is left for an operator, not guessed at") + @DisplayName("해시가 없는 이벤트는 추측하지 않고 운영자에게 남긴다") void anEventWithNoHashIsLeftAlone() { - resolver.register(HASH, attempt); + // given + ProviderEventRecord stored = storedBeforeItsAttempt(Optional.empty()); + AttemptSnapshots.store(requests, attempts, attempt, RecipientDeliveryState.DISPATCHING); - Optional result = - projection.project( - CallbackFixtures.event( + // when + Optional result = projection.project(stored); + + // then + assertThat(result).isEmpty(); + assertThat(ledger.eventsForAttempt(attempt.attemptId())).isEmpty(); + } + + /** + * A delivery callback appended while no attempt carried its request id, as the ledger keeps it. + */ + private ProviderEventRecord storedBeforeItsAttempt(Optional providerRequestId) { + VerifiedProviderEvent callback = + new VerifiedProviderEvent( + CallbackFixtures.PROFILE, + new NormalizedProviderEvent( NormalizedEventType.DELIVERY_CONFIRMED, "delivered", Optional.empty(), - Optional.empty())); - - assertThat(result).isEmpty(); - assertThat(ledger.bound()).isEmpty(); - } - - /** Records what the service asked the ledger to bind. */ - private static final class RecordingLedger implements ProviderEventLedger { - - private final List> bound = - new ArrayList<>(); - - private List> bound() { - return List.copyOf(bound); - } - - @Override - public AppendEventResult append(VerifiedProviderEvent event) { - return new AppendEventResult(List.of(), List.of()); - } - - @Override - public AppendEventResult appendAll(List events) { - return new AppendEventResult(List.of(), List.of()); - } - - @Override - public List pendingProjection(int limit) { - return List.of(); - } - - @Override - public void markApplied(ProviderEventRecordId eventId, ProjectionResult result) { - // The status transition is the ledger's contract, not this one's. - } - - @Override - public void markFailed(ProviderEventRecordId eventId, String errorCode) { - // Same. - } - - @Override - public List unmatched(int limit) { - return List.of(); - } - - @Override - public List bindUnmatched( - ProviderProfileId providerProfileId, - String providerRequestId, - DeliveryAttemptId attemptId) { - return List.of(); - } - - @Override - public boolean bindAttempt(ProviderEventRecordId eventId, DeliveryAttemptId attemptId) { - bound.add(Map.entry(eventId, attemptId)); - return true; - } - - @Override - public List eventsForAttempt(DeliveryAttemptId attemptId) { - return List.of(); - } - } - - /** Answers only for the hash it was given, and never for a raw identifier. */ - private static final class RecordingResolver implements DeliveryAttemptResolverPort { - - private final Map byHash = - new java.util.HashMap<>(); - - private void register(ProviderRequestIdHash hash, DeliveryAttemptSnapshot attempt) { - byHash.put(hash, attempt); - } - - @Override - public Optional byAttemptId(DeliveryAttemptId attemptId) { - return Optional.empty(); - } - - @Override - public Optional byProviderRequestId( - ProviderProfileId profileId, String providerRequestId) { - return Optional.empty(); - } - - @Override - public Optional byProviderRequestIdHash( - ProviderProfileId profileId, ProviderRequestIdHash providerRequestIdHash) { - return Optional.ofNullable(byHash.get(providerRequestIdHash)); - } - } - - private static final class InMemoryProjections implements DeliveryProjectionStorePort { - - private final Map saved = new java.util.HashMap<>(); - - private Map saved() { - return Map.copyOf(saved); - } - - @Override - public DeliveryProjection load(DeliveryAttemptId attemptId) { - return saved.getOrDefault(attemptId, DeliveryProjection.accepted()); - } - - @Override - public void save(DeliveryAttemptId attemptId, DeliveryProjection projection) { - saved.put(attemptId, projection); - } - - @Override - public boolean claimSuppressionSideEffect(DeliveryAttemptId attemptId) { - return false; - } + providerRequestId, + Optional.of(CallbackFixtures.NOW), + Map.of()), + Optional.empty(), + ProviderEventSource.CALLBACK, + true, + CallbackFixtures.NOW, + "{}".getBytes(StandardCharsets.UTF_8), + "a".repeat(64), + "b".repeat(64)); + return ledger.append(callback).newEvents().getFirst(); } /** Marks the attempt delivered, which is enough to observe that projection ran. */ @@ -243,46 +167,4 @@ class ProviderEventLateMatchTest { "delivered"); } } - - /** Runs the action where it stands: this test is about matching, not about transactions. */ - private static final class DirectTransactions implements TransactionPort { - - @Override - public T inWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRootWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } - - private static final class DiscardingMetrics implements NotificationMetricsPort { - - @Override - public void increment(String metricName, Map tags) { - // Nothing here asserts on metrics. - } - - @Override - public void record(String metricName, Map tags, Duration value) { - // Same. - } - - @Override - public void gauge(String metricName, Map tags, double value) { - // Same. - } - } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryDeliveryAttemptResolverTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryDeliveryAttemptResolverTest.java new file mode 100644 index 00000000..a88d3429 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryDeliveryAttemptResolverTest.java @@ -0,0 +1,53 @@ +package dev.caskeleton.application.notification.platform.callback.testkit; + +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; +import java.util.UUID; +import java.util.function.Supplier; + +/** The in-memory attempt store held to the same resolver contract as the JPA store. */ +class InMemoryDeliveryAttemptResolverTest extends DeliveryAttemptResolverContract { + + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final ProviderRequestIdHasherPort hasher = new Sha256ProviderRequestIdHasher(); + private final InMemoryDeliveryAttemptStore attempts = + new InMemoryDeliveryAttemptStore(requests, hasher, clock()); + + @Override + protected NotificationRequestStorePort requests() { + return requests; + } + + @Override + protected DeliveryAttemptStorePort attempts() { + return attempts; + } + + @Override + protected ProviderRequestIdHasherPort hasher() { + return hasher; + } + + @Override + protected ContactPointId givenAContactPoint(TenantId tenant) { + // The fake has no contact point table to refer to; the id is all an attempt carries. + return new ContactPointId(UUID.randomUUID()); + } + + @Override + protected DeliveryAttemptResolverPort resolver() { + return attempts; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryDeliveryProjectionStoreTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryDeliveryProjectionStoreTest.java new file mode 100644 index 00000000..1ce5d13c --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryDeliveryProjectionStoreTest.java @@ -0,0 +1,53 @@ +package dev.caskeleton.application.notification.platform.callback.testkit; + +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.callback.DeliveryProjectionStorePort; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; +import java.util.UUID; +import java.util.function.Supplier; + +/** The in-memory attempt store held to the same projection contract as the JPA store. */ +class InMemoryDeliveryProjectionStoreTest extends DeliveryProjectionStoreContract { + + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final ProviderRequestIdHasherPort hasher = new Sha256ProviderRequestIdHasher(); + private final InMemoryDeliveryAttemptStore attempts = + new InMemoryDeliveryAttemptStore(requests, hasher, clock()); + + @Override + protected NotificationRequestStorePort requests() { + return requests; + } + + @Override + protected DeliveryAttemptStorePort attempts() { + return attempts; + } + + @Override + protected ProviderRequestIdHasherPort hasher() { + return hasher; + } + + @Override + protected ContactPointId givenAContactPoint(TenantId tenant) { + // The fake has no contact point table to refer to; the id is all an attempt carries. + return new ContactPointId(UUID.randomUUID()); + } + + @Override + protected DeliveryProjectionStorePort projections() { + return attempts; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryProviderEventLedgerTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryProviderEventLedgerTest.java new file mode 100644 index 00000000..a2150d71 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryProviderEventLedgerTest.java @@ -0,0 +1,55 @@ +package dev.caskeleton.application.notification.platform.callback.testkit; + +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; +import java.util.UUID; +import java.util.function.Supplier; + +/** The in-memory ledger held to the same contract as the JPA ledger. */ +class InMemoryProviderEventLedgerTest extends ProviderEventLedgerContract { + + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final ProviderRequestIdHasherPort hasher = new Sha256ProviderRequestIdHasher(); + private final InMemoryDeliveryAttemptStore attempts = + new InMemoryDeliveryAttemptStore(requests, hasher, clock()); + private final InMemoryProviderEventLedger ledger = + new InMemoryProviderEventLedger(attempts, hasher); + + @Override + protected NotificationRequestStorePort requests() { + return requests; + } + + @Override + protected DeliveryAttemptStorePort attempts() { + return attempts; + } + + @Override + protected ProviderRequestIdHasherPort hasher() { + return hasher; + } + + @Override + protected ContactPointId givenAContactPoint(TenantId tenant) { + // The fake has no contact point table to refer to; the id is all an attempt carries. + return new ContactPointId(UUID.randomUUID()); + } + + @Override + protected ProviderEventLedger ledger() { + return ledger; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} 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 a204984d..ac1d51f7 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 @@ -8,16 +8,16 @@ import dev.caskeleton.application.notification.platform.api.NotificationPlan; import dev.caskeleton.application.notification.platform.api.NotificationReceipt; import dev.caskeleton.application.notification.platform.api.NotificationVariable; import dev.caskeleton.application.notification.platform.api.RequestStatus; -import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.api.routing.Channel; -import dev.caskeleton.application.notification.platform.contact.ContactPointStatus; import dev.caskeleton.application.notification.platform.contact.ContactPointValue; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryContactPointStore; import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationCommand; import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationCommand; import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationUseCase; import dev.caskeleton.application.notification.platform.security.AccessContext; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import dev.caskeleton.application.notification.platform.security.ProtectedContactPoint; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; @@ -38,7 +38,8 @@ class AcceptNotificationApplicationUseCaseTest { @Test void derivedIdempotencyKeyIsStableSha256OverTheCanonicalPlan() { CapturingSubmit submit = new CapturingSubmit(); - InMemoryContactPoints contactPoints = new InMemoryContactPoints(); + InMemoryContactPointStore contactPoints = + new InMemoryContactPointStore(Clock.fixed(NOW, ZoneOffset.UTC)); PlatformFakes.SequentialIds ids = new PlatformFakes.SequentialIds(); AcceptNotificationApplicationUseCase useCase = @@ -49,7 +50,7 @@ class AcceptNotificationApplicationUseCaseTest { PlatformFakes.tenant("tenant-a"), ids, PlatformFakes.fingerprints(), - new PlatformFakes.RecordingTransactions(), + new DirectTransactionPort(), Clock.fixed(NOW, ZoneOffset.UTC), DEFAULT_LOCALE); @@ -71,7 +72,8 @@ class AcceptNotificationApplicationUseCaseTest { @Test void variableInsertionOrderDoesNotChangeTheDerivedKey() { CapturingSubmit submit = new CapturingSubmit(); - InMemoryContactPoints contactPoints = new InMemoryContactPoints(); + InMemoryContactPointStore contactPoints = + new InMemoryContactPointStore(Clock.fixed(NOW, ZoneOffset.UTC)); PlatformFakes.SequentialIds ids = new PlatformFakes.SequentialIds(); AcceptNotificationApplicationUseCase useCase = @@ -82,7 +84,7 @@ class AcceptNotificationApplicationUseCaseTest { PlatformFakes.tenant("tenant-a"), ids, PlatformFakes.fingerprints(), - new PlatformFakes.RecordingTransactions(), + new DirectTransactionPort(), Clock.fixed(NOW, ZoneOffset.UTC), DEFAULT_LOCALE); @@ -129,12 +131,12 @@ class AcceptNotificationApplicationUseCaseTest { AcceptNotificationApplicationUseCase useCase = new AcceptNotificationApplicationUseCase( submit, - new InMemoryContactPoints(), + new InMemoryContactPointStore(Clock.fixed(NOW, ZoneOffset.UTC)), protector(), PlatformFakes.tenant("tenant-a"), new PlatformFakes.SequentialIds(), PlatformFakes.fingerprints(), - new PlatformFakes.RecordingTransactions(), + new DirectTransactionPort(), Clock.fixed(NOW, ZoneOffset.UTC), DEFAULT_LOCALE); AcceptNotificationCommand command = @@ -166,7 +168,8 @@ class AcceptNotificationApplicationUseCaseTest { @Test void anAcceptanceForATenantOutsideTheTransportGrammarRegistersNothing() { // given - InMemoryContactPoints contactPoints = new InMemoryContactPoints(); + InMemoryContactPointStore contactPoints = + new InMemoryContactPointStore(Clock.fixed(NOW, ZoneOffset.UTC)); AcceptNotificationApplicationUseCase useCase = new AcceptNotificationApplicationUseCase( new CapturingSubmit(), @@ -175,7 +178,7 @@ class AcceptNotificationApplicationUseCaseTest { PlatformFakes.tenant("tenant-a"), new PlatformFakes.SequentialIds(), PlatformFakes.fingerprints(), - new PlatformFakes.RecordingTransactions(), + new DirectTransactionPort(), Clock.fixed(NOW, ZoneOffset.UTC), DEFAULT_LOCALE); AcceptNotificationCommand command = @@ -210,12 +213,12 @@ class AcceptNotificationApplicationUseCaseTest { () -> new AcceptNotificationApplicationUseCase( new CapturingSubmit(), - new InMemoryContactPoints(), + new InMemoryContactPointStore(Clock.fixed(NOW, ZoneOffset.UTC)), protector(), PlatformFakes.tenant("tenant-a"), new PlatformFakes.SequentialIds(), PlatformFakes.fingerprints(), - new PlatformFakes.RecordingTransactions(), + new DirectTransactionPort(), Clock.fixed(NOW, ZoneOffset.UTC), Locale.ROOT)); @@ -273,34 +276,4 @@ class AcceptNotificationApplicationUseCaseTest { new NotificationId(new UUID(0L, plans.size())), RequestStatus.CREATED, NOW); } } - - private static final class InMemoryContactPoints implements ContactPointStorePort { - private final Map byFingerprint = new java.util.HashMap<>(); - - @Override - public Optional find( - TenantId tenantId, dev.caskeleton.application.notification.platform.api.ContactPointId id) { - return byFingerprint.values().stream().filter(record -> record.id().equals(id)).findFirst(); - } - - @Override - public Optional findByFingerprint(TenantId tenantId, String lookupHmac) { - return Optional.ofNullable(byFingerprint.get(lookupHmac)); - } - - @Override - public ContactPointRecord save(ContactPointRecord record) { - byFingerprint.put(record.protectedValue().lookupHmac(), record); - return record; - } - - @Override - public ContactPointRecord updateStatus( - TenantId tenantId, - dev.caskeleton.application.notification.platform.api.ContactPointId id, - ContactPointStatus status, - String reasonCode) { - throw new UnsupportedOperationException("not used"); - } - } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AttemptSnapshots.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AttemptSnapshots.java new file mode 100644 index 00000000..6153b37d --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AttemptSnapshots.java @@ -0,0 +1,102 @@ +package dev.caskeleton.application.notification.platform.dispatch; + +import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * Writes the rows a snapshot is read from, for a use-case test that starts from "this attempt + * exists". + * + *

        The attempt fake joins an attempt to its recipient job the way the read model does, so a + * snapshot exists only when both rows do. The old fake kept snapshots in a map of their own, which + * let a test describe an attempt no store held. + */ +public final class AttemptSnapshots { + + private AttemptSnapshots() {} + + /** + * Stores the job (unless the request store already has it) and the attempt {@code snapshot} + * describes. + * + * @param requests the store holding the recipient jobs + * @param attempts the attempt store + * @param snapshot what the attempt and its job should read back as + * @param jobState the state the job is in + */ + public static void store( + InMemoryNotificationRequestStore requests, + InMemoryDeliveryAttemptStore attempts, + DeliveryAttemptSnapshot snapshot, + RecipientDeliveryState jobState) { + boolean jobStored = + requests.recipients.values().stream() + .flatMap(List::stream) + .anyMatch(job -> job.id().equals(snapshot.recipientDeliveryId())); + if (!jobStored) { + requests + .recipients + .computeIfAbsent(snapshot.notificationId(), ignored -> new ArrayList<>()) + .add( + new RecipientDeliveryRecord( + snapshot.recipientDeliveryId(), + snapshot.notificationId(), + snapshot.tenantId(), + "user-1", + Optional.empty(), + Optional.empty(), + List.of(), + 0, + jobState, + snapshot.submissionOutcome(), + snapshot.deliveryOutcome(), + snapshot.evidenceLevel(), + snapshot.confirmation() == AttemptConfirmation.AMBIGUOUS, + false, + Optional.of(snapshot.startedAt()), + Optional.empty(), + Optional.of("worker-a"), + Optional.of(snapshot.startedAt()), + snapshot.attemptNo(), + Optional.empty(), + snapshot.startedAt(), + snapshot.startedAt())); + } + attempts.insertDispatching( + new DeliveryAttemptRecord( + snapshot.attemptId(), + snapshot.recipientDeliveryId(), + snapshot.contactPointId(), + snapshot.attemptNo(), + snapshot.channel(), + snapshot.providerId(), + snapshot.providerProfileId(), + snapshot.providerRequestId(), + snapshot.confirmation() == AttemptConfirmation.CONFIRMED + ? ProviderExecutionEvidence.completed(true) + : ProviderExecutionEvidence.undetermined(), + snapshot.submissionOutcome(), + snapshot.deliveryOutcome(), + snapshot.confirmation(), + snapshot.evidenceLevel(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + snapshot.startedAt(), + snapshot.completedAt(), + snapshot + .completedAt() + .map(completed -> Duration.between(snapshot.startedAt(), completed)), + snapshot.credentialGeneration(), + snapshot.renderedContentDigest())); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java index ad270c1c..79f07cf4 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchOutcomeRecorderTest.java @@ -3,13 +3,9 @@ package dev.caskeleton.application.notification.platform.dispatch; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.notification.platform.api.ContactPointId; -import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.NormalizedEventType; import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; -import dev.caskeleton.application.notification.platform.api.NotificationId; -import dev.caskeleton.application.notification.platform.api.ProviderId; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; -import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; @@ -18,69 +14,79 @@ import dev.caskeleton.application.notification.platform.api.delivery.RecipientDe import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; import dev.caskeleton.application.notification.platform.api.error.FailureCategory; import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; -import dev.caskeleton.application.notification.platform.api.routing.Channel; -import dev.caskeleton.application.notification.platform.callback.AppendEventResult; -import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort; import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; import dev.caskeleton.application.notification.platform.callback.DeliveryProjection; -import dev.caskeleton.application.notification.platform.callback.DeliveryProjectionStorePort; -import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort; import dev.caskeleton.application.notification.platform.callback.ProjectionResult; -import dev.caskeleton.application.notification.platform.callback.ProjectionStatus; -import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord; -import dev.caskeleton.application.notification.platform.callback.ProviderEventRecordId; import dev.caskeleton.application.notification.platform.callback.ProviderEventSource; -import dev.caskeleton.application.notification.platform.callback.ProviderRequestIdHash; -import dev.caskeleton.application.notification.platform.callback.StandardDeliveryProjector; import dev.caskeleton.application.notification.platform.callback.VerifiedProviderEvent; +import dev.caskeleton.application.notification.platform.callback.testkit.InMemoryProviderEventLedger; +import dev.caskeleton.application.notification.platform.dispatch.testkit.ContractClock; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryContactPointStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryRecipientQueue; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryReconciliationJobStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.NotificationRows; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; import dev.caskeleton.application.notification.platform.observation.NotificationMetricName; +import dev.caskeleton.application.notification.platform.policy.testkit.InMemorySuppressionStore; import dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence; import dev.caskeleton.application.notification.platform.provider.ProviderFailure; import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import java.nio.charset.StandardCharsets; +import java.time.Clock; import java.time.Duration; import java.time.Instant; +import java.time.ZoneOffset; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +/** + * What the recorder writes once a provider call has returned, over the store fakes. + * + *

        The attempt, the job, the ledger and the reconciliation queue are the fakes held to the same + * contracts as the JPA stores, so "the job is RECONCILIATION_REQUIRED" and "a new holder's row is + * untouched" are read off the rows rather than off what a recording stub was handed. + */ class DispatchOutcomeRecorderTest { private static final Instant STARTED = Instant.parse("2026-09-20T00:00:00Z"); private static final Instant COMPLETED = STARTED.plusSeconds(2); - private static final DeliveryAttemptId ATTEMPT_ID = - new DeliveryAttemptId(UUID.fromString("00000000-0000-7000-8000-000000000031")); - private static final RecipientDeliveryId RECIPIENT_ID = - new RecipientDeliveryId(UUID.fromString("00000000-0000-7000-8000-000000000032")); private static final ProviderProfileId PROFILE = new ProviderProfileId("ses-primary"); - private static final RecipientLease LEASE = - new RecipientLease(RECIPIENT_ID, "worker-a", 1L, STARTED.plusSeconds(30)); + private static final Clock CLOCK = Clock.fixed(COMPLETED, ZoneOffset.UTC); + + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final ContractClock queueClock = new ContractClock(STARTED); + private final InMemoryRecipientQueue recipients = + new InMemoryRecipientQueue(requests, queueClock); + private final InMemoryDeliveryAttemptStore attempts = + new InMemoryDeliveryAttemptStore(requests, new Sha256ProviderRequestIdHasher(), CLOCK); + private final InMemoryProviderEventLedger ledger = + new InMemoryProviderEventLedger(attempts, new Sha256ProviderRequestIdHasher()); + private final InMemoryReconciliationJobStore jobs = new InMemoryReconciliationJobStore(CLOCK); @Test + @DisplayName("결과가 모호한 제출은 증거째 저장되고 수신자를 정산 대기로 옮겨 정산 job을 예약한다") void ambiguousSubmissionIsPersistedAndSchedulesReconciliation() { - RecordingAttemptStore attempts = new RecordingAttemptStore(); - RecordingRecipientStore recipients = new RecordingRecipientStore(recipient()); - RecordingReconciliationJobs jobs = new RecordingReconciliationJobs(); + // given + Dispatched dispatched = givenADispatchedAttempt(); PlatformFakes.RecordingMetrics metrics = new PlatformFakes.RecordingMetrics(); - DispatchOutcomeRecorder recorder = - new DispatchOutcomeRecorder( - attempts, - recipients, - jobs, - new NoopLedger(), - noopProjection(), - metrics, - Duration.ofSeconds(30)); + DispatchOutcomeRecorder recorder = recorder(projection(acceptedOnly()), metrics); + // when DeliveryAttemptRecord stored = recorder.record( - attempt(), - recipient(), - LEASE, + dispatched.attempt(), + dispatched.job(), + dispatched.lease(), ProviderSubmissionResult.ambiguous( ProviderFailure.of( NotificationFailureCode.PROVIDER_RESPONSE_LOST, @@ -90,14 +96,19 @@ class DispatchOutcomeRecorderTest { Duration.ofSeconds(2)), COMPLETED); + // then + RecipientDeliveryRecord job = recipients.find(dispatched.job().id()).orElseThrow(); assertThat(stored.confirmation()).isEqualTo(AttemptConfirmation.AMBIGUOUS); assertThat(stored.submissionOutcome()).isEqualTo(SubmissionOutcome.AMBIGUOUS); assertThat(stored.executionEvidence()).isEqualTo(ProviderExecutionEvidence.responseLost()); - assertThat(recipients.saved.state()).isEqualTo(RecipientDeliveryState.RECONCILIATION_REQUIRED); - assertThat(recipients.saved.ambiguousAttemptExists()).isTrue(); - assertThat(recipients.saved.duplicateRisk()).isTrue(); - assertThat(jobs.scheduledAttempt).isEqualTo(ATTEMPT_ID); - assertThat(jobs.dueAt).isEqualTo(COMPLETED.plusSeconds(30)); + assertThat(job.state()).isEqualTo(RecipientDeliveryState.RECONCILIATION_REQUIRED); + assertThat(job.ambiguousAttemptExists()).isTrue(); + assertThat(job.duplicateRisk()).isTrue(); + assertThat(jobs.claimDue(10, COMPLETED.plusSeconds(29), Duration.ofMinutes(1))).isEmpty(); + assertThat(jobs.claimDue(10, COMPLETED.plusSeconds(30), Duration.ofMinutes(1))) + .extracting( + dev.caskeleton.application.notification.platform.dispatch.ReconciliationJob::attemptId) + .containsExactly(dispatched.attempt().id()); assertThat(metrics.counters) .contains(NotificationMetricName.DISPATCH, NotificationMetricName.AMBIGUOUS); } @@ -106,27 +117,22 @@ class DispatchOutcomeRecorderTest { @DisplayName("늦게 짝지어진 콜백이 수신자에 반영한 배달 결과를 recorder가 덮어쓰지 않는다") void aLateMatchedCallbackProjectionIsNotOverwrittenByTheRecorder() { // given - RecordingRecipientStore recipients = new RecordingRecipientStore(recipient()); + Dispatched dispatched = givenADispatchedAttempt(); + // The provider's delivery callback beat the outcome: it is stored with no attempt to bind to. + ledger.append(deliveredCallback("ses-message-1")); DispatchOutcomeRecorder recorder = - new DispatchOutcomeRecorder( - new RecordingAttemptStore(), - recipients, - new RecordingReconciliationJobs(), - new OneUnmatchedEventLedger(), - deliveringProjection(recipients), - new PlatformFakes.RecordingMetrics(), - Duration.ofSeconds(30)); + recorder(projection(delivered()), new PlatformFakes.RecordingMetrics()); // when recorder.record( - attempt(), - recipient(), - LEASE, + dispatched.attempt(), + dispatched.job(), + dispatched.lease(), ProviderSubmissionResult.accepted("ses-message-1", "Accepted", Duration.ofSeconds(1)), COMPLETED); // then - assertThat(recipients.saved) + assertThat(recipients.find(dispatched.job().id()).orElseThrow()) .extracting( RecipientDeliveryRecord::deliveryOutcome, RecipientDeliveryRecord::evidenceLevel) .containsExactly(DeliveryOutcome.DELIVERED, EvidenceLevel.DEVICE_DELIVERED); @@ -136,427 +142,110 @@ class DispatchOutcomeRecorderTest { @DisplayName("lease를 잃은 worker의 recorder는 수신자 행에 아무것도 쓰지 않는다") void aRecorderThatLostItsLeaseWritesNothingToTheRecipient() { // given - RecordingRecipientStore recipients = new RecordingRecipientStore(recipient()); - recipients.superseded = true; + Dispatched dispatched = givenADispatchedAttempt(); + // The lease ran out during the provider call and another worker claimed the job. + queueClock.moveTo(dispatched.lease().leaseUntil().plusSeconds(1)); + recipients.transition( + dispatched.job().id(), + RecipientDeliveryState.READY_TO_DISPATCH, + Optional.of(queueClock.instant())); + recipients.claim("worker-b", 1, Duration.ofSeconds(30)); + RecipientDeliveryRecord newHolders = recipients.find(dispatched.job().id()).orElseThrow(); DispatchOutcomeRecorder recorder = - new DispatchOutcomeRecorder( - new RecordingAttemptStore(), - recipients, - new RecordingReconciliationJobs(), - new NoopLedger(), - noopProjection(), - new PlatformFakes.RecordingMetrics(), - Duration.ofSeconds(30)); + recorder(projection(acceptedOnly()), new PlatformFakes.RecordingMetrics()); // when recorder.record( - attempt(), - recipient(), - LEASE, + dispatched.attempt(), + dispatched.job(), + dispatched.lease(), ProviderSubmissionResult.accepted("ses-message-1", "Accepted", Duration.ofSeconds(1)), COMPLETED); // then - assertThat(recipients.writes) + assertThat(recipients.find(dispatched.job().id()).orElseThrow()) .as("a new holder owns the row; the stale snapshot must not land on it") - .isZero(); + .isEqualTo(newHolders); } - /** - * A projection whose store rolls the delivered outcome up onto the recipient row, as the JPA - * store does, for an event the ledger hands back once the provider request id is known. - */ - private static ProviderEventProjectionService deliveringProjection( - RecordingRecipientStore recipients) { - DeliveryAttemptSnapshot snapshot = - new DeliveryAttemptSnapshot( - ATTEMPT_ID, - RECIPIENT_ID, - new NotificationId(UUID.fromString("00000000-0000-7000-8000-000000000034")), - new TenantId("tenant-a"), - 1, - Channel.EMAIL, - new ProviderId("ses"), - PROFILE, - Optional.of("ses-message-1"), - new ContactPointId(UUID.fromString("00000000-0000-7000-8000-000000000033")), - AttemptConfirmation.CONFIRMED, - SubmissionOutcome.CONFIRMED_ACCEPTED, - DeliveryOutcome.UNKNOWN, - EvidenceLevel.PROVIDER_ACCEPTED, - 1L, - "a".repeat(64), - STARTED, - Optional.of(COMPLETED), - Optional.empty()); - DeliveryAttemptResolverPort resolver = - new DeliveryAttemptResolverPort() { - @Override - public Optional byAttemptId(DeliveryAttemptId attemptId) { - return Optional.of(snapshot); - } - - @Override - public Optional byProviderRequestId( - ProviderProfileId profileId, String providerRequestId) { - return Optional.of(snapshot); - } - - @Override - public Optional byProviderRequestIdHash( - ProviderProfileId profileId, ProviderRequestIdHash providerRequestIdHash) { - return Optional.of(snapshot); - } - }; - DeliveryProjectionStorePort projections = - new DeliveryProjectionStorePort() { - @Override - public DeliveryProjection load(DeliveryAttemptId attemptId) { - return DeliveryProjection.accepted(); - } - - @Override - public void save(DeliveryAttemptId attemptId, DeliveryProjection projection) { - RecipientDeliveryRecord current = recipients.saved; - recipients.saved = - new RecipientDeliveryRecord( - current.id(), - current.notificationId(), - current.tenantId(), - current.recipientRef(), - current.locale(), - current.timeZone(), - current.routingPlan(), - current.routeCursor(), - current.state(), - projection.submissionOutcome(), - projection.deliveryOutcome(), - current.evidenceLevel().strongerOf(projection.evidenceLevel()), - current.ambiguousAttemptExists(), - current.duplicateRisk(), - current.nextDispatchAt(), - current.expiresAt(), - current.leaseOwner(), - current.leaseUntil(), - current.attemptCount(), - current.lastFailureCategory(), - current.createdAt(), - COMPLETED); - } - - @Override - public boolean claimSuppressionSideEffect(DeliveryAttemptId attemptId) { - return false; - } - }; - ProviderEventProjector delivered = - new ProviderEventProjector() { - - @Override - public ProjectionResult project( - DeliveryAttemptSnapshot attempt, - ProviderEventRecord event, - DeliveryProjection current) { - return ProjectionResult.applied( - current.withDelivery(DeliveryOutcome.DELIVERED, EvidenceLevel.DEVICE_DELIVERED), - "DELIVERED"); - } - }; - return new ProviderEventProjectionService( - new NoopLedger(), - delivered, - resolver, - projections, - (attempt, facts) -> {}, - new PlatformFakes.RecordingTransactions(), - new PlatformFakes.RecordingMetrics()); + /** A claimed job with the attempt row the dispatcher commits before calling the provider. */ + private Dispatched givenADispatchedAttempt() { + NotificationRequestRecord request = + NotificationRows.request(new TenantId("tenant-a"), "idem-" + UUID.randomUUID(), STARTED); + RecipientDeliveryRecord job = + NotificationRows.job( + request, + RecipientDeliveryState.READY_TO_DISPATCH, + Optional.of(STARTED), + Optional.empty(), + STARTED); + requests.insert(request, List.of(job)); + RecipientLease lease = recipients.claim("worker-a", 1, Duration.ofSeconds(30)).getFirst(); + DeliveryAttemptRecord attempt = + NotificationRows.dispatchingAttempt( + job.id(), new ContactPointId(UUID.randomUUID()), 1, PROFILE, STARTED); + attempts.insertDispatching(attempt); + return new Dispatched(recipients.find(job.id()).orElseThrow(), lease, attempt); } - /** A ledger holding one delivery event that arrived before the provider request id was known. */ - private static final class OneUnmatchedEventLedger extends NoopLedgerBase { - @Override - public List bindUnmatched( - ProviderProfileId providerProfileId, - String providerRequestId, - DeliveryAttemptId attemptId) { - return List.of( - new ProviderEventRecord( - new ProviderEventRecordId(UUID.fromString("00000000-0000-7000-8000-000000000036")), - PROFILE, - new NormalizedProviderEvent( - NormalizedEventType.DELIVERY_CONFIRMED, - "Delivery", - Optional.empty(), - Optional.of(providerRequestId), - Optional.of(STARTED), - java.util.Map.of()), - Optional.of(attemptId), - Optional.empty(), - ProviderEventSource.CALLBACK, - true, - STARTED, - "a".repeat(64), - "b".repeat(64), - ProjectionStatus.PENDING, - Optional.empty())); - } + private DispatchOutcomeRecorder recorder( + ProviderEventProjectionService projection, PlatformFakes.RecordingMetrics metrics) { + return new DispatchOutcomeRecorder( + attempts, recipients, jobs, ledger, projection, metrics, Duration.ofSeconds(30)); } - private static DeliveryAttemptRecord attempt() { - return new DeliveryAttemptRecord( - ATTEMPT_ID, - RECIPIENT_ID, - new ContactPointId(UUID.fromString("00000000-0000-7000-8000-000000000033")), - 1, - Channel.EMAIL, - new ProviderId("ses"), - PROFILE, - Optional.empty(), - ProviderExecutionEvidence.notStarted(), - SubmissionOutcome.NOT_SUBMITTED, - DeliveryOutcome.UNKNOWN, - AttemptConfirmation.AMBIGUOUS, - EvidenceLevel.PLATFORM_QUEUED, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - STARTED, - Optional.empty(), - Optional.empty(), - 1L, - "a".repeat(64)); - } - - private static RecipientDeliveryRecord recipient() { - return new RecipientDeliveryRecord( - RECIPIENT_ID, - new NotificationId(UUID.fromString("00000000-0000-7000-8000-000000000034")), - new TenantId("tenant-a"), - "user-1", - Optional.empty(), - Optional.empty(), - List.of(), - 0, - RecipientDeliveryState.DISPATCHING, - SubmissionOutcome.NOT_SUBMITTED, - DeliveryOutcome.UNKNOWN, - EvidenceLevel.PLATFORM_QUEUED, - false, - false, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - 0, - Optional.empty(), - STARTED, - STARTED); - } - - private static ProviderEventProjectionService noopProjection() { - ProviderEventLedger ledger = new NoopLedger(); - DeliveryAttemptResolverPort resolver = - new DeliveryAttemptResolverPort() { - @Override - public Optional byAttemptId(DeliveryAttemptId attemptId) { - return Optional.empty(); - } - - @Override - public Optional byProviderRequestId( - ProviderProfileId profileId, String providerRequestId) { - return Optional.empty(); - } - - @Override - public Optional byProviderRequestIdHash( - ProviderProfileId profileId, ProviderRequestIdHash providerRequestIdHash) { - return Optional.empty(); - } - }; - DeliveryProjectionStorePort projections = - new DeliveryProjectionStorePort() { - @Override - public DeliveryProjection load(DeliveryAttemptId attemptId) { - return DeliveryProjection.accepted(); - } - - @Override - public void save(DeliveryAttemptId attemptId, DeliveryProjection projection) {} - - @Override - public boolean claimSuppressionSideEffect(DeliveryAttemptId attemptId) { - return false; - } - }; - NotificationSideEffectPort sideEffects = (attempt, facts) -> {}; + private ProviderEventProjectionService projection(ProviderEventProjector projector) { return new ProviderEventProjectionService( ledger, - new StandardDeliveryProjector(), - resolver, - projections, - sideEffects, - new PlatformFakes.RecordingTransactions(), + projector, + attempts, + attempts, + new SuppressionSideEffect( + new InMemoryContactPointStore(CLOCK), + new InMemorySuppressionStore(), + new PlatformFakes.SequentialIds(), + CLOCK), + new DirectTransactionPort(), new PlatformFakes.RecordingMetrics()); } - private static final class RecordingAttemptStore implements DeliveryAttemptStorePort { - private DeliveryAttemptRecord stored; - - @Override - public DeliveryAttemptRecord insertDispatching(DeliveryAttemptRecord attempt) { - throw new UnsupportedOperationException(); - } - - @Override - public DeliveryAttemptRecord recordOutcome(DeliveryAttemptRecord attempt) { - stored = attempt; - return attempt; - } - - @Override - public Optional find(DeliveryAttemptId id) { - return Optional.ofNullable(stored); - } - - @Override - public List attemptsOf(RecipientDeliveryId recipientDeliveryId) { - return List.of(); - } - - @Override - public Optional snapshot(DeliveryAttemptId id) { - return Optional.empty(); - } - - @Override - public int nextAttemptNo(RecipientDeliveryId recipientDeliveryId) { - return 1; - } + /** Marks the attempt delivered on the device, which is what the callback reported. */ + private static ProviderEventProjector delivered() { + return (DeliveryAttemptSnapshot attempt, + ProviderEventRecord event, + DeliveryProjection current) -> + ProjectionResult.applied( + current.withDelivery(DeliveryOutcome.DELIVERED, EvidenceLevel.DEVICE_DELIVERED), + "DELIVERED"); } - private static final class RecordingRecipientStore implements RecipientDeliveryStorePort { - private RecipientDeliveryRecord saved; - private boolean superseded; - private int writes; - - private RecordingRecipientStore(RecipientDeliveryRecord initial) { - this.saved = initial; - } - - @Override - public Optional find(RecipientDeliveryId id) { - return Optional.ofNullable(saved); - } - - @Override - public RecipientDeliveryRecord save(RecipientDeliveryRecord record) { - writes++; - saved = record; - return record; - } - - @Override - public RecipientDeliveryRecord transition( - RecipientDeliveryId id, RecipientDeliveryState state, Optional nextDispatchAt) { - throw new UnsupportedOperationException(); - } - - @Override - public Optional saveHeldBy( - RecipientDeliveryRecord record, RecipientLease lease) { - return superseded ? Optional.empty() : Optional.of(save(record)); - } - - @Override - public Optional transitionHeldBy( - RecipientDeliveryId id, - RecipientDeliveryState state, - Optional nextDispatchAt, - RecipientLease lease) { - throw new UnsupportedOperationException(); - } + /** Leaves the projection as it is; the case does not involve a callback. */ + private static ProviderEventProjector acceptedOnly() { + return (DeliveryAttemptSnapshot attempt, + ProviderEventRecord event, + DeliveryProjection current) -> ProjectionResult.ignored(current, "UNCHANGED"); } - private static final class RecordingReconciliationJobs implements ReconciliationJobStorePort { - private DeliveryAttemptId scheduledAttempt; - private Instant dueAt; - - @Override - public ReconciliationJob schedule( - DeliveryAttemptId attemptId, ProviderProfileId providerProfileId, Instant dueAt) { - scheduledAttempt = attemptId; - this.dueAt = dueAt; - return new ReconciliationJob( - UUID.fromString("00000000-0000-7000-8000-000000000035"), - attemptId, - providerProfileId, - dueAt, - 0, - Optional.empty(), - COMPLETED, - COMPLETED, - 0); - } - - @Override - public List claimDue(int limit, Instant now, Duration lease) { - return List.of(); - } - - @Override - public void reschedule(ReconciliationJob job, String result, Instant nextCheckAt) {} - - @Override - public void complete(ReconciliationJob job) {} + private static VerifiedProviderEvent deliveredCallback(String providerRequestId) { + return new VerifiedProviderEvent( + PROFILE, + new NormalizedProviderEvent( + NormalizedEventType.DELIVERY_CONFIRMED, + "Delivery", + Optional.empty(), + Optional.of(providerRequestId), + Optional.of(STARTED), + Map.of()), + Optional.empty(), + ProviderEventSource.CALLBACK, + true, + STARTED, + "{}".getBytes(StandardCharsets.UTF_8), + "a".repeat(64), + "b".repeat(64)); } - private static final class NoopLedger extends NoopLedgerBase {} - - private static class NoopLedgerBase implements ProviderEventLedger { - @Override - public AppendEventResult append(VerifiedProviderEvent event) { - return new AppendEventResult(List.of(), List.of()); - } - - @Override - public AppendEventResult appendAll(List events) { - return new AppendEventResult(List.of(), List.of()); - } - - @Override - public List pendingProjection(int limit) { - return List.of(); - } - - @Override - public void markApplied(ProviderEventRecordId eventId, ProjectionResult result) {} - - @Override - public void markFailed(ProviderEventRecordId eventId, String errorCode) {} - - @Override - public List unmatched(int limit) { - return List.of(); - } - - @Override - public List bindUnmatched( - ProviderProfileId providerProfileId, - String providerRequestId, - DeliveryAttemptId attemptId) { - return List.of(); - } - - @Override - public boolean bindAttempt(ProviderEventRecordId eventId, DeliveryAttemptId attemptId) { - return false; - } - - @Override - public List eventsForAttempt(DeliveryAttemptId attemptId) { - return List.of(); - } - } + /** What the dispatcher holds when the provider call returns. */ + private record Dispatched( + RecipientDeliveryRecord job, RecipientLease lease, DeliveryAttemptRecord attempt) {} } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchPipelineTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchPipelineTest.java index 8f059028..41d3fba7 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchPipelineTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/DispatchPipelineTest.java @@ -15,10 +15,13 @@ import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLev import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; import dev.caskeleton.application.notification.platform.api.routing.Channel; -import dev.caskeleton.application.notification.platform.contact.ContactPointStatus; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryContactPointStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.NotificationRows; import dev.caskeleton.application.notification.platform.policy.NotificationEligibilityPolicy; import dev.caskeleton.application.notification.platform.policy.RouteCandidate; +import java.time.Clock; import java.time.Instant; +import java.time.ZoneOffset; import java.util.List; import java.util.Locale; import java.util.Map; @@ -37,7 +40,11 @@ class DispatchPipelineTest { @Test void expiredRequestStopsBeforeContactLookup() { - RecordingContactStore contacts = new RecordingContactStore(); + // An unusable contact point would block the delivery as well; EXPIRED shows the expiry check + // decided first, before the contact point was looked at. + InMemoryContactPointStore contacts = + new InMemoryContactPointStore(Clock.fixed(NOW, ZoneOffset.UTC)); + contacts.save(invalidContactPoint()); DispatchPipeline pipeline = new DispatchPipeline( contacts, @@ -55,12 +62,12 @@ class DispatchPipelineTest { assertThat(result) .isEqualTo(new DispatchGuardOutcome.Blocked(RecipientDeliveryState.EXPIRED, "EXPIRED")); - assertThat(contacts.findCalls).isZero(); } @Test void missingContactPointFailsBeforeEligibility() { - RecordingContactStore contacts = new RecordingContactStore(); + InMemoryContactPointStore contacts = + new InMemoryContactPointStore(Clock.fixed(NOW, ZoneOffset.UTC)); DispatchPipeline pipeline = new DispatchPipeline( contacts, @@ -80,7 +87,6 @@ class DispatchPipelineTest { .isEqualTo( new DispatchGuardOutcome.Blocked( RecipientDeliveryState.FAILED, "CONTACT_POINT_NOT_FOUND")); - assertThat(contacts.findCalls).isEqualTo(1); } private static NotificationRequestRecord request( @@ -136,29 +142,25 @@ class DispatchPipelineTest { 0, Channel.EMAIL, CONTACT, new ProviderProfileId("ses-primary"), true, true); } - private static final class RecordingContactStore implements ContactPointStorePort { - private int findCalls; - - @Override - public Optional find(TenantId tenantId, ContactPointId id) { - findCalls++; - return Optional.empty(); - } - - @Override - public Optional findByFingerprint(TenantId tenantId, String lookupHmac) { - throw new UnsupportedOperationException(); - } - - @Override - public ContactPointRecord save(ContactPointRecord record) { - throw new UnsupportedOperationException(); - } - - @Override - public ContactPointRecord updateStatus( - TenantId tenantId, ContactPointId id, ContactPointStatus status, String reasonCode) { - throw new UnsupportedOperationException(); - } + /** The route's contact point, already reported dead by the provider. */ + private static ContactPointRecord invalidContactPoint() { + ContactPointRecord registered = NotificationRows.contactPoint(TENANT, "c3".repeat(32), NOW); + return new ContactPointRecord( + CONTACT, + registered.tenantId(), + registered.ownerRef(), + registered.type(), + registered.provider(), + registered.applicationId(), + registered.environment(), + registered.protectedValue(), + dev.caskeleton.application.notification.platform.contact.ContactPointStatus.INVALID, + registered.verified(), + registered.lastConfirmedAt(), + registered.lastSuccessfulDeliveryAt(), + Optional.of(NOW), + Optional.of("HARD_BOUNCE"), + registered.createdAt(), + registered.updatedAt()); } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryServiceTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryServiceTest.java index 0f73e442..7ff29358 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryServiceTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryServiceTest.java @@ -4,14 +4,20 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.dispatch.testkit.ContractClock; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryRecipientQueue; +import dev.caskeleton.application.notification.platform.dispatch.testkit.NotificationRows; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.DisplayName; @@ -30,18 +36,19 @@ class LeaseRecoveryServiceTest { private static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); - private final RecordingLeases leases = new RecordingLeases(); - private final RecordingAttempts attempts = new RecordingAttempts(); - private final RecordingDeliveries deliveries = new RecordingDeliveries(); + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final ContractClock queueClock = new ContractClock(NOW); + private final InMemoryRecipientQueue queue = new InMemoryRecipientQueue(requests, queueClock); + private final InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests); private final List reconciled = new ArrayList<>(); private final LeaseRecoveryService recovery = new LeaseRecoveryService( - leases, + queue, attempts, - deliveries, + queue, reconciled::add, - new PlatformFakes.RecordingTransactions(), + new DirectTransactionPort(), CLOCK, Duration.ofMinutes(1), 10); @@ -49,64 +56,63 @@ class LeaseRecoveryServiceTest { @Test @DisplayName("a delivery with no attempt is requeued, because nothing can have been sent") void aDeliveryWithNoAttemptIsRequeued() { - RecipientDeliveryId id = new RecipientDeliveryId(UUID.randomUUID()); - leases.abandoned.add(id); + RecipientDeliveryId id = abandonedJob(); + workerDied(); assertThat(recovery.recoverOnce()).isEqualTo(1); - assertThat(deliveries.transitions) + assertThat(stateOf(id)) .as("the worker died between claiming and recording an attempt: no provider call happened") - .containsExactly(Map.entry(id, RecipientDeliveryState.READY_TO_DISPATCH)); + .isEqualTo(RecipientDeliveryState.READY_TO_DISPATCH); assertThat(reconciled).isEmpty(); } @Test @DisplayName("a delivery with an incomplete attempt is reconciled, never requeued") void aDeliveryWithAnIncompleteAttemptIsReconciled() { - RecipientDeliveryId id = new RecipientDeliveryId(UUID.randomUUID()); + RecipientDeliveryId id = abandonedJob(); DeliveryAttemptId attemptId = new DeliveryAttemptId(UUID.randomUUID()); - leases.abandoned.add(id); - attempts.byDelivery.put(id, List.of(incompleteAttempt(attemptId))); + attempts.insertDispatching(incompleteAttempt(attemptId, id)); + workerDied(); assertThat(recovery.recoverOnce()).isEqualTo(1); assertThat(reconciled) .as("a provider call may have happened; re-dispatching would choose to duplicate") .containsExactly(attemptId); - assertThat(deliveries.transitions).isEmpty(); + assertThat(stateOf(id)).isEqualTo(RecipientDeliveryState.DISPATCHING); } @Test @DisplayName("an attempt proven never to have started is requeued rather than reconciled") void anAttemptProvenNeverStartedIsRequeued() { - RecipientDeliveryId id = new RecipientDeliveryId(UUID.randomUUID()); - leases.abandoned.add(id); - attempts.byDelivery.put( - id, List.of(attemptWith(new DeliveryAttemptId(UUID.randomUUID()), notStarted()))); + RecipientDeliveryId id = abandonedJob(); + attempts.insertDispatching( + attemptWith(new DeliveryAttemptId(UUID.randomUUID()), id, notStarted())); + workerDied(); assertThat(recovery.recoverOnce()).isEqualTo(1); assertThat(reconciled) .as("the row says, with certainty, that no request began; a provider has nothing to add") .isEmpty(); - assertThat(deliveries.transitions) - .containsExactly(Map.entry(id, RecipientDeliveryState.READY_TO_DISPATCH)); + assertThat(stateOf(id)).isEqualTo(RecipientDeliveryState.READY_TO_DISPATCH); } @Test @DisplayName("an attempt that may have started is reconciled, never requeued") void anAttemptThatMayHaveStartedIsReconciled() { - RecipientDeliveryId id = new RecipientDeliveryId(UUID.randomUUID()); + RecipientDeliveryId id = abandonedJob(); DeliveryAttemptId attemptId = new DeliveryAttemptId(UUID.randomUUID()); - leases.abandoned.add(id); - attempts.byDelivery.put(id, List.of(attemptWith(attemptId, unknownWhetherStarted()))); + attempts.insertDispatching(attemptWith(attemptId, id, unknownWhetherStarted())); + workerDied(); assertThat(recovery.recoverOnce()).isEqualTo(1); assertThat(reconciled) .as("'we do not know whether it started' must never become a requeue") .containsExactly(attemptId); - assertThat(deliveries.transitions).isEmpty(); + assertThat(stateOf(id)).isEqualTo(RecipientDeliveryState.DISPATCHING); } @Test @@ -115,11 +121,11 @@ class LeaseRecoveryServiceTest { // given // The row the dispatcher commits before the call is, unchanged, the row a worker killed during // the SES/SMTP call leaves behind: nothing writes it again until the outcome is recorded. - RecipientDeliveryId id = new RecipientDeliveryId(UUID.randomUUID()); + RecipientDeliveryId id = abandonedJob(); DeliveryAttemptId attemptId = new DeliveryAttemptId(UUID.randomUUID()); - leases.abandoned.add(id); - attempts.byDelivery.put( - id, List.of(DeliveryAttemptFixtures.attemptAsTheDispatcherWritesIt(attemptId.value()))); + attempts.insertDispatching( + onJob(DeliveryAttemptFixtures.attemptAsTheDispatcherWritesIt(attemptId.value()), id)); + workerDied(); // when int handled = recovery.recoverOnce(); @@ -129,35 +135,34 @@ class LeaseRecoveryServiceTest { assertThat(reconciled) .as("the provider may already have the message; only the provider can say whether it does") .containsExactly(attemptId); - assertThat(deliveries.transitions) + assertThat(stateOf(id)) .as("a requeue here hands the same notification to another worker, which sends it again") - .isEmpty(); + .isEqualTo(RecipientDeliveryState.DISPATCHING); } @Test @DisplayName("attempt가 모두 끝난 DISPATCHING 수신자는 다시 꺼낼 수 있게 되돌린다") void aDispatchingDeliveryWhoseAttemptsAllCompletedIsRequeued() { // given - RecipientDeliveryId id = new RecipientDeliveryId(UUID.randomUUID()); - leases.abandoned.add(id); - attempts.byDelivery.put( - id, - List.of( - completed( - attemptWith( - new DeliveryAttemptId(UUID.randomUUID()), - dev.caskeleton.application.notification.platform.provider - .ProviderExecutionEvidence.completed(true))))); + RecipientDeliveryId id = abandonedJob(); + attempts.insertDispatching( + completed( + attemptWith( + new DeliveryAttemptId(UUID.randomUUID()), + id, + dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence + .completed(true)))); + workerDied(); // when recovery.recoverOnce(); // then - assertThat(deliveries.transitions) + assertThat(stateOf(id)) .as( "the worker died after recording the outcome and before applying the next step; left" + " DISPATCHING, the row is selected again on every pass and starves the rest") - .containsExactly(Map.entry(id, RecipientDeliveryState.READY_TO_DISPATCH)); + .isEqualTo(RecipientDeliveryState.READY_TO_DISPATCH); } @Test @@ -174,7 +179,9 @@ class LeaseRecoveryServiceTest { @Test @DisplayName("recovery also retires deliveries whose window closed") void recoveryAlsoRetiresExpiredDeliveries() { - leases.expired = 3; + for (int i = 0; i < 3; i++) { + jobOf(NOW.minusSeconds(60), Optional.of(NOW.minusSeconds(1))); + } assertThat(recovery.recoverOnce()).isEqualTo(3); } @@ -196,9 +203,10 @@ class LeaseRecoveryServiceTest { private static DeliveryAttemptRecord attemptWith( DeliveryAttemptId id, + RecipientDeliveryId job, dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence evidence) { - DeliveryAttemptRecord base = incompleteAttempt(id); + DeliveryAttemptRecord base = incompleteAttempt(id, job); return new DeliveryAttemptRecord( base.id(), base.recipientDeliveryId(), @@ -253,10 +261,11 @@ class LeaseRecoveryServiceTest { } /** An attempt row that exists with no completion: the provider may or may not have seen it. */ - private static DeliveryAttemptRecord incompleteAttempt(DeliveryAttemptId id) { + private static DeliveryAttemptRecord incompleteAttempt( + DeliveryAttemptId id, RecipientDeliveryId job) { return new DeliveryAttemptRecord( id, - new RecipientDeliveryId(UUID.randomUUID()), + job, new dev.caskeleton.application.notification.platform.api.ContactPointId(UUID.randomUUID()), 1, dev.caskeleton.application.notification.platform.api.routing.Channel.EMAIL, @@ -286,119 +295,56 @@ class LeaseRecoveryServiceTest { "0".repeat(64)); } - private static final class RecordingLeases implements RecipientLeaseStorePort { - - private final List abandoned = new ArrayList<>(); - private int expired; - - @Override - public List claim(String workerId, int limit, Duration leaseDuration) { - return List.of(); - } - - @Override - public Optional renew(RecipientLease lease, Duration leaseDuration) { - return Optional.empty(); - } - - @Override - public void release(RecipientLease lease) { - // Not part of this contract. - } - - @Override - public boolean stillHeld(RecipientLease lease) { - return false; - } - - @Override - public int expireOverdue(int limit) { - return expired; - } - - @Override - public List expiredDispatching(int limit, Duration olderThan) { - return List.copyOf(abandoned); - } + /** A due job that worker-a claimed; it stays DISPATCHING under that lease. */ + private RecipientDeliveryId abandonedJob() { + RecipientDeliveryId id = jobOf(NOW, Optional.empty()); + queue.claim("worker-a", 10, Duration.ofSeconds(30)); + return id; } - private static final class RecordingAttempts implements DeliveryAttemptStorePort { - - private final Map> byDelivery = - new java.util.HashMap<>(); - - @Override - public DeliveryAttemptRecord insertDispatching(DeliveryAttemptRecord attempt) { - return attempt; - } - - @Override - public DeliveryAttemptRecord recordOutcome(DeliveryAttemptRecord attempt) { - return attempt; - } - - @Override - public Optional find(DeliveryAttemptId id) { - return Optional.empty(); - } - - @Override - public int nextAttemptNo(RecipientDeliveryId recipientDeliveryId) { - return 1; - } - - @Override - public List attemptsOf(RecipientDeliveryId recipientDeliveryId) { - return byDelivery.getOrDefault(recipientDeliveryId, List.of()); - } - - @Override - public Optional< - dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot> - snapshot(DeliveryAttemptId id) { - return Optional.empty(); - } + /** The claiming worker is gone: its lease ran out well past the staleness threshold. */ + private void workerDied() { + queueClock.moveTo(NOW.plus(Duration.ofMinutes(5))); } - private static final class RecordingDeliveries implements RecipientDeliveryStorePort { + private RecipientDeliveryId jobOf(Instant dueAt, Optional expiresAt) { + NotificationRequestRecord request = + NotificationRows.request(new TenantId("tenant-a"), "idem-" + UUID.randomUUID(), NOW); + RecipientDeliveryRecord job = + NotificationRows.job( + request, RecipientDeliveryState.READY_TO_DISPATCH, Optional.of(dueAt), expiresAt, NOW); + requests.insert(request, List.of(job)); + return job.id(); + } - private final List> transitions = - new ArrayList<>(); + private RecipientDeliveryState stateOf(RecipientDeliveryId id) { + return queue.find(id).orElseThrow().state(); + } - @Override - public Optional find(RecipientDeliveryId id) { - return Optional.empty(); - } - - @Override - public RecipientDeliveryRecord save(RecipientDeliveryRecord record) { - return record; - } - - @Override - public RecipientDeliveryRecord transition( - RecipientDeliveryId id, RecipientDeliveryState state, Optional nextDispatchAt) { - transitions.add(Map.entry(id, state)); - return null; - } - - @Override - public Optional saveHeldBy( - RecipientDeliveryRecord record, - dev.caskeleton.application.notification.platform.dispatch.RecipientLease lease) { - return Optional.of(save(record)); - } - - @Override - public Optional transitionHeldBy( - RecipientDeliveryId id, - RecipientDeliveryState state, - Optional nextDispatchAt, - dev.caskeleton.application.notification.platform.dispatch.RecipientLease lease) { - // This fake belongs to lease *recovery*, which runs for jobs whose holder is gone; the fenced - // variants are the dispatch path's and are not exercised here. - transition(id, state, nextDispatchAt); - return Optional.empty(); - } + /** The same attempt, written for {@code job}. */ + private static DeliveryAttemptRecord onJob(DeliveryAttemptRecord base, RecipientDeliveryId job) { + return new DeliveryAttemptRecord( + base.id(), + job, + base.contactPointId(), + base.attemptNo(), + base.channel(), + base.providerId(), + base.providerProfileId(), + base.providerRequestId(), + base.executionEvidence(), + base.submissionOutcome(), + base.deliveryOutcome(), + base.confirmation(), + base.evidenceLevel(), + base.failureCategory(), + base.failureCode(), + base.nativeStatus(), + base.providerOccurredAt(), + base.startedAt(), + base.completedAt(), + base.elapsed(), + base.credentialGeneration(), + base.renderedContentDigest()); } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationApplicationUseCasesTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationApplicationUseCasesTest.java index 9c337bbd..a14a9bd8 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationApplicationUseCasesTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationApplicationUseCasesTest.java @@ -5,10 +5,15 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.notification.platform.api.CancelCommand; import dev.caskeleton.application.notification.platform.api.RequestStatus; import dev.caskeleton.application.notification.platform.api.routing.Channel; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryRecipientQueue; import dev.caskeleton.application.notification.platform.port.in.CancelNotificationCommand; import dev.caskeleton.application.notification.platform.port.in.GetNotificationQuery; import dev.caskeleton.application.notification.platform.port.in.ScheduleNotificationCommand; import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationCommand; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; @@ -20,12 +25,10 @@ class NotificationApplicationUseCasesTest { private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-09-20T00:00:00Z"), ZoneOffset.UTC); - private final PlatformFakes.RequestStore requests = new PlatformFakes.RequestStore(); - private final PlatformFakes.RecipientStore recipients = - new PlatformFakes.RecipientStore(requests); - private final PlatformFakes.AttemptStore attempts = new PlatformFakes.AttemptStore(); - private final PlatformFakes.RecordingTransactions transactions = - new PlatformFakes.RecordingTransactions(); + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final InMemoryRecipientQueue recipients = new InMemoryRecipientQueue(requests, CLOCK); + private final InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests); + private final DirectTransactionPort transactions = new DirectTransactionPort(); private final NotificationSubmissionService service = new NotificationSubmissionService( requests, @@ -50,7 +53,7 @@ class NotificationApplicationUseCasesTest { useCase.handle(new SubmitNotificationCommand(PlatformFakes.plan("submit-1", Map.of()))); assertThat(requests.byId).containsKey(receipt.notificationId()); - assertThat(transactions.boundaries).containsExactly("WRITE"); + assertThat(transactions.committed()).containsExactly(Boundary.WRITE); } @Test @@ -73,7 +76,7 @@ class NotificationApplicationUseCasesTest { .getFirst() .nextDispatchAt()) .contains(dueAt); - assertThat(transactions.boundaries).containsExactly("WRITE"); + assertThat(transactions.committed()).containsExactly(Boundary.WRITE); } @Test @@ -81,14 +84,14 @@ class NotificationApplicationUseCasesTest { var receipt = new SubmitNotificationApplicationUseCase(service, transactions) .handle(new SubmitNotificationCommand(PlatformFakes.plan("get-1", Map.of()))); - transactions.boundaries.clear(); + DirectTransactionPort readTransactions = new DirectTransactionPort(); GetNotificationApplicationUseCase useCase = - new GetNotificationApplicationUseCase(service, transactions); + new GetNotificationApplicationUseCase(service, readTransactions); var snapshot = useCase.handle(new GetNotificationQuery(receipt.notificationId())); assertThat(snapshot.notificationId()).isEqualTo(receipt.notificationId()); - assertThat(transactions.boundaries).containsExactly("READ"); + assertThat(readTransactions.committed()).containsExactly(Boundary.READ); } @Test @@ -96,9 +99,9 @@ class NotificationApplicationUseCasesTest { var receipt = new SubmitNotificationApplicationUseCase(service, transactions) .handle(new SubmitNotificationCommand(PlatformFakes.plan("cancel-1", Map.of()))); - transactions.boundaries.clear(); + DirectTransactionPort cancelTransactions = new DirectTransactionPort(); CancelNotificationApplicationUseCase useCase = - new CancelNotificationApplicationUseCase(service, transactions); + new CancelNotificationApplicationUseCase(service, cancelTransactions); var result = useCase.handle( @@ -106,6 +109,6 @@ class NotificationApplicationUseCasesTest { receipt.notificationId(), new CancelCommand("OPERATOR_REQUEST", false))); assertThat(result.canceledRecipients()).isEqualTo(1); - assertThat(transactions.boundaries).containsExactly("WRITE"); + assertThat(cancelTransactions.committed()).containsExactly(Boundary.WRITE); } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchServiceTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchServiceTest.java index 49125be7..e4e13f18 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchServiceTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationDispatchServiceTest.java @@ -2,6 +2,8 @@ package dev.caskeleton.application.notification.platform.dispatch; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.application.notification.platform.api.CollapseScope; +import dev.caskeleton.application.notification.platform.api.CollapseSpec; import dev.caskeleton.application.notification.platform.api.ContactPointId; import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.api.NotificationPlan; @@ -22,6 +24,11 @@ import dev.caskeleton.application.notification.platform.api.error.TemplateVariab import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.contact.ContactPointStatus; import dev.caskeleton.application.notification.platform.contact.ContactPointType; +import dev.caskeleton.application.notification.platform.dispatch.testkit.ContractClock; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryContactPointStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryRecipientQueue; import dev.caskeleton.application.notification.platform.policy.DefaultNotificationRetryPolicy; import dev.caskeleton.application.notification.platform.policy.JitterSource; import dev.caskeleton.application.notification.platform.policy.NotificationEligibilityPolicy; @@ -38,6 +45,8 @@ import dev.caskeleton.application.notification.platform.security.ProtectedContac import dev.caskeleton.application.notification.platform.template.NotificationTemplateRenderer; import dev.caskeleton.application.notification.platform.template.RenderCommand; import dev.caskeleton.application.notification.platform.template.RenderedNotificationContent; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -56,11 +65,11 @@ class NotificationDispatchServiceTest { @Test void missingLeasedRecipientIsReleasedWithoutCallingTheProvider() { - PlatformFakes.RequestStore requests = new PlatformFakes.RequestStore(); - PlatformFakes.RecipientStore recipients = new PlatformFakes.RecipientStore(requests); - PlatformFakes.AttemptStore attempts = new PlatformFakes.AttemptStore(); - PlatformFakes.RecordingTransactions transactions = new PlatformFakes.RecordingTransactions(); - RecordingLeases leases = new RecordingLeases(); + InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + InMemoryRecipientQueue recipients = + new InMemoryRecipientQueue(requests, Clock.fixed(NOW, ZoneOffset.UTC)); + InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests); + DirectTransactionPort transactions = new DirectTransactionPort(); FailingGateway gateway = new FailingGateway(); NotificationDispatchService service = new NotificationDispatchService( @@ -68,18 +77,18 @@ class NotificationDispatchServiceTest { recipients, attempts, new DispatchPipeline( - new EmptyContactStore(), + new InMemoryContactPointStore(Clock.fixed(NOW, ZoneOffset.UTC)), NotificationEligibilityPolicy.permitAll(), new PlatformFakes.RecordingMetrics()), new RoutingDecisionEngine(), context -> new RetryDecision.Stop("unused"), new DeliveryAttemptFactory(new PlatformFakes.SequentialIds()), - NotificationPlatformNoops.outcomeRecorder(attempts, recipients), + PlatformCollaborators.outcomeRecorder(attempts, recipients), gateway, command -> { throw new AssertionError("renderer must not be reached for a missing recipient"); }, - leases, + recipients, transactions, Clock.fixed(NOW, ZoneOffset.UTC), 3, @@ -93,17 +102,18 @@ class NotificationDispatchServiceTest { service.dispatch(lease); - assertThat(leases.released).containsExactly(lease); - assertThat(transactions.boundaries).containsExactly("READ", "WRITE"); + // The WRITE boundary after the read is the release; the queue has no row to show it on. + assertThat(transactions.committed()).containsExactly(Boundary.READ, Boundary.WRITE); assertThat(gateway.calls).isZero(); } @Test void losingTheLeaseAfterAttemptInsertClosesTheAttemptWithoutCallingTheProvider() { - PlatformFakes.RequestStore requests = new PlatformFakes.RequestStore(); - PlatformFakes.RecipientStore recipients = new PlatformFakes.RecipientStore(requests); - PlatformFakes.AttemptStore attempts = new PlatformFakes.AttemptStore(); - PlatformFakes.RecordingTransactions transactions = new PlatformFakes.RecordingTransactions(); + InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + ContractClock queueClock = new ContractClock(NOW); + InMemoryRecipientQueue recipients = new InMemoryRecipientQueue(requests, queueClock); + InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests); + DirectTransactionPort transactions = new DirectTransactionPort(); NotificationSubmissionService submissions = new NotificationSubmissionService( @@ -122,10 +132,12 @@ class NotificationDispatchServiceTest { var receipt = new SubmitNotificationApplicationUseCase(submissions, transactions) .handle(new SubmitNotificationCommand(PlatformFakes.plan("lease-loss", Map.of()))); + RecipientLease lease = recipients.claim("worker-a", 1, Duration.ofSeconds(30)).getFirst(); + // The lease runs out while the attempt row is being written: the worker no longer holds it. + queueClock.moveTo(lease.leaseUntil().plusSeconds(1)); RecipientDeliveryRecord recipient = requests.recipientsOf(new TenantId("tenant-a"), receipt.notificationId()).getFirst(); - RecordingLeases leases = new RecordingLeases(); ProfileOnlyGateway gateway = new ProfileOnlyGateway(); NotificationDispatchService service = new NotificationDispatchService( @@ -133,27 +145,26 @@ class NotificationDispatchServiceTest { recipients, attempts, new DispatchPipeline( - new SingleContactStore(contactPoint()), + contactStore(contactPoint()), NotificationEligibilityPolicy.permitAll(), new PlatformFakes.RecordingMetrics()), new RoutingDecisionEngine(), context -> new RetryDecision.Stop("unused"), new DeliveryAttemptFactory(new PlatformFakes.SequentialIds()), - NotificationPlatformNoops.outcomeRecorder(attempts, recipients), + PlatformCollaborators.outcomeRecorder(attempts, recipients), gateway, renderer(), - leases, + recipients, transactions, Clock.fixed(NOW, ZoneOffset.UTC), 3, Duration.ofSeconds(5)); - RecipientLease lease = new RecipientLease(recipient.id(), "worker-a", 1L, NOW.plusSeconds(30)); service.dispatch(lease); assertThat(gateway.submitCalls).isZero(); - assertThat(attempts.rows).hasSize(1); - DeliveryAttemptRecord stored = attempts.rows.getFirst(); + assertThat(attempts.rows()).hasSize(1); + DeliveryAttemptRecord stored = attempts.rows().getFirst(); assertThat(stored.submissionOutcome()).isEqualTo(SubmissionOutcome.NOT_SUBMITTED); assertThat(stored.failureCode()).contains(NotificationFailureCode.DISPATCH_LEASE_LOST); assertThat(stored.executionEvidence()) @@ -169,10 +180,8 @@ class NotificationDispatchServiceTest { void aTemplateThatCannotRenderFailsTheDeliveryInsteadOfLeavingItClaimed() { // given Scenario scenario = new Scenario(PlatformFakes.plan("render-failure", Map.of())); - RecordingLeases leases = new RecordingLeases(); NotificationDispatchService service = scenario.service( - leases, new NotificationTemplateRenderer() { @Override @@ -218,7 +227,7 @@ class NotificationDispatchServiceTest { // An operator redrive makes the delivery due now, ahead of its notBefore. scenario.recipients.transition( scenario.recipient.id(), RecipientDeliveryState.READY_TO_DISPATCH, Optional.of(NOW)); - NotificationDispatchService service = scenario.service(new RecordingLeases(), renderer()); + NotificationDispatchService service = scenario.service(renderer()); // when service.dispatch(scenario.lease()); @@ -253,8 +262,8 @@ class NotificationDispatchServiceTest { base.boundedMetadata())); scenario.recipients.transition( scenario.recipient.id(), RecipientDeliveryState.READY_TO_DISPATCH, Optional.of(NOW)); - scenario.requests.observe(scenario.dispatchTransactions); - NotificationDispatchService service = scenario.service(new RecordingLeases(), renderer()); + scenario.requests.observe(scenario.dispatchTransactions::active); + NotificationDispatchService service = scenario.service(renderer()); // when service.dispatch(scenario.lease()); @@ -268,9 +277,7 @@ class NotificationDispatchServiceTest { void aRouteWhoseProviderProfileIsGoneWaitsForTheRetryBackoff() { // given Scenario scenario = new Scenario(PlatformFakes.plan("profile-gone", Map.of())); - RecordingLeases leases = new RecordingLeases(); - NotificationDispatchService service = - scenario.service(leases, renderer(), new ProfileGoneGateway(), 3); + NotificationDispatchService service = scenario.service(renderer(), new ProfileGoneGateway(), 3); // when service.dispatch(scenario.lease()); @@ -290,20 +297,59 @@ class NotificationDispatchServiceTest { } @Test - @DisplayName("provider profile 이 사라진 route 는 재시도 한도를 다 쓰면 FAILED 로 닫힌다") - void aRouteWhoseProviderProfileIsGoneFailsOnceTheRetryBudgetIsSpent() { + @DisplayName("collapse 를 지원하지 않는 provider 로 가는 collapse 요청은 attempt 를 만들기 전에 FAILED 로 닫힌다") + void aCollapseRequestToAProviderWithoutCollapseFailsBeforeAnyAttemptIsWritten() { // given - Scenario scenario = new Scenario(PlatformFakes.plan("profile-gone-budget", Map.of())); - RecordingLeases leases = new RecordingLeases(); - NotificationDispatchService service = - scenario.service(leases, renderer(), new ProfileGoneGateway(), 0); + NotificationPlan base = PlatformFakes.plan("collapse-unsupported", Map.of()); + Scenario scenario = + new Scenario( + new NotificationPlan( + base.tenantId(), + base.idempotencyKey(), + base.category(), + base.template(), + base.variables(), + base.recipients(), + base.deliveryStrategy(), + base.notBefore(), + base.expiresAt(), + base.deduplication(), + Optional.of(new CollapseSpec("order-42", CollapseScope.RECIPIENT)), + base.correlationId(), + base.boundedMetadata())); + NotificationDispatchService service = scenario.service(renderer(), new ProfileOnlyGateway(), 3); // when service.dispatch(scenario.lease()); // then - assertThat(List.of(scenario.stored().state(), leases.released)) - .containsExactly(RecipientDeliveryState.FAILED, List.of(scenario.lease())); + assertThat( + List.of( + scenario.stored().state(), + scenario.stored().lastFailureCategory(), + scenario.attempts.rows(), + scenario.stored().leaseOwner())) + .as("the lease is released, so the next pass is not blocked until it expires") + .containsExactly( + RecipientDeliveryState.FAILED, + Optional.of("INVALID_PAYLOAD"), + List.of(), + Optional.empty()); + } + + @Test + @DisplayName("provider profile 이 사라진 route 는 재시도 한도를 다 쓰면 FAILED 로 닫힌다") + void aRouteWhoseProviderProfileIsGoneFailsOnceTheRetryBudgetIsSpent() { + // given + Scenario scenario = new Scenario(PlatformFakes.plan("profile-gone-budget", Map.of())); + NotificationDispatchService service = scenario.service(renderer(), new ProfileGoneGateway(), 0); + + // when + service.dispatch(scenario.lease()); + + // then + assertThat(List.of(scenario.stored().state(), scenario.stored().leaseOwner())) + .containsExactly(RecipientDeliveryState.FAILED, Optional.empty()); } @Test @@ -328,9 +374,9 @@ class NotificationDispatchServiceTest { base.boundedMetadata())); scenario.recipients.transition( scenario.recipient.id(), RecipientDeliveryState.READY_TO_DISPATCH, Optional.of(NOW)); + scenario.supersede(); RecipientDeliveryRecord beforeDispatch = scenario.stored(); - scenario.recipients.supersededLeases.add(scenario.lease()); - NotificationDispatchService service = scenario.service(new RecordingLeases(), renderer()); + NotificationDispatchService service = scenario.service(renderer()); // when service.dispatch(scenario.lease()); @@ -345,33 +391,33 @@ class NotificationDispatchServiceTest { Scenario scenario = new Scenario(PlatformFakes.plan("stop-lease-lost", Map.of())); RecipientDeliveryRecord r = scenario.stored(); // A non-retryable last failure makes the routing engine stop without selecting a route. - RecipientDeliveryRecord beforeDispatch = - scenario.recipients.save( - new RecipientDeliveryRecord( - r.id(), - r.notificationId(), - r.tenantId(), - r.recipientRef(), - r.locale(), - r.timeZone(), - r.routingPlan(), - r.routeCursor(), - RecipientDeliveryState.READY_TO_DISPATCH, - r.submissionOutcome(), - r.deliveryOutcome(), - r.evidenceLevel(), - r.ambiguousAttemptExists(), - r.duplicateRisk(), - Optional.of(NOW), - r.expiresAt(), - r.leaseOwner(), - r.leaseUntil(), - r.attemptCount(), - Optional.of("TEMPLATE_FAILURE"), - r.createdAt(), - r.updatedAt())); - scenario.recipients.supersededLeases.add(scenario.lease()); - NotificationDispatchService service = scenario.service(new RecordingLeases(), renderer()); + scenario.recipients.save( + new RecipientDeliveryRecord( + r.id(), + r.notificationId(), + r.tenantId(), + r.recipientRef(), + r.locale(), + r.timeZone(), + r.routingPlan(), + r.routeCursor(), + RecipientDeliveryState.READY_TO_DISPATCH, + r.submissionOutcome(), + r.deliveryOutcome(), + r.evidenceLevel(), + r.ambiguousAttemptExists(), + r.duplicateRisk(), + Optional.of(NOW), + r.expiresAt(), + r.leaseOwner(), + r.leaseUntil(), + r.attemptCount(), + Optional.of("TEMPLATE_FAILURE"), + r.createdAt(), + r.updatedAt())); + scenario.supersede(); + RecipientDeliveryRecord beforeDispatch = scenario.stored(); + NotificationDispatchService service = scenario.service(renderer()); // when service.dispatch(scenario.lease()); @@ -382,17 +428,20 @@ class NotificationDispatchServiceTest { /** One accepted request and its recipient, dispatched against fakes. */ private static final class Scenario { - private final PlatformFakes.RequestStore requests = new PlatformFakes.RequestStore(); - private final PlatformFakes.RecipientStore recipients = - new PlatformFakes.RecipientStore(requests); - private final PlatformFakes.AttemptStore attempts = new PlatformFakes.AttemptStore(); - private final PlatformFakes.RecordingTransactions dispatchTransactions = - new PlatformFakes.RecordingTransactions(); + private final InMemoryNotificationRequestStore requests = + new InMemoryNotificationRequestStore(); + private final ContractClock queueClock = new ContractClock(NOW); + private final InMemoryRecipientQueue recipients = + new InMemoryRecipientQueue(requests, queueClock); + private final InMemoryDeliveryAttemptStore attempts = + new InMemoryDeliveryAttemptStore(requests); + private RecipientLease lease; + private final DirectTransactionPort dispatchTransactions = new DirectTransactionPort(); private final NotificationId notificationId; private final RecipientDeliveryRecord recipient; private Scenario(NotificationPlan plan) { - PlatformFakes.RecordingTransactions transactions = new PlatformFakes.RecordingTransactions(); + DirectTransactionPort transactions = new DirectTransactionPort(); NotificationSubmissionService submissions = new NotificationSubmissionService( requests, @@ -418,13 +467,27 @@ class NotificationDispatchServiceTest { return requests.recipientsOf(new TenantId("tenant-a"), notificationId).getFirst(); } + /** This worker's lease, claimed from the queue the first time it is asked for. */ private RecipientLease lease() { - return new RecipientLease(recipient.id(), "worker-a", 1L, NOW.plusSeconds(30)); + if (lease == null) { + lease = recipients.claim("worker-a", 1, Duration.ofSeconds(30)).getFirst(); + } + return lease; + } + + /** This worker's lease runs out, recovery requeues the job, and another worker claims it. */ + private void supersede() { + RecipientLease mine = lease(); + queueClock.moveTo(mine.leaseUntil().plusSeconds(1)); + recipients.transition( + mine.recipientDeliveryId(), + RecipientDeliveryState.READY_TO_DISPATCH, + Optional.of(queueClock.instant())); + recipients.claim("worker-b", 1, Duration.ofSeconds(30)); } /** Dispatches through the real retry policy with no jitter, so the backoff is exact. */ private NotificationDispatchService service( - RecipientLeaseStorePort leases, NotificationTemplateRenderer renderer, ProviderDispatchGatewayPort gateway, int maxAdditionalAttempts) { @@ -433,40 +496,39 @@ class NotificationDispatchServiceTest { recipients, attempts, new DispatchPipeline( - new SingleContactStore(contactPoint()), + contactStore(contactPoint()), NotificationEligibilityPolicy.permitAll(), new PlatformFakes.RecordingMetrics()), new RoutingDecisionEngine(), new DefaultNotificationRetryPolicy( RetryBackoff.DEFAULT, JitterSource.none(), Duration.ofMinutes(1)), new DeliveryAttemptFactory(new PlatformFakes.SequentialIds()), - NotificationPlatformNoops.outcomeRecorder(attempts, recipients), + PlatformCollaborators.outcomeRecorder(attempts, recipients), gateway, renderer, - leases, - new PlatformFakes.RecordingTransactions(), + recipients, + new DirectTransactionPort(), Clock.fixed(NOW, ZoneOffset.UTC), maxAdditionalAttempts, Duration.ofSeconds(5)); } - private NotificationDispatchService service( - RecipientLeaseStorePort leases, NotificationTemplateRenderer renderer) { + private NotificationDispatchService service(NotificationTemplateRenderer renderer) { return new NotificationDispatchService( requests, recipients, attempts, new DispatchPipeline( - new SingleContactStore(contactPoint()), + contactStore(contactPoint()), NotificationEligibilityPolicy.permitAll(), new PlatformFakes.RecordingMetrics()), new RoutingDecisionEngine(), context -> new RetryDecision.Stop("unused"), new DeliveryAttemptFactory(new PlatformFakes.SequentialIds()), - NotificationPlatformNoops.outcomeRecorder(attempts, recipients), + PlatformCollaborators.outcomeRecorder(attempts, recipients), new ProfileOnlyGateway(), renderer, - leases, + recipients, dispatchTransactions, Clock.fixed(NOW, ZoneOffset.UTC), 3, @@ -495,6 +557,14 @@ class NotificationDispatchServiceTest { NOW); } + /** A contact point store holding exactly {@code contactPoint}. */ + private static InMemoryContactPointStore contactStore(ContactPointRecord contactPoint) { + InMemoryContactPointStore store = + new InMemoryContactPointStore(Clock.fixed(NOW, ZoneOffset.UTC)); + store.save(contactPoint); + return store; + } + private static NotificationTemplateRenderer renderer() { return new NotificationTemplateRenderer() { @@ -521,37 +591,6 @@ class NotificationDispatchServiceTest { Map.of()); } - private static final class SingleContactStore implements ContactPointStorePort { - private final ContactPointRecord contactPoint; - - private SingleContactStore(ContactPointRecord contactPoint) { - this.contactPoint = contactPoint; - } - - @Override - public Optional find(TenantId tenantId, ContactPointId id) { - return contactPoint.tenantId().equals(tenantId) && contactPoint.id().equals(id) - ? Optional.of(contactPoint) - : Optional.empty(); - } - - @Override - public Optional findByFingerprint(TenantId tenantId, String lookupHmac) { - return Optional.empty(); - } - - @Override - public ContactPointRecord save(ContactPointRecord record) { - throw new UnsupportedOperationException(); - } - - @Override - public ContactPointRecord updateStatus( - TenantId tenantId, ContactPointId id, ContactPointStatus status, String reasonCode) { - throw new UnsupportedOperationException(); - } - } - private static final class ProfileOnlyGateway implements ProviderDispatchGatewayPort { private int submitCalls; @@ -593,29 +632,6 @@ class NotificationDispatchServiceTest { } } - private static final class EmptyContactStore implements ContactPointStorePort { - @Override - public Optional find(TenantId tenantId, ContactPointId id) { - return Optional.empty(); - } - - @Override - public Optional findByFingerprint(TenantId tenantId, String lookupHmac) { - return Optional.empty(); - } - - @Override - public ContactPointRecord save(ContactPointRecord record) { - throw new UnsupportedOperationException(); - } - - @Override - public ContactPointRecord updateStatus( - TenantId tenantId, ContactPointId id, ContactPointStatus status, String reasonCode) { - throw new UnsupportedOperationException(); - } - } - private static final class FailingGateway implements ProviderDispatchGatewayPort { private int calls; @@ -637,38 +653,4 @@ class NotificationDispatchServiceTest { throw new AssertionError("provider submit must not be reached"); } } - - private static final class RecordingLeases implements RecipientLeaseStorePort { - private final List released = new java.util.ArrayList<>(); - - @Override - public List claim(String workerId, int limit, Duration leaseDuration) { - return List.of(); - } - - @Override - public Optional renew(RecipientLease lease, Duration leaseDuration) { - return Optional.empty(); - } - - @Override - public void release(RecipientLease lease) { - released.add(lease); - } - - @Override - public boolean stillHeld(RecipientLease lease) { - return false; - } - - @Override - public List expiredDispatching(int limit, Duration olderThan) { - return List.of(); - } - - @Override - public int expireOverdue(int limit) { - return 0; - } - } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java deleted file mode 100644 index 39f1dcd2..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java +++ /dev/null @@ -1,215 +0,0 @@ -package dev.caskeleton.application.notification.platform.dispatch; - -import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; -import dev.caskeleton.application.notification.platform.api.ProviderProfileId; -import dev.caskeleton.application.notification.platform.callback.AppendEventResult; -import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort; -import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; -import dev.caskeleton.application.notification.platform.callback.DeliveryProjection; -import dev.caskeleton.application.notification.platform.callback.DeliveryProjectionStorePort; -import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort; -import dev.caskeleton.application.notification.platform.callback.ProjectionResult; -import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; -import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord; -import dev.caskeleton.application.notification.platform.callback.ProviderEventRecordId; -import dev.caskeleton.application.notification.platform.callback.ProviderRequestIdHash; -import dev.caskeleton.application.notification.platform.callback.StandardDeliveryProjector; -import dev.caskeleton.application.notification.platform.callback.VerifiedProviderEvent; -import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; -import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; -import dev.caskeleton.application.notification.platform.provider.ReconciliationResult; -import java.time.Clock; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -/** Minimal collaborators for application tests that do not exercise reconciliation itself. */ -public final class NotificationPlatformNoops { - - private NotificationPlatformNoops() {} - - public static ReconciliationService reconciliation( - DeliveryAttemptStorePort attempts, RecipientDeliveryStorePort recipients, Clock clock) { - return reconciliation( - attempts, - recipients, - new ReconciliationGatewayPort() { - @Override - public boolean supports(ProviderProfileId profileId) { - return false; - } - - @Override - public ReconciliationResult reconcile(DeliveryAttemptSnapshot attempt) { - return new ReconciliationResult.Unsupported(); - } - }, - clock); - } - - /** Reconciliation over a caller-supplied gateway, everything else a no-op. */ - public static ReconciliationService reconciliation( - DeliveryAttemptStorePort attempts, - RecipientDeliveryStorePort recipients, - ReconciliationGatewayPort gateway, - Clock clock) { - ProviderEventLedger ledger = new NoopLedger(); - return new ReconciliationService( - attempts, - recipients, - gateway, - ledger, - projection(ledger), - audit(), - metrics(), - new SyntheticEventFingerprint(), - new PlatformFakes.RecordingTransactions(), - clock); - } - - public static DispatchOutcomeRecorder outcomeRecorder( - DeliveryAttemptStorePort attempts, RecipientDeliveryStorePort recipients) { - ProviderEventLedger ledger = new NoopLedger(); - ReconciliationJobStorePort jobs = - new ReconciliationJobStorePort() { - @Override - public ReconciliationJob schedule( - DeliveryAttemptId attemptId, - ProviderProfileId providerProfileId, - java.time.Instant dueAt) { - throw new UnsupportedOperationException(); - } - - @Override - public List claimDue( - int limit, java.time.Instant now, java.time.Duration lease) { - return List.of(); - } - - @Override - public void reschedule( - ReconciliationJob job, String result, java.time.Instant nextCheckAt) {} - - @Override - public void complete(ReconciliationJob job) {} - }; - return new DispatchOutcomeRecorder( - attempts, - recipients, - jobs, - ledger, - projection(ledger), - metrics(), - java.time.Duration.ofSeconds(30)); - } - - public static NotificationAuditPort audit() { - return event -> {}; - } - - public static NotificationMetricsPort metrics() { - return new NotificationMetricsPort() { - @Override - public void increment(String metricName, Map tags) {} - - @Override - public void record(String metricName, Map tags, java.time.Duration value) {} - - @Override - public void gauge(String metricName, Map tags, double value) {} - }; - } - - private static ProviderEventProjectionService projection(ProviderEventLedger ledger) { - DeliveryAttemptResolverPort resolver = - new DeliveryAttemptResolverPort() { - @Override - public Optional byAttemptId(DeliveryAttemptId attemptId) { - return Optional.empty(); - } - - @Override - public Optional byProviderRequestId( - ProviderProfileId profileId, String providerRequestId) { - return Optional.empty(); - } - - @Override - public Optional byProviderRequestIdHash( - ProviderProfileId profileId, ProviderRequestIdHash providerRequestIdHash) { - return Optional.empty(); - } - }; - DeliveryProjectionStorePort projections = - new DeliveryProjectionStorePort() { - @Override - public DeliveryProjection load(DeliveryAttemptId attemptId) { - return DeliveryProjection.accepted(); - } - - @Override - public void save(DeliveryAttemptId attemptId, DeliveryProjection projection) {} - - @Override - public boolean claimSuppressionSideEffect(DeliveryAttemptId attemptId) { - return false; - } - }; - NotificationSideEffectPort sideEffects = (attempt, facts) -> {}; - return new ProviderEventProjectionService( - ledger, - new StandardDeliveryProjector(), - resolver, - projections, - sideEffects, - new PlatformFakes.RecordingTransactions(), - metrics()); - } - - private static final class NoopLedger implements ProviderEventLedger { - @Override - public AppendEventResult append(VerifiedProviderEvent event) { - return new AppendEventResult(List.of(), List.of()); - } - - @Override - public AppendEventResult appendAll(List events) { - return new AppendEventResult(List.of(), List.of()); - } - - @Override - public List pendingProjection(int limit) { - return List.of(); - } - - @Override - public void markApplied(ProviderEventRecordId eventId, ProjectionResult result) {} - - @Override - public void markFailed(ProviderEventRecordId eventId, String errorCode) {} - - @Override - public List unmatched(int limit) { - return List.of(); - } - - @Override - public List bindUnmatched( - ProviderProfileId providerProfileId, - String providerRequestId, - DeliveryAttemptId attemptId) { - return List.of(); - } - - @Override - public boolean bindAttempt(ProviderEventRecordId eventId, DeliveryAttemptId attemptId) { - return false; - } - - @Override - public List eventsForAttempt(DeliveryAttemptId attemptId) { - return List.of(); - } - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java index b4c0853f..51b92d8e 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionServiceTest.java @@ -14,9 +14,14 @@ import dev.caskeleton.application.notification.platform.api.delivery.RecipientDe import dev.caskeleton.application.notification.platform.api.error.IdempotencyConflictException; import dev.caskeleton.application.notification.platform.api.error.NotificationValidationException; import dev.caskeleton.application.notification.platform.api.routing.Channel; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryRecipientQueue; import dev.caskeleton.application.notification.platform.observation.NotificationMetricName; import dev.caskeleton.application.notification.platform.port.in.ScheduleNotificationCommand; import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationCommand; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; @@ -39,12 +44,10 @@ class NotificationSubmissionServiceTest { private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-08-14T00:00:00Z"), ZoneOffset.UTC); - private final PlatformFakes.RequestStore requests = new PlatformFakes.RequestStore(); - private final PlatformFakes.RecipientStore recipients = - new PlatformFakes.RecipientStore(requests); - private final PlatformFakes.AttemptStore attempts = new PlatformFakes.AttemptStore(); - private final PlatformFakes.RecordingTransactions transactions = - new PlatformFakes.RecordingTransactions(); + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final InMemoryRecipientQueue recipients = new InMemoryRecipientQueue(requests, CLOCK); + private final InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests); + private final DirectTransactionPort transactions = new DirectTransactionPort(); private final PlatformFakes.RecordingMetrics metrics = new PlatformFakes.RecordingMetrics(); private final NotificationSubmissionService service = @@ -126,7 +129,7 @@ class NotificationSubmissionServiceTest { .get(0) .state()) .isEqualTo(RecipientDeliveryState.READY_TO_DISPATCH); - assertThat(transactions.boundaries).containsExactly("WRITE"); + assertThat(transactions.committed()).containsExactly(Boundary.WRITE); } @Test @@ -236,7 +239,7 @@ class NotificationSubmissionServiceTest { // Accepting a version that cannot be rendered would only defer the failure to dispatch time, // where the caller is gone and the only signal is a stuck job. assertThat(requests.byId).isEmpty(); - assertThat(transactions.boundaries).isEmpty(); + assertThat(transactions.committed()).isEmpty(); } @Test @@ -339,6 +342,32 @@ class NotificationSubmissionServiceTest { .DROPPED_AS_DUPLICATE); } + @org.junit.jupiter.api.Test + @org.junit.jupiter.api.DisplayName("DROP 으로 버린 제출을 같은 idempotency key 로 다시 보내면 처음과 같은 영수증을 받는다") + void aDroppedSubmissionRetriedWithTheSameIdempotencyKeyGetsTheSameReceipt() { + // given + var spec = + new dev.caskeleton.application.notification.platform.api.DeduplicationSpec( + "order-drop-retry", + java.time.Duration.ofMinutes(10), + dev.caskeleton.application.notification.platform.api.DeduplicationAction.DROP); + submit(planWithDedup("idem-drop-first", spec)); + var dropped = submit(planWithDedup("idem-drop-second", spec)); + + // when + var retried = submit(planWithDedup("idem-drop-second", spec)); + + // then + assertThat( + java.util.List.of( + retried, + requests.findById(new TenantId("tenant-a"), dropped.notificationId()).isPresent())) + .as( + "the drop was never stored, so a retry minted a new id and re-ran deduplication — " + + "after the window it would be accepted and sent") + .containsExactly(dropped, true); + } + @org.junit.jupiter.api.Test @org.junit.jupiter.api.DisplayName("RETURN_EXISTING converges on the earlier notification") void returnExistingConvergesOnTheEarlierNotification() { diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformCollaborators.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformCollaborators.java new file mode 100644 index 00000000..550d96e5 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformCollaborators.java @@ -0,0 +1,125 @@ +package dev.caskeleton.application.notification.platform.dispatch; + +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; +import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; +import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; +import dev.caskeleton.application.notification.platform.callback.StandardDeliveryProjector; +import dev.caskeleton.application.notification.platform.callback.testkit.InMemoryProviderEventLedger; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryContactPointStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryReconciliationJobStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.Sha256ProviderRequestIdHasher; +import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; +import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; +import dev.caskeleton.application.notification.platform.policy.testkit.InMemorySuppressionStore; +import dev.caskeleton.application.notification.platform.provider.ReconciliationResult; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import java.time.Clock; +import java.util.Map; + +/** + * The collaborators an application test needs but does not exercise: reconciliation, the outcome + * recorder and the ledger projection, assembled over the store fakes. + * + *

        They used to be assembled over stubs — a ledger that stored nothing, a resolver that found + * nothing, a projection store that always answered "accepted" — so a path that reached them did + * nothing a test could see. Now the ledger, the resolver and the projections are the fakes held to + * the same contracts as the JPA stores, sharing the test's attempt store; only the gateway that + * would call a provider, the audit sink and the metrics are inert. + */ +public final class PlatformCollaborators { + + private PlatformCollaborators() {} + + /** Reconciliation over a gateway that supports no profile. */ + public static ReconciliationService reconciliation( + InMemoryDeliveryAttemptStore attempts, RecipientDeliveryStorePort recipients, Clock clock) { + return reconciliation( + attempts, + recipients, + new ReconciliationGatewayPort() { + @Override + public boolean supports(ProviderProfileId profileId) { + return false; + } + + @Override + public ReconciliationResult reconcile(DeliveryAttemptSnapshot attempt) { + return new ReconciliationResult.Unsupported(); + } + }, + clock); + } + + /** Reconciliation over a caller-supplied gateway. */ + public static ReconciliationService reconciliation( + InMemoryDeliveryAttemptStore attempts, + RecipientDeliveryStorePort recipients, + ReconciliationGatewayPort gateway, + Clock clock) { + ProviderEventLedger ledger = ledger(attempts); + return new ReconciliationService( + attempts, + recipients, + gateway, + ledger, + projection(ledger, attempts, clock), + audit(), + metrics(), + new SyntheticEventFingerprint(), + new DirectTransactionPort(), + clock); + } + + /** The outcome recorder over the test's stores, with an in-memory reconciliation queue. */ + public static DispatchOutcomeRecorder outcomeRecorder( + InMemoryDeliveryAttemptStore attempts, RecipientDeliveryStorePort recipients) { + ProviderEventLedger ledger = ledger(attempts); + return new DispatchOutcomeRecorder( + attempts, + recipients, + new InMemoryReconciliationJobStore(Clock.systemUTC()), + ledger, + projection(ledger, attempts, Clock.systemUTC()), + metrics(), + java.time.Duration.ofSeconds(30)); + } + + public static NotificationAuditPort audit() { + return event -> {}; + } + + public static NotificationMetricsPort metrics() { + return new NotificationMetricsPort() { + @Override + public void increment(String metricName, Map tags) {} + + @Override + public void record(String metricName, Map tags, java.time.Duration value) {} + + @Override + public void gauge(String metricName, Map tags, double value) {} + }; + } + + private static ProviderEventLedger ledger(InMemoryDeliveryAttemptStore attempts) { + return new InMemoryProviderEventLedger(attempts, new Sha256ProviderRequestIdHasher()); + } + + private static ProviderEventProjectionService projection( + ProviderEventLedger ledger, InMemoryDeliveryAttemptStore attempts, Clock clock) { + return new ProviderEventProjectionService( + ledger, + new StandardDeliveryProjector(), + attempts, + attempts, + new SuppressionSideEffect( + new InMemoryContactPointStore(clock), + new InMemorySuppressionStore(), + new PlatformFakes.SequentialIds(), + clock), + new DirectTransactionPort(), + metrics()); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformFakes.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformFakes.java index a8890657..a04d1631 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformFakes.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PlatformFakes.java @@ -3,38 +3,25 @@ package dev.caskeleton.application.notification.platform.dispatch; import dev.caskeleton.application.notification.platform.api.ContactPointId; import dev.caskeleton.application.notification.platform.api.ContactPointSelector; import dev.caskeleton.application.notification.platform.api.CorrelationId; -import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.IdempotencyKey; -import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.api.NotificationPlan; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; -import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; import dev.caskeleton.application.notification.platform.api.RecipientSpec; -import dev.caskeleton.application.notification.platform.api.RequestStatus; import dev.caskeleton.application.notification.platform.api.TemplateSelection; import dev.caskeleton.application.notification.platform.api.TenantId; -import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.api.routing.DeliveryStrategy; import dev.caskeleton.application.notification.platform.api.routing.ExplicitChannel; -import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; import dev.caskeleton.application.notification.platform.policy.RouteCandidate; -import dev.caskeleton.application.transaction.TransactionPort; import java.time.Duration; -import java.time.Instant; import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Supplier; /** * Hand-rolled in-memory ports for the platform's application services. @@ -48,296 +35,6 @@ public final class PlatformFakes { private PlatformFakes() {} - /** - * Transaction port that records nesting so "no provider call inside a transaction" is testable. - */ - public static final class RecordingTransactions implements TransactionPort { - - public final List boundaries = new ArrayList<>(); - private int depth; - - /** True while a transaction is open. */ - public boolean inTransaction() { - return depth > 0; - } - - @Override - public T inWrite(Supplier action) { - return run("WRITE", action); - } - - @Override - public T inRootWrite(Supplier action) { - if (depth > 0) { - throw new dev.caskeleton.application.transaction.NestedRootTransactionRejectedException(); - } - return run("ROOT_WRITE", action); - } - - @Override - public T inRead(Supplier action) { - return run("READ", action); - } - - @Override - public T inNew(Supplier action) { - return run("NEW", action); - } - - @Override - public void inWrite(Runnable action) { - run("WRITE", toSupplier(action)); - } - - @Override - public void inRead(Runnable action) { - run("READ", toSupplier(action)); - } - - @Override - public void inNew(Runnable action) { - run("NEW", toSupplier(action)); - } - - private static Supplier toSupplier(Runnable action) { - return () -> { - action.run(); - return null; - }; - } - - private T run(String boundary, Supplier action) { - boundaries.add(boundary); - depth++; - try { - return action.get(); - } finally { - depth--; - } - } - } - - /** Request store with idempotency-key uniqueness enforced the way the database would. */ - public static final class RequestStore implements NotificationRequestStorePort { - - public final Map byId = new LinkedHashMap<>(); - public final Map byIdempotency = new HashMap<>(); - public final Map> recipients = new HashMap<>(); - - /** Whether each status write ran inside {@link #observe}'s transactions, in call order. */ - public final List statusWritesInTransaction = new ArrayList<>(); - - private RecordingTransactions observed; - - /** - * Records, for every later status write, whether {@code transactions} had one open — what the - * JPA store's {@code CallerTransaction} guard refuses when it did not. - */ - public void observe(RecordingTransactions transactions) { - this.observed = transactions; - } - - /** - * Set to make the next insert lose the race, as a concurrent claim would. - * - *

        Losing is reported, not thrown. The real store used to raise a unique violation, which - * left the PostgreSQL transaction aborted and made the winner unreadable — so a fake that - * throws would model the bug rather than the contract. - */ - private static final char KEY_SEPARATOR = '\u0000'; - - public boolean failNextInsertAsDuplicate; - - @Override - public NotificationRequestInsertOutcome insert( - NotificationRequestRecord request, List jobs) { - String key = request.tenantId().value() + KEY_SEPARATOR + request.idempotencyKey(); - if (failNextInsertAsDuplicate || byIdempotency.containsKey(key)) { - failNextInsertAsDuplicate = false; - NotificationRequestRecord winner = byId.get(byIdempotency.get(key)); - if (winner == null) { - throw new DuplicateIdempotencyKeyException( - "idempotency key is claimed but its request cannot be read"); - } - // Deliberately no recipient jobs on this path: the loser's jobs would attach a second set - // to the winner's request. - return NotificationRequestInsertOutcome.lost(winner); - } - byId.put(request.id(), request); - byIdempotency.put(key, request.id()); - recipients.put(request.id(), new ArrayList<>(jobs)); - return NotificationRequestInsertOutcome.won(request); - } - - @Override - public Optional findByIdempotency( - TenantId tenantId, String idempotencyKey) { - return Optional.ofNullable(byIdempotency.get(tenantId.value() + '' + idempotencyKey)) - .map(byId::get); - } - - @Override - public Optional findById(TenantId tenantId, NotificationId id) { - return Optional.ofNullable(byId.get(id)).filter(row -> row.tenantId().equals(tenantId)); - } - - @Override - public List recipientsOf( - TenantId tenantId, NotificationId notificationId) { - // Scoped like the real store: another tenant's id answers with nothing, not with rows. - NotificationRequestRecord owner = byId.get(notificationId); - if (owner == null || !owner.tenantId().equals(tenantId)) { - return List.of(); - } - return List.copyOf(recipients.getOrDefault(notificationId, List.of())); - } - - @Override - public NotificationRequestRecord updateStatus( - TenantId tenantId, NotificationId notificationId, RequestStatus status) { - if (observed != null) { - statusWritesInTransaction.add(observed.inTransaction()); - } - NotificationRequestRecord current = byId.get(notificationId); - if (current == null || !current.tenantId().equals(tenantId)) { - throw new IllegalStateException("notification request no longer exists"); - } - NotificationRequestRecord updated = current.withStatus(status); - byId.put(notificationId, updated); - return updated; - } - - /** Overwrite a stored job, as the recipient store's save would. */ - public void replace(RecipientDeliveryRecord job) { - List jobs = recipients.get(job.notificationId()); - jobs.replaceAll(existing -> existing.id().equals(job.id()) ? job : existing); - } - } - - /** Recipient job store sharing rows with the request store. */ - public static final class RecipientStore implements RecipientDeliveryStorePort { - - private final RequestStore requests; - - public RecipientStore(RequestStore requests) { - this.requests = requests; - } - - @Override - public Optional find(RecipientDeliveryId id) { - return requests.recipients.values().stream() - .flatMap(List::stream) - .filter(job -> job.id().equals(id)) - .findFirst(); - } - - @Override - public RecipientDeliveryRecord save(RecipientDeliveryRecord record) { - requests.replace(record); - return record; - } - - @Override - public RecipientDeliveryRecord transition( - RecipientDeliveryId id, RecipientDeliveryState state, Optional nextDispatchAt) { - RecipientDeliveryRecord job = find(id).orElseThrow(); - RecipientDeliveryRecord moved = - new RecipientDeliveryRecord( - job.id(), - job.notificationId(), - job.tenantId(), - job.recipientRef(), - job.locale(), - job.timeZone(), - job.routingPlan(), - job.routeCursor(), - state, - job.submissionOutcome(), - job.deliveryOutcome(), - job.evidenceLevel(), - job.ambiguousAttemptExists(), - job.duplicateRisk(), - nextDispatchAt, - job.expiresAt(), - job.leaseOwner(), - job.leaseUntil(), - job.attemptCount(), - job.lastFailureCategory(), - job.createdAt(), - job.updatedAt()); - requests.replace(moved); - return moved; - } - - /** - * Leases this fake considers superseded. Add one and the fenced writes below stop matching, the - * way the database stops matching once another worker has claimed the job. - */ - public final Set supersededLeases = new HashSet<>(); - - @Override - public Optional saveHeldBy( - RecipientDeliveryRecord record, RecipientLease lease) { - if (supersededLeases.contains(lease)) { - return Optional.empty(); - } - return Optional.of(save(record)); - } - - @Override - public Optional transitionHeldBy( - RecipientDeliveryId id, - RecipientDeliveryState state, - Optional nextDispatchAt, - RecipientLease lease) { - if (supersededLeases.contains(lease)) { - return Optional.empty(); - } - return Optional.of(transition(id, state, nextDispatchAt)); - } - } - - /** Attempt store that keeps insertion order, which is what attempt numbering depends on. */ - public static final class AttemptStore implements DeliveryAttemptStorePort { - - public final List rows = new ArrayList<>(); - public final Map snapshots = new HashMap<>(); - - @Override - public DeliveryAttemptRecord insertDispatching(DeliveryAttemptRecord attempt) { - rows.add(attempt); - return attempt; - } - - @Override - public DeliveryAttemptRecord recordOutcome(DeliveryAttemptRecord attempt) { - rows.replaceAll(existing -> existing.id().equals(attempt.id()) ? attempt : existing); - return attempt; - } - - @Override - public Optional find(DeliveryAttemptId id) { - return rows.stream().filter(row -> row.id().equals(id)).findFirst(); - } - - @Override - public List attemptsOf(RecipientDeliveryId recipientDeliveryId) { - return rows.stream() - .filter(row -> row.recipientDeliveryId().equals(recipientDeliveryId)) - .toList(); - } - - @Override - public Optional snapshot(DeliveryAttemptId id) { - return Optional.ofNullable(snapshots.get(id)); - } - - @Override - public int nextAttemptNo(RecipientDeliveryId recipientDeliveryId) { - return attemptsOf(recipientDeliveryId).size() + 1; - } - } - /** Metrics sink that keeps what it was told, so tag discipline stays assertable. */ public static final class RecordingMetrics implements NotificationMetricsPort { @@ -498,33 +195,15 @@ public final class PlatformFakes { /** * A deduplication service over an in-memory window store. * - *

        The real store is a JPA one whose uniqueness makes the claim atomic; this keeps the same - * shape — first claim wins, later claims in the same window see the winner — so a test that - * passes here is testing the protocol. + *

        The store is the deduplication fake, held to the same contract as the JPA store whose + * uniqueness makes the claim atomic — first claim wins, later claims in the same window see the + * winner — so a test that passes here is testing the protocol. */ public static dev.caskeleton.application.notification.platform.policy.DeduplicationService deduplication(java.time.Clock clock) { - java.util.Map - claimed = new java.util.concurrent.ConcurrentHashMap<>(); dev.caskeleton.application.notification.platform.policy.DeduplicationStorePort store = - (recipient, dedupKey, windowBucket, candidate) -> { - String key = - recipient.tenantId().value() - + "\u0000" - + recipient.recipientRef() - + "\u0000" - + recipient.category() - + "\u0000" - + dedupKey - + "\u0000" - + windowBucket; - var winner = claimed.putIfAbsent(key, candidate); - return winner == null - ? dev.caskeleton.application.notification.platform.policy.DeduplicationResult.first( - candidate) - : new dev.caskeleton.application.notification.platform.policy.DeduplicationResult( - candidate, java.util.Optional.of(winner)); - }; + new dev.caskeleton.application.notification.platform.policy.testkit + .InMemoryDeduplicationStore(); return new dev.caskeleton.application.notification.platform.policy.DeduplicationService( store, clock); } 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 c5ce0a55..29b00856 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 @@ -8,6 +8,8 @@ import dev.caskeleton.application.notification.platform.port.in.PublishNotificat import dev.caskeleton.application.notification.platform.template.NotificationTemplateVersion; import dev.caskeleton.application.notification.platform.template.TemplateRegistry; import dev.caskeleton.application.notification.platform.template.TemplateSlot; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import java.util.Locale; import java.util.Map; import java.util.Optional; @@ -19,7 +21,7 @@ class PublishNotificationTemplateApplicationUseCaseTest { @Test void publishComputesTheDigestAndWritesInsideOneTransaction() { RecordingTemplates templates = new RecordingTemplates(); - PlatformFakes.RecordingTransactions transactions = new PlatformFakes.RecordingTransactions(); + DirectTransactionPort transactions = new DirectTransactionPort(); PublishNotificationTemplateApplicationUseCase useCase = new PublishNotificationTemplateApplicationUseCase(templates, transactions); PublishNotificationTemplateCommand command = @@ -37,7 +39,7 @@ class PublishNotificationTemplateApplicationUseCaseTest { assertThat(published.contentDigest()).matches("[0-9a-f]{64}"); assertThat(templates.published).isEqualTo(published); - assertThat(transactions.boundaries).containsExactly("WRITE"); + assertThat(transactions.committed()).containsExactly(Boundary.WRITE); } @Test @@ -45,7 +47,7 @@ class PublishNotificationTemplateApplicationUseCaseTest { // given PublishNotificationTemplateApplicationUseCase useCase = new PublishNotificationTemplateApplicationUseCase( - new RecordingTemplates(), new PlatformFakes.RecordingTransactions()); + new RecordingTemplates(), new DirectTransactionPort()); PublishNotificationTemplateCommand command = new PublishNotificationTemplateCommand( "payment-receipt", diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationServiceTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationServiceTest.java index d806b52d..f1ac9473 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationServiceTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationServiceTest.java @@ -16,11 +16,13 @@ import dev.caskeleton.application.notification.platform.api.delivery.RecipientDe import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryDeliveryAttemptStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryNotificationRequestStore; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryRecipientQueue; import dev.caskeleton.application.notification.platform.provider.ReconciliationResult; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; -import java.util.List; import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.DisplayName; @@ -29,16 +31,17 @@ import org.junit.jupiter.api.Test; class ReconciliationServiceTest { private static final Instant NOW = Instant.parse("2026-09-20T00:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); @Test void unsupportedProviderProfileDoesNotInventAStatus() { - PlatformFakes.AttemptStore attempts = new PlatformFakes.AttemptStore(); - PlatformFakes.RequestStore requests = new PlatformFakes.RequestStore(); - PlatformFakes.RecipientStore recipients = new PlatformFakes.RecipientStore(requests); + InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests); + InMemoryRecipientQueue recipients = new InMemoryRecipientQueue(requests, CLOCK); DeliveryAttemptSnapshot snapshot = snapshot(); - attempts.snapshots.put(snapshot.attemptId(), snapshot); + AttemptSnapshots.store(requests, attempts, snapshot, RecipientDeliveryState.DISPATCHING); ReconciliationService service = - NotificationPlatformNoops.reconciliation( + PlatformCollaborators.reconciliation( attempts, recipients, Clock.fixed(NOW, ZoneOffset.UTC)); ReconciliationResult result = service.reconcile(snapshot.attemptId()); @@ -48,11 +51,11 @@ class ReconciliationServiceTest { @Test void unknownAttemptIsUnsupportedRatherThanGuessed() { - PlatformFakes.AttemptStore attempts = new PlatformFakes.AttemptStore(); - PlatformFakes.RequestStore requests = new PlatformFakes.RequestStore(); + InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + InMemoryDeliveryAttemptStore attempts = new InMemoryDeliveryAttemptStore(requests); ReconciliationService service = - NotificationPlatformNoops.reconciliation( - attempts, new PlatformFakes.RecipientStore(requests), Clock.fixed(NOW, ZoneOffset.UTC)); + PlatformCollaborators.reconciliation( + attempts, new InMemoryRecipientQueue(requests, CLOCK), CLOCK); ReconciliationResult result = service.reconcile( @@ -67,7 +70,7 @@ class ReconciliationServiceTest { // given Stores stores = new Stores(RecipientDeliveryState.DISPATCHING); ReconciliationService service = - NotificationPlatformNoops.reconciliation( + PlatformCollaborators.reconciliation( stores.attempts, stores.recipients, Clock.fixed(NOW, ZoneOffset.UTC)); // when @@ -85,7 +88,7 @@ class ReconciliationServiceTest { // given Stores stores = new Stores(RecipientDeliveryState.DISPATCHING); ReconciliationService service = - NotificationPlatformNoops.reconciliation( + PlatformCollaborators.reconciliation( stores.attempts, stores.recipients, answering(new ReconciliationResult.Failed("PROVIDER_TIMEOUT", true)), @@ -106,7 +109,7 @@ class ReconciliationServiceTest { // given Stores stores = new Stores(RecipientDeliveryState.COMPLETED); ReconciliationService service = - NotificationPlatformNoops.reconciliation( + PlatformCollaborators.reconciliation( stores.attempts, stores.recipients, Clock.fixed(NOW, ZoneOffset.UTC)); // when @@ -132,41 +135,15 @@ class ReconciliationServiceTest { /** One attempt and its recipient delivery in the given state. */ private static final class Stores { - private final PlatformFakes.AttemptStore attempts = new PlatformFakes.AttemptStore(); - private final PlatformFakes.RequestStore requests = new PlatformFakes.RequestStore(); - private final PlatformFakes.RecipientStore recipients = - new PlatformFakes.RecipientStore(requests); + private final InMemoryNotificationRequestStore requests = + new InMemoryNotificationRequestStore(); + private final InMemoryDeliveryAttemptStore attempts = + new InMemoryDeliveryAttemptStore(requests); + private final InMemoryRecipientQueue recipients = new InMemoryRecipientQueue(requests, CLOCK); private final DeliveryAttemptSnapshot snapshot = snapshot(); private Stores(RecipientDeliveryState state) { - attempts.snapshots.put(snapshot.attemptId(), snapshot); - requests.recipients.put( - snapshot.notificationId(), - new java.util.ArrayList<>( - List.of( - new RecipientDeliveryRecord( - snapshot.recipientDeliveryId(), - snapshot.notificationId(), - snapshot.tenantId(), - "user-1", - Optional.empty(), - Optional.empty(), - List.of(), - 0, - state, - SubmissionOutcome.AMBIGUOUS, - DeliveryOutcome.UNKNOWN, - EvidenceLevel.PLATFORM_QUEUED, - false, - false, - Optional.of(NOW), - Optional.empty(), - Optional.of("worker-a"), - Optional.of(NOW), - 1, - Optional.empty(), - NOW, - NOW)))); + AttemptSnapshots.store(requests, attempts, snapshot, state); } private RecipientDeliveryRecord recipient() { diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/SuppressionSideEffectTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/SuppressionSideEffectTest.java new file mode 100644 index 00000000..739b2ea8 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/SuppressionSideEffectTest.java @@ -0,0 +1,38 @@ +package dev.caskeleton.application.notification.platform.dispatch; + +import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort; +import dev.caskeleton.application.notification.platform.callback.testkit.NotificationSideEffectContract; +import dev.caskeleton.application.notification.platform.dispatch.testkit.InMemoryContactPointStore; +import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; +import dev.caskeleton.application.notification.platform.policy.testkit.InMemorySuppressionStore; +import java.util.function.Supplier; + +/** The side effect over the contact point and suppression fakes, held to the shared contract. */ +class SuppressionSideEffectTest extends NotificationSideEffectContract { + + private final InMemoryContactPointStore contactPoints = new InMemoryContactPointStore(clock()); + private final InMemorySuppressionStore suppressions = new InMemorySuppressionStore(); + private final SuppressionSideEffect sideEffects = + new SuppressionSideEffect( + contactPoints, suppressions, new PlatformFakes.SequentialIds(), clock()); + + @Override + protected NotificationSideEffectPort sideEffects() { + return sideEffects; + } + + @Override + protected ContactPointStorePort contactPoints() { + return contactPoints; + } + + @Override + protected SuppressionStorePort suppressions() { + return suppressions; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryContactPointStoreTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryContactPointStoreTest.java new file mode 100644 index 00000000..8503cc74 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryContactPointStoreTest.java @@ -0,0 +1,20 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; +import java.util.function.Supplier; + +/** The in-memory contact point store held to the same contract as the JPA store. */ +class InMemoryContactPointStoreTest extends ContactPointStoreContract { + + private final InMemoryContactPointStore store = new InMemoryContactPointStore(clock()); + + @Override + protected ContactPointStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryDeliveryAttemptStoreTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryDeliveryAttemptStoreTest.java new file mode 100644 index 00000000..00875b1d --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryDeliveryAttemptStoreTest.java @@ -0,0 +1,44 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import java.util.UUID; +import java.util.function.Supplier; + +/** The in-memory attempt store held to the same contract as the JPA store. */ +class InMemoryDeliveryAttemptStoreTest extends DeliveryAttemptStoreContract { + + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final ProviderRequestIdHasherPort hasher = new Sha256ProviderRequestIdHasher(); + private final InMemoryDeliveryAttemptStore attempts = + new InMemoryDeliveryAttemptStore(requests, hasher, clock()); + + @Override + protected NotificationRequestStorePort requests() { + return requests; + } + + @Override + protected DeliveryAttemptStorePort attempts() { + return attempts; + } + + @Override + protected ProviderRequestIdHasherPort hasher() { + return hasher; + } + + @Override + protected ContactPointId givenAContactPoint(TenantId tenant) { + // The fake has no contact point table to refer to; the id is all an attempt carries. + return new ContactPointId(UUID.randomUUID()); + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStoreTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStoreTest.java new file mode 100644 index 00000000..77e76cd1 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStoreTest.java @@ -0,0 +1,26 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeEach; + +/** The in-memory fake held to the same contract as the JPA store. */ +class InMemoryNotificationRequestStoreTest extends NotificationRequestStoreContract { + + private InMemoryNotificationRequestStore store; + + @BeforeEach + void freshStore() { + store = new InMemoryNotificationRequestStore(); + } + + @Override + protected NotificationRequestStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueueDeliveryTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueueDeliveryTest.java new file mode 100644 index 00000000..7d6d5ea0 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueueDeliveryTest.java @@ -0,0 +1,33 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; +import java.util.function.Supplier; + +/** The in-memory queue held to the same recipient contract as the JPA recipient store. */ +class InMemoryRecipientQueueDeliveryTest extends RecipientDeliveryStoreContract { + + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final InMemoryRecipientQueue queue = new InMemoryRecipientQueue(requests, clock()); + + @Override + protected RecipientLeaseStorePort leases() { + return queue; + } + + @Override + protected RecipientDeliveryStorePort deliveries() { + return queue; + } + + @Override + protected NotificationRequestStorePort requests() { + return requests; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueueLeaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueueLeaseTest.java new file mode 100644 index 00000000..b90fd3ae --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueueLeaseTest.java @@ -0,0 +1,33 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; +import java.util.function.Supplier; + +/** The in-memory queue held to the same lease contract as the JPA lease store. */ +class InMemoryRecipientQueueLeaseTest extends RecipientLeaseStoreContract { + + private final InMemoryNotificationRequestStore requests = new InMemoryNotificationRequestStore(); + private final InMemoryRecipientQueue queue = new InMemoryRecipientQueue(requests, clock()); + + @Override + protected RecipientLeaseStorePort leases() { + return queue; + } + + @Override + protected RecipientDeliveryStorePort deliveries() { + return queue; + } + + @Override + protected NotificationRequestStorePort requests() { + return requests; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStoreTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStoreTest.java new file mode 100644 index 00000000..c9609adb --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStoreTest.java @@ -0,0 +1,29 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort; +import java.time.Clock; +import java.time.ZoneOffset; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; + +/** The in-memory fake held to the same contract as the JDBC store. */ +class InMemoryReconciliationJobStoreTest extends ReconciliationJobStoreContract { + + private InMemoryReconciliationJobStore store; + + @BeforeEach + void freshStore() { + store = new InMemoryReconciliationJobStore(Clock.fixed(NOW, ZoneOffset.UTC)); + } + + @Override + protected ReconciliationJobStorePort store() { + return store; + } + + @Override + protected DeliveryAttemptId givenAnAttempt() { + return new DeliveryAttemptId(UUID.randomUUID()); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/DeduplicationAndCollapseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/DeduplicationAndCollapseTest.java index be47d978..ecc03283 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/DeduplicationAndCollapseTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/DeduplicationAndCollapseTest.java @@ -7,14 +7,13 @@ import dev.caskeleton.application.notification.platform.api.CollapseSpec; import dev.caskeleton.application.notification.platform.api.DeduplicationAction; import dev.caskeleton.application.notification.platform.api.DeduplicationSpec; import dev.caskeleton.application.notification.platform.api.NotificationId; +import dev.caskeleton.application.notification.platform.policy.testkit.InMemoryDeduplicationStore; import dev.caskeleton.application.notification.platform.provider.CollapseCapability; import dev.caskeleton.application.notification.platform.provider.ProviderCollapseMapping; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; -import java.util.HashMap; -import java.util.Map; import java.util.UUID; import org.junit.jupiter.api.Test; @@ -66,29 +65,4 @@ class DeduplicationAndCollapseTest { assertThat(mapped.guaranteesSingleUserNotification()).isFalse(); assertThat(mapped.nativeKey()).isEqualTo("feed:user-1"); } - - /** In-memory store using the same insert-or-find contract as the durable one. */ - private static final class InMemoryDeduplicationStore implements DeduplicationStorePort { - - private final Map claims = new HashMap<>(); - - @Override - public DeduplicationResult insertOrFind( - RecipientIdentity recipient, String dedupKey, long windowBucket, NotificationId candidate) { - String key = - recipient.tenantId().value() - + "|" - + recipient.recipientRef() - + "|" - + recipient.category() - + "|" - + dedupKey - + "|" - + windowBucket; - NotificationId existing = claims.putIfAbsent(key, candidate); - return existing == null - ? DeduplicationResult.first(candidate) - : DeduplicationResult.duplicateOf(candidate, existing); - } - } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryDeduplicationStoreTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryDeduplicationStoreTest.java new file mode 100644 index 00000000..46a3fac6 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryDeduplicationStoreTest.java @@ -0,0 +1,26 @@ +package dev.caskeleton.application.notification.platform.policy.testkit; + +import dev.caskeleton.application.notification.platform.policy.DeduplicationStorePort; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeEach; + +/** The in-memory fake held to the same contract as the JPA store. */ +class InMemoryDeduplicationStoreTest extends DeduplicationStoreContract { + + private InMemoryDeduplicationStore store; + + @BeforeEach + void freshStore() { + store = new InMemoryDeduplicationStore(); + } + + @Override + protected DeduplicationStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/TemplateRegistryContractTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/TemplateRegistryContractTest.java deleted file mode 100644 index 197b5776..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/TemplateRegistryContractTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package dev.caskeleton.application.notification.platform.template; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.notification.platform.api.TemplateSelection; -import dev.caskeleton.application.notification.platform.api.error.TemplateNotFoundException; -import dev.caskeleton.application.notification.platform.api.routing.Channel; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class TemplateRegistryContractTest { - - private final InMemoryTemplateRegistry registry = new InMemoryTemplateRegistry(Locale.ENGLISH); - - @Test - void publishedVersionCannotBeOverwrittenWithDifferentContent() { - registry.publish(version(1, Locale.KOREAN, "a".repeat(64))); - assertThatThrownBy(() -> registry.publish(version(1, Locale.KOREAN, "b".repeat(64)))) - .isInstanceOf(TemplateVersionConflictException.class); - } - - @Test - void republishingIdenticalContentIsIdempotent() { - registry.publish(version(1, Locale.KOREAN, "a".repeat(64))); - registry.publish(version(1, Locale.KOREAN, "a".repeat(64))); - assertThat(registry.get(new TemplateSelection("password-reset", 1, Locale.KOREAN)).version()) - .isEqualTo(1); - } - - @Test - void selectionPinsExactVersion() { - var selection = new TemplateSelection("password-reset", 3, Locale.KOREAN); - assertThat(selection.version()).isEqualTo(3); - } - - @Test - void localeResolutionFallsBackToThePlatformDefault() { - registry.publish(version(1, Locale.ENGLISH, "c".repeat(64))); - assertThat(registry.resolve("password-reset", 1, Channel.EMAIL, Locale.JAPANESE).locale()) - .isEqualTo(Locale.ENGLISH); - } - - @Test - void disablingKeepsTheVersionReadableForRetryAndRedrive() { - registry.publish(version(1, Locale.KOREAN, "a".repeat(64))); - registry.disable("password-reset", 1); - var stored = registry.get(new TemplateSelection("password-reset", 1, Locale.KOREAN)); - assertThat(stored.status()).isEqualTo(TemplateStatus.DISABLED); - assertThat(stored.content().slot(TemplateSlot.TEXT_BODY)).isPresent(); - } - - @Test - void anUnknownSelectionFailsBeforeAnyProviderCall() { - assertThatThrownBy(() -> registry.get(new TemplateSelection("missing", 1, Locale.KOREAN))) - .isInstanceOf(TemplateNotFoundException.class); - } - - private static NotificationTemplateVersion version(long number, Locale locale, String digest) { - return new NotificationTemplateVersion( - "password-reset", - number, - Channel.EMAIL, - locale, - Optional.of(Locale.ENGLISH), - VariableSchema.NONE, - new TemplateContentDefinition( - Map.of(TemplateSlot.SUBJECT, "Reset", TemplateSlot.TEXT_BODY, "code: {code}")), - TemplateStatus.PUBLISHED, - digest); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/TemplateSelectionTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/TemplateSelectionTest.java new file mode 100644 index 00000000..4920a6d0 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/TemplateSelectionTest.java @@ -0,0 +1,15 @@ +package dev.caskeleton.application.notification.platform.template; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.notification.platform.api.TemplateSelection; +import java.util.Locale; +import org.junit.jupiter.api.Test; + +class TemplateSelectionTest { + + @Test + void aSelectionPinsTheExactVersion() { + assertThat(new TemplateSelection("password-reset", 3, Locale.KOREAN).version()).isEqualTo(3); + } +} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/testkit/InMemoryTemplateRegistryTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/testkit/InMemoryTemplateRegistryTest.java new file mode 100644 index 00000000..d7fe19f7 --- /dev/null +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/testkit/InMemoryTemplateRegistryTest.java @@ -0,0 +1,26 @@ +package dev.caskeleton.application.notification.platform.template.testkit; + +import dev.caskeleton.application.notification.platform.template.TemplateRegistry; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeEach; + +/** The in-memory fake held to the same contract as the JPA registry. */ +class InMemoryTemplateRegistryTest extends TemplateRegistryContract { + + private InMemoryTemplateRegistry registry; + + @BeforeEach + void freshRegistry() { + registry = new InMemoryTemplateRegistry(PLATFORM_DEFAULT); + } + + @Override + protected TemplateRegistry registry() { + return registry; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/AdminOperationStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/AdminOperationStoreContract.java new file mode 100644 index 00000000..86409ca8 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/AdminOperationStoreContract.java @@ -0,0 +1,206 @@ +package dev.caskeleton.application.notification.platform.admin.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.notification.platform.admin.AdminActor; +import dev.caskeleton.application.notification.platform.admin.AdminOperationClaim; +import dev.caskeleton.application.notification.platform.admin.AdminOperationClaim.Outcome; +import dev.caskeleton.application.notification.platform.admin.AdminOperationResult; +import dev.caskeleton.application.notification.platform.admin.AdminOperationStorePort; +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.NotificationId; +import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.policy.testkit.OverlappingWrites; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link AdminOperationStorePort} promises, run against the in-memory fake and the JPA + * store alike (review 2026-11-01 04-14). + * + *

        The claim is the idempotency key being held, not just checked: of two callers presenting one + * operation id, exactly one may act; a repeat after the result is a replay of that result; and the + * same id with a different command is a conflict, never a replay. Writes go through {@link + * #inTransaction}, because the real store refuses a claim or a result without a caller transaction. + */ +public abstract class AdminOperationStoreContract { + + private static final String FINGERPRINT = "a".repeat(64); + private static final String OTHER_FINGERPRINT = "b".repeat(64); + private static final String ACTION = "ADMIN_REDRIVE"; + private static final AdminActor OPERATOR = + new AdminActor("operator-1", Set.of(), Optional.of(new TenantId("tenant-a"))); + + /** The store under test, empty at the start of each test. */ + protected abstract AdminOperationStorePort store(); + + /** Runs {@code work} in one committed write transaction of the store under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + @DisplayName("처음 claim한 operation id는 진행해도 된다") + void theFirstClaimOfAnOperationIdMayProceed() { + // when + AdminOperationClaim claim = claim("op-1", FINGERPRINT); + + // then + assertThat(claim).isEqualTo(AdminOperationClaim.claimed()); + } + + @Test + @DisplayName("결과가 아직 없는 operation id를 같은 명령으로 다시 claim하면 진행 중이라고 답한다") + void aSecondClaimBeforeTheResultIsInProgress() { + // given + claim("op-1", FINGERPRINT); + + // when + AdminOperationClaim second = claim("op-1", FINGERPRINT); + + // then + assertThat(second) + .as("both callers used to read 'not found' and both ran the operation") + .isEqualTo(AdminOperationClaim.inProgress()); + } + + @Test + @DisplayName("다른 operation id는 따로 claim된다") + void aDifferentOperationIdClaimsIndependently() { + // given + claim("op-1", FINGERPRINT); + + // when + AdminOperationClaim other = claim("op-2", FINGERPRINT); + + // then + assertThat(other).isEqualTo(AdminOperationClaim.claimed()); + } + + @Test + @DisplayName("결과를 저장한 operation id를 같은 명령으로 다시 claim하면 저장된 결과를 재생한다") + void aClaimAfterTheResultReplaysIt() { + // given + claim("op-1", FINGERPRINT); + AdminOperationResult stored = save(result("op-1")); + + // when + AdminOperationClaim replay = claim("op-1", FINGERPRINT); + + // then + assertThat(replay).isEqualTo(AdminOperationClaim.replay(stored)); + } + + @Test + @DisplayName("같은 operation id를 다른 명령으로 claim하면 재생이 아니라 충돌이다") + void theSameIdWithADifferentCommandConflicts() { + // given + claim("op-1", FINGERPRINT); + save(result("op-1")); + + // when + AdminOperationClaim conflict = claim("op-1", OTHER_FINGERPRINT); + + // then + assertThat(conflict) + .as("answering with the earlier result would silently execute neither command") + .isEqualTo(AdminOperationClaim.conflict()); + } + + @Test + @DisplayName("claim만 된 operation은 아직 결과로 조회되지 않는다") + void aClaimedOperationIsNotAResultYet() { + // given + claim("op-1", FINGERPRINT); + + // when + Optional found = store().findByOperationId("op-1"); + + // then + assertThat(found).isEmpty(); + } + + @Test + @DisplayName("저장한 결과는 operation id로 그대로 조회된다") + void aSavedResultIsFoundByItsOperationId() { + // given + claim("op-1", FINGERPRINT); + AdminOperationResult stored = save(result("op-1")); + + // when + Optional found = store().findByOperationId("op-1"); + + // then + assertThat(found).contains(stored); + } + + @Test + @DisplayName("claim하지 않은 operation의 결과는 저장을 거부한다") + void aResultWithoutAClaimIsRefused() { + // when + Throwable refused = catchThrowable(() -> save(result("op-unclaimed"))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("non-claimed operation"); + } + + @Test + @DisplayName("한 operation의 결과는 한 번만 저장된다") + void aResultIsSavedOnlyOnce() { + // given + claim("op-1", FINGERPRINT); + save(result("op-1")); + + // when + Throwable second = catchThrowable(() -> save(result("op-1"))); + + // then + assertThat(second) + .as("the result completes the claimed row in place; it is not inserted a second time") + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("non-claimed operation"); + } + + @Test + @DisplayName("같은 operation id의 claim 두 개가 겹쳐도 진행하는 쪽은 하나다") + void ofTwoOverlappingClaimsExactlyOneMayProceed() { + // when + List claims = + OverlappingWrites.run( + this::inTransaction, + () -> store().claim("op-1", FINGERPRINT, OPERATOR, ACTION), + () -> store().claim("op-1", FINGERPRINT, OPERATOR, ACTION)); + + // then + assertThat(claims) + .extracting(AdminOperationClaim::outcome) + .containsExactly(Outcome.CLAIMED, Outcome.IN_PROGRESS); + } + + private AdminOperationClaim claim(String operationId, String fingerprint) { + return inTransaction(() -> store().claim(operationId, fingerprint, OPERATOR, ACTION)); + } + + private AdminOperationResult save(AdminOperationResult result) { + return inTransaction(() -> store().save(result, OPERATOR, ACTION)); + } + + private static AdminOperationResult result(String operationId) { + return new AdminOperationResult( + operationId, + false, + 1, + Optional.of(new NotificationId(UUID.fromString("00000000-0000-7000-8000-000000000001"))), + Optional.of( + new RecipientDeliveryId(UUID.fromString("00000000-0000-7000-8000-000000000002"))), + Optional.of(new DeliveryAttemptId(UUID.fromString("00000000-0000-7000-8000-000000000003"))), + List.of("REDRIVEN")); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/InMemoryAdminOperationStore.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/InMemoryAdminOperationStore.java new file mode 100644 index 00000000..8c222dcf --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/InMemoryAdminOperationStore.java @@ -0,0 +1,84 @@ +package dev.caskeleton.application.notification.platform.admin.testkit; + +import dev.caskeleton.application.notification.platform.admin.AdminActor; +import dev.caskeleton.application.notification.platform.admin.AdminOperationClaim; +import dev.caskeleton.application.notification.platform.admin.AdminOperationResult; +import dev.caskeleton.application.notification.platform.admin.AdminOperationStorePort; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** + * The {@link AdminOperationStorePort} fake, held to {@link AdminOperationStoreContract} like the + * JPA store. + * + *

        One row per operation id, as the audit table has: the claim creates it, the result completes + * it in place, and only a completed row is a result. Synchronized, because the claim is the race + * this port exists to settle. + */ +public final class InMemoryAdminOperationStore implements AdminOperationStorePort { + + private final Map rows = new HashMap<>(); + + @Override + public synchronized Optional findByOperationId(String operationId) { + Objects.requireNonNull(operationId, "operationId"); + return Optional.ofNullable(rows.get(operationId)).flatMap(row -> row.result); + } + + @Override + public synchronized AdminOperationResult save( + AdminOperationResult result, AdminActor actor, String action) { + Objects.requireNonNull(result, "result"); + Objects.requireNonNull(actor, "actor"); + Objects.requireNonNull(action, "action"); + Row row = rows.get(result.operationId()); + // The table's UPDATE matches the claimed row of this actor and action; anything else is zero + // rows, which the store reports as a missing claim. + if (row == null + || row.result.isPresent() + || !row.action.equals(action) + || !row.actorRef.equals(actor.actorRef())) { + throw new IllegalStateException( + "admin operation result cannot complete a missing or non-claimed operation"); + } + row.result = Optional.of(result); + return result; + } + + @Override + public synchronized AdminOperationClaim claim( + String operationId, String commandFingerprint, AdminActor actor, String action) { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(commandFingerprint, "commandFingerprint"); + Objects.requireNonNull(actor, "actor"); + Objects.requireNonNull(action, "action"); + Row existing = rows.get(operationId); + if (existing == null) { + rows.put(operationId, new Row(commandFingerprint, actor.actorRef(), action)); + return AdminOperationClaim.claimed(); + } + if (!existing.fingerprint.equals(commandFingerprint)) { + return AdminOperationClaim.conflict(); + } + return existing + .result + .map(AdminOperationClaim::replay) + .orElseGet(AdminOperationClaim::inProgress); + } + + private static final class Row { + + private final String fingerprint; + private final String actorRef; + private final String action; + private Optional result = Optional.empty(); + + private Row(String fingerprint, String actorRef, String action) { + this.fingerprint = fingerprint; + this.actorRef = actorRef; + this.action = action; + } + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/DeliveryAttemptResolverContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/DeliveryAttemptResolverContract.java new file mode 100644 index 00000000..f7a4046d --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/DeliveryAttemptResolverContract.java @@ -0,0 +1,116 @@ +package dev.caskeleton.application.notification.platform.callback.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; +import dev.caskeleton.application.notification.platform.callback.ProviderRequestIdHash; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptRecord; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.dispatch.testkit.AttemptStoreFixture; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link DeliveryAttemptResolverPort} promises, run against the in-memory attempt store + * and the JPA one alike (review 2026-11-01 04-14). + * + *

        A callback finds its attempt by the attempt id it carries, by the provider's request id while + * the callback is in flight, or — for a stored event, which keeps only the keyed hash — by that + * hash. Every lookup by request id is scoped to the profile: two profiles can mint the same id, and + * matching across them attaches one tenant's callback to another's attempt. + */ +public abstract class DeliveryAttemptResolverContract extends AttemptStoreFixture { + + /** The resolver under test, over the attempt store {@link #attempts()} writes to. */ + protected abstract DeliveryAttemptResolverPort resolver(); + + @Test + @DisplayName("attempt id로 그 attempt를 찾고 없는 id는 비어 있다") + void anAttemptIsFoundByItsIdAndAnUnknownIdIsEmpty() { + // given + RecipientDeliveryRecord job = givenAJob(); + DeliveryAttemptRecord attempt = givenADispatchingAttempt(job, 1); + + // when + List> found = + List.of( + resolver().byAttemptId(attempt.id()).map(DeliveryAttemptSnapshot::attemptId), + resolver() + .byAttemptId(new DeliveryAttemptId(UUID.randomUUID())) + .map(DeliveryAttemptSnapshot::attemptId)); + + // then + assertThat(found).containsExactly(Optional.of(attempt.id()), Optional.empty()); + } + + @Test + @DisplayName("provider 요청 id로는 그 profile 안에서만 찾는다") + void aProviderRequestIdIsMatchedOnlyWithinItsProfile() { + // given + RecipientDeliveryRecord job = givenAJob(); + DeliveryAttemptRecord accepted = givenAnAcceptedAttempt(job, "ses-message-1"); + + // when + List> found = + List.of( + resolver() + .byProviderRequestId(PROFILE, "ses-message-1") + .map(DeliveryAttemptSnapshot::attemptId), + resolver() + .byProviderRequestId(new ProviderProfileId("sms-main"), "ses-message-1") + .map(DeliveryAttemptSnapshot::attemptId), + resolver() + .byProviderRequestId(PROFILE, "ses-message-2") + .map(DeliveryAttemptSnapshot::attemptId)); + + // then + assertThat(found) + .as("another profile's identical request id is another message") + .containsExactly(Optional.of(accepted.id()), Optional.empty(), Optional.empty()); + } + + @Test + @DisplayName("저장된 이벤트가 가진 해시로도 같은 profile의 attempt를 찾는다") + void aStoredEventsHashFindsTheAttemptWithinItsProfile() { + // given + RecipientDeliveryRecord job = givenAJob(); + DeliveryAttemptRecord accepted = givenAnAcceptedAttempt(job, "ses-message-1"); + ProviderRequestIdHash hash = new ProviderRequestIdHash(hasher().hash(PROFILE, "ses-message-1")); + + // when + List> found = + List.of( + resolver() + .byProviderRequestIdHash(PROFILE, hash) + .map(DeliveryAttemptSnapshot::attemptId), + resolver() + .byProviderRequestIdHash(new ProviderProfileId("sms-main"), hash) + .map(DeliveryAttemptSnapshot::attemptId)); + + // then + assertThat(found) + .as("a stored event has the hash and nothing else to find its attempt with") + .containsExactly(Optional.of(accepted.id()), Optional.empty()); + } + + @Test + @DisplayName("아직 provider 요청 id가 없는 attempt는 요청 id로 찾히지 않는다") + void anAttemptWithoutARequestIdIsNotFoundByOne() { + // given + RecipientDeliveryRecord job = givenAJob(); + givenADispatchingAttempt(job, 1); + + // when + Optional found = + resolver().byProviderRequestId(PROFILE, "ses-message-1"); + + // then + assertThat(found).isEmpty(); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/DeliveryProjectionStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/DeliveryProjectionStoreContract.java new file mode 100644 index 00000000..eaec783f --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/DeliveryProjectionStoreContract.java @@ -0,0 +1,170 @@ +package dev.caskeleton.application.notification.platform.callback.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; +import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; +import dev.caskeleton.application.notification.platform.callback.DeliveryProjection; +import dev.caskeleton.application.notification.platform.callback.DeliveryProjectionStorePort; +import dev.caskeleton.application.notification.platform.callback.EngagementFacts; +import dev.caskeleton.application.notification.platform.callback.SuppressionFacts; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptRecord; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.dispatch.testkit.AttemptStoreFixture; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link DeliveryProjectionStorePort} promises, run against the in-memory attempt store + * and the JPA one alike (review 2026-11-01 04-14). + * + *

        A fact the platform observed — an open, a read, a hard bounce, a complaint — survives a reload + * and is never withdrawn by a later event that does not mention it; without that, a restart forgets + * the hard bounce and a late "delivered" brings a dead address back. The outcome is rolled up onto + * the job, whose evidence only gets stronger. The suppression side effect is claimed once, however + * often the ledger is replayed. + */ +public abstract class DeliveryProjectionStoreContract extends AttemptStoreFixture { + + /** The projection store under test, over the attempt store {@link #attempts()} writes to. */ + protected abstract DeliveryProjectionStorePort projections(); + + @Test + @DisplayName("저장한 배달 결과·증거·hard bounce는 다시 읽어도 그대로이고 없는 attempt는 빈 projection이다") + void aSavedProjectionSurvivesAReload() { + // given + DeliveryAttemptRecord attempt = givenADispatchingAttempt(givenAJob(), 1); + DeliveryProjection bounced = + DeliveryProjection.accepted() + .withDelivery(DeliveryOutcome.BOUNCED, EvidenceLevel.NETWORK_OR_CARRIER_ACCEPTED) + .withSuppression(new SuppressionFacts(true, false, false, false, false)); + inTransaction( + () -> { + projections().save(attempt.id(), bounced); + return null; + }); + + // when + DeliveryProjection reloaded = projections().load(attempt.id()); + + // then + assertThat( + List.of( + reloaded.deliveryOutcome(), + reloaded.evidenceLevel(), + reloaded.suppressionFacts(), + projections().load(new DeliveryAttemptId(UUID.randomUUID())))) + .as("a hard bounce that lived only in memory let a later 'delivered' be applied") + .containsExactly( + DeliveryOutcome.BOUNCED, + EvidenceLevel.NETWORK_OR_CARRIER_ACCEPTED, + new SuppressionFacts(true, false, false, false, false), + DeliveryProjection.empty()); + } + + @Test + @DisplayName("나중 저장이 언급하지 않은 사실은 지워지지 않고 마지막 참여 시각은 뒤로 가지 않는다") + void observedFactsAccumulateAndTheLastEngagementNeverMovesBack() { + // given + DeliveryAttemptRecord attempt = givenADispatchingAttempt(givenAJob(), 1); + Instant later = NOW.plusSeconds(120); + save(attempt.id(), new EngagementFacts(false, false, true, Optional.of(later)), complaint()); + save( + attempt.id(), + new EngagementFacts(true, false, false, Optional.of(NOW)), + SuppressionFacts.NONE); + + // when + DeliveryProjection reloaded = projections().load(attempt.id()); + + // then + assertThat(List.of(reloaded.engagementFacts(), reloaded.suppressionFacts())) + .as("a second event that says nothing about the read must not unset it") + .containsExactly(new EngagementFacts(true, false, true, Optional.of(later)), complaint()); + } + + @Test + @DisplayName("저장한 결과는 작업으로 올라가고 작업의 증거는 더 강한 쪽이 남는다") + void theOutcomeIsRolledUpAndTheJobsEvidenceOnlyStrengthens() { + // given + RecipientDeliveryRecord job = givenAJob(); + DeliveryAttemptRecord attempt = givenADispatchingAttempt(job, 1); + save( + attempt.id(), + DeliveryProjection.accepted() + .withDelivery(DeliveryOutcome.DELIVERED, EvidenceLevel.DEVICE_DELIVERED)); + + // when + save(attempt.id(), DeliveryProjection.accepted()); + + // then + RecipientDeliveryRecord rolledUp = + requests().recipientsOf(TENANT, job.notificationId()).getFirst(); + assertThat(List.of(rolledUp.submissionOutcome(), rolledUp.evidenceLevel())) + .as("a weaker, later projection must not weaken what the job already proved") + .containsExactly( + DeliveryProjection.accepted().submissionOutcome(), EvidenceLevel.DEVICE_DELIVERED); + } + + @Test + @DisplayName("억제 부수효과는 한 attempt에 한 번만 claim되고 없는 attempt는 claim되지 않는다") + void theSuppressionSideEffectIsClaimedOnce() { + // given + DeliveryAttemptRecord attempt = givenADispatchingAttempt(givenAJob(), 1); + + // when + List claims = + List.of( + inTransaction(() -> projections().claimSuppressionSideEffect(attempt.id())), + inTransaction(() -> projections().claimSuppressionSideEffect(attempt.id())), + inTransaction( + () -> + projections() + .claimSuppressionSideEffect(new DeliveryAttemptId(UUID.randomUUID())))); + + // then + assertThat(claims) + .as("the ledger is replayed by design, so 'the facts say suppressed' is true every time") + .containsExactly(true, false, false); + } + + @Test + @DisplayName("없는 attempt에 projection을 저장하면 조용히 넘어가지 않고 거부된다") + void savingAProjectionForAnUnknownAttemptIsRefused() { + // given + DeliveryAttemptId unknown = new DeliveryAttemptId(UUID.randomUUID()); + + // when + Throwable refused = catchThrowable(() -> save(unknown, DeliveryProjection.accepted())); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no longer exists"); + } + + private void save(DeliveryAttemptId attemptId, DeliveryProjection projection) { + inTransaction( + () -> { + projections().save(attemptId, projection); + return null; + }); + } + + private void save( + DeliveryAttemptId attemptId, EngagementFacts engagement, SuppressionFacts suppression) { + save( + attemptId, + DeliveryProjection.accepted().withEngagement(engagement).withSuppression(suppression)); + } + + private static SuppressionFacts complaint() { + return new SuppressionFacts(false, true, false, false, false); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryProviderEventLedger.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryProviderEventLedger.java new file mode 100644 index 00000000..355082c8 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/InMemoryProviderEventLedger.java @@ -0,0 +1,257 @@ +package dev.caskeleton.application.notification.platform.callback.testkit; + +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.callback.AppendEventResult; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; +import dev.caskeleton.application.notification.platform.callback.ProjectionResult; +import dev.caskeleton.application.notification.platform.callback.ProjectionStatus; +import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; +import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord; +import dev.caskeleton.application.notification.platform.callback.ProviderEventRecordId; +import dev.caskeleton.application.notification.platform.callback.ProviderRequestIdHash; +import dev.caskeleton.application.notification.platform.callback.VerifiedProviderEvent; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Predicate; + +/** + * The {@link ProviderEventLedger} fake, held to {@link ProviderEventLedgerContract} like the JPA + * ledger. + * + *

        An event is stored once per profile — by the provider's event id when it has one, by its + * fingerprint otherwise — and a repeat is reported as a duplicate. The provider request id is kept + * only as its keyed hash, and the attempt is resolved through the attempt store at append time, so + * an event that beats its attempt stays unbound until a bind finds it. A projection status only + * ever leaves {@code PENDING}. The old stubs answered every call with nothing, so a test could not + * see an event it had appended. + */ +public final class InMemoryProviderEventLedger implements ProviderEventLedger { + + private final DeliveryAttemptResolverPort attempts; + private final ProviderRequestIdHasherPort hasher; + private final Map rows = new LinkedHashMap<>(); + + /** + * A ledger that resolves attempts through {@code attempts}. + * + * @param attempts the attempt store an incoming event is bound through + * @param hasher the keyed hash the provider request id is stored as + */ + public InMemoryProviderEventLedger( + DeliveryAttemptResolverPort attempts, ProviderRequestIdHasherPort hasher) { + this.attempts = Objects.requireNonNull(attempts, "attempts"); + this.hasher = Objects.requireNonNull(hasher, "hasher"); + } + + /** + * Every stored event, in arrival order. + * + * @return the events + */ + public synchronized List rows() { + return List.copyOf(rows.values()); + } + + @Override + public synchronized AppendEventResult append(VerifiedProviderEvent event) { + return appendAll(List.of(event)); + } + + @Override + public synchronized AppendEventResult appendAll(List events) { + Objects.requireNonNull(events, "events"); + List created = new ArrayList<>(); + List duplicates = new ArrayList<>(); + for (VerifiedProviderEvent event : events) { + Optional existing = existing(event); + if (existing.isPresent()) { + duplicates.add(existing.get()); + continue; + } + ProviderEventRecord stored = stored(event); + rows.put(stored.id(), stored); + created.add(stored); + } + return new AppendEventResult(created, duplicates); + } + + @Override + public synchronized List pendingProjection(int limit) { + return oldestFirst(row -> row.projectionStatus() == ProjectionStatus.PENDING, limit); + } + + @Override + public synchronized void markApplied(ProviderEventRecordId eventId, ProjectionResult result) { + Objects.requireNonNull(result, "result"); + leavePending( + eventId, + result.changed() ? ProjectionStatus.APPLIED : ProjectionStatus.IGNORED, + Optional.empty()); + } + + @Override + public synchronized void markFailed(ProviderEventRecordId eventId, String errorCode) { + Objects.requireNonNull(errorCode, "errorCode"); + leavePending(eventId, ProjectionStatus.FAILED, Optional.of(errorCode)); + } + + @Override + public synchronized List unmatched(int limit) { + return oldestFirst( + row -> row.attemptId().isEmpty() && row.projectionStatus() == ProjectionStatus.PENDING, + limit); + } + + @Override + public synchronized List bindUnmatched( + ProviderProfileId providerProfileId, String providerRequestId, DeliveryAttemptId attemptId) { + Objects.requireNonNull(providerProfileId, "providerProfileId"); + Objects.requireNonNull(providerRequestId, "providerRequestId"); + Objects.requireNonNull(attemptId, "attemptId"); + ProviderRequestIdHash hash = + new ProviderRequestIdHash(hasher.hash(providerProfileId, providerRequestId)); + List bound = new ArrayList<>(); + for (ProviderEventRecord candidate : + oldestFirst( + row -> + row.providerProfileId().equals(providerProfileId) + && row.providerRequestIdHash().equals(Optional.of(hash)) + && row.attemptId().isEmpty(), + Integer.MAX_VALUE)) { + bound.add(bind(candidate, attemptId)); + } + return List.copyOf(bound); + } + + @Override + public synchronized boolean bindAttempt( + ProviderEventRecordId eventId, DeliveryAttemptId attemptId) { + Objects.requireNonNull(attemptId, "attemptId"); + ProviderEventRecord row = rows.get(eventId); + if (row == null || row.attemptId().isPresent()) { + return false; + } + bind(row, attemptId); + return true; + } + + @Override + public synchronized List eventsForAttempt(DeliveryAttemptId attemptId) { + Objects.requireNonNull(attemptId, "attemptId"); + return oldestFirst(row -> row.attemptId().equals(Optional.of(attemptId)), Integer.MAX_VALUE); + } + + private Optional existing(VerifiedProviderEvent event) { + Optional byEventId = + event + .event() + .providerEventId() + .flatMap( + eventId -> + rows.values().stream() + .filter(row -> row.providerProfileId().equals(event.providerProfileId())) + .filter(row -> row.event().providerEventId().equals(Optional.of(eventId))) + .findFirst()); + if (byEventId.isPresent()) { + return byEventId; + } + return rows.values().stream() + .filter(row -> row.providerProfileId().equals(event.providerProfileId())) + .filter(row -> row.eventFingerprint().equals(event.eventFingerprint())) + .findFirst(); + } + + /** The row an append writes: the attempt resolved now if it can be, the request id hashed. */ + private ProviderEventRecord stored(VerifiedProviderEvent event) { + NormalizedProviderEvent normalized = event.event(); + Optional attemptId = + event + .attemptId() + .or( + () -> + normalized + .providerRequestId() + .flatMap( + requestId -> + attempts.byProviderRequestId(event.providerProfileId(), requestId)) + .map(DeliveryAttemptSnapshot::attemptId)); + return new ProviderEventRecord( + new ProviderEventRecordId(UUID.randomUUID()), + event.providerProfileId(), + new NormalizedProviderEvent( + normalized.type(), + normalized.providerNativeType(), + normalized.providerEventId(), + // Never kept in clear; the hash below is how a stored event finds its attempt. + Optional.empty(), + normalized.providerOccurredAt(), + normalized.attributes()), + attemptId, + normalized + .providerRequestId() + .map(value -> new ProviderRequestIdHash(hasher.hash(event.providerProfileId(), value))), + event.source(), + event.signatureVerified(), + event.receivedAt(), + event.rawPayloadDigest(), + event.eventFingerprint(), + ProjectionStatus.PENDING, + Optional.empty()); + } + + private void leavePending( + ProviderEventRecordId eventId, ProjectionStatus next, Optional errorCode) { + Objects.requireNonNull(eventId, "eventId"); + ProviderEventRecord row = rows.get(eventId); + if (row == null || row.projectionStatus() != ProjectionStatus.PENDING) { + // Only out of PENDING: a resumed worker cannot move an event another worker resolved. + return; + } + rows.put(eventId, copy(row, row.attemptId(), next, errorCode)); + } + + private ProviderEventRecord bind(ProviderEventRecord row, DeliveryAttemptId attemptId) { + ProviderEventRecord bound = + copy(row, Optional.of(attemptId), row.projectionStatus(), row.projectionErrorCode()); + rows.put(row.id(), bound); + return bound; + } + + private List oldestFirst(Predicate filter, int limit) { + return rows.values().stream() + .filter(filter) + .sorted(Comparator.comparing(ProviderEventRecord::receivedAt)) + .limit(limit) + .toList(); + } + + private static ProviderEventRecord copy( + ProviderEventRecord row, + Optional attemptId, + ProjectionStatus status, + Optional errorCode) { + return new ProviderEventRecord( + row.id(), + row.providerProfileId(), + row.event(), + attemptId, + row.providerRequestIdHash(), + row.source(), + row.signatureVerified(), + row.receivedAt(), + row.rawPayloadDigest(), + row.eventFingerprint(), + status, + errorCode); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/NotificationSideEffectContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/NotificationSideEffectContract.java new file mode 100644 index 00000000..f3951e68 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/NotificationSideEffectContract.java @@ -0,0 +1,186 @@ +package dev.caskeleton.application.notification.platform.callback.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.NotificationId; +import dev.caskeleton.application.notification.platform.api.ProviderId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; +import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; +import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; +import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; +import dev.caskeleton.application.notification.platform.api.routing.Channel; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; +import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort; +import dev.caskeleton.application.notification.platform.callback.SuppressionFacts; +import dev.caskeleton.application.notification.platform.contact.ContactPointStatus; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointRecord; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; +import dev.caskeleton.application.notification.platform.dispatch.testkit.ContractClock; +import dev.caskeleton.application.notification.platform.dispatch.testkit.NotificationRows; +import dev.caskeleton.application.notification.platform.policy.SuppressionEntry; +import dev.caskeleton.application.notification.platform.policy.SuppressionReason; +import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What a projected event's side effect does to the contact point and the suppression list, run over + * the in-memory stores and the JPA stores alike (review 2026-11-01 04-14). + * + *

        A hard bounce or an invalid target makes the contact point {@code INVALID}; a complaint, an + * opt-out or a provider block makes it {@code SUPPRESSED}; either way the address's fingerprint is + * suppressed under the reason that says which. Facts that require nothing change nothing, and a + * contact point the tenant does not have is left alone. Everything is observed through the two + * store ports, so the same cases say the same thing over a fake and over PostgreSQL. + */ +public abstract class NotificationSideEffectContract { + + /** The instant every case starts at. */ + protected static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); + + private static final TenantId TENANT = new TenantId("tenant-a"); + private static final String FINGERPRINT = "a1".repeat(32); + + private final ContractClock clock = new ContractClock(NOW); + + /** + * The clock the side effect and the stores must read. + * + * @return the clock + */ + protected final ContractClock clock() { + return clock; + } + + /** + * The side effect under test, writing through {@link #contactPoints()} and {@link + * #suppressions()}. + */ + protected abstract NotificationSideEffectPort sideEffects(); + + /** The contact point store the side effect writes to, empty at the start. */ + protected abstract ContactPointStorePort contactPoints(); + + /** The suppression store the side effect writes to, empty at the start. */ + protected abstract SuppressionStorePort suppressions(); + + /** Runs {@code work} in one committed write transaction of the stores under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + @DisplayName("hard bounce는 연락처를 INVALID로 만들고 그 지문을 HARD_BOUNCE로 억제한다") + void aHardBounceInvalidatesTheContactPointAndSuppressesItsFingerprint() { + // given + ContactPointRecord contactPoint = givenAContactPoint(); + + // when + apply(contactPoint.id(), new SuppressionFacts(true, false, false, false, false)); + + // then + assertThat(List.of(statusOf(contactPoint), reasons())) + .containsExactly( + Optional.of(ContactPointStatus.INVALID), List.of(SuppressionReason.HARD_BOUNCE)); + } + + @Test + @DisplayName("complaint는 연락처를 SUPPRESSED로 만들고 사유를 COMPLAINT로 남겨 hard bounce와 구별한다") + void aComplaintSuppressesTheContactPointUnderItsOwnReason() { + // given + ContactPointRecord contactPoint = givenAContactPoint(); + + // when + apply(contactPoint.id(), new SuppressionFacts(false, true, false, false, false)); + + // then + assertThat(List.of(statusOf(contactPoint), reasons())) + .as("one reason for both would hide why an address stopped receiving") + .containsExactly( + Optional.of(ContactPointStatus.SUPPRESSED), List.of(SuppressionReason.COMPLAINT)); + } + + @Test + @DisplayName("억제할 사실이 없으면 연락처도 억제 목록도 바뀌지 않는다") + void factsThatRequireNothingChangeNothing() { + // given + ContactPointRecord contactPoint = givenAContactPoint(); + + // when + apply(contactPoint.id(), SuppressionFacts.NONE); + + // then + assertThat(List.of(statusOf(contactPoint), reasons())) + .containsExactly(Optional.of(ContactPointStatus.UNVERIFIED), List.of()); + } + + @Test + @DisplayName("그 테넌트에 없는 연락처의 hard bounce는 아무것도 바꾸지 않는다") + void aBounceForAContactPointTheTenantDoesNotHaveChangesNothing() { + // given + ContactPointRecord contactPoint = givenAContactPoint(); + + // when + apply( + new ContactPointId(UUID.randomUUID()), + new SuppressionFacts(true, false, false, false, false)); + + // then + assertThat(List.of(statusOf(contactPoint), reasons())) + .containsExactly(Optional.of(ContactPointStatus.UNVERIFIED), List.of()); + } + + private ContactPointRecord givenAContactPoint() { + ContactPointRecord contactPoint = NotificationRows.contactPoint(TENANT, FINGERPRINT, NOW); + return inTransaction(() -> contactPoints().save(contactPoint)); + } + + private void apply(ContactPointId contactPoint, SuppressionFacts facts) { + inTransaction( + () -> { + sideEffects().apply(attemptTo(contactPoint), facts); + return null; + }); + } + + private Optional statusOf(ContactPointRecord contactPoint) { + return contactPoints().find(TENANT, contactPoint.id()).map(ContactPointRecord::status); + } + + private List reasons() { + return suppressions().activeFor(TENANT, FINGERPRINT, NOW.plusSeconds(1)).stream() + .map(SuppressionEntry::reason) + .toList(); + } + + private static DeliveryAttemptSnapshot attemptTo(ContactPointId contactPoint) { + return new DeliveryAttemptSnapshot( + new DeliveryAttemptId(UUID.randomUUID()), + new RecipientDeliveryId(UUID.randomUUID()), + new NotificationId(UUID.randomUUID()), + TENANT, + 1, + Channel.EMAIL, + new ProviderId("ses"), + new ProviderProfileId("email-main"), + Optional.empty(), + contactPoint, + AttemptConfirmation.CONFIRMED, + SubmissionOutcome.CONFIRMED_ACCEPTED, + DeliveryOutcome.BOUNCED, + EvidenceLevel.NETWORK_OR_CARRIER_ACCEPTED, + 1L, + "d".repeat(64), + NOW, + Optional.of(NOW), + Optional.empty()); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/ProviderEventLedgerContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/ProviderEventLedgerContract.java new file mode 100644 index 00000000..902dd6f7 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/callback/testkit/ProviderEventLedgerContract.java @@ -0,0 +1,279 @@ +package dev.caskeleton.application.notification.platform.callback.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.notification.platform.api.NormalizedEventType; +import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.callback.AppendEventResult; +import dev.caskeleton.application.notification.platform.callback.DeliveryProjection; +import dev.caskeleton.application.notification.platform.callback.ProjectionResult; +import dev.caskeleton.application.notification.platform.callback.ProjectionStatus; +import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; +import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord; +import dev.caskeleton.application.notification.platform.callback.ProviderEventRecordId; +import dev.caskeleton.application.notification.platform.callback.ProviderEventSource; +import dev.caskeleton.application.notification.platform.callback.VerifiedProviderEvent; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptRecord; +import dev.caskeleton.application.notification.platform.dispatch.testkit.AttemptStoreFixture; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link ProviderEventLedger} promises, run against the in-memory ledger and the JPA one + * alike (review 2026-11-01 04-14). + * + *

        An event is stored exactly once per profile — by the provider's event id when there is one, by + * its fingerprint when there is not — and a repeat is an answer, not an error. The provider's + * request id is never kept in clear. An event that arrives before its attempt has recorded that id + * stays unbound until the dispatch side binds it, once; a bound event is never moved. A projection + * status only ever leaves {@code PENDING}. + */ +public abstract class ProviderEventLedgerContract extends AttemptStoreFixture { + + private static final ProviderProfileId OTHER_PROFILE = new ProviderProfileId("sms-main"); + + /** The ledger under test, resolving attempts through the store {@link #attempts()} writes to. */ + protected abstract ProviderEventLedger ledger(); + + @Test + @DisplayName("이벤트 id가 같은 이벤트가 다시 오면 저장하지 않고 중복으로 답한다") + void anEventWithAKnownEventIdIsADuplicate() { + // given + append(event(PROFILE, Optional.of("evt-1"), "first", Optional.empty(), NOW)); + + // when + AppendEventResult repeat = + append(event(PROFILE, Optional.of("evt-1"), "second", Optional.empty(), NOW)); + + // then + assertThat(List.of(repeat.created(), repeat.duplicates().size())) + .as("a provider retry must be answered, not turned into a constraint violation") + .containsExactly(false, 1); + } + + @Test + @DisplayName("이벤트 id가 없으면 지문이 같은 이벤트가 중복이고 다른 profile의 같은 이벤트는 새 이벤트다") + void withoutAnEventIdTheFingerprintDecidesWithinAProfile() { + // given + append(event(PROFILE, Optional.empty(), "same", Optional.empty(), NOW)); + + // when + List created = + List.of( + append(event(PROFILE, Optional.empty(), "same", Optional.empty(), NOW)).created(), + append(event(OTHER_PROFILE, Optional.empty(), "same", Optional.empty(), NOW)) + .created()); + + // then + assertThat(created).containsExactly(false, true); + } + + @Test + @DisplayName("요청 id를 기록한 attempt의 이벤트는 저장 때 그 attempt에 묶이고 요청 id는 해시로만 남는다") + void anEventForAKnownRequestIdIsBoundOnAppendAndKeepsOnlyTheHash() { + // given + DeliveryAttemptRecord attempt = givenAnAcceptedAttempt(givenAJob(), "ses-message-1"); + + // when + ProviderEventRecord stored = + append(event(PROFILE, Optional.of("evt-1"), "d", Optional.of("ses-message-1"), NOW)) + .newEvents() + .getFirst(); + + // then + assertThat( + List.of( + stored.attemptId(), + stored.event().providerRequestId(), + stored.providerRequestIdHash().isPresent(), + stored.projectionStatus())) + .containsExactly( + Optional.of(attempt.id()), Optional.empty(), true, ProjectionStatus.PENDING); + } + + @Test + @DisplayName("attempt보다 먼저 온 이벤트는 미매칭으로 남았다가 bindUnmatched로 한 번만 묶인다") + void anEarlyEventStaysUnmatchedUntilBoundOnce() { + // given + ProviderEventRecord early = + append(event(PROFILE, Optional.of("evt-1"), "d", Optional.of("ses-early"), NOW)) + .newEvents() + .getFirst(); + List unmatched = ledger().unmatched(10); + DeliveryAttemptRecord attempt = givenAnAcceptedAttempt(givenAJob(), "ses-early"); + + // when + List bound = + List.of( + inTransaction(() -> ledger().bindUnmatched(PROFILE, "ses-early", attempt.id())).size(), + inTransaction(() -> ledger().bindUnmatched(PROFILE, "ses-early", attempt.id())).size()); + + // then + assertThat( + List.of( + unmatched.stream().map(ProviderEventRecord::id).toList(), + bound, + ledger().eventsForAttempt(attempt.id()).stream() + .map(ProviderEventRecord::id) + .toList(), + ledger().unmatched(10))) + .as("two matchers racing must resolve to one winner, and only the winner projects") + .containsExactly(List.of(early.id()), List.of(1, 0), List.of(early.id()), List.of()); + } + + @Test + @DisplayName("다른 profile의 같은 요청 id 이벤트는 묶이지 않는다") + void anEventOfAnotherProfileWithTheSameRequestIdIsNotBound() { + // given + append(event(OTHER_PROFILE, Optional.of("evt-1"), "d", Optional.of("ses-early"), NOW)); + DeliveryAttemptRecord attempt = givenAnAcceptedAttempt(givenAJob(), "ses-early"); + + // when + List bound = + inTransaction(() -> ledger().bindUnmatched(PROFILE, "ses-early", attempt.id())); + + // then + assertThat(bound) + .as("providers can mint the same request id; binding across profiles crosses tenants") + .isEmpty(); + } + + @Test + @DisplayName("이미 묶인 이벤트는 다른 attempt로 옮겨지지 않고 묶이지 않은 이벤트만 묶인다") + void aBoundEventIsNeverMovedAndAnUnboundOneIsBound() { + // given + DeliveryAttemptRecord owner = givenAnAcceptedAttempt(givenAJob(), "ses-message-1"); + DeliveryAttemptRecord other = givenADispatchingAttempt(givenAJob(), 1); + ProviderEventRecord bound = + append(event(PROFILE, Optional.of("evt-1"), "a", Optional.of("ses-message-1"), NOW)) + .newEvents() + .getFirst(); + ProviderEventRecord unbound = + append(event(PROFILE, Optional.of("evt-2"), "b", Optional.empty(), NOW)) + .newEvents() + .getFirst(); + + // when + List binds = + List.of( + inTransaction(() -> ledger().bindAttempt(bound.id(), other.id())), + inTransaction(() -> ledger().bindAttempt(unbound.id(), other.id()))); + + // then + assertThat( + List.of( + binds, + ledger().eventsForAttempt(owner.id()).stream() + .map(ProviderEventRecord::id) + .toList(), + ledger().eventsForAttempt(other.id()).stream() + .map(ProviderEventRecord::id) + .toList())) + .as("a sweep must not move an event from the attempt that already owns it") + .containsExactly(List.of(false, true), List.of(bound.id()), List.of(unbound.id())); + } + + @Test + @DisplayName("투영 상태는 PENDING에서만 떠나고 실패는 이벤트를 지우지 않고 사유를 남긴다") + void aProjectionStatusOnlyLeavesPending() { + // given + DeliveryAttemptRecord attempt = givenAnAcceptedAttempt(givenAJob(), "ses-message-1"); + ProviderEventRecordId applied = appendFor("evt-1", "a"); + ProviderEventRecordId failed = appendFor("evt-2", "b"); + ProjectionResult changed = ProjectionResult.applied(DeliveryProjection.accepted(), "accepted"); + + // when + inTransaction( + () -> { + ledger().markApplied(applied, changed); + ledger().markFailed(applied, "LATE_FAILURE"); + ledger().markFailed(failed, "NO_PROJECTOR"); + ledger().markApplied(failed, changed); + return null; + }); + + // then + assertThat( + ledger().eventsForAttempt(attempt.id()).stream() + .map(row -> List.of(row.projectionStatus(), row.projectionErrorCode())) + .toList()) + .as("a resumed worker must not move an event another worker has already resolved") + .containsExactlyInAnyOrder( + List.of(ProjectionStatus.APPLIED, Optional.empty()), + List.of(ProjectionStatus.FAILED, Optional.of("NO_PROJECTOR"))); + } + + @Test + @DisplayName("투영 대기 이벤트는 받은 순서대로 limit만큼 나온다") + void pendingEventsComeOldestFirstUpToTheLimit() { + // given + append(event(PROFILE, Optional.of("evt-3"), "c", Optional.empty(), NOW.plusSeconds(3))); + append(event(PROFILE, Optional.of("evt-1"), "a", Optional.empty(), NOW.plusSeconds(1))); + append(event(PROFILE, Optional.of("evt-2"), "b", Optional.empty(), NOW.plusSeconds(2))); + + // when + List pending = ledger().pendingProjection(2); + + // then + assertThat(pending) + .extracting(row -> row.event().providerEventId()) + .containsExactly(Optional.of("evt-1"), Optional.of("evt-2")); + } + + private AppendEventResult append(VerifiedProviderEvent event) { + return inTransaction(() -> ledger().append(event)); + } + + private ProviderEventRecordId appendFor(String eventId, String payload) { + return append(event(PROFILE, Optional.of(eventId), payload, Optional.of("ses-message-1"), NOW)) + .newEvents() + .getFirst() + .id(); + } + + /** A verified delivery callback; {@code payload} decides the fingerprint. */ + private static VerifiedProviderEvent event( + ProviderProfileId profile, + Optional eventId, + String payload, + Optional providerRequestId, + Instant receivedAt) { + Instant at = receivedAt.truncatedTo(ChronoUnit.MICROS); + return new VerifiedProviderEvent( + profile, + new NormalizedProviderEvent( + NormalizedEventType.DELIVERY_CONFIRMED, + "delivered", + eventId, + providerRequestId, + Optional.of(at), + Map.of()), + Optional.empty(), + ProviderEventSource.CALLBACK, + true, + at, + payload.getBytes(StandardCharsets.UTF_8), + sha256(payload + "/raw"), + sha256(payload)); + } + + private static String sha256(String text) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("every JVM provides SHA-256", impossible); + } + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/AttemptStoreFixture.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/AttemptStoreFixture.java new file mode 100644 index 00000000..45588449 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/AttemptStoreFixture.java @@ -0,0 +1,126 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptRecord; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; + +/** + * What the attempt-table contracts share: the stores an attempt is written through, and the rows an + * attempt needs before it can exist. + * + *

        An attempt belongs to a recipient job, which belongs to a request, and names a contact point; + * the database refuses an attempt whose parents are missing, and a snapshot joins the job. So every + * case seeds them the way the platform does — the request and its job through the request store, + * the attempt through the attempt store — and only the contact point, whose store has its own + * contract, is left to the implementation. + */ +public abstract class AttemptStoreFixture { + + /** The instant every case starts at. */ + protected static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); + + /** The tenant every seeded row belongs to. */ + protected static final TenantId TENANT = new TenantId("tenant-a"); + + /** The profile every seeded attempt runs under. */ + protected static final ProviderProfileId PROFILE = new ProviderProfileId("email-main"); + + private final ContractClock clock = new ContractClock(NOW); + + /** + * The clock the stores under test must read; the contract moves it. + * + * @return the clock + */ + protected final ContractClock clock() { + return clock; + } + + /** The request store the jobs are inserted through. */ + protected abstract NotificationRequestStorePort requests(); + + /** The attempt store the attempts are written through, over an empty table. */ + protected abstract DeliveryAttemptStorePort attempts(); + + /** + * The keyed hash the attempt store was built with, for the cases that look up by hash. + * + * @return the hasher + */ + protected abstract ProviderRequestIdHasherPort hasher(); + + /** + * A contact point of {@code tenant} that an attempt may name. + * + * @param tenant the tenant + * @return its id + */ + protected abstract ContactPointId givenAContactPoint(TenantId tenant); + + /** Runs {@code work} in one committed write transaction of the stores under test. */ + protected abstract T inTransaction(Supplier work); + + /** + * A dispatching job of a fresh request. + * + * @return the job as inserted + */ + protected final RecipientDeliveryRecord givenAJob() { + NotificationRequestRecord request = + NotificationRows.request(TENANT, "idem-" + UUID.randomUUID(), NOW); + RecipientDeliveryRecord job = + NotificationRows.job( + request, RecipientDeliveryState.DISPATCHING, Optional.of(NOW), Optional.empty(), NOW); + inTransaction(() -> requests().insert(request, List.of(job))); + return job; + } + + /** + * The attempt row the dispatcher commits before it calls the provider. + * + * @param job the job it belongs to + * @param attemptNo its number within the job + * @return the attempt as inserted + */ + protected final DeliveryAttemptRecord givenADispatchingAttempt( + RecipientDeliveryRecord job, int attemptNo) { + DeliveryAttemptRecord attempt = + NotificationRows.dispatchingAttempt( + job.id(), givenAContactPoint(job.tenantId()), attemptNo, PROFILE, NOW); + inTransaction(() -> attempts().insertDispatching(attempt)); + return attempt; + } + + /** + * A dispatching attempt the provider accepted under {@code providerRequestId}. + * + * @param job the job it belongs to + * @param providerRequestId the provider's own id for the message + * @return the attempt as completed, before the store dropped the clear identifier + */ + protected final DeliveryAttemptRecord givenAnAcceptedAttempt( + RecipientDeliveryRecord job, String providerRequestId) { + DeliveryAttemptRecord completed = + givenADispatchingAttempt(job, 1) + .completed( + ProviderSubmissionResult.accepted( + providerRequestId, "Accepted", Duration.ofMillis(120)), + NOW.plusSeconds(1)); + inTransaction(() -> attempts().recordOutcome(completed)); + return completed; + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ContactPointStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ContactPointStoreContract.java new file mode 100644 index 00000000..da62424e --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ContactPointStoreContract.java @@ -0,0 +1,189 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.contact.ContactPointStatus; +import dev.caskeleton.application.notification.platform.contact.ContactPointType; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointRecord; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; +import dev.caskeleton.application.notification.platform.security.ProtectedContactPoint; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link ContactPointStorePort} promises, run against the in-memory fake and the JPA + * store alike (review 2026-11-01 04-14). + * + *

        The store never holds an address it can read, so a value lookup is by the keyed fingerprint + * the caller computed, and every lookup is inside one tenant. Saving a contact point that exists + * re-protects it — new ciphertext, key and fingerprint — and leaves its lifecycle alone: a key + * rotation must not reactivate an address the provider reported dead. + */ +public abstract class ContactPointStoreContract { + + /** The instant every case starts at. */ + protected static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); + + private static final TenantId TENANT = new TenantId("tenant-a"); + private static final TenantId OTHER_TENANT = new TenantId("tenant-b"); + private static final String FINGERPRINT = "a1".repeat(32); + private static final String ROTATED_FINGERPRINT = "b2".repeat(32); + + private final ContractClock clock = new ContractClock(NOW); + + /** + * The clock the store under test must read. + * + * @return the clock + */ + protected final ContractClock clock() { + return clock; + } + + /** The store under test, empty at the start of each test. */ + protected abstract ContactPointStorePort store(); + + /** Runs {@code work} in one committed write transaction of the store under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + @DisplayName("등록한 연락처는 그 테넌트 안에서 id와 지문으로 찾히고 다른 테넌트에서는 찾히지 않는다") + void aContactPointIsFoundByIdAndFingerprintOnlyInsideItsTenant() { + // given + ContactPointRecord saved = save(NotificationRows.contactPoint(TENANT, FINGERPRINT, NOW)); + + // when + List> found = + List.of( + store().find(TENANT, saved.id()).map(ContactPointRecord::id), + store().findByFingerprint(TENANT, FINGERPRINT).map(ContactPointRecord::id), + store().find(OTHER_TENANT, saved.id()).map(ContactPointRecord::id), + store().findByFingerprint(OTHER_TENANT, FINGERPRINT).map(ContactPointRecord::id)); + + // then + assertThat(found) + .containsExactly( + Optional.of(saved.id()), Optional.of(saved.id()), Optional.empty(), Optional.empty()); + } + + @Test + @DisplayName("이미 있는 연락처를 다시 저장하면 보호 값만 바뀌고 상태는 그대로다") + void savingAnExistingContactPointReprotectsItAndKeepsItsLifecycle() { + // given + ContactPointRecord original = save(NotificationRows.contactPoint(TENANT, FINGERPRINT, NOW)); + inTransaction( + () -> + store().updateStatus(TENANT, original.id(), ContactPointStatus.INVALID, "HARD_BOUNCE")); + ContactPointRecord rotated = rotated(original); + + // when + save(rotated); + + // then + ContactPointRecord stored = store().find(TENANT, original.id()).orElseThrow(); + assertThat( + List.of( + stored.protectedValue().keyId(), + stored.protectedValue().lookupHmac(), + stored.status(), + store().findByFingerprint(TENANT, FINGERPRINT).isPresent())) + .as("a re-registration must not bring back an address the provider reported dead") + .containsExactly("key-2", ROTATED_FINGERPRINT, ContactPointStatus.INVALID, false); + } + + @Test + @DisplayName("상태를 바꾸면 사유와 무효화 시각이 남고 ACTIVE로 돌리면 무효화 시각이 지워진다") + void aStatusChangeRecordsWhyAndWhenAndReactivationClearsTheWhen() { + // given + ContactPointRecord saved = save(NotificationRows.contactPoint(TENANT, FINGERPRINT, NOW)); + clock.moveTo(NOW.plusSeconds(60)); + ContactPointRecord invalidated = + inTransaction( + () -> + store() + .updateStatus(TENANT, saved.id(), ContactPointStatus.INVALID, "HARD_BOUNCE")); + + // when + ContactPointRecord reactivated = + inTransaction( + () -> store().updateStatus(TENANT, saved.id(), ContactPointStatus.ACTIVE, "VERIFIED")); + + // then + assertThat( + List.of( + invalidated.invalidatedAt(), + invalidated.invalidationReason(), + reactivated.invalidatedAt(), + store().find(TENANT, saved.id()).map(ContactPointRecord::status))) + .containsExactly( + Optional.of(NOW.plusSeconds(60)), + Optional.of("HARD_BOUNCE"), + Optional.empty(), + Optional.of(ContactPointStatus.ACTIVE)); + } + + @Test + @DisplayName("다른 테넌트의 연락처 상태는 바꾸지 못하고 거부된다") + void anotherTenantsContactPointStatusCannotBeChanged() { + // given + ContactPointRecord saved = save(NotificationRows.contactPoint(TENANT, FINGERPRINT, NOW)); + + // when + Throwable refused = + catchThrowable( + () -> + inTransaction( + () -> + store() + .updateStatus( + OTHER_TENANT, + saved.id(), + ContactPointStatus.INVALID, + "HARD_BOUNCE"))); + + // then + assertThat(List.of(refused instanceof IllegalStateException, statusOf(saved))) + .containsExactly(true, Optional.of(ContactPointStatus.UNVERIFIED)); + } + + private ContactPointRecord save(ContactPointRecord record) { + return inTransaction(() -> store().save(record)); + } + + private Optional statusOf(ContactPointRecord record) { + return store().find(TENANT, record.id()).map(ContactPointRecord::status); + } + + /** The same contact point after a key rotation, as a re-registration would submit it. */ + private static ContactPointRecord rotated(ContactPointRecord original) { + return new ContactPointRecord( + original.id(), + original.tenantId(), + original.ownerRef(), + original.type(), + original.provider(), + original.applicationId(), + original.environment(), + new ProtectedContactPoint( + ContactPointType.EMAIL, + "key-2", + new byte[] {7, 8, 9}, + new byte[] {9, 8, 7}, + ROTATED_FINGERPRINT), + ContactPointStatus.UNVERIFIED, + false, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + original.createdAt(), + original.updatedAt()); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ContractClock.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ContractClock.java new file mode 100644 index 00000000..d43970dc --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ContractClock.java @@ -0,0 +1,51 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; + +/** + * A UTC clock only a contract moves. + * + *

        The notification store contracts hand it to the store under test — the in-memory fake and the + * JPA store alike — and move it to make a lease run out or a window close, so "later" means the + * same thing to both. + */ +public final class ContractClock extends Clock { + + private volatile Instant now; + + /** + * A clock standing at {@code now}. + * + * @param now where it starts + */ + public ContractClock(Instant now) { + this.now = now; + } + + /** + * Moves the clock. + * + * @param instant where it stands from now on + */ + public void moveTo(Instant instant) { + this.now = instant; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + throw new UnsupportedOperationException("the contract clock is UTC only"); + } + + @Override + public Instant instant() { + return now; + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/DeliveryAttemptStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/DeliveryAttemptStoreContract.java new file mode 100644 index 00000000..26ca4d5e --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/DeliveryAttemptStoreContract.java @@ -0,0 +1,187 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; +import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; +import dev.caskeleton.application.notification.platform.api.error.FailureCategory; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptRecord; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence; +import dev.caskeleton.application.notification.platform.provider.ProviderFailure; +import dev.caskeleton.application.notification.platform.provider.ProviderSubmissionResult; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link DeliveryAttemptStorePort} promises, run against the in-memory fake and the JPA + * store alike (review 2026-11-01 04-14). + * + *

        An attempt row is the platform's only record of whether a provider may have the message, so + * the evidence has to come back with its certainty: "proven not started" and "unknown whether + * started" decide between a safe retry and a duplicate. Attempts are numbered per job, the + * provider's request id never comes back in clear, and the snapshot is the attempt joined to its + * job. + */ +public abstract class DeliveryAttemptStoreContract extends AttemptStoreFixture { + + @Test + @DisplayName("넣은 attempt는 id로 다시 읽히고 아직 끝나지 않은 상태 그대로다") + void anInsertedAttemptReadsBackUnfinished() { + // given + RecipientDeliveryRecord job = givenAJob(); + DeliveryAttemptRecord attempt = givenADispatchingAttempt(job, 1); + + // when + DeliveryAttemptRecord stored = attempts().find(attempt.id()).orElseThrow(); + + // then + assertThat( + List.of( + stored.attemptNo(), + stored.executionEvidence(), + stored.confirmation(), + stored.completedAt(), + stored.renderedContentDigest())) + .containsExactly( + 1, + ProviderExecutionEvidence.undetermined(), + AttemptConfirmation.AMBIGUOUS, + Optional.empty(), + attempt.renderedContentDigest()); + } + + @Test + @DisplayName("attempt 번호는 작업마다 1부터 이어지고 목록은 그 작업의 것만 번호순이다") + void attemptsAreNumberedPerJobAndListedInOrder() { + // given + RecipientDeliveryRecord job = givenAJob(); + RecipientDeliveryRecord other = givenAJob(); + int first = attempts().nextAttemptNo(job.id()); + givenADispatchingAttempt(job, 2); + givenADispatchingAttempt(job, 1); + givenADispatchingAttempt(other, 1); + + // when + List numbers = + attempts().attemptsOf(job.id()).stream().map(DeliveryAttemptRecord::attemptNo).toList(); + + // then + assertThat(List.of(first, numbers, attempts().nextAttemptNo(job.id()))) + .containsExactly(1, List.of(1, 2), 3); + } + + @Test + @DisplayName("결과를 기록하면 증거가 값과 확실성째 저장된다") + void aRecordedOutcomeKeepsTheEvidenceWithItsCertainty() { + // given + RecipientDeliveryRecord job = givenAJob(); + DeliveryAttemptRecord lost = + givenADispatchingAttempt(job, 1) + .completed( + ProviderSubmissionResult.ambiguous( + ProviderFailure.of( + "PROVIDER_RESPONSE_LOST", FailureCategory.AMBIGUOUS_SUBMISSION, false), + ProviderExecutionEvidence.responseLost(), + Duration.ofMillis(1500)), + NOW.plusSeconds(2)); + DeliveryAttemptRecord neverStarted = + givenADispatchingAttempt(job, 2).closedBeforeSubmission("PROFILE_GONE", NOW.plusSeconds(3)); + + // when + inTransaction( + () -> List.of(attempts().recordOutcome(lost), attempts().recordOutcome(neverStarted))); + + // then + DeliveryAttemptRecord storedLost = attempts().find(lost.id()).orElseThrow(); + DeliveryAttemptRecord storedNeverStarted = attempts().find(neverStarted.id()).orElseThrow(); + assertThat( + List.of( + storedLost.executionEvidence(), + storedLost.submissionOutcome(), + storedLost.failureCategory(), + storedLost.completedAt(), + storedLost.elapsed(), + storedNeverStarted.executionEvidence())) + .as("a restart must still tell 'proven not sent' from 'unknown whether sent'") + .containsExactly( + ProviderExecutionEvidence.responseLost(), + SubmissionOutcome.AMBIGUOUS, + Optional.of(FailureCategory.AMBIGUOUS_SUBMISSION), + Optional.of(NOW.plusSeconds(2)), + Optional.of(Duration.ofMillis(1500)), + ProviderExecutionEvidence.notStarted()); + } + + @Test + @DisplayName("provider 요청 id는 평문으로 저장되지 않아 attempt와 snapshot 어디에도 돌아오지 않는다") + void theProviderRequestIdNeverComesBackInClear() { + // given + RecipientDeliveryRecord job = givenAJob(); + DeliveryAttemptRecord accepted = givenAnAcceptedAttempt(job, "ses-message-1"); + + // when + List> exposed = + List.of( + attempts().find(accepted.id()).orElseThrow().providerRequestId(), + attempts().snapshot(accepted.id()).orElseThrow().providerRequestId()); + + // then + assertThat(exposed) + .as("a readable request id turns the attempt table into an index of every message sent") + .containsExactly(Optional.empty(), Optional.empty()); + } + + @Test + @DisplayName("snapshot은 attempt에 그 작업의 알림과 테넌트를 붙여 보여주고 없는 id는 비어 있다") + void aSnapshotJoinsTheAttemptToItsJob() { + // given + RecipientDeliveryRecord job = givenAJob(); + DeliveryAttemptRecord attempt = givenADispatchingAttempt(job, 1); + + // when + Optional snapshot = attempts().snapshot(attempt.id()); + + // then + assertThat( + List.of( + snapshot.map(DeliveryAttemptSnapshot::notificationId), + snapshot.map(DeliveryAttemptSnapshot::tenantId), + snapshot.map(DeliveryAttemptSnapshot::providerProfileId), + snapshot.map(DeliveryAttemptSnapshot::contactPointId), + attempts().snapshot(new DeliveryAttemptId(UUID.randomUUID())))) + .containsExactly( + Optional.of(job.notificationId()), + Optional.of(job.tenantId()), + Optional.of(PROFILE), + Optional.of(attempt.contactPointId()), + Optional.empty()); + } + + @Test + @DisplayName("없는 attempt의 결과 기록은 조용히 넘어가지 않고 거부된다") + void recordingTheOutcomeOfAnUnknownAttemptIsRefused() { + // given + RecipientDeliveryRecord job = givenAJob(); + DeliveryAttemptRecord neverInserted = + NotificationRows.dispatchingAttempt(job.id(), givenAContactPoint(TENANT), 1, PROFILE, NOW) + .closedBeforeSubmission("PROFILE_GONE", NOW.plusSeconds(1)); + + // when + Throwable refused = + catchThrowable(() -> inTransaction(() -> attempts().recordOutcome(neverInserted))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no longer exists"); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryContactPointStore.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryContactPointStore.java new file mode 100644 index 00000000..6f6169d9 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryContactPointStore.java @@ -0,0 +1,128 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.contact.ContactPointStatus; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointRecord; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; +import dev.caskeleton.application.notification.platform.security.ProtectedContactPoint; +import java.time.Clock; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** + * The {@link ContactPointStorePort} fake, held to {@link ContactPointStoreContract} like the JPA + * store. + * + *

        Every lookup is inside a tenant, and the value lookup is by the keyed fingerprint the caller + * computed — the store never sees an address, so it cannot compute one and must not try. Saving a + * contact point that already exists re-protects it (new ciphertext, nonce, key and fingerprint) and + * leaves its lifecycle alone, as a key rotation does; the old fakes replaced the whole record, so a + * re-registration could silently reactivate an address the provider had reported dead. + */ +public final class InMemoryContactPointStore implements ContactPointStorePort { + + private final Map rows = new LinkedHashMap<>(); + private final Clock clock; + + /** + * An empty store. + * + * @param clock what "now" is for a status change and a re-protection + */ + public InMemoryContactPointStore(Clock clock) { + this.clock = Objects.requireNonNull(clock, "clock"); + } + + /** + * Every stored contact point, in registration order. + * + * @return the contact points + */ + public synchronized List rows() { + return List.copyOf(rows.values()); + } + + @Override + public synchronized Optional find(TenantId tenantId, ContactPointId id) { + return Optional.ofNullable(rows.get(id)).filter(row -> row.tenantId().equals(tenantId)); + } + + @Override + public synchronized Optional findByFingerprint( + TenantId tenantId, String lookupHmac) { + return rows.values().stream() + .filter(row -> row.tenantId().equals(tenantId)) + .filter(row -> row.protectedValue().lookupHmac().equals(lookupHmac)) + .findFirst(); + } + + @Override + public synchronized ContactPointRecord save(ContactPointRecord record) { + Objects.requireNonNull(record, "record"); + Optional existing = find(record.tenantId(), record.id()); + ContactPointRecord stored = + existing + .map(row -> reprotected(row, record.protectedValue(), clock.instant())) + .orElse(record); + rows.put(stored.id(), stored); + return stored; + } + + @Override + public synchronized ContactPointRecord updateStatus( + TenantId tenantId, ContactPointId id, ContactPointStatus status, String reasonCode) { + Objects.requireNonNull(status, "status"); + Objects.requireNonNull(reasonCode, "reasonCode"); + ContactPointRecord row = + find(tenantId, id) + .orElseThrow(() -> new IllegalStateException("contact point no longer exists")); + Instant now = clock.instant(); + ContactPointRecord changed = + new ContactPointRecord( + row.id(), + row.tenantId(), + row.ownerRef(), + row.type(), + row.provider(), + row.applicationId(), + row.environment(), + row.protectedValue(), + status, + row.verified(), + row.lastConfirmedAt(), + row.lastSuccessfulDeliveryAt(), + status == ContactPointStatus.ACTIVE ? Optional.empty() : Optional.of(now), + Optional.of(reasonCode), + row.createdAt(), + now); + rows.put(id, changed); + return changed; + } + + private static ContactPointRecord reprotected( + ContactPointRecord row, ProtectedContactPoint value, Instant now) { + return new ContactPointRecord( + row.id(), + row.tenantId(), + row.ownerRef(), + row.type(), + row.provider(), + row.applicationId(), + row.environment(), + new ProtectedContactPoint( + row.type(), value.keyId(), value.nonce(), value.ciphertext(), value.lookupHmac()), + row.status(), + row.verified(), + row.lastConfirmedAt(), + row.lastSuccessfulDeliveryAt(), + row.invalidatedAt(), + row.invalidationReason(), + row.createdAt(), + now); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryDeliveryAttemptStore.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryDeliveryAttemptStore.java new file mode 100644 index 00000000..ae257085 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryDeliveryAttemptStore.java @@ -0,0 +1,393 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; +import dev.caskeleton.application.notification.platform.callback.DeliveryProjection; +import dev.caskeleton.application.notification.platform.callback.DeliveryProjectionStorePort; +import dev.caskeleton.application.notification.platform.callback.EngagementFacts; +import dev.caskeleton.application.notification.platform.callback.ProviderRequestIdHash; +import dev.caskeleton.application.notification.platform.callback.SuppressionFacts; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptRecord; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import java.time.Clock; +import java.time.Instant; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + +/** + * The fake of the attempt store and the two read models built on it, held to {@link + * DeliveryAttemptStoreContract}, {@code DeliveryAttemptResolverContract} and {@code + * DeliveryProjectionStoreContract} like {@code JpaDeliveryAttemptStore}, which implements the same + * three ports over one table. + * + *

        What the row keeps is what the fake keeps. The provider request id is stored as its keyed hash + * and never comes back in clear; a snapshot joins the attempt to its recipient job — the request + * store's row — and is empty without one; observed facts only accumulate; the suppression side + * effect is claimed once. The old fake held snapshots in a map a test filled by hand, so a snapshot + * could exist for an attempt that did not. + */ +public final class InMemoryDeliveryAttemptStore + implements DeliveryAttemptStorePort, DeliveryAttemptResolverPort, DeliveryProjectionStorePort { + + private final InMemoryNotificationRequestStore requests; + private final ProviderRequestIdHasherPort hasher; + private final Clock clock; + + /** Stored attempts, in insertion order, as their rows read back. */ + private final Map rows = new LinkedHashMap<>(); + + private final Map requestIdHashes = new LinkedHashMap<>(); + private final Map engagement = new LinkedHashMap<>(); + private final Map suppression = new LinkedHashMap<>(); + private final Set sideEffectsClaimed = new HashSet<>(); + + /** + * A store whose snapshots join the request store's recipient rows. + * + * @param requests the store holding the recipient jobs the attempts belong to + * @param hasher the keyed hash the provider request id is stored as + * @param clock what "now" is for a completion without a time and for the roll-up + */ + public InMemoryDeliveryAttemptStore( + InMemoryNotificationRequestStore requests, ProviderRequestIdHasherPort hasher, Clock clock) { + this.requests = Objects.requireNonNull(requests, "requests"); + this.hasher = Objects.requireNonNull(hasher, "hasher"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + /** + * A store over the test hasher and the system clock, for a use-case test that asserts on neither. + * + * @param requests the store holding the recipient jobs the attempts belong to + */ + public InMemoryDeliveryAttemptStore(InMemoryNotificationRequestStore requests) { + this(requests, new Sha256ProviderRequestIdHasher(), Clock.systemUTC()); + } + + /** + * Every stored attempt, oldest first, as the rows read back. + * + * @return the attempts + */ + public synchronized List rows() { + return List.copyOf(rows.values()); + } + + // ---- DeliveryAttemptStorePort ----------------------------------------------------------------- + + @Override + public synchronized DeliveryAttemptRecord insertDispatching(DeliveryAttemptRecord attempt) { + Objects.requireNonNull(attempt, "attempt"); + rows.put(attempt.id(), withoutRequestId(attempt)); + hashOf(attempt) + .ifPresentOrElse( + hash -> requestIdHashes.put(attempt.id(), hash), + () -> requestIdHashes.remove(attempt.id())); + return rows.get(attempt.id()); + } + + @Override + public synchronized DeliveryAttemptRecord recordOutcome(DeliveryAttemptRecord attempt) { + Objects.requireNonNull(attempt, "attempt"); + DeliveryAttemptRecord stored = existing(attempt.id()); + DeliveryAttemptRecord completed = + new DeliveryAttemptRecord( + stored.id(), + stored.recipientDeliveryId(), + stored.contactPointId(), + stored.attemptNo(), + stored.channel(), + stored.providerId(), + stored.providerProfileId(), + Optional.empty(), + attempt.executionEvidence(), + attempt.submissionOutcome(), + attempt.deliveryOutcome(), + attempt.confirmation(), + attempt.evidenceLevel(), + attempt.failureCategory(), + attempt.failureCode(), + attempt.nativeStatus(), + attempt.providerOccurredAt(), + stored.startedAt(), + Optional.of(attempt.completedAt().orElse(clock.instant())), + attempt.elapsed().map(elapsed -> java.time.Duration.ofMillis(elapsed.toMillis())), + stored.credentialGeneration(), + stored.renderedContentDigest()); + rows.put(stored.id(), completed); + // The completion writes the hash column whether or not it has a value, as the row does. + hashOf(attempt) + .ifPresentOrElse( + hash -> requestIdHashes.put(stored.id(), hash), + () -> requestIdHashes.remove(stored.id())); + return completed; + } + + @Override + public synchronized Optional find(DeliveryAttemptId id) { + return Optional.ofNullable(rows.get(id)); + } + + @Override + public synchronized List attemptsOf( + RecipientDeliveryId recipientDeliveryId) { + return rows.values().stream() + .filter(row -> row.recipientDeliveryId().equals(recipientDeliveryId)) + .sorted(Comparator.comparingInt(DeliveryAttemptRecord::attemptNo)) + .toList(); + } + + @Override + public synchronized Optional snapshot(DeliveryAttemptId id) { + return find(id).flatMap(this::toSnapshot); + } + + @Override + public synchronized int nextAttemptNo(RecipientDeliveryId recipientDeliveryId) { + return attemptsOf(recipientDeliveryId).stream() + .mapToInt(DeliveryAttemptRecord::attemptNo) + .max() + .orElse(0) + + 1; + } + + // ---- DeliveryAttemptResolverPort -------------------------------------------------------------- + + @Override + public synchronized Optional byAttemptId(DeliveryAttemptId attemptId) { + return snapshot(attemptId); + } + + @Override + public synchronized Optional byProviderRequestId( + ProviderProfileId profileId, String providerRequestId) { + Objects.requireNonNull(profileId, "profileId"); + Objects.requireNonNull(providerRequestId, "providerRequestId"); + return byHash(profileId, hasher.hash(profileId, providerRequestId)); + } + + @Override + public synchronized Optional byProviderRequestIdHash( + ProviderProfileId profileId, ProviderRequestIdHash providerRequestIdHash) { + Objects.requireNonNull(profileId, "profileId"); + Objects.requireNonNull(providerRequestIdHash, "providerRequestIdHash"); + return byHash(profileId, providerRequestIdHash.value()); + } + + // ---- DeliveryProjectionStorePort -------------------------------------------------------------- + + @Override + public synchronized DeliveryProjection load(DeliveryAttemptId attemptId) { + return find(attemptId) + .map( + row -> + new DeliveryProjection( + row.submissionOutcome(), + row.deliveryOutcome(), + row.evidenceLevel(), + engagement.getOrDefault(attemptId, EngagementFacts.NONE), + suppression.getOrDefault(attemptId, SuppressionFacts.NONE))) + .orElseGet(DeliveryProjection::empty); + } + + /** + * Writes the delivery outcome, the evidence and the facts, and rolls them up onto the job. + * + *

        The attempt's submission outcome is not a projection column, so a projection does not change + * it; the job's is rolled up. A fact once written stays written, and the last engagement time + * only moves forward — a later event that does not mention an open does not withdraw it. + */ + @Override + public synchronized void save(DeliveryAttemptId attemptId, DeliveryProjection projection) { + Objects.requireNonNull(attemptId, "attemptId"); + Objects.requireNonNull(projection, "projection"); + DeliveryAttemptRecord stored = existing(attemptId); + rows.put( + attemptId, + new DeliveryAttemptRecord( + stored.id(), + stored.recipientDeliveryId(), + stored.contactPointId(), + stored.attemptNo(), + stored.channel(), + stored.providerId(), + stored.providerProfileId(), + stored.providerRequestId(), + stored.executionEvidence(), + stored.submissionOutcome(), + projection.deliveryOutcome(), + stored.confirmation(), + projection.evidenceLevel(), + stored.failureCategory(), + stored.failureCode(), + stored.nativeStatus(), + stored.providerOccurredAt(), + stored.startedAt(), + stored.completedAt(), + stored.elapsed(), + stored.credentialGeneration(), + stored.renderedContentDigest())); + engagement.put( + attemptId, + accumulated( + engagement.getOrDefault(attemptId, EngagementFacts.NONE), + projection.engagementFacts())); + suppression.put( + attemptId, + accumulated( + suppression.getOrDefault(attemptId, SuppressionFacts.NONE), + projection.suppressionFacts())); + requests.recipients.values().stream() + .flatMap(List::stream) + .filter(job -> job.id().equals(stored.recipientDeliveryId())) + .findFirst() + .ifPresent(job -> requests.replace(rolledUp(job, projection, clock.instant()))); + } + + @Override + public synchronized boolean claimSuppressionSideEffect(DeliveryAttemptId attemptId) { + Objects.requireNonNull(attemptId, "attemptId"); + return rows.containsKey(attemptId) && sideEffectsClaimed.add(attemptId); + } + + // ---- rows ------------------------------------------------------------------------------------- + + private DeliveryAttemptRecord existing(DeliveryAttemptId id) { + DeliveryAttemptRecord stored = rows.get(id); + if (stored == null) { + throw new IllegalStateException("delivery attempt no longer exists"); + } + return stored; + } + + private Optional hashOf(DeliveryAttemptRecord attempt) { + return attempt + .providerRequestId() + .map(value -> hasher.hash(attempt.providerProfileId(), value)); + } + + private Optional byHash(ProviderProfileId profileId, String hash) { + return rows.values().stream() + .filter(row -> row.providerProfileId().equals(profileId)) + .filter(row -> hash.equals(requestIdHashes.get(row.id()))) + .findFirst() + .flatMap(this::toSnapshot); + } + + /** The attempt joined to its job, as the read model is; no job, no snapshot. */ + private Optional toSnapshot(DeliveryAttemptRecord row) { + return requests.recipients.values().stream() + .flatMap(List::stream) + .filter(job -> job.id().equals(row.recipientDeliveryId())) + .findFirst() + .map( + job -> + new DeliveryAttemptSnapshot( + row.id(), + row.recipientDeliveryId(), + job.notificationId(), + job.tenantId(), + row.attemptNo(), + row.channel(), + row.providerId(), + row.providerProfileId(), + // Only the hash is stored, so the read model has no identifier to expose. + Optional.empty(), + row.contactPointId(), + row.confirmation(), + row.submissionOutcome(), + row.deliveryOutcome(), + row.evidenceLevel(), + row.credentialGeneration(), + row.renderedContentDigest(), + row.startedAt(), + row.completedAt(), + Optional.empty())); + } + + private static DeliveryAttemptRecord withoutRequestId(DeliveryAttemptRecord attempt) { + return new DeliveryAttemptRecord( + attempt.id(), + attempt.recipientDeliveryId(), + attempt.contactPointId(), + attempt.attemptNo(), + attempt.channel(), + attempt.providerId(), + attempt.providerProfileId(), + Optional.empty(), + attempt.executionEvidence(), + attempt.submissionOutcome(), + attempt.deliveryOutcome(), + attempt.confirmation(), + attempt.evidenceLevel(), + attempt.failureCategory(), + attempt.failureCode(), + attempt.nativeStatus(), + attempt.providerOccurredAt(), + attempt.startedAt(), + attempt.completedAt(), + attempt.elapsed().map(elapsed -> java.time.Duration.ofMillis(elapsed.toMillis())), + attempt.credentialGeneration(), + attempt.renderedContentDigest()); + } + + private static EngagementFacts accumulated(EngagementFacts stored, EngagementFacts written) { + Optional last = + written + .lastEngagedAt() + .filter(at -> stored.lastEngagedAt().map(at::isAfter).orElse(true)) + .or(stored::lastEngagedAt); + return new EngagementFacts( + stored.opened() || written.opened(), + stored.clicked() || written.clicked(), + stored.read() || written.read(), + last); + } + + private static SuppressionFacts accumulated(SuppressionFacts stored, SuppressionFacts written) { + return new SuppressionFacts( + stored.hardBounced() || written.hardBounced(), + stored.complained() || written.complained(), + stored.providerSuppressed() || written.providerSuppressed(), + stored.userOptedOut() || written.userOptedOut(), + stored.invalidTarget() || written.invalidTarget()); + } + + private static RecipientDeliveryRecord rolledUp( + RecipientDeliveryRecord job, DeliveryProjection projection, Instant now) { + return new RecipientDeliveryRecord( + job.id(), + job.notificationId(), + job.tenantId(), + job.recipientRef(), + job.locale(), + job.timeZone(), + job.routingPlan(), + job.routeCursor(), + job.state(), + projection.submissionOutcome(), + projection.deliveryOutcome(), + job.evidenceLevel().strongerOf(projection.evidenceLevel()), + job.ambiguousAttemptExists(), + job.duplicateRisk(), + job.nextDispatchAt(), + job.expiresAt(), + job.leaseOwner(), + job.leaseUntil(), + job.attemptCount(), + job.lastFailureCategory(), + job.createdAt(), + now); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java new file mode 100644 index 00000000..b5bed077 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryNotificationRequestStore.java @@ -0,0 +1,138 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.api.NotificationId; +import dev.caskeleton.application.notification.platform.api.RequestStatus; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.dispatch.DuplicateIdempotencyKeyException; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestInsertOutcome; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.BooleanSupplier; + +/** + * The {@link NotificationRequestStorePort} fake, held to {@link NotificationRequestStoreContract} + * like the JPA store: idempotency-key uniqueness per tenant the way the database enforces it, and + * tenant-scoped reads. + * + *

        The rows are public so a use-case test can assert what the database would end up containing, + * and the recipient queue ({@link InMemoryRecipientQueue}) and the attempt store's snapshots + * ({@link InMemoryDeliveryAttemptStore}) read them, as the tables share a foreign key. Every method + * is synchronized, because the duplicate-key race is what the contract exercises. + */ +public final class InMemoryNotificationRequestStore implements NotificationRequestStorePort { + + private static final char KEY_SEPARATOR = '\u0000'; + + /** Stored requests, in insertion order. */ + public final Map byId = new LinkedHashMap<>(); + + /** The idempotency claim: tenant and key to the request that won it. */ + public final Map byIdempotency = new HashMap<>(); + + /** Recipient jobs per request, written only for the request that won its key. */ + public final Map> recipients = new HashMap<>(); + + /** Whether each status write ran inside the observed transaction, in call order. */ + public final List statusWritesInTransaction = new ArrayList<>(); + + /** + * Set to make the next insert lose the race, as a concurrent claim would. + * + *

        Losing is reported, not thrown. The real store used to raise a unique violation, which left + * the PostgreSQL transaction aborted and made the winner unreadable — so a fake that throws would + * model the bug rather than the contract. + */ + public boolean failNextInsertAsDuplicate; + + private BooleanSupplier transactionOpen; + + /** + * Records, for every later status write, whether a transaction was open — what the JPA store's + * {@code CallerTransaction} guard refuses when it was not. + * + * @param transactionOpen answers whether the caller's transaction is open right now + */ + public synchronized void observe(BooleanSupplier transactionOpen) { + this.transactionOpen = transactionOpen; + } + + @Override + public synchronized NotificationRequestInsertOutcome insert( + NotificationRequestRecord request, List jobs) { + String key = key(request.tenantId(), request.idempotencyKey()); + if (failNextInsertAsDuplicate || byIdempotency.containsKey(key)) { + failNextInsertAsDuplicate = false; + NotificationRequestRecord winner = byId.get(byIdempotency.get(key)); + if (winner == null) { + throw new DuplicateIdempotencyKeyException( + "idempotency key is claimed but its request cannot be read"); + } + // Deliberately no recipient jobs on this path: the loser's jobs would attach a second set + // to the winner's request. + return NotificationRequestInsertOutcome.lost(winner); + } + byId.put(request.id(), request); + byIdempotency.put(key, request.id()); + recipients.put(request.id(), new ArrayList<>(jobs)); + return NotificationRequestInsertOutcome.won(request); + } + + @Override + public synchronized Optional findByIdempotency( + TenantId tenantId, String idempotencyKey) { + return Optional.ofNullable(byIdempotency.get(key(tenantId, idempotencyKey))).map(byId::get); + } + + @Override + public synchronized Optional findById( + TenantId tenantId, NotificationId id) { + return Optional.ofNullable(byId.get(id)).filter(row -> row.tenantId().equals(tenantId)); + } + + @Override + public synchronized List recipientsOf( + TenantId tenantId, NotificationId notificationId) { + // Scoped like the real store: another tenant's id answers with nothing, not with rows. + NotificationRequestRecord owner = byId.get(notificationId); + if (owner == null || !owner.tenantId().equals(tenantId)) { + return List.of(); + } + return List.copyOf(recipients.getOrDefault(notificationId, List.of())); + } + + @Override + public synchronized NotificationRequestRecord updateStatus( + TenantId tenantId, NotificationId notificationId, RequestStatus status) { + if (transactionOpen != null) { + statusWritesInTransaction.add(transactionOpen.getAsBoolean()); + } + NotificationRequestRecord current = byId.get(notificationId); + if (current == null || !current.tenantId().equals(tenantId)) { + throw new IllegalStateException("notification request no longer exists"); + } + NotificationRequestRecord updated = current.withStatus(status); + byId.put(notificationId, updated); + return updated; + } + + /** + * Overwrites a stored job, as the recipient store's save would. + * + * @param job the job, matched by id within its request + */ + public synchronized void replace(RecipientDeliveryRecord job) { + List jobs = recipients.get(job.notificationId()); + jobs.replaceAll(existing -> existing.id().equals(job.id()) ? job : existing); + } + + private static String key(TenantId tenantId, String idempotencyKey) { + return tenantId.value() + KEY_SEPARATOR + idempotencyKey; + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueue.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueue.java new file mode 100644 index 00000000..89517a47 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryRecipientQueue.java @@ -0,0 +1,377 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLease; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Stream; + +/** + * The fake of both recipient ports, held to {@link RecipientLeaseStoreContract} and {@link + * RecipientDeliveryStoreContract} like the JPA stores. + * + *

        One class for two ports because they are two views of one row, as {@code + * JpaRecipientLeaseStore} and {@code JpaRecipientDeliveryStore} are two classes over one table: the + * claim writes the lease and the fence, and a fenced write reads them back. Two fakes would have to + * share that state through a third object, and the old pair did not share it at all — the recipient + * fake decided "superseded" from a set a test filled by hand, not from the lease in the row. + * + *

        The rows are {@link InMemoryNotificationRequestStore}'s, as the table is the request store's + * child: a job the submission service inserted is the job this queue claims. The fence, which the + * record does not carry, is kept here per job. Every operation locks the request store, so a claim + * is atomic against another worker's claim and against the request store's own writes. + */ +public final class InMemoryRecipientQueue + implements RecipientLeaseStorePort, RecipientDeliveryStorePort { + + private static final Set CLAIMABLE = + EnumSet.of( + RecipientDeliveryState.PENDING, + RecipientDeliveryState.READY_TO_DISPATCH, + RecipientDeliveryState.RETRY_WAITING); + + private final InMemoryNotificationRequestStore requests; + private final Clock clock; + private final Map fences = new HashMap<>(); + + /** + * A queue over the request store's recipient rows. + * + * @param requests the store whose recipient rows this queue owns + * @param clock what "now" is for due times, expiry and leases + */ + public InMemoryRecipientQueue(InMemoryNotificationRequestStore requests, Clock clock) { + this.requests = Objects.requireNonNull(requests, "requests"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + // ---- RecipientLeaseStorePort ------------------------------------------------------------------ + + @Override + public List claim(String workerId, int limit, Duration leaseDuration) { + Objects.requireNonNull(workerId, "workerId"); + Objects.requireNonNull(leaseDuration, "leaseDuration"); + if (limit < 1) { + throw new IllegalArgumentException("limit"); + } + synchronized (requests) { + Instant now = clock.instant(); + Instant leaseUntil = now.plus(leaseDuration); + List due = + jobs() + .filter(job -> CLAIMABLE.contains(job.state())) + .filter(job -> job.nextDispatchAt().filter(at -> !at.isAfter(now)).isPresent()) + .filter(job -> job.expiresAt().map(at -> at.isAfter(now)).orElse(true)) + .filter(job -> job.leaseUntil().map(at -> at.isBefore(now)).orElse(true)) + .sorted( + Comparator.comparing((RecipientDeliveryRecord job) -> job.nextDispatchAt().get()) + .thenComparing(job -> job.id().value())) + .limit(limit) + .toList(); + List leases = new ArrayList<>(); + for (RecipientDeliveryRecord job : due) { + long fence = fences.merge(job.id(), 1L, Long::sum); + requests.replace( + copy( + job, + RecipientDeliveryState.DISPATCHING, + job.nextDispatchAt(), + Optional.of(workerId), + Optional.of(leaseUntil), + now)); + leases.add(new RecipientLease(job.id(), workerId, fence, leaseUntil)); + } + return List.copyOf(leases); + } + } + + @Override + public Optional renew(RecipientLease lease, Duration leaseDuration) { + Objects.requireNonNull(lease, "lease"); + Objects.requireNonNull(leaseDuration, "leaseDuration"); + synchronized (requests) { + Instant now = clock.instant(); + Optional held = + heldBy(lease) + .filter(job -> job.state() == RecipientDeliveryState.DISPATCHING) + // An expired lease is not renewable, exactly as the database refuses it. + .filter(job -> job.leaseUntil().filter(until -> until.isAfter(now)).isPresent()); + if (held.isEmpty()) { + return Optional.empty(); + } + Instant leaseUntil = now.plus(leaseDuration); + RecipientDeliveryRecord job = held.get(); + requests.replace( + copy( + job, + job.state(), + job.nextDispatchAt(), + job.leaseOwner(), + Optional.of(leaseUntil), + now)); + return Optional.of( + new RecipientLease( + lease.recipientDeliveryId(), lease.owner(), lease.fence(), leaseUntil)); + } + } + + @Override + public void release(RecipientLease lease) { + Objects.requireNonNull(lease, "lease"); + synchronized (requests) { + heldBy(lease) + .ifPresent( + job -> + requests.replace( + copy( + job, + job.state(), + job.nextDispatchAt(), + Optional.empty(), + Optional.empty(), + clock.instant()))); + } + } + + @Override + public boolean stillHeld(RecipientLease lease) { + Objects.requireNonNull(lease, "lease"); + synchronized (requests) { + Instant now = clock.instant(); + return heldBy(lease) + .flatMap(RecipientDeliveryRecord::leaseUntil) + .filter(until -> until.isAfter(now)) + .isPresent(); + } + } + + @Override + public List expiredDispatching(int limit, Duration olderThan) { + Objects.requireNonNull(olderThan, "olderThan"); + if (limit < 1) { + throw new IllegalArgumentException("limit"); + } + synchronized (requests) { + Instant threshold = clock.instant().minus(olderThan); + return jobs() + .filter(job -> job.state() == RecipientDeliveryState.DISPATCHING) + .filter(job -> job.leaseUntil().filter(until -> until.isBefore(threshold)).isPresent()) + .sorted(Comparator.comparing((RecipientDeliveryRecord job) -> job.leaseUntil().get())) + .limit(limit) + .map(RecipientDeliveryRecord::id) + .toList(); + } + } + + @Override + public int expireOverdue(int limit) { + if (limit < 1) { + throw new IllegalArgumentException("limit"); + } + synchronized (requests) { + Instant now = clock.instant(); + List overdue = + jobs() + .filter(job -> CLAIMABLE.contains(job.state())) + .filter(job -> job.expiresAt().filter(at -> !at.isAfter(now)).isPresent()) + .sorted(Comparator.comparing((RecipientDeliveryRecord job) -> job.expiresAt().get())) + .limit(limit) + .toList(); + overdue.forEach( + job -> + requests.replace( + copy( + job, + RecipientDeliveryState.EXPIRED, + Optional.empty(), + job.leaseOwner(), + job.leaseUntil(), + now))); + return overdue.size(); + } + } + + // ---- RecipientDeliveryStorePort --------------------------------------------------------------- + + @Override + public Optional find(RecipientDeliveryId id) { + synchronized (requests) { + return jobs().filter(job -> job.id().equals(id)).findFirst(); + } + } + + /** + * Writes the job's state and outcome, and only those: the lease is the lease store's, so a saved + * record that says "no lease" does not release one, as the JPA store's projection write does not. + */ + @Override + public RecipientDeliveryRecord save(RecipientDeliveryRecord record) { + Objects.requireNonNull(record, "record"); + synchronized (requests) { + RecipientDeliveryRecord stored = existing(record.id()); + RecipientDeliveryRecord updated = projected(stored, record, clock.instant()); + requests.replace(updated); + return updated; + } + } + + @Override + public RecipientDeliveryRecord transition( + RecipientDeliveryId id, RecipientDeliveryState state, Optional nextDispatchAt) { + Objects.requireNonNull(state, "state"); + Objects.requireNonNull(nextDispatchAt, "nextDispatchAt"); + synchronized (requests) { + RecipientDeliveryRecord stored = existing(id); + RecipientDeliveryRecord moved = + copy( + stored, + state, + nextDispatchAt, + stored.leaseOwner(), + stored.leaseUntil(), + clock.instant()); + requests.replace(moved); + return moved; + } + } + + @Override + public Optional saveHeldBy( + RecipientDeliveryRecord record, RecipientLease lease) { + Objects.requireNonNull(record, "record"); + Objects.requireNonNull(lease, "lease"); + synchronized (requests) { + return heldBy(lease) + .filter(job -> job.id().equals(record.id())) + .map( + job -> { + RecipientDeliveryRecord updated = projected(job, record, clock.instant()); + requests.replace(updated); + return updated; + }); + } + } + + @Override + public Optional transitionHeldBy( + RecipientDeliveryId id, + RecipientDeliveryState state, + Optional nextDispatchAt, + RecipientLease lease) { + Objects.requireNonNull(state, "state"); + Objects.requireNonNull(nextDispatchAt, "nextDispatchAt"); + Objects.requireNonNull(lease, "lease"); + synchronized (requests) { + return heldBy(lease) + .filter(job -> job.id().equals(id)) + .map( + job -> { + RecipientDeliveryRecord moved = + copy( + job, + state, + nextDispatchAt, + job.leaseOwner(), + job.leaseUntil(), + clock.instant()); + requests.replace(moved); + return moved; + }); + } + } + + // ---- rows ------------------------------------------------------------------------------------- + + private Stream jobs() { + return requests.recipients.values().stream().flatMap(List::stream); + } + + private RecipientDeliveryRecord existing(RecipientDeliveryId id) { + return find(id) + .orElseThrow(() -> new IllegalStateException("recipient delivery no longer exists")); + } + + /** + * The job when this lease is still the one in the row: owner and fence both. Expiry is not part + * of it — a holder whose lease lapsed but was not replaced still writes, as the database lets it. + */ + private Optional heldBy(RecipientLease lease) { + return find(lease.recipientDeliveryId()) + .filter(job -> job.leaseOwner().equals(Optional.of(lease.owner()))) + .filter(job -> fences.getOrDefault(job.id(), 0L) == lease.fence()); + } + + /** The stored job with the fields a projection write carries taken from {@code record}. */ + private static RecipientDeliveryRecord projected( + RecipientDeliveryRecord stored, RecipientDeliveryRecord record, Instant now) { + return new RecipientDeliveryRecord( + stored.id(), + stored.notificationId(), + stored.tenantId(), + stored.recipientRef(), + stored.locale(), + stored.timeZone(), + stored.routingPlan(), + record.routeCursor(), + record.state(), + record.submissionOutcome(), + record.deliveryOutcome(), + record.evidenceLevel(), + record.ambiguousAttemptExists(), + record.duplicateRisk(), + record.nextDispatchAt(), + stored.expiresAt(), + stored.leaseOwner(), + stored.leaseUntil(), + record.attemptCount(), + record.lastFailureCategory(), + stored.createdAt(), + now); + } + + private static RecipientDeliveryRecord copy( + RecipientDeliveryRecord job, + RecipientDeliveryState state, + Optional nextDispatchAt, + Optional leaseOwner, + Optional leaseUntil, + Instant now) { + return new RecipientDeliveryRecord( + job.id(), + job.notificationId(), + job.tenantId(), + job.recipientRef(), + job.locale(), + job.timeZone(), + job.routingPlan(), + job.routeCursor(), + state, + job.submissionOutcome(), + job.deliveryOutcome(), + job.evidenceLevel(), + job.ambiguousAttemptExists(), + job.duplicateRisk(), + nextDispatchAt, + job.expiresAt(), + leaseOwner, + leaseUntil, + job.attemptCount(), + job.lastFailureCategory(), + job.createdAt(), + now); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStore.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStore.java new file mode 100644 index 00000000..f937cffb --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStore.java @@ -0,0 +1,161 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJob; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +/** + * The {@link ReconciliationJobStorePort} fake, held to {@link ReconciliationJobStoreContract} like + * the JDBC store. + * + *

        It keeps what the table keeps: one job per attempt, a claim lease in the row and a fence that + * every claim advances, so a holder whose lease ran out changes nothing once somebody else has + * claimed the job. Every method is synchronized — the store is shared by every worker that polls + * it, the way the table is. + */ +public final class InMemoryReconciliationJobStore implements ReconciliationJobStorePort { + + private static final int LAST_RESULT_LIMIT = 40; + + private final Clock clock; + private final Map rows = new LinkedHashMap<>(); + + /** + * Creates an empty store. + * + * @param clock the time source for {@code createdAt} and {@code updatedAt} + */ + public InMemoryReconciliationJobStore(Clock clock) { + this.clock = Objects.requireNonNull(clock, "clock"); + } + + @Override + public synchronized ReconciliationJob schedule( + DeliveryAttemptId attemptId, ProviderProfileId providerProfileId, Instant dueAt) { + Objects.requireNonNull(attemptId, "attemptId"); + Objects.requireNonNull(providerProfileId, "providerProfileId"); + Objects.requireNonNull(dueAt, "dueAt"); + Instant now = clock.instant(); + Row existing = rows.get(attemptId); + if (existing == null) { + Row created = new Row(UUID.randomUUID(), attemptId, providerProfileId, dueAt, now); + rows.put(attemptId, created); + return created.copy(); + } + // One question per attempt: scheduling it again only brings the earlier due time forward. + if (dueAt.isBefore(existing.nextCheckAt)) { + existing.nextCheckAt = dueAt; + } + existing.updatedAt = now; + return existing.copy(); + } + + @Override + public synchronized List claimDue(int limit, Instant now, Duration lease) { + Objects.requireNonNull(now, "now"); + Objects.requireNonNull(lease, "lease"); + if (limit < 1) { + throw new IllegalArgumentException("limit"); + } + if (lease.isNegative() || lease.isZero()) { + throw new IllegalArgumentException("lease must be positive"); + } + List due = + rows.values().stream() + .filter(row -> !row.nextCheckAt.isAfter(now)) + .filter(row -> row.claimedUntil == null || !row.claimedUntil.isAfter(now)) + .sorted(Comparator.comparing((Row row) -> row.nextCheckAt).thenComparing(row -> row.id)) + .limit(limit) + .toList(); + List claimed = new ArrayList<>(); + for (Row row : due) { + row.claimedUntil = now.plus(lease); + row.claimFence++; + claimed.add(row.copy()); + } + return List.copyOf(claimed); + } + + @Override + public synchronized void reschedule(ReconciliationJob job, String result, Instant nextCheckAt) { + Objects.requireNonNull(job, "job"); + Objects.requireNonNull(nextCheckAt, "nextCheckAt"); + heldBy(job) + .ifPresent( + row -> { + row.attempts++; + row.lastResult = + result == null + ? null + : result.substring(0, Math.min(result.length(), LAST_RESULT_LIMIT)); + row.nextCheckAt = nextCheckAt; + row.claimedUntil = null; + row.updatedAt = clock.instant(); + }); + } + + @Override + public synchronized void complete(ReconciliationJob job) { + Objects.requireNonNull(job, "job"); + heldBy(job).ifPresent(row -> rows.remove(row.attemptId)); + } + + private Optional heldBy(ReconciliationJob job) { + return rows.values().stream() + .filter(row -> row.id.equals(job.id()) && row.claimFence == job.claimFence()) + .findFirst(); + } + + private static final class Row { + + private final UUID id; + private final DeliveryAttemptId attemptId; + private final ProviderProfileId providerProfileId; + private final Instant createdAt; + private Instant nextCheckAt; + private int attempts; + private String lastResult; + private Instant updatedAt; + private Instant claimedUntil; + private long claimFence; + + private Row( + UUID id, + DeliveryAttemptId attemptId, + ProviderProfileId providerProfileId, + Instant nextCheckAt, + Instant now) { + this.id = id; + this.attemptId = attemptId; + this.providerProfileId = providerProfileId; + this.nextCheckAt = nextCheckAt; + this.createdAt = now; + this.updatedAt = now; + } + + private ReconciliationJob copy() { + return new ReconciliationJob( + id, + attemptId, + providerProfileId, + nextCheckAt, + attempts, + Optional.ofNullable(lastResult), + createdAt, + updatedAt, + claimFence); + } + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRequestStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRequestStoreContract.java new file mode 100644 index 00000000..96238b7f --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRequestStoreContract.java @@ -0,0 +1,205 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.groups.Tuple.tuple; + +import dev.caskeleton.application.notification.platform.api.NotificationId; +import dev.caskeleton.application.notification.platform.api.RequestStatus; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestInsertOutcome; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.policy.testkit.OverlappingWrites; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link NotificationRequestStorePort} promises, run against the in-memory fake and the + * JPA store alike (review 2026-11-01 04-14). + * + *

        The idempotency key is claimed by the insert: a request whose key a tenant already used loses + * and is answered with the winner, its recipient jobs are not attached to anybody, and losing is an + * answer rather than an exception. Every read is scoped to the tenant that asks. Writes go through + * {@link #inTransaction}, because the real store refuses them without a caller transaction. + */ +public abstract class NotificationRequestStoreContract { + + private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z"); + private static final TenantId TENANT = new TenantId("tenant-a"); + private static final TenantId OTHER_TENANT = new TenantId("tenant-b"); + + /** The store under test, empty at the start of each test. */ + protected abstract NotificationRequestStorePort store(); + + /** Runs {@code work} in one committed write transaction of the store under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + @DisplayName("처음 쓰인 멱등성 키의 요청은 이기고 그 키로 조회된다") + void aRequestWithAFreshKeyWinsAndIsFoundByThatKey() { + // given + NotificationRequestRecord request = request(TENANT, "idem-1"); + + // when + NotificationRequestInsertOutcome outcome = insert(request, List.of(job(request))); + + // then + assertThat(List.of(outcome.inserted(), idOf(store().findByIdempotency(TENANT, "idem-1")))) + .containsExactly(true, Optional.of(request.id())); + } + + @Test + @DisplayName("이미 쓰인 키로 다시 넣으면 예외 없이 지고 이긴 요청을 돌려받는다") + void aRequestWithAUsedKeyLosesAndIsAnsweredWithTheWinner() { + // given + NotificationRequestRecord winner = request(TENANT, "idem-1"); + insert(winner, List.of(job(winner))); + NotificationRequestRecord loser = request(TENANT, "idem-1"); + + // when + NotificationRequestInsertOutcome outcome = insert(loser, List.of(job(loser))); + + // then + assertThat(List.of(outcome.inserted(), outcome.stored().id())) + .containsExactly(false, winner.id()); + } + + @Test + @DisplayName("진 요청의 수신자 작업은 이긴 요청에 붙지 않는다") + void theLosersRecipientJobsAreNotAttachedToTheWinner() { + // given + NotificationRequestRecord winner = request(TENANT, "idem-1"); + RecipientDeliveryRecord winnersJob = job(winner); + insert(winner, List.of(winnersJob)); + NotificationRequestRecord loser = request(TENANT, "idem-1"); + insert(loser, List.of(job(loser))); + + // when + List jobs = store().recipientsOf(TENANT, winner.id()); + + // then + assertThat(jobs) + .as("the loser's jobs would give the winner's request a second set") + .extracting(RecipientDeliveryRecord::id) + .containsExactly(winnersJob.id()); + } + + @Test + @DisplayName("같은 키라도 테넌트가 다르면 다른 요청이다") + void theSameKeyInAnotherTenantIsAnotherRequest() { + // given + insert(request(TENANT, "idem-1"), List.of()); + NotificationRequestRecord other = request(OTHER_TENANT, "idem-1"); + + // when + NotificationRequestInsertOutcome outcome = insert(other, List.of()); + + // then + assertThat(List.of(outcome.inserted(), outcome.stored().id())) + .containsExactly(true, other.id()); + } + + @Test + @DisplayName("다른 테넌트는 같은 id의 요청도 그 수신자 작업도 보지 못한다") + void anotherTenantSeesNeitherTheRequestNorItsJobs() { + // given + NotificationRequestRecord request = request(TENANT, "idem-1"); + insert(request, List.of(job(request))); + + // when + List seen = + List.of( + store().findById(OTHER_TENANT, request.id()), + store().findByIdempotency(OTHER_TENANT, "idem-1"), + store().recipientsOf(OTHER_TENANT, request.id())); + + // then + assertThat(seen).containsExactly(Optional.empty(), Optional.empty(), List.of()); + } + + @Test + @DisplayName("상태를 바꾸면 그 테넌트의 조회에 바뀐 상태가 보인다") + void anUpdatedStatusIsWhatTheTenantReadsBack() { + // given + NotificationRequestRecord request = request(TENANT, "idem-1"); + insert(request, List.of()); + + // when + inTransaction(() -> store().updateStatus(TENANT, request.id(), RequestStatus.COMPLETED)); + + // then + assertThat(store().findById(TENANT, request.id())) + .get() + .extracting(NotificationRequestRecord::status) + .isEqualTo(RequestStatus.COMPLETED); + } + + @Test + @DisplayName("다른 테넌트의 요청 상태는 바꾸지 못한다") + void anotherTenantsRequestStatusCannotBeChanged() { + // given + NotificationRequestRecord request = request(TENANT, "idem-1"); + insert(request, List.of()); + + // when + Throwable refused = + catchThrowable( + () -> + inTransaction( + () -> + store().updateStatus(OTHER_TENANT, request.id(), RequestStatus.CANCELED))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no longer exists"); + } + + @Test + @DisplayName("같은 키의 첫 요청 두 개가 겹치면 하나만 이기고 다른 하나는 그 요청을 돌려받는다") + void ofTwoOverlappingFirstRequestsOneWinsAndTheOtherGetsTheWinner() { + // given + NotificationRequestRecord first = request(TENANT, "idem-race"); + NotificationRequestRecord second = request(TENANT, "idem-race"); + + // when + List outcomes = + OverlappingWrites.run( + this::inTransaction, + () -> store().insert(first, List.of(job(first))), + () -> store().insert(second, List.of(job(second)))); + + // then + assertThat(outcomes) + .as("the loser used to read the winner in a transaction its unique violation had aborted") + .extracting(NotificationRequestInsertOutcome::inserted, outcome -> outcome.stored().id()) + .containsExactly(tuple(true, first.id()), tuple(false, first.id())); + } + + private NotificationRequestInsertOutcome insert( + NotificationRequestRecord request, List jobs) { + return inTransaction(() -> store().insert(request, jobs)); + } + + private static Optional idOf(Optional found) { + return found.map(NotificationRequestRecord::id); + } + + /** A request as the submission service builds one; timestamps at the precision a column keeps. */ + protected static NotificationRequestRecord request(TenantId tenant, String idempotencyKey) { + return NotificationRows.request(tenant, idempotencyKey, NOW); + } + + /** One queued recipient job of {@code request}. */ + protected static RecipientDeliveryRecord job(NotificationRequestRecord request) { + return NotificationRows.job( + request, RecipientDeliveryState.READY_TO_DISPATCH, Optional.of(NOW), Optional.empty(), NOW); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRows.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRows.java new file mode 100644 index 00000000..513a16fb --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRows.java @@ -0,0 +1,193 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.api.ContactPointId; +import dev.caskeleton.application.notification.platform.api.CorrelationId; +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.NotificationId; +import dev.caskeleton.application.notification.platform.api.ProviderId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.RequestStatus; +import dev.caskeleton.application.notification.platform.api.TemplateSelection; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; +import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; +import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; +import dev.caskeleton.application.notification.platform.api.routing.Channel; +import dev.caskeleton.application.notification.platform.contact.ContactPointStatus; +import dev.caskeleton.application.notification.platform.contact.ContactPointType; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointRecord; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptRecord; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.provider.ProviderExecutionEvidence; +import dev.caskeleton.application.notification.platform.security.ProtectedContactPoint; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +/** + * Rows as the platform writes them, for the notification store contracts. + * + *

        One place, so the request, recipient, attempt and contact point contracts seed the same shapes + * the services produce. Every instant is truncated to the microsecond a PostgreSQL column keeps, + * and the routing plan is empty because the plan codec is not what any store contract is about. + */ +public final class NotificationRows { + + private NotificationRows() {} + + /** + * A validated request, as the submission service stores one. + * + * @param tenant the tenant + * @param idempotencyKey the key the request claims + * @param at when it was accepted + * @return the request + */ + public static NotificationRequestRecord request( + TenantId tenant, String idempotencyKey, Instant at) { + Instant stored = at.truncatedTo(ChronoUnit.MICROS); + return new NotificationRequestRecord( + new NotificationId(UUID.randomUUID()), + tenant, + idempotencyKey, + "0".repeat(64), + "TRANSACTIONAL", + new TemplateSelection("welcome", 1L, Locale.KOREAN), + "SingleRoute", + "{}", + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + RequestStatus.VALIDATED, + new CorrelationId("correlation-1"), + Map.of(), + stored, + stored); + } + + /** + * One recipient job of {@code request}, not leased. + * + * @param request the request it belongs to + * @param state the queue state + * @param dueAt when it becomes claimable, if it does + * @param expiresAt when its window closes, if it does + * @param at when it was written + * @return the job + */ + public static RecipientDeliveryRecord job( + NotificationRequestRecord request, + RecipientDeliveryState state, + Optional dueAt, + Optional expiresAt, + Instant at) { + Instant stored = at.truncatedTo(ChronoUnit.MICROS); + return new RecipientDeliveryRecord( + new RecipientDeliveryId(UUID.randomUUID()), + request.id(), + request.tenantId(), + "user-1", + Optional.empty(), + Optional.empty(), + List.of(), + 0, + state, + SubmissionOutcome.NOT_SUBMITTED, + DeliveryOutcome.UNKNOWN, + EvidenceLevel.PLATFORM_QUEUED, + false, + false, + dueAt.map(instant -> instant.truncatedTo(ChronoUnit.MICROS)), + expiresAt.map(instant -> instant.truncatedTo(ChronoUnit.MICROS)), + Optional.empty(), + Optional.empty(), + 0, + Optional.empty(), + stored, + stored); + } + + /** + * The attempt row the dispatcher commits before it calls a provider: started, outcome unknown. + * + * @param job the recipient job + * @param contactPoint the contact point the route names + * @param attemptNo its number within the job + * @param profile the provider profile it runs under + * @param startedAt when it started + * @return the attempt + */ + public static DeliveryAttemptRecord dispatchingAttempt( + RecipientDeliveryId job, + ContactPointId contactPoint, + int attemptNo, + ProviderProfileId profile, + Instant startedAt) { + return new DeliveryAttemptRecord( + new DeliveryAttemptId(UUID.randomUUID()), + job, + contactPoint, + attemptNo, + Channel.EMAIL, + new ProviderId("ses"), + profile, + Optional.empty(), + ProviderExecutionEvidence.undetermined(), + SubmissionOutcome.NOT_SUBMITTED, + DeliveryOutcome.UNKNOWN, + AttemptConfirmation.AMBIGUOUS, + EvidenceLevel.PLATFORM_QUEUED, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + startedAt.truncatedTo(ChronoUnit.MICROS), + Optional.empty(), + Optional.empty(), + 1L, + "d".repeat(64)); + } + + /** + * An unverified email contact point, as a submission registers one. + * + * @param tenant the tenant + * @param lookupHmac its keyed fingerprint, 64 hex characters as the column holds it + * @param at when it was registered + * @return the contact point + */ + public static ContactPointRecord contactPoint(TenantId tenant, String lookupHmac, Instant at) { + Instant stored = at.truncatedTo(ChronoUnit.MICROS); + return new ContactPointRecord( + new ContactPointId(UUID.randomUUID()), + tenant, + "user-1", + ContactPointType.EMAIL, + Optional.empty(), + Optional.empty(), + "PRODUCTION", + new ProtectedContactPoint( + ContactPointType.EMAIL, + "key-1", + new byte[] {4, 5, 6}, + new byte[] {1, 2, 3}, + lookupHmac), + ContactPointStatus.UNVERIFIED, + false, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + stored, + stored); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/RecipientDeliveryStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/RecipientDeliveryStoreContract.java new file mode 100644 index 00000000..7ceefe82 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/RecipientDeliveryStoreContract.java @@ -0,0 +1,293 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; +import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLease; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link RecipientDeliveryStorePort} promises, run against the in-memory queue and the + * JPA store alike (review 2026-11-01 04-14). + * + *

        The job's state and outcome are what this store writes; the lease is the lease store's, so a + * write here never takes one or gives one back. The fenced writes are the point: a worker whose + * lease another worker has since claimed writes nothing, however recent its read of the row was. + */ +public abstract class RecipientDeliveryStoreContract { + + /** The instant every case starts at. */ + protected static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); + + private static final TenantId TENANT = new TenantId("tenant-a"); + private static final Duration LEASE = Duration.ofMinutes(5); + + private final ContractClock clock = new ContractClock(NOW); + + /** + * The clock the stores under test must read; the contract moves it. + * + * @return the clock + */ + protected final Clock clock() { + return clock; + } + + /** The recipient store under test, over an empty queue. */ + protected abstract RecipientDeliveryStorePort deliveries(); + + /** The lease store over the same rows, which is what takes and supersedes a lease. */ + protected abstract RecipientLeaseStorePort leases(); + + /** The request store the jobs are inserted through. */ + protected abstract NotificationRequestStorePort requests(); + + /** Runs {@code work} in one committed write transaction of the stores under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + @DisplayName("넣은 작업은 id로 다시 읽히고 없는 id는 비어 있다") + void aStoredJobIsFoundByIdAndAnUnknownIdIsEmpty() { + // given + RecipientDeliveryRecord job = givenAQueuedJob(); + + // when + Optional found = deliveries().find(job.id()); + + // then + assertThat( + List.of( + found.map(RecipientDeliveryRecord::notificationId), + found.map(RecipientDeliveryRecord::state), + found.flatMap(RecipientDeliveryRecord::nextDispatchAt), + deliveries().find(new RecipientDeliveryId(UUID.randomUUID())))) + .containsExactly( + Optional.of(job.notificationId()), + Optional.of(RecipientDeliveryState.READY_TO_DISPATCH), + job.nextDispatchAt(), + Optional.empty()); + } + + @Test + @DisplayName("save는 상태·결과·시도 수를 쓰고 lease는 바꾸지 않는다") + void saveWritesStateAndOutcomeButNotTheLease() { + // given + RecipientDeliveryRecord job = givenAQueuedJob(); + claim(); + RecipientDeliveryRecord outcome = + withOutcome(job, RecipientDeliveryState.RETRY_WAITING, 1, NOW.plusSeconds(60)); + + // when + inTransaction(() -> deliveries().save(outcome)); + + // then + RecipientDeliveryRecord stored = deliveries().find(job.id()).orElseThrow(); + assertThat( + List.of( + stored.state(), + stored.attemptCount(), + stored.submissionOutcome(), + stored.evidenceLevel(), + stored.nextDispatchAt(), + stored.leaseOwner())) + .as("releasing the lease is the lease store's write, not a side effect of this one") + .containsExactly( + RecipientDeliveryState.RETRY_WAITING, + 1, + SubmissionOutcome.CONFIRMED_REJECTED, + EvidenceLevel.NONE, + Optional.of(NOW.plusSeconds(60)), + Optional.of("worker-a")); + } + + @Test + @DisplayName("없어진 작업을 save하면 조용히 넘어가지 않고 거부된다") + void savingAJobThatNoLongerExistsIsRefused() { + // given + RecipientDeliveryRecord job = givenAQueuedJob(); + RecipientDeliveryRecord unknown = + new RecipientDeliveryRecord( + new RecipientDeliveryId(UUID.randomUUID()), + job.notificationId(), + job.tenantId(), + job.recipientRef(), + job.locale(), + job.timeZone(), + job.routingPlan(), + job.routeCursor(), + job.state(), + job.submissionOutcome(), + job.deliveryOutcome(), + job.evidenceLevel(), + job.ambiguousAttemptExists(), + job.duplicateRisk(), + job.nextDispatchAt(), + job.expiresAt(), + job.leaseOwner(), + job.leaseUntil(), + job.attemptCount(), + job.lastFailureCategory(), + job.createdAt(), + job.updatedAt()); + + // when + Throwable refused = catchThrowable(() -> inTransaction(() -> deliveries().save(unknown))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no longer exists"); + } + + @Test + @DisplayName("transition은 상태와 다음 시각만 바꾸고 결과는 그대로 둔다") + void aTransitionMovesStateAndScheduleOnly() { + // given + RecipientDeliveryRecord job = givenAQueuedJob(); + + // when + inTransaction( + () -> deliveries().transition(job.id(), RecipientDeliveryState.FAILED, Optional.empty())); + + // then + RecipientDeliveryRecord stored = deliveries().find(job.id()).orElseThrow(); + assertThat(List.of(stored.state(), stored.nextDispatchAt(), stored.submissionOutcome())) + .containsExactly( + RecipientDeliveryState.FAILED, Optional.empty(), SubmissionOutcome.NOT_SUBMITTED); + } + + @Test + @DisplayName("lease를 가진 worker의 fenced 쓰기는 반영되고 저장된 작업을 돌려준다") + void theHoldersFencedWritesLand() { + // given + RecipientDeliveryRecord job = givenAQueuedJob(); + RecipientLease lease = claim(); + RecipientDeliveryRecord outcome = withOutcome(job, RecipientDeliveryState.DISPATCHING, 1, NOW); + + // when + List> writes = + List.of( + inTransaction(() -> deliveries().saveHeldBy(outcome, lease)), + inTransaction( + () -> + deliveries() + .transitionHeldBy( + job.id(), RecipientDeliveryState.COMPLETED, Optional.empty(), lease))); + + // then + RecipientDeliveryRecord stored = deliveries().find(job.id()).orElseThrow(); + assertThat( + List.of( + writes.get(0).map(RecipientDeliveryRecord::attemptCount), + writes.get(1).map(RecipientDeliveryRecord::state), + stored.state(), + stored.attemptCount())) + .containsExactly( + Optional.of(1), + Optional.of(RecipientDeliveryState.COMPLETED), + RecipientDeliveryState.COMPLETED, + 1); + } + + @Test + @DisplayName("다른 worker가 다시 claim한 뒤에는 이전 lease의 fenced 쓰기가 아무것도 쓰지 않는다") + void aSupersededHoldersFencedWritesWriteNothing() { + // given + RecipientDeliveryRecord job = givenAQueuedJob(); + RecipientLease stale = claim(); + clock.moveTo(NOW.plus(LEASE).plusSeconds(1)); + inTransaction( + () -> + deliveries() + .transition( + job.id(), + RecipientDeliveryState.READY_TO_DISPATCH, + Optional.of(clock.instant()))); + claim(); + RecipientDeliveryRecord lateOutcome = + withOutcome(job, RecipientDeliveryState.COMPLETED, 1, NOW); + + // when + List> writes = + List.of( + inTransaction(() -> deliveries().saveHeldBy(lateOutcome, stale)), + inTransaction( + () -> + deliveries() + .transitionHeldBy( + job.id(), RecipientDeliveryState.FAILED, Optional.empty(), stale))); + + // then + RecipientDeliveryRecord stored = deliveries().find(job.id()).orElseThrow(); + assertThat(List.of(writes, stored.state(), stored.attemptCount())) + .as("the late worker's read was recent; only the fence says it is no longer the holder") + .containsExactly( + List.of(Optional.empty(), Optional.empty()), RecipientDeliveryState.DISPATCHING, 0); + } + + private RecipientDeliveryRecord givenAQueuedJob() { + NotificationRequestRecord request = + NotificationRows.request(TENANT, "idem-" + UUID.randomUUID(), NOW); + RecipientDeliveryRecord job = + NotificationRows.job( + request, + RecipientDeliveryState.READY_TO_DISPATCH, + Optional.of(NOW), + Optional.empty(), + NOW); + inTransaction(() -> requests().insert(request, List.of(job))); + return job; + } + + private RecipientLease claim() { + String worker = clock.instant().equals(NOW) ? "worker-a" : "worker-b"; + return inTransaction(() -> leases().claim(worker, 10, LEASE)).getFirst(); + } + + /** The job after one rejected attempt, as the dispatcher would write it. */ + private static RecipientDeliveryRecord withOutcome( + RecipientDeliveryRecord job, RecipientDeliveryState state, int attempts, Instant next) { + return new RecipientDeliveryRecord( + job.id(), + job.notificationId(), + job.tenantId(), + job.recipientRef(), + job.locale(), + job.timeZone(), + job.routingPlan(), + job.routeCursor(), + state, + SubmissionOutcome.CONFIRMED_REJECTED, + DeliveryOutcome.UNKNOWN, + EvidenceLevel.NONE, + false, + false, + Optional.of(next), + job.expiresAt(), + Optional.empty(), + Optional.empty(), + attempts, + Optional.of("INVALID_RECIPIENT"), + job.createdAt(), + job.updatedAt()); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/RecipientLeaseStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/RecipientLeaseStoreContract.java new file mode 100644 index 00000000..0a97a7c1 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/RecipientLeaseStoreContract.java @@ -0,0 +1,336 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLease; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link RecipientLeaseStorePort} promises, run against the in-memory queue and the JPA + * store alike (review 2026-11-01 04-14). + * + *

        Four things: a job is claimed when it is due and not before; a job whose window closed is + * never claimed and is retired instead; two workers never hold one job; and a holder that has been + * replaced finds out through the fence rather than carrying on. Jobs are seeded through the request + * store and moved back to the queue through the recipient store, the way the submission service and + * lease recovery do it, so the only thing written by hand is the clock. + */ +public abstract class RecipientLeaseStoreContract { + + /** The instant every case starts at. */ + protected static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); + + private static final TenantId TENANT = new TenantId("tenant-a"); + private static final Duration LEASE = Duration.ofMinutes(5); + + private final ContractClock clock = new ContractClock(NOW); + + /** + * The clock the stores under test must read; the contract moves it. + * + * @return the clock + */ + protected final Clock clock() { + return clock; + } + + /** The lease store under test, over an empty queue. */ + protected abstract RecipientLeaseStorePort leases(); + + /** The recipient store over the same rows, for requeueing and for reading a job back. */ + protected abstract RecipientDeliveryStorePort deliveries(); + + /** The request store the jobs are inserted through. */ + protected abstract NotificationRequestStorePort requests(); + + /** Runs {@code work} in one committed write transaction of the stores under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + @DisplayName("지금 기한이 된 작업은 한 번만 claim되고 두 번째 claim에는 나오지 않는다") + void aJobDueNowIsClaimedExactlyOnce() { + // given + RecipientDeliveryId id = given(RecipientDeliveryState.READY_TO_DISPATCH, NOW, null); + claim("worker-a"); + + // when + List second = claim("worker-a"); + + // then + assertThat(List.of(second, stateOf(id))) + .as("the claim moved it to DISPATCHING and took the lease") + .containsExactly(List.of(), RecipientDeliveryState.DISPATCHING); + } + + @Test + @DisplayName("1마이크로초 뒤에 기한이 되는 작업은 아직 claim되지 않는다") + void aJobNotYetDueIsNotClaimed() { + // given + given(RecipientDeliveryState.READY_TO_DISPATCH, NOW.plusNanos(1_000), null); + + // when + List claimed = claim("worker-a"); + + // then + assertThat(claimed).isEmpty(); + } + + @Test + @DisplayName("이전 인스턴스가 PENDING으로 남긴 작업과 재시도 대기 작업도 claim된다") + void pendingAndRetryWaitingJobsAreClaimed() { + // given + RecipientDeliveryId pending = given(RecipientDeliveryState.PENDING, NOW, null); + RecipientDeliveryId retrying = + given(RecipientDeliveryState.RETRY_WAITING, NOW.minusSeconds(1), null); + + // when + List claimed = claim("worker-a"); + + // then + assertThat(claimed) + .as("PENDING is the state every scheduled delivery used to be stranded in") + .extracting(RecipientLease::recipientDeliveryId) + .containsExactlyInAnyOrder(pending, retrying); + } + + @Test + @DisplayName("창이 닫힌 작업은 기한이 지났어도 claim되지 않고 창 안의 작업만 claim된다") + void aJobPastItsExpiryIsNeverClaimed() { + // given + given(RecipientDeliveryState.READY_TO_DISPATCH, NOW.minusSeconds(3600), NOW.minusSeconds(1)); + RecipientDeliveryId inWindow = + given(RecipientDeliveryState.READY_TO_DISPATCH, NOW, NOW.plusSeconds(1)); + + // when + List claimed = claim("worker-a"); + + // then + assertThat(claimed) + .as("the expiry is checked in the claim itself, not after it") + .extracting(RecipientLease::recipientDeliveryId) + .containsExactly(inWindow); + } + + @Test + @DisplayName("창이 닫힌 작업은 EXPIRED로 정리되고 다음 시각이 지워진다") + void anOverdueJobIsRetiredToExpired() { + // given + RecipientDeliveryId overdue = + given( + RecipientDeliveryState.READY_TO_DISPATCH, NOW.minusSeconds(3600), NOW.minusSeconds(1)); + given(RecipientDeliveryState.READY_TO_DISPATCH, NOW, NOW.plusSeconds(1)); + + // when + int retired = inTransaction(() -> leases().expireOverdue(10)); + + // then + RecipientDeliveryRecord job = deliveries().find(overdue).orElseThrow(); + assertThat(List.of(retired, job.state(), job.nextDispatchAt())) + .as("never claimed is a fact an operator can count, not a queue that looks stuck") + .containsExactly(1, RecipientDeliveryState.EXPIRED, Optional.empty()); + } + + @Test + @DisplayName("두 worker가 같은 작업을 동시에 claim하면 한쪽만 가져간다") + void twoWorkersRacingForOneJobProduceOneClaim() throws Exception { + // given + given(RecipientDeliveryState.READY_TO_DISPATCH, NOW, null); + CountDownLatch start = new CountDownLatch(1); + ExecutorService pool = Executors.newFixedThreadPool(2); + List left; + List right; + try { + Future> first = pool.submit(racer(start, "worker-a")); + Future> second = pool.submit(racer(start, "worker-b")); + + // when + start.countDown(); + left = first.get(); + right = second.get(); + } finally { + pool.shutdownNow(); + } + + // then + assertThat(left.size() + right.size()) + .as("two holders of one job both send the notification") + .isEqualTo(1); + } + + @Test + @DisplayName("갱신한 lease는 원래 만료 시각이 지나도 아직 잡고 있다") + void aRenewedLeaseIsStillHeldPastItsOriginalExpiry() { + // given + given(RecipientDeliveryState.READY_TO_DISPATCH, NOW, null); + RecipientLease lease = claim("worker-a").getFirst(); + clock.moveTo(NOW.plus(LEASE).minusSeconds(60)); + inTransaction(() -> leases().renew(lease, LEASE)); + clock.moveTo(NOW.plus(LEASE).plusSeconds(60)); + + // when + boolean held = leases().stillHeld(lease); + + // then + assertThat(held) + .as("a renew that does not extend the lease loses a slow provider call") + .isTrue(); + } + + @Test + @DisplayName("이미 만료된 lease는 갱신되지 않고 더는 잡고 있지 않다") + void anExpiredLeaseCannotBeRenewedAndIsNotHeld() { + // given + given(RecipientDeliveryState.READY_TO_DISPATCH, NOW, null); + RecipientLease lease = claim("worker-a").getFirst(); + clock.moveTo(NOW.plus(LEASE).plusSeconds(1)); + + // when + Optional renewed = inTransaction(() -> leases().renew(lease, LEASE)); + + // then + assertThat(List.of(renewed, leases().stillHeld(lease))) + .as("a worker paused past its expiry must not resume as though it never lost the job") + .containsExactly(Optional.empty(), false); + } + + @Test + @DisplayName("다른 worker가 다시 claim한 뒤 이전 lease는 갱신도 확인도 해제도 통하지 않는다") + void aSupersededLeaseNeitherRenewsNorHoldsNorReleases() { + // given + RecipientDeliveryId id = given(RecipientDeliveryState.READY_TO_DISPATCH, NOW, null); + RecipientLease first = claim("worker-a").getFirst(); + RecipientLease second = reclaimAfterExpiry(id, "worker-b"); + inTransaction( + () -> { + leases().release(first); + return null; + }); + + // when + Optional renewed = inTransaction(() -> leases().renew(first, LEASE)); + + // then + assertThat( + List.of( + renewed, + leases().stillHeld(first), + leases().stillHeld(second), + deliveries().find(id).orElseThrow().leaseOwner())) + .as("only the fence tells an expired holder that it has been replaced") + .containsExactly(Optional.empty(), false, true, Optional.of("worker-b")); + } + + @Test + @DisplayName("같은 worker 이름으로 다시 claim해도 fence가 올라가 이전 lease와 구별된다") + void aReclaimUnderTheSameOwnerAdvancesTheFence() { + // given + RecipientDeliveryId id = given(RecipientDeliveryState.READY_TO_DISPATCH, NOW, null); + RecipientLease first = claim("worker-a").getFirst(); + + // when + RecipientLease second = reclaimAfterExpiry(id, "worker-a"); + + // then + assertThat(List.of(second.fence() > first.fence(), leases().stillHeld(first))) + .as("two incarnations of one configured worker id share the owner string") + .containsExactly(true, false); + } + + @Test + @DisplayName("lease를 해제하면 행의 lease가 비고 상태는 그대로다") + void releasingALeaseClearsItAndLeavesTheState() { + // given + RecipientDeliveryId id = given(RecipientDeliveryState.READY_TO_DISPATCH, NOW, null); + RecipientLease lease = claim("worker-a").getFirst(); + + // when + inTransaction( + () -> { + leases().release(lease); + return null; + }); + + // then + RecipientDeliveryRecord job = deliveries().find(id).orElseThrow(); + assertThat(List.of(job.leaseOwner(), job.leaseUntil(), job.state())) + .containsExactly(Optional.empty(), Optional.empty(), RecipientDeliveryState.DISPATCHING); + } + + @Test + @DisplayName("lease가 기준보다 오래 전에 끝난 DISPATCHING 작업만 복구 대상으로 나온다") + void onlyJobsWhoseLeaseEndedLongEnoughAgoAreAbandoned() { + // given + RecipientDeliveryId abandoned = given(RecipientDeliveryState.READY_TO_DISPATCH, NOW, null); + claim("worker-a"); + clock.moveTo(NOW.plus(LEASE).plusSeconds(30)); + given(RecipientDeliveryState.READY_TO_DISPATCH, NOW.plus(LEASE), null); + claim("worker-b"); + clock.moveTo(NOW.plus(LEASE).plus(Duration.ofMinutes(2))); + + // when + List expired = leases().expiredDispatching(10, Duration.ofMinutes(1)); + + // then + assertThat(expired) + .as("a job whose lease is still running belongs to a live worker") + .containsExactly(abandoned); + } + + private RecipientDeliveryId given( + RecipientDeliveryState state, Instant dueAt, Instant expiresAt) { + NotificationRequestRecord request = + NotificationRows.request(TENANT, "idem-" + UUID.randomUUID(), clock.instant()); + RecipientDeliveryRecord job = + NotificationRows.job( + request, state, Optional.of(dueAt), Optional.ofNullable(expiresAt), clock.instant()); + inTransaction(() -> requests().insert(request, List.of(job))); + return job.id(); + } + + private List claim(String worker) { + return inTransaction(() -> leases().claim(worker, 10, LEASE)); + } + + private Callable> racer(CountDownLatch start, String worker) { + return () -> { + start.await(); + return claim(worker); + }; + } + + /** The holder's lease runs out, recovery puts the job back, and another claim takes it. */ + private RecipientLease reclaimAfterExpiry(RecipientDeliveryId id, String worker) { + clock.moveTo(clock.instant().plus(LEASE).plusSeconds(1)); + inTransaction( + () -> + deliveries() + .transition( + id, RecipientDeliveryState.READY_TO_DISPATCH, Optional.of(clock.instant()))); + return claim(worker).getFirst(); + } + + private RecipientDeliveryState stateOf(RecipientDeliveryId id) { + return deliveries().find(id).orElseThrow().state(); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ReconciliationJobStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ReconciliationJobStoreContract.java new file mode 100644 index 00000000..d50ab68e --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ReconciliationJobStoreContract.java @@ -0,0 +1,227 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.groups.Tuple.tuple; + +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJob; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort; +import java.time.Duration; +import java.time.Instant; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link ReconciliationJobStorePort} promises, run against the in-memory fake and the + * JDBC store alike (review 2026-11-01 04-14). + * + *

        Two instances polling one table must never ask the same question at the same time, and an + * instance that outlived its lease must not change a job somebody else has claimed since. Every + * observation goes through the port: whether a job still exists, and how many times it has asked, + * is what the next claim after the lease hands back. + */ +public abstract class ReconciliationJobStoreContract { + + /** The instant every case starts at; the store's clock reads it. */ + protected static final Instant NOW = Instant.parse("2026-08-15T09:00:00Z"); + + /** The provider profile every attempt was sent through. */ + protected static final String PROFILE = "email-main"; + + private static final Duration LEASE = Duration.ofMinutes(2); + + /** + * A handle on the store under test, empty at the start of each test. Two calls give two handles + * on the same table — two instances of the application polling it. + */ + protected abstract ReconciliationJobStorePort store(); + + /** An attempt sent through {@link #PROFILE} whose outcome is unknown, existing in the store. */ + protected abstract DeliveryAttemptId givenAnAttempt(); + + @Test + @DisplayName("한 인스턴스가 가져간 정산 job은 다른 인스턴스의 claim에 다시 나오지 않는다") + void aClaimedJobIsNotHandedToAnotherInstance() { + // given + UUID id = scheduleDueJob(); + store().claimDue(10, NOW, LEASE); + + // when + List secondClaim = store().claimDue(10, NOW, LEASE); + + // then + assertThat(secondClaim) + .as("only the lease in the row still says who owns a job " + id) + .isEmpty(); + } + + @Test + @DisplayName("두 인스턴스가 동시에 claim하면 겹쳐서 가져간 job이 없고 빠진 job도 없다") + void twoConcurrentClaimsShareNoJob() throws Exception { + // given + for (int i = 0; i < 40; i++) { + scheduleDueJob(); + } + CountDownLatch start = new CountDownLatch(1); + Callable> claimer = + () -> { + start.await(); + return store().claimDue(40, NOW, LEASE).stream().map(ReconciliationJob::id).toList(); + }; + ExecutorService pool = Executors.newFixedThreadPool(2); + List left; + List right; + try { + Future> first = pool.submit(claimer); + Future> second = pool.submit(claimer); + + // when + start.countDown(); + left = first.get(); + right = second.get(); + } finally { + pool.shutdownNow(); + } + + // then + Set overlap = new HashSet<>(left); + overlap.retainAll(right); + assertThat(List.of(overlap.size(), left.size() + right.size())) + .as("a job taken by both instances is asked about twice; a job taken by neither waits") + .containsExactly(0, 40); + } + + @Test + @DisplayName("lease가 지난 job은 다른 인스턴스가 다시 가져간다") + void aJobWhoseLeaseHasPassedIsClaimedAgain() { + // given + UUID id = scheduleDueJob(); + store().claimDue(10, NOW, LEASE); + + // when + List reclaimed = store().claimDue(10, NOW.plus(LEASE), LEASE); + + // then + assertThat(reclaimed) + .as("a holder that died mid-pass must not strand its jobs") + .extracting(ReconciliationJob::id) + .containsExactly(id); + } + + @Test + @DisplayName("lease가 1마이크로초라도 남은 job은 다른 인스턴스가 가져가지 못한다") + void aJobWhoseLeaseHasNotPassedIsNotClaimed() { + // given + scheduleDueJob(); + store().claimDue(10, NOW, LEASE); + + // when + List early = store().claimDue(10, NOW.plus(LEASE).minusNanos(1_000), LEASE); + + // then + assertThat(early).isEmpty(); + } + + @Test + @DisplayName("다른 인스턴스가 다시 가져간 job은 이전 소유자가 완료해도 지워지지 않는다") + void aSupersededHolderCannotCompleteTheJob() { + // given + UUID id = scheduleDueJob(); + ReconciliationJob stale = store().claimDue(10, NOW, LEASE).get(0); + store().claimDue(10, NOW.plus(LEASE), LEASE); + + // when + store().complete(stale); + + // then + assertThat(store().claimDue(10, NOW.plus(LEASE.multipliedBy(2)), LEASE)) + .as("the new holder has not answered yet, so the job is still there") + .extracting(ReconciliationJob::id) + .containsExactly(id); + } + + @Test + @DisplayName("다른 인스턴스가 다시 가져간 job은 이전 소유자의 재예약이 시도 횟수를 올리지 않는다") + void aSupersededHolderCannotRescheduleTheJob() { + // given + scheduleDueJob(); + ReconciliationJob stale = store().claimDue(10, NOW, LEASE).get(0); + store().claimDue(10, NOW.plus(LEASE), LEASE); + + // when + store().reschedule(stale, "STILL_UNKNOWN", NOW.plus(Duration.ofHours(1))); + + // then + assertThat(store().claimDue(10, NOW.plus(LEASE.multipliedBy(2)), LEASE)) + .as("two holders counting one question would reach the attempt limit early") + .extracting(ReconciliationJob::attempts) + .containsExactly(0); + } + + @Test + @DisplayName("현재 소유자가 재예약하면 claim이 풀려 lease 만료 전이라도 다음 확인 시각에 다시 나온다") + void theHoldersRescheduleReleasesTheClaim() { + // given + UUID id = scheduleDueJob(); + ReconciliationJob held = store().claimDue(10, NOW, LEASE).get(0); + Instant nextCheck = NOW.plusSeconds(30); + store().reschedule(held, "STILL_UNKNOWN", nextCheck); + + // when + List next = store().claimDue(10, nextCheck, LEASE); + + // then + assertThat(next) + .extracting( + ReconciliationJob::id, + ReconciliationJob::attempts, + job -> job.lastResult().orElseThrow()) + .containsExactly(tuple(id, 1, "STILL_UNKNOWN")); + } + + @Test + @DisplayName("현재 소유자가 완료하면 job이 지워져 다시 나오지 않는다") + void theHolderCompletesTheJob() { + // given + scheduleDueJob(); + ReconciliationJob held = store().claimDue(10, NOW, LEASE).get(0); + + // when + store().complete(held); + + // then + assertThat(store().claimDue(10, NOW.plus(Duration.ofDays(1)), LEASE)).isEmpty(); + } + + @Test + @DisplayName("같은 시도를 다시 예약하면 두 번째 job을 만들지 않고 이른 확인 시각만 남긴다") + void schedulingTheSameAttemptAgainKeepsOneJobAtTheEarlierDueTime() { + // given + DeliveryAttemptId attempt = givenAnAttempt(); + ReconciliationJob first = + store().schedule(attempt, new ProviderProfileId(PROFILE), NOW.plusSeconds(60)); + + // when + store().schedule(attempt, new ProviderProfileId(PROFILE), NOW); + + // then + assertThat(store().claimDue(10, NOW, LEASE)) + .as("an attempt recorded AMBIGUOUS twice must not queue two identical questions") + .extracting(ReconciliationJob::id, ReconciliationJob::nextCheckAt) + .containsExactly(tuple(first.id(), NOW)); + } + + private UUID scheduleDueJob() { + return store().schedule(givenAnAttempt(), new ProviderProfileId(PROFILE), NOW).id(); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/Sha256ProviderRequestIdHasher.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/Sha256ProviderRequestIdHasher.java new file mode 100644 index 00000000..28db0845 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/Sha256ProviderRequestIdHasher.java @@ -0,0 +1,32 @@ +package dev.caskeleton.application.notification.platform.dispatch.testkit; + +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.dispatch.ProviderRequestIdHasherPort; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** + * A deterministic, unkeyed stand-in for the keyed hash, for tests only. + * + *

        The stores never see the key — they are handed a hasher and compare what it returns — so a + * test needs one that every store under test shares and that produces what the columns hold: 64 + * lowercase hex characters. Scoped to the profile like the real one, so two profiles minting the + * same request id still hash apart. + */ +public final class Sha256ProviderRequestIdHasher implements ProviderRequestIdHasherPort { + + @Override + public String hash(ProviderProfileId profileId, String providerRequestId) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + digest.update(profileId.value().getBytes(StandardCharsets.UTF_8)); + digest.update((byte) 0); + digest.update(providerRequestId.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("every JVM provides SHA-256", impossible); + } + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/DeduplicationStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/DeduplicationStoreContract.java new file mode 100644 index 00000000..73ddfe82 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/DeduplicationStoreContract.java @@ -0,0 +1,125 @@ +package dev.caskeleton.application.notification.platform.policy.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.notification.platform.api.NotificationId; +import dev.caskeleton.application.notification.platform.api.TenantId; +import dev.caskeleton.application.notification.platform.policy.DeduplicationResult; +import dev.caskeleton.application.notification.platform.policy.DeduplicationStorePort; +import dev.caskeleton.application.notification.platform.policy.RecipientIdentity; +import java.util.List; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link DeduplicationStorePort} promises, run against the in-memory fake and the JPA + * store alike (review 2026-11-01 04-14). + * + *

        A window is claimed once: the first submission in it is sent, and every later one is told + * which notification it duplicates — including one that raced the first. Writes go through {@link + * #inTransaction}, because the real store refuses a claim without a caller transaction. + */ +public abstract class DeduplicationStoreContract { + + private static final RecipientIdentity RECIPIENT = + new RecipientIdentity(new TenantId("tenant-a"), "user-1", "payment.receipt"); + private static final String KEY = "order-42"; + private static final long WINDOW = 29_000_000L; + + /** The store under test, empty at the start of each test. */ + protected abstract DeduplicationStorePort store(); + + /** Runs {@code work} in one committed write transaction of the store under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + @DisplayName("window의 첫 claim은 첫 알림으로 판정된다") + void theFirstClaimOfAWindowIsFirst() { + // given + NotificationId candidate = notification(); + + // when + DeduplicationResult result = claim(RECIPIENT, WINDOW, candidate); + + // then + assertThat(result).isEqualTo(DeduplicationResult.first(candidate)); + } + + @Test + @DisplayName("같은 window의 다음 claim은 먼저 claim한 알림의 중복으로 판정된다") + void aLaterClaimOfTheSameWindowIsADuplicateOfTheFirst() { + // given + NotificationId first = notification(); + claim(RECIPIENT, WINDOW, first); + NotificationId second = notification(); + + // when + DeduplicationResult result = claim(RECIPIENT, WINDOW, second); + + // then + assertThat(result).isEqualTo(DeduplicationResult.duplicateOf(second, first)); + } + + @Test + @DisplayName("다음 window의 claim은 다시 첫 알림이다") + void aClaimInTheNextWindowIsFirstAgain() { + // given + claim(RECIPIENT, WINDOW, notification()); + NotificationId next = notification(); + + // when + DeduplicationResult result = claim(RECIPIENT, WINDOW + 1, next); + + // then + assertThat(result).isEqualTo(DeduplicationResult.first(next)); + } + + @Test + @DisplayName("다른 테넌트의 같은 수신자·키는 서로 중복이 아니다") + void anotherTenantsClaimIsNotADuplicate() { + // given + claim(RECIPIENT, WINDOW, notification()); + RecipientIdentity otherTenant = + new RecipientIdentity( + new TenantId("tenant-b"), RECIPIENT.recipientRef(), RECIPIENT.category()); + NotificationId candidate = notification(); + + // when + DeduplicationResult result = claim(otherTenant, WINDOW, candidate); + + // then + assertThat(result).isEqualTo(DeduplicationResult.first(candidate)); + } + + @Test + @DisplayName("같은 window의 claim 두 개가 겹치면 하나만 첫 알림이고 다른 하나는 그 중복이다") + void ofTwoOverlappingClaimsOneIsFirstAndTheOtherItsDuplicate() { + // given + NotificationId first = notification(); + NotificationId second = notification(); + + // when + List results = + OverlappingWrites.run( + this::inTransaction, + () -> store().insertOrFind(RECIPIENT, KEY, WINDOW, first), + () -> store().insertOrFind(RECIPIENT, KEY, WINDOW, second)); + + // then + assertThat(results) + .as("two concurrent submissions used to both conclude they were first") + .containsExactly( + DeduplicationResult.first(first), DeduplicationResult.duplicateOf(second, first)); + } + + private DeduplicationResult claim( + RecipientIdentity recipient, long window, NotificationId candidate) { + return inTransaction(() -> store().insertOrFind(recipient, KEY, window, candidate)); + } + + private static NotificationId notification() { + return new NotificationId(UUID.randomUUID()); + } +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryDeduplicationStore.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryDeduplicationStore.java new file mode 100644 index 00000000..719d4348 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/InMemoryDeduplicationStore.java @@ -0,0 +1,37 @@ +package dev.caskeleton.application.notification.platform.policy.testkit; + +import dev.caskeleton.application.notification.platform.api.NotificationId; +import dev.caskeleton.application.notification.platform.policy.DeduplicationResult; +import dev.caskeleton.application.notification.platform.policy.DeduplicationStorePort; +import dev.caskeleton.application.notification.platform.policy.RecipientIdentity; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + * The {@link DeduplicationStorePort} fake, held to {@link DeduplicationStoreContract} like the JPA + * store. + * + *

        The first claim of a window wins and every later claim of that window is told who won — the + * unique constraint {@code (tenant, recipient, category, dedup key, window)} of the real table, as + * a synchronized map. + */ +public final class InMemoryDeduplicationStore implements DeduplicationStorePort { + + private final Map winners = new HashMap<>(); + + @Override + public synchronized DeduplicationResult insertOrFind( + RecipientIdentity recipient, String dedupKey, long windowBucket, NotificationId candidate) { + Objects.requireNonNull(recipient, "recipient"); + Objects.requireNonNull(dedupKey, "dedupKey"); + Objects.requireNonNull(candidate, "candidate"); + NotificationId winner = + winners.putIfAbsent(new Window(recipient, dedupKey, windowBucket), candidate); + return winner == null + ? DeduplicationResult.first(candidate) + : DeduplicationResult.duplicateOf(candidate, winner); + } + + private record Window(RecipientIdentity recipient, String dedupKey, long windowBucket) {} +} diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/OverlappingWrites.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/OverlappingWrites.java index 7c04d6e8..6ce99191 100644 --- a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/OverlappingWrites.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/OverlappingWrites.java @@ -20,8 +20,11 @@ import java.util.function.Supplier; * only once the second has either finished or had time to block on the first's row. A store that * has no transactions simply runs the two one after the other, which is the answer it must give * anyway. + * + *

        Public because every store contract with an insert-or-find has the same race to show: the + * suppression and preference contracts here, and the admin operation claim. */ -final class OverlappingWrites { +public final class OverlappingWrites { private static final Duration SECOND_WRITE_HEAD_START = Duration.ofMillis(500); private static final Duration LIMIT = Duration.ofSeconds(30); @@ -36,7 +39,7 @@ final class OverlappingWrites { * @param second the write that starts while the first is uncommitted * @return both results; a write that failed fails this call with its cause */ - static List run( + public static List run( Function, T> inTransaction, Supplier first, Supplier second) { CountDownLatch firstWrote = new CountDownLatch(1); CountDownLatch releaseFirst = new CountDownLatch(1); diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ProviderAdapterContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider/testkit/ProviderAdapterContract.java similarity index 98% rename from src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ProviderAdapterContract.java rename to src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider/testkit/ProviderAdapterContract.java index 5c64b64a..82e29d7c 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ProviderAdapterContract.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider/testkit/ProviderAdapterContract.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.notification.platform.testkit; +package dev.caskeleton.application.notification.platform.provider.testkit; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ProviderFaultHarness.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider/testkit/ProviderFaultHarness.java similarity index 98% rename from src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ProviderFaultHarness.java rename to src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider/testkit/ProviderFaultHarness.java index 6a4e2bc8..54c1581e 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ProviderFaultHarness.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider/testkit/ProviderFaultHarness.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.notification.platform.testkit; +package dev.caskeleton.application.notification.platform.provider.testkit; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ProviderFixtures.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider/testkit/ProviderFixtures.java similarity index 98% rename from src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ProviderFixtures.java rename to src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider/testkit/ProviderFixtures.java index 8d1790dc..bb43eb6a 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/testkit/ProviderFixtures.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/provider/testkit/ProviderFixtures.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.notification.platform.testkit; +package dev.caskeleton.application.notification.platform.provider.testkit; import dev.caskeleton.application.notification.platform.api.ContactPointId; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/InMemoryTemplateRegistry.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/template/testkit/InMemoryTemplateRegistry.java similarity index 78% rename from src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/InMemoryTemplateRegistry.java rename to src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/template/testkit/InMemoryTemplateRegistry.java index a5a7f390..ae0bdd13 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/template/InMemoryTemplateRegistry.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/template/testkit/InMemoryTemplateRegistry.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.notification.platform.template; +package dev.caskeleton.application.notification.platform.template.testkit; import dev.caskeleton.application.notification.platform.api.TemplateSelection; import dev.caskeleton.application.notification.platform.api.error.FailureCategory; @@ -6,18 +6,31 @@ import dev.caskeleton.application.notification.platform.api.error.NotificationFa import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor; import dev.caskeleton.application.notification.platform.api.error.TemplateNotFoundException; import dev.caskeleton.application.notification.platform.api.routing.Channel; +import dev.caskeleton.application.notification.platform.template.NotificationTemplateVersion; +import dev.caskeleton.application.notification.platform.template.TemplateRegistry; +import dev.caskeleton.application.notification.platform.template.TemplateVersionConflictException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Optional; -/** Test registry that applies the published-is-immutable and locale-fallback rules. */ -final class InMemoryTemplateRegistry implements TemplateRegistry { +/** + * The {@link TemplateRegistry} fake, held to {@link TemplateRegistryContract} like the JPA + * registry: a published version is immutable, republishing identical content is a no-op, disabling + * keeps the version readable, and locale resolution falls back exact, language, declared fallback, + * platform default. + */ +public final class InMemoryTemplateRegistry implements TemplateRegistry { private final Map versions = new HashMap<>(); private final Locale platformDefault; - InMemoryTemplateRegistry(Locale platformDefault) { + /** + * Creates an empty registry. + * + * @param platformDefault the locale resolution ends at + */ + public InMemoryTemplateRegistry(Locale platformDefault) { this.platformDefault = platformDefault; } diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/template/testkit/TemplateRegistryContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/template/testkit/TemplateRegistryContract.java new file mode 100644 index 00000000..77e0b408 --- /dev/null +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/template/testkit/TemplateRegistryContract.java @@ -0,0 +1,157 @@ +package dev.caskeleton.application.notification.platform.template.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.notification.platform.api.TemplateSelection; +import dev.caskeleton.application.notification.platform.api.error.TemplateNotFoundException; +import dev.caskeleton.application.notification.platform.api.routing.Channel; +import dev.caskeleton.application.notification.platform.template.NotificationTemplateVersion; +import dev.caskeleton.application.notification.platform.template.TemplateContentDefinition; +import dev.caskeleton.application.notification.platform.template.TemplateRegistry; +import dev.caskeleton.application.notification.platform.template.TemplateSlot; +import dev.caskeleton.application.notification.platform.template.TemplateStatus; +import dev.caskeleton.application.notification.platform.template.TemplateVersionConflictException; +import dev.caskeleton.application.notification.platform.template.VariableSchema; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link TemplateRegistry} promises, run against the in-memory fake and the JPA registry + * alike (review 2026-11-01 04-14). + * + *

        A published version is immutable: the same content again is a no-op, different content under + * the same number is a conflict. Disabling stops new selections but keeps the version readable, + * because a retry must still render what it was pinned to. Writes go through {@link + * #inTransaction}, because the real registry refuses them without a caller transaction. + */ +public abstract class TemplateRegistryContract { + + /** The locale every registry under test resolves to last. */ + protected static final Locale PLATFORM_DEFAULT = Locale.ENGLISH; + + /** The registry under test, empty, resolving to {@link #PLATFORM_DEFAULT} last. */ + protected abstract TemplateRegistry registry(); + + /** Runs {@code work} in one committed write transaction of the registry under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + @DisplayName("게시한 버전은 같은 번호로 다른 내용을 다시 게시하면 충돌로 거부된다") + void aPublishedVersionCannotBeOverwrittenWithDifferentContent() { + // given + publish(version(Locale.KOREAN, "a".repeat(64))); + + // when + Throwable refused = catchThrowable(() -> publish(version(Locale.KOREAN, "b".repeat(64)))); + + // then + assertThat(refused).isInstanceOf(TemplateVersionConflictException.class); + } + + @Test + @DisplayName("같은 내용을 다시 게시해도 오류 없이 처음 게시한 버전이 남는다") + void republishingIdenticalContentKeepsTheFirstPublication() { + // given + publish(version(Locale.KOREAN, "a".repeat(64))); + + // when + publish(version(Locale.KOREAN, "a".repeat(64))); + + // then + assertThat(registry().get(selection(Locale.KOREAN))) + .extracting( + NotificationTemplateVersion::version, NotificationTemplateVersion::contentDigest) + .containsExactly(1L, "a".repeat(64)); + } + + @Test + @DisplayName("요청한 locale도 그 언어도 없으면 플랫폼 기본 locale 버전을 고른다") + void localeResolutionFallsBackToThePlatformDefault() { + // given + publish(version(Locale.ENGLISH, "c".repeat(64))); + + // when + NotificationTemplateVersion resolved = + registry().resolve("password-reset", 1, Channel.EMAIL, Locale.JAPANESE); + + // then + assertThat(resolved.locale()).isEqualTo(Locale.ENGLISH); + } + + @Test + @DisplayName("요청한 locale이 있으면 그 버전을 고른다") + void anExactLocaleIsResolvedToItself() { + // given + publish(version(Locale.ENGLISH, "c".repeat(64))); + publish(version(Locale.KOREAN, "d".repeat(64))); + + // when + NotificationTemplateVersion resolved = + registry().resolve("password-reset", 1, Channel.EMAIL, Locale.KOREAN); + + // then + assertThat(resolved.locale()).isEqualTo(Locale.KOREAN); + } + + @Test + @DisplayName("비활성화한 버전도 재시도와 redrive를 위해 내용째 읽힌다") + void disablingKeepsTheVersionReadableForRetryAndRedrive() { + // given + publish(version(Locale.KOREAN, "a".repeat(64))); + + // when + inTransaction( + () -> { + registry().disable("password-reset", 1); + return null; + }); + + // then + NotificationTemplateVersion stored = registry().get(selection(Locale.KOREAN)); + assertThat(List.of(stored.status(), stored.content().slot(TemplateSlot.TEXT_BODY))) + .containsExactly(TemplateStatus.DISABLED, Optional.of("code: {code}")); + } + + @Test + @DisplayName("게시한 적 없는 선택은 provider 호출 전에 템플릿 없음으로 실패한다") + void anUnknownSelectionFailsBeforeAnyProviderCall() { + // when + Throwable missing = + catchThrowable(() -> registry().get(new TemplateSelection("missing", 1, Locale.KOREAN))); + + // then + assertThat(missing).isInstanceOf(TemplateNotFoundException.class); + } + + private void publish(NotificationTemplateVersion version) { + inTransaction( + () -> { + registry().publish(version); + return null; + }); + } + + private static TemplateSelection selection(Locale locale) { + return new TemplateSelection("password-reset", 1, locale); + } + + private static NotificationTemplateVersion version(Locale locale, String digest) { + return new NotificationTemplateVersion( + "password-reset", + 1, + Channel.EMAIL, + locale, + Optional.of(Locale.ENGLISH), + VariableSchema.NONE, + new TemplateContentDefinition( + Map.of(TemplateSlot.SUBJECT, "Reset", TemplateSlot.TEXT_BODY, "code: {code}")), + TemplateStatus.PUBLISHED, + digest); + } +} diff --git a/src/application-objectstorage/build.gradle b/src/application-objectstorage/build.gradle index fa1d5162..d89e6abc 100644 --- a/src/application-objectstorage/build.gradle +++ b/src/application-objectstorage/build.gradle @@ -5,6 +5,8 @@ plugins { // Optional object-storage application product. Provider SDKs stay in outbound adapters. dependencies { implementation project(':application-core') + // Sha256 for the identity check and the content digest (review 2026-11-01 01-11). + implementation project(':shared-contract') // Property-based verification for bounded identity/value contracts moved with this product. testImplementation libs.jqwik diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbound/CallBudget.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content/CallBudget.java similarity index 83% rename from src/application-core/src/main/java/dev/caskeleton/application/outbound/CallBudget.java rename to src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content/CallBudget.java index 18857c46..521a40f6 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbound/CallBudget.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content/CallBudget.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.outbound; +package dev.caskeleton.application.objectstorage.content; import java.time.Duration; import java.util.Objects; @@ -6,6 +6,11 @@ import java.util.Objects; /** * Absolute monotonic deadline carrier for nested application calls. It is process-local and must * never be serialized as a wall-clock timestamp. + * + *

        It sits beside {@link CancellationView} because every object-storage request and content + * callback carries the two together, and object storage is its only user. It used to live in + * application-core's {@code outbound} package next to two unrelated secret types (review 2026-11-01 + * 01-10). */ public record CallBudget(long monotonicDeadlineNanos) { diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content/ObjectContentProductionContext.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content/ObjectContentProductionContext.java index d435bfa5..3df48005 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content/ObjectContentProductionContext.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content/ObjectContentProductionContext.java @@ -1,6 +1,5 @@ package dev.caskeleton.application.objectstorage.content; -import dev.caskeleton.application.outbound.CallBudget; import java.util.Objects; /** Process-local callback scope for a bounded content producer. */ diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content/ObjectContentReadContext.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content/ObjectContentReadContext.java index 698c8784..81c47d14 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content/ObjectContentReadContext.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/content/ObjectContentReadContext.java @@ -3,7 +3,6 @@ package dev.caskeleton.application.objectstorage.content; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectReadRange; -import dev.caskeleton.application.outbound.CallBudget; import java.util.Objects; /** Process-local callback scope with the validated exact read facts visible to a consumer. */ diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/identity/ObjectIdentitySupport.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/identity/ObjectIdentitySupport.java index a9ee9224..d5951b3f 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/identity/ObjectIdentitySupport.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/identity/ObjectIdentitySupport.java @@ -1,9 +1,8 @@ package dev.caskeleton.application.objectstorage.identity; +import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; final class ObjectIdentitySupport { @@ -72,13 +71,7 @@ final class ObjectIdentitySupport { } private static String sha256Hex(String value) { - try { - byte[] digest = - MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(digest); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("SHA-256 must be available", e); - } + return Sha256.ofUtf8(value).hex(); } private static IllegalArgumentException invalid(String label) { diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/model/ObjectDigest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/model/ObjectDigest.java index 8bb5d2df..bb4375a9 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/model/ObjectDigest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/model/ObjectDigest.java @@ -1,7 +1,6 @@ package dev.caskeleton.application.objectstorage.model; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import dev.caskeleton.shared.digest.Sha256; import java.util.Base64; import java.util.Objects; @@ -31,13 +30,9 @@ public record ObjectDigest(ObjectDigestAlgorithm algorithm, String base64Value) public static ObjectDigest sha256(byte[] content) { Objects.requireNonNull(content, "content must be non-null"); - try { - byte[] digest = MessageDigest.getInstance("SHA-256").digest(content); - return new ObjectDigest( - ObjectDigestAlgorithm.SHA_256, Base64.getEncoder().encodeToString(digest)); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } + return new ObjectDigest( + ObjectDigestAlgorithm.SHA_256, + Base64.getEncoder().encodeToString(Sha256.of(content).bytes())); } public byte[] decodedValue() { diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectAbortRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectAbortRequest.java index f45ed33c..cb1e217e 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectAbortRequest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectAbortRequest.java @@ -1,9 +1,9 @@ package dev.caskeleton.application.objectstorage.request; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.identity.ObjectStageHandle; -import dev.caskeleton.application.outbound.CallBudget; /** Abort request that must carry the exact application-issued authorization. */ public record ObjectAbortRequest( diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectFinalizeRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectFinalizeRequest.java index c33ae7a3..9f76cbb1 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectFinalizeRequest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectFinalizeRequest.java @@ -1,12 +1,12 @@ package dev.caskeleton.application.objectstorage.request; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.identity.ObjectStageHandle; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; import dev.caskeleton.application.objectstorage.model.ObjectModelSupport; import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement; -import dev.caskeleton.application.outbound.CallBudget; /** * Finalize is the sole staged operation allowed to mint a published reference. It carries the diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffClaimRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffClaimRequest.java index e2d3625c..740e2552 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffClaimRequest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffClaimRequest.java @@ -1,11 +1,11 @@ package dev.caskeleton.application.objectstorage.request; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.identity.ObjectStageHandle; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; import dev.caskeleton.application.objectstorage.model.ObjectModelSupport; -import dev.caskeleton.application.outbound.CallBudget; import java.time.Duration; /** Claim request that starts a monotonically fenced publication handoff lease. */ diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffReleaseRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffReleaseRequest.java index e1549998..73308258 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffReleaseRequest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffReleaseRequest.java @@ -1,10 +1,10 @@ package dev.caskeleton.application.objectstorage.request; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.identity.ObjectStageHandle; import dev.caskeleton.application.objectstorage.model.ObjectModelSupport; -import dev.caskeleton.application.outbound.CallBudget; /** Conditional release of the exact claimant/fence pair. */ public record ObjectHandoffReleaseRequest( diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffRenewRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffRenewRequest.java index d51396f6..f99ab41d 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffRenewRequest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectHandoffRenewRequest.java @@ -1,10 +1,10 @@ package dev.caskeleton.application.objectstorage.request; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.identity.ObjectStageHandle; import dev.caskeleton.application.objectstorage.model.ObjectModelSupport; -import dev.caskeleton.application.outbound.CallBudget; import java.time.Duration; /** Renewal request for the same claimant and exact monotonic handoff fence. */ diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectPublishRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectPublishRequest.java index c72bf9da..53b9d7c7 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectPublishRequest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectPublishRequest.java @@ -1,5 +1,6 @@ package dev.caskeleton.application.objectstorage.request; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.model.ObjectCapabilityRequirement; @@ -8,7 +9,6 @@ import dev.caskeleton.application.objectstorage.model.ObjectEncryptionRequiremen import dev.caskeleton.application.objectstorage.model.ObjectMediaType; import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement; import dev.caskeleton.application.objectstorage.model.ObjectRetentionRequirement; -import dev.caskeleton.application.outbound.CallBudget; import java.util.Set; /** Immutable intent for a managed scan-free publication. */ diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectReadRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectReadRequest.java index 88dd1409..33852915 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectReadRequest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectReadRequest.java @@ -1,11 +1,11 @@ package dev.caskeleton.application.objectstorage.request; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectReference; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; import dev.caskeleton.application.objectstorage.model.ObjectDigestVerification; import dev.caskeleton.application.objectstorage.model.ObjectReadRange; -import dev.caskeleton.application.outbound.CallBudget; import java.util.Objects; import java.util.Optional; diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRetireRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRetireRequest.java index adc4847b..f2baa48e 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRetireRequest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRetireRequest.java @@ -1,10 +1,10 @@ package dev.caskeleton.application.objectstorage.request; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.identity.ObjectReference; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; -import dev.caskeleton.application.outbound.CallBudget; /** Logical business retirement of one exact published reference/version. */ public record ObjectRetireRequest( diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectScanReadRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectScanReadRequest.java index 36b1866a..ba9c3862 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectScanReadRequest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectScanReadRequest.java @@ -1,11 +1,11 @@ package dev.caskeleton.application.objectstorage.request; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.identity.ObjectStageHandle; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; import dev.caskeleton.application.objectstorage.model.ObjectReadRange; -import dev.caskeleton.application.outbound.CallBudget; /** Narrow maintenance read of one exact unpublished version for a scanner workflow. */ public record ObjectScanReadRequest( diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectStageRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectStageRequest.java index 6a257c39..74e211c6 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectStageRequest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectStageRequest.java @@ -1,5 +1,6 @@ package dev.caskeleton.application.objectstorage.request; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.model.ObjectCapabilityRequirement; @@ -8,7 +9,6 @@ import dev.caskeleton.application.objectstorage.model.ObjectEncryptionRequiremen import dev.caskeleton.application.objectstorage.model.ObjectMediaType; import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement; import dev.caskeleton.application.objectstorage.model.ObjectRetentionRequirement; -import dev.caskeleton.application.outbound.CallBudget; import java.util.Set; /** Immutable unpublished-stage intent. */ diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectVerifyRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectVerifyRequest.java index eda56c8f..dd35fe13 100644 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectVerifyRequest.java +++ b/src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectVerifyRequest.java @@ -1,11 +1,11 @@ package dev.caskeleton.application.objectstorage.request; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.identity.ObjectStageHandle; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; -import dev.caskeleton.application.outbound.CallBudget; /** Full-content integrity verification request for an exact unpublished stage/version. */ public record ObjectVerifyRequest( diff --git a/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectContentContractTest.java b/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectContentContractTest.java index b97fa10a..e29cf531 100644 --- a/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectContentContractTest.java +++ b/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectContentContractTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.application.objectstorage; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.content.ObjectChunkReadException; import dev.caskeleton.application.objectstorage.content.ObjectChunkSink; @@ -12,7 +13,6 @@ import dev.caskeleton.application.objectstorage.content.ObjectContentReadContext import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectReadRange; -import dev.caskeleton.application.outbound.CallBudget; import java.time.Duration; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbound/CallBudgetTest.java b/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/content/CallBudgetTest.java similarity index 96% rename from src/application-core/src/test/java/dev/caskeleton/application/outbound/CallBudgetTest.java rename to src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/content/CallBudgetTest.java index f63ca26c..cb522d5d 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbound/CallBudgetTest.java +++ b/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/content/CallBudgetTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.outbound; +package dev.caskeleton.application.objectstorage.content; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/identity/ObjectIdentityDigestOutputTest.java b/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/identity/ObjectIdentityDigestOutputTest.java new file mode 100644 index 00000000..7acec7e0 --- /dev/null +++ b/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/identity/ObjectIdentityDigestOutputTest.java @@ -0,0 +1,54 @@ +package dev.caskeleton.application.objectstorage.identity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.objectstorage.model.ObjectDigest; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * An opaque object identity carries a check that clients and stored rows already hold, and the + * content digest is compared with what providers report. These pin the outputs against vectors + * computed outside the JVM (Python {@code hashlib}), so moving the computation onto + * shared-contract's {@code Sha256} (review 2026-11-01 01-11) cannot change them. + */ +class ObjectIdentityDigestOutputTest { + + private static final String PAYLOAD = "bucket.0123456789ab.0123456789abcdefghjkmnpqrs"; + + @Test + @DisplayName("routed identity의 check는 앞 세 부분 SHA-256 hex의 앞 10자다") + void theRoutedCheckIsTheFirstTenHexOfThePayloadsSha256() { + // when + String accepted = ObjectIdentitySupport.requireRouted(PAYLOAD + ".33cebe05f7", "bucket"); + + // then + assertThat(accepted).isEqualTo(PAYLOAD + ".33cebe05f7"); + assertThat( + catchThrowable( + () -> ObjectIdentitySupport.requireRouted(PAYLOAD + ".33cebe05f8", "bucket"))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("로그 토큰은 family와 정규 문자열 SHA-256 hex의 앞 12자다") + void theLogTokenIsTheFamilyAndTheFirstTwelveHexOfTheSha256() { + // when + String token = ObjectIdentitySupport.redactedLogToken(PAYLOAD + ".x"); + + // then + assertThat(token).isEqualTo("bucket#33844df14dda"); + } + + @Test + @DisplayName("내용 digest는 내용 SHA-256의 표준 base64다") + void theContentDigestIsTheStandardBase64Sha256() { + // when + ObjectDigest digest = ObjectDigest.sha256("hello object".getBytes(StandardCharsets.UTF_8)); + + // then + assertThat(digest.base64Value()).isEqualTo("XNkommlmTmnF4sMBUGJ5ZZCi1u1fMv6dTsHzyUY25Fc="); + } +} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java index 8df5c113..5c364cf7 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java @@ -61,20 +61,45 @@ public final class QualityConventionsPlugin implements Plugin { SpotBugsExtension spotBugs = project.getExtensions().getByType(SpotBugsExtension.class); spotBugs.getToolVersion().set(version(catalog, "spotbugs")); - // HIGH, measured (review 2026-11-01 08-07). One `qualityCheck --continue` at MEDIUM over the 53 - // analysed leaves reported 298 findings, all priority 2, against 0 at HIGH: - // 252 EI_EXPOSE_REP / EI_EXPOSE_REP2 / CT_CONSTRUCTOR_THROW — mutable-field exposure and - // throwing constructors, which records, Spring beans and fail-fast value constructors - // produce by design; - // 25 SECURITY — REDOS 11 (identifier patterns), UNSAFE_HASH_EQUALS 7 (content checksums, not - // secrets), SQL_INJECTION_* 3, PREDICTABLE_RANDOM 2 (sampling, backoff jitter), XSS 1, - // WEAK_MESSAGE_DIGEST_SHA1 1; - // 21 others — NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE 12, AT_NONATOMIC 2, RV_RETURN_VALUE 2, - // MS_EXPOSE_REP 2, BC_IMPOSSIBLE_INSTANCEOF 1, BX_UNBOXING 1, NP_NULL_ON_SOME_PATH 1. - // MEDIUM is the target once the 46 findings outside the first three patterns are each fixed in - // their owning leaf or excluded in config/spotbugs/exclude.xml with a reason, and the three - // patterns are excluded there with theirs. Until then MEDIUM would fail every pull request. - spotBugs.getReportLevel().set(Confidence.HIGH); + // MEDIUM (review 2026-11-01 08-07, decided 2026-11-03). HIGH reported 0 findings and left out + // FindSecBugs' injection, ReDoS and weak-crypto rules, which report at MEDIUM. The first MEDIUM + // run over every analysed leaf reported 307 findings, all priority 2, and each was judged + // against the code it names: "fixed" changed the code, "excluded" is a Match in + // config/spotbugs/exclude.xml that carries its reason. + // + // pattern / group found fixed excluded + // EI_EXPOSE_REP, EI_EXPOSE_REP2 196 11 185 + // non-collection references (collaborators) 97 - 97 pattern + // settings binding carriers 43 - 43 by class + // transport DTOs under adapter.inbound 23 - 23 pattern + // collection already copied at construction 20 - 20 class+field + // value type exposing mutable state 13 11 2 per site + // CT_CONSTRUCTOR_THROW 63 24 39 + // made final (21 classes) 24 24 - + // CGLIB-proxied (@RequiresPermission, @Configuration) 30 - 30 annotation + // designed for extension (exception roots, bases) 9 - 9 by class + // SECURITY: REDOS 11, UNSAFE_HASH_EQUALS 7, 25 0 25 per site + // SQL_INJECTION_* 3, PREDICTABLE_RANDOM 2, XSS 1, WEAK_MESSAGE_DIGEST_SHA1 1 + // others 23 11 12 per site + // NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE 13 (6 fixed), AT_NONATOMIC 2 (fixed), + // NP_NULL_ON_SOME_PATH 1 (fixed), BC_IMPOSSIBLE_INSTANCEOF 1 (fixed), BX_UNBOXING 1 + // (fixed), RV_RETURN_VALUE_IGNORED 2, MS_EXPOSE_REP 2, DLS_DEAD_LOCAL_STORE 1 + // total 307 46 261 + // + // Found afterwards and judged the same way (review 15절, r3-L): the optional-platforms (gRPC) + // build reads this same exclude file and had not been analysed at MEDIUM (13), and the + // httpclient retry jitter source r3-J added (1). + // USO_UNSAFE_METHOD_SYNCHRONIZATION 6 6 - + // GrpcAdmissionController: private lock object + // SECURITY: REDOS 4, UNSAFE_HASH_EQUALS 1, 7 0 7 per site + // COMMAND_INJECTION 1, PREDICTABLE_RANDOM 1 + // CT_CONSTRUCTOR_THROW (GrpcPlatformException root) 1 0 1 by class + // total 14 6 8 + // + // A new finding fails qualityCheck. Fix it, or add a Match scoped to the class and method (or + // field) with the reason it is not a defect. A pattern-wide Match needs a reason that holds for + // every class it can ever match, as the EI reference and DTO patterns state theirs. + spotBugs.getReportLevel().set(Confidence.MEDIUM); spotBugs.getExcludeFilter().set(new File(repositoryConfigDirectory, "spotbugs/exclude.xml")); // Keep local check fast; qualityCheck is the explicit bytecode-analysis lane. spotBugs.getRunOnCheck().set(false); diff --git a/src/composition/fileserver-platform/README.md b/src/composition/fileserver-platform/README.md index 61dfb73b..3f4304e6 100644 --- a/src/composition/fileserver-platform/README.md +++ b/src/composition/fileserver-platform/README.md @@ -49,3 +49,22 @@ SSOT다. 설명은 `docs/fileserver/configuration.md`. | 접근 정책 | 기본 `required`는 `FileAccessPolicyPort` bean이 있어야 한다. 아니면 `APP_FILESERVER_PLATFORM_SECURITY_ACCESS_POLICY=role-based` | 나머지(업로드·다운로드 상한, quota, cleanup, tus, nginx 위임)는 기본값으로 동작한다. + +## 필요한 마운트 + +저장 루트(`/var/lib/backend/files`)는 쓰기 가능한 전용 volume이어야 한다. 기본 이미지와 기본 +`docker-compose.yml`은 이 모듈이 없으므로 volume도 갖지 않는다(리뷰 07-08). 이 모듈을 고른 서비스가 +volume을 붙인다. + +| 실행 환경 | 붙이는 방법 | +| --- | --- | +| Compose | `-f infra/fileserver/compose/docker-compose.fileserver.yml`을 더한다. `fileserver-data` named volume을 마운트하고, 앱보다 먼저 `fileserver-storage-init`이 앱 이미지 안에서 root로 한 번 돌아 volume 소유자를 이미지의 `app` 계정으로 바꾼다(0750). 새 volume, 재사용한 volume, bind mount 모두 같다 | +| Kubernetes | PersistentVolumeClaim을 같은 경로에 마운트하고 pod `securityContext.fsGroup`을 앱 그룹으로 둔다(`infra/fileserver/kubernetes/pvc-certification-job.yaml`) | +| `docker run` | `-v :/var/lib/backend/files`. volume 소유자를 이미지의 `app` 계정으로 먼저 맞춘다 | + +소유자가 맞지 않으면 모든 쓰기가 거부되고, 저장소 probe가 기동 때 `storage root is not writable`로 +멈춘다. 루트를 다른 경로로 바꾸면(`APP_FILESERVER_PLATFORM_STORAGE_ROOT`) 마운트 경로도 함께 바꾼다. +Compose lane(`local-fileserver`, `all-adapters`)은 `compose-profile-contracts.json`에서 이 overlay와 +one-shot을 함께 가져온다. 메타데이터는 JPA로 PostgreSQL에 두므로 두 lane 모두 `db`와 JPA 모듈을 켜고, +`fileserver` schema stream을 `db-migrate-capabilities`로 설치하고 `db-promote-capabilities`로 활성화한 뒤 +앱을 띄운다. 예전 `local-fileserver`는 DB 없이 떠서 `entityManagerFactory`가 없어 기동하지 못했다. diff --git a/src/composition/fileserver-platform/build.gradle b/src/composition/fileserver-platform/build.gradle index 4a94d6f1..b46ed6b1 100644 --- a/src/composition/fileserver-platform/build.gradle +++ b/src/composition/fileserver-platform/build.gradle @@ -51,6 +51,8 @@ dependencies { dependencies { testImplementation 'org.springframework.boot:spring-boot-starter-test' + // The assembly fixture's transaction port is application-core's shared fake. + testImplementation testFixtures(project(':application-core')) testImplementation 'org.springframework.boot:spring-boot-test' testImplementation 'ch.qos.logback:logback-classic' testImplementation libs.logstash.logback.encoder diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupConfiguration.java index cc150ef7..06d897f6 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupConfiguration.java @@ -12,7 +12,11 @@ import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; /** - * Runs reclamation in the background when a deployment opts in. + * Runs reclamation in the background unless a deployment turns it off. + * + *

        On by default and when the key is absent (review 05-13): without it, nothing turns expired + * sessions into cleanup work and the volume fills. {@link FileserverCleanupDisabledConfiguration} + * warns at startup when it is off. * *

        Separate from the cleanup service itself, which the admin plane also drives on demand. The * service decides what may be deleted; this decides only whether anything drives it unattended, and @@ -24,7 +28,8 @@ import org.springframework.scheduling.annotation.SchedulingConfigurer; @ConditionalOnProperty( prefix = "app.fileserver-platform.cleanup", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) public class FileserverCleanupConfiguration { @Bean diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupDisabledConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupDisabledConfiguration.java new file mode 100644 index 00000000..4cc9551c --- /dev/null +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupDisabledConfiguration.java @@ -0,0 +1,41 @@ +package dev.caskeleton.composition.fileserver; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Makes a node without the cleanup worker say so at startup. + * + *

        The worker is on by default (review 05-13); turning it off is legitimate — another node may + * run it, or an operator drives cleanup through the admin plane — but on a single node it means + * staging leftovers and rejected content accumulate until the hard high-water mark refuses every + * upload. A warning keeps that choice visible without blocking it. + * + *

        Chosen over requiring an explicit reason key: a reason key adds a setting whose only effect is + * to silence startup, and every non-worker node of a multi-node deployment would have to carry it. + * A warning costs nothing on those nodes and still cannot be missed in a startup log. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "app.fileserver-platform.cleanup", + name = "enabled", + havingValue = "false") +public class FileserverCleanupDisabledConfiguration { + + private static final Logger LOG = + LoggerFactory.getLogger(FileserverCleanupDisabledConfiguration.class); + + @Bean + SmartInitializingSingleton fileserverCleanupDisabledWarning() { + return () -> + LOG.warn( + "app.fileserver-platform.cleanup.enabled=false: this node runs no cleanup worker. " + + "Cancelled and expired staging, rejected and deleted content stay on the volume " + + "until another node's worker or the admin plane reclaims them; with neither, " + + "uploads stop at the hard high-water mark."); + } +} diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupWorker.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupWorker.java index 60de461b..fd0a7aae 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupWorker.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCleanupWorker.java @@ -29,7 +29,7 @@ import org.slf4j.LoggerFactory; * interval — one typed and validated, one a raw string with its own default — is one declaration * too many: they drift, and the one that wins is whichever the scheduler happened to read. */ -public class FileserverCleanupWorker { +public final class FileserverCleanupWorker { private static final Logger LOG = LoggerFactory.getLogger(FileserverCleanupWorker.class); diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCorePolicyConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCorePolicyConfiguration.java index 12e29252..f2321bcc 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCorePolicyConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverCorePolicyConfiguration.java @@ -4,7 +4,11 @@ import dev.caskeleton.adapter.inbound.web.fileserver.config.FileserverWebPropert import dev.caskeleton.adapter.inbound.web.fileserver.config.TransferExecutorProperties; import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.FileserverPlatformSettings; import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.lifecycle.TargetNamespacePolicy; +import dev.caskeleton.application.fileserver.quota.NamespaceQuota; import dev.caskeleton.application.fileserver.upload.UploadPolicy; +import java.util.LinkedHashSet; +import java.util.Set; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -39,6 +43,21 @@ class FileserverCorePolicyConfiguration { properties.upload().reservationTtl(), properties.upload().leaseDuration(), StorageNamespace.of(properties.defaultNamespace()), - properties.upload().ttl()); + properties.upload().ttl(), + properties.quota().namespaceLimit() == null + ? NamespaceQuota.unlimited() + : NamespaceQuota.ofBytes(properties.quota().namespaceLimit().toBytes())); + } + + /** + * Where copies and moves may write: the upload default namespace plus any the deployment lists. + */ + @Bean + @ConditionalOnMissingBean + TargetNamespacePolicy fileserverTargetNamespacePolicy(FileserverPlatformSettings properties) { + Set allowed = new LinkedHashSet<>(); + allowed.add(StorageNamespace.of(properties.defaultNamespace())); + properties.targetNamespaces().stream().map(StorageNamespace::of).forEach(allowed::add); + return new TargetNamespacePolicy(allowed); } } diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java index ca9222d4..163f2181 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java @@ -16,6 +16,7 @@ import dev.caskeleton.application.fileserver.lifecycle.CopyContentPort; import dev.caskeleton.application.fileserver.lifecycle.CopyFileApplicationUseCase; import dev.caskeleton.application.fileserver.lifecycle.DeleteFileApplicationUseCase; import dev.caskeleton.application.fileserver.lifecycle.MoveFileApplicationUseCase; +import dev.caskeleton.application.fileserver.lifecycle.TargetNamespacePolicy; import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort; import dev.caskeleton.application.fileserver.port.in.CopyFileUseCase; import dev.caskeleton.application.fileserver.port.in.DeleteFileUseCase; @@ -97,6 +98,7 @@ class FileserverFileUseCaseConfiguration { FileMetadataPort metadataStore, CopyContentPort copyGateway, UploadPolicies policies, + TargetNamespacePolicy targetNamespaces, FileQuotaPort quotaService, TransferAdmissionController admissionController, UploadIdentifierPort identifierFactory, @@ -106,6 +108,7 @@ class FileserverFileUseCaseConfiguration { metadataStore, copyGateway, policies, + targetNamespaces, quotaService, admissionController, identifierFactory, @@ -118,7 +121,9 @@ class FileserverFileUseCaseConfiguration { MoveFileUseCase fileserverMoveFile( FileMetadataPort metadataStore, FileAccessPolicyPort accessPolicy, + TargetNamespacePolicy targetNamespaces, TransactionPort transactions) { - return new MoveFileApplicationUseCase(metadataStore, accessPolicy, transactions); + return new MoveFileApplicationUseCase( + metadataStore, accessPolicy, targetNamespaces, transactions); } } diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java index e9060f45..6b093f55 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java @@ -46,6 +46,7 @@ import org.springframework.context.annotation.Import; FileserverAdminReadUseCaseConfiguration.class, FileserverAdminActionUseCaseConfiguration.class, FileserverCleanupConfiguration.class, + FileserverCleanupDisabledConfiguration.class, // The HTTP surface itself. Its controllers used to be found by the composition root's component // scan of `dev.caskeleton.adapter`; the capability now brings them, so selecting it is enough. FileserverHttpSurfaceConfiguration.class diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadUseCaseConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadUseCaseConfiguration.java index b3ad559e..a736d640 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadUseCaseConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadUseCaseConfiguration.java @@ -139,6 +139,7 @@ class FileserverUploadUseCaseConfiguration { CleanupQueuePort cleanupQueue, RecoveryQueuePort recoveryQueue, FileAccessPolicyPort accessPolicy, + WriterLeaseCoordinator leaseCoordinator, LocalBlockingContentStore store, TransactionPort transactions, Clock clock) { @@ -151,6 +152,7 @@ class FileserverUploadUseCaseConfiguration { cleanupQueue, recoveryQueue, accessPolicy, + leaseCoordinator, store.effectivePublishMode(), transactions, clock); diff --git a/src/composition/fileserver-platform/src/main/resources/config/module-defaults/fileserver.yml b/src/composition/fileserver-platform/src/main/resources/config/module-defaults/fileserver.yml index 9b13d71c..18a02677 100644 --- a/src/composition/fileserver-platform/src/main/resources/config/module-defaults/fileserver.yml +++ b/src/composition/fileserver-platform/src/main/resources/config/module-defaults/fileserver.yml @@ -37,6 +37,9 @@ app: # gate treats the default as single-instance. instance-id: ${APP_FILESERVER_PLATFORM_INSTANCE_ID:local-node} default-namespace: ${APP_FILESERVER_PLATFORM_DEFAULT_NAMESPACE:default} + # copy·move 가 쓸 수 있는 namespace(쉼표 목록). default-namespace 는 항상 포함된다. 비우면 + # default-namespace 하나만 허용한다. 목록 밖 대상은 ACCESS_DENIED. + target-namespaces: ${APP_FILESERVER_PLATFORM_TARGET_NAMESPACES:} storage: # Absolute, on its own volume, and never under a web or configuration root. A relative path # resolves against the process working directory, which differs between a container and a @@ -88,11 +91,14 @@ app: direct-download-permits: ${APP_FILESERVER_PLATFORM_QUOTA_DIRECT_DOWNLOAD_PERMITS:64} soft-high-water: ${APP_FILESERVER_PLATFORM_QUOTA_SOFT_HIGH_WATER:0.70} hard-high-water: ${APP_FILESERVER_PLATFORM_QUOTA_HARD_HIGH_WATER:0.85} + # namespace 하나가 가질 수 있는 최대 바이트(예약+확정). 비우면 무제한. 넘으면 QUOTA_EXCEEDED(413). + namespace-limit: ${APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT:} admin: enabled: ${APP_FILESERVER_PLATFORM_ADMIN_ENABLED:false} orphan-minimum-age: ${APP_FILESERVER_PLATFORM_ADMIN_ORPHAN_MINIMUM_AGE:1h} cleanup: - enabled: ${APP_FILESERVER_PLATFORM_CLEANUP_ENABLED:false} + # true | false — 기본 on. 끄면 기동 시 WARN 로그를 남긴다(정리는 다른 노드나 admin 경로가 맡아야 한다). + enabled: ${APP_FILESERVER_PLATFORM_CLEANUP_ENABLED:true} interval: ${APP_FILESERVER_PLATFORM_CLEANUP_INTERVAL:60s} max-items: ${APP_FILESERVER_PLATFORM_CLEANUP_MAX_ITEMS:100} max-bytes: ${APP_FILESERVER_PLATFORM_CLEANUP_MAX_BYTES:1GB} diff --git a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverAssemblyFixture.java b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverAssemblyFixture.java index a507a5d4..abcb676c 100644 --- a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverAssemblyFixture.java +++ b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverAssemblyFixture.java @@ -12,6 +12,7 @@ import dev.caskeleton.application.fileserver.recovery.RecoveryQueuePort; import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort; import dev.caskeleton.application.fileserver.upload.QuotaCommitPort; import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -51,27 +52,7 @@ public abstract class FileserverAssemblyFixture { */ @Bean TransactionPort transactions() { - return new TransactionPort() { - @Override - public T inWrite(java.util.function.Supplier action) { - return action.get(); - } - - @Override - public T inRootWrite(java.util.function.Supplier action) { - return action.get(); - } - - @Override - public T inRead(java.util.function.Supplier action) { - return action.get(); - } - - @Override - public T inNew(java.util.function.Supplier action) { - return action.get(); - } - }; + return new DirectTransactionPort(); } @Bean diff --git a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverModuleDefaultsTest.java b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverModuleDefaultsTest.java index dc29acfe..4d9d1713 100644 --- a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverModuleDefaultsTest.java +++ b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverModuleDefaultsTest.java @@ -4,8 +4,11 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.support.startup.ModuleDefaultsEnvironmentPostProcessor; import java.util.Map; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.StandardEnvironment; @@ -38,6 +41,29 @@ class FileserverModuleDefaultsTest { .isEqualTo("5MB"); } + @Test + @DisplayName("파일 역할 권한 매핑은 이 모듈 기본 설정과 함께 들어오고 배포가 둔 역할과 합쳐진다") + void theFileRolePermissionsShipWithTheModuleAndMergeWithADeploymentsOwnRoles() { + // given + StandardEnvironment environment = + processed(Map.of("app.authz.role-permissions.auditor", "audit:read")); + + // when + Map bound = + Binder.get(environment) + .bind("app.authz.role-permissions", Bindable.mapOf(String.class, String.class)) + .orElse(Map.of()); + + // then + assertThat(bound) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "ROLE_FILE_READ", "file:read", + "ROLE_FILE_WRITE", "file:upload,file:delete,file:copy,file:move", + "ROLE_FILE_ADMIN", "file:admin", + "auditor", "audit:read")); + } + private static StandardEnvironment processed(Map deployment) { StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("deployment", deployment)); diff --git a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformEnvRoundTripTest.java b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformEnvRoundTripTest.java index 3f9ab250..255a14de 100644 --- a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformEnvRoundTripTest.java +++ b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformEnvRoundTripTest.java @@ -3,6 +3,8 @@ package dev.caskeleton.composition.fileserver; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.FileserverPlatformSettings; +import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder; +import dev.caskeleton.adapter.outbound.support.startup.ModuleDefaultsEnvironmentPostProcessor; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -10,7 +12,9 @@ import java.nio.file.Path; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; import org.springframework.boot.context.properties.bind.BindHandler; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; @@ -57,7 +61,8 @@ class FileserverPlatformEnvRoundTripTest { /** * The shipped defaults must be the conservative ones, in the file operators actually copy. The * master switch is on — the capability is present only where a service selected it — and every - * optional surface inside it stays off. + * optional surface inside it stays off — except the cleanup worker, whose absence is the unsafe + * choice (review 05-13). */ @Test void theShippedEnvironmentKeepsEveryOptionalSurfaceOff() { @@ -66,7 +71,8 @@ class FileserverPlatformEnvRoundTripTest { assertThat(environmentVariables) .containsEntry("APP_FILESERVER_PLATFORM_ENABLED", "true") .containsEntry("APP_FILESERVER_PLATFORM_ADMIN_ENABLED", "false") - .containsEntry("APP_FILESERVER_PLATFORM_CLEANUP_ENABLED", "false") + // The one surface that ships on: without the cleanup worker the volume fills (05-13). + .containsEntry("APP_FILESERVER_PLATFORM_CLEANUP_ENABLED", "true") .containsEntry("APP_FILESERVER_PLATFORM_TUS_ENABLED", "false") .containsEntry("APP_FILESERVER_PLATFORM_HTTPBIS_DRAFT12_ENABLED", "false") .containsEntry("APP_FILESERVER_PLATFORM_NGINX_ENABLED", "false") @@ -74,6 +80,47 @@ class FileserverPlatformEnvRoundTripTest { .containsEntry("APP_FILESERVER_PLATFORM_SECURITY_ACCESS_POLICY", "required"); } + /** + * The file operators copy, blanks included, on top of the module defaults, through the binder the + * auto-configuration uses (review 15절, r3-I). {@code QUOTA_NAMESPACE_LIMIT} ships empty — "no + * limit" — and the module default reads it through an empty placeholder, so the strict binder + * used to call the property "left unbound" and the all-adapters lane never started. + */ + @Test + @DisplayName(".env.example을 빈 값까지 그대로 env로 넣어도 strict 바인딩이 되고 빈 namespace 상한은 무제한이다") + void theShippedEnvironmentWithItsBlankValuesBindsAndAnEmptyLimitMeansNoLimit() { + // given + StandardEnvironment environment = new StandardEnvironment(); + environment + .getPropertySources() + .addFirst( + new SystemEnvironmentPropertySource( + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + shippedPlatformEnvironmentWithBlanks())); + new ModuleDefaultsEnvironmentPostProcessor() + .postProcessEnvironment(environment, new SpringApplication()); + + // when + FileserverPlatformSettings bound = + StrictSettingsBinder.bind( + environment, FileserverPlatformSettings.PREFIX, FileserverPlatformSettings.class); + + // then + assertThat(bound.quota().namespaceLimit()).isNull(); + } + + private static Map shippedPlatformEnvironmentWithBlanks() { + Map variables = new LinkedHashMap<>(); + for (String line : readEnvFile()) { + String trimmed = line.trim(); + if (trimmed.startsWith(ENV_PREFIX)) { + int separator = trimmed.indexOf('='); + variables.put(trimmed.substring(0, separator), trimmed.substring(separator + 1)); + } + } + return variables; + } + private static FileserverPlatformSettings bindStrictly(Map environmentVariables) { StandardEnvironment environment = new StandardEnvironment(); environment diff --git a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverRuntimeAssemblyTest.java b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverRuntimeAssemblyTest.java index b23742fc..de21ec56 100644 --- a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverRuntimeAssemblyTest.java +++ b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverRuntimeAssemblyTest.java @@ -48,9 +48,13 @@ import dev.caskeleton.application.fileserver.upload.UploadStoragePort; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.TaskDecorator; @@ -67,6 +71,7 @@ import org.springframework.core.task.TaskDecorator; * so replacing a storage backend or an authorization policy does not break it — what it pins is * that something satisfies each seam. */ +@ExtendWith(OutputCaptureExtension.class) class FileserverRuntimeAssemblyTest { private final ApplicationContextRunner runner = @@ -138,7 +143,8 @@ class FileserverRuntimeAssemblyTest { ListIncompleteUploadsUseCase.class, CleanupUploadsUseCase.class) .forEach(operation -> assertThat(context).doesNotHaveBean(operation)); - assertThat(context).doesNotHaveBean(FileserverCleanupWorker.class); + // The cleanup worker is on unless turned off (05-13), so the baseline has it. + assertThat(context).hasSingleBean(FileserverCleanupWorker.class); }); } @@ -206,6 +212,28 @@ class FileserverRuntimeAssemblyTest { .run(context -> assertThat(context).hasSingleBean(FileserverCleanupWorker.class)); } + /** 05-13: staging leftovers and rejected content pile up until high-water unless swept. */ + @Test + @DisplayName("cleanup 설정이 없으면 정리 worker가 기본으로 켜진다") + void theCleanupWorkerRunsWhenNothingTurnsItOff() { + enabled().run(context -> assertThat(context).hasSingleBean(FileserverCleanupWorker.class)); + } + + @Test + @DisplayName("정리 worker를 끄면 기동 시 WARN 로그로 알린다") + void aCleanupWorkerTurnedOffIsAnnouncedAtStartup(CapturedOutput output) { + enabled() + .withPropertyValues("app.fileserver-platform.cleanup.enabled=false") + .run( + context -> + assertThat( + List.of( + context.getBeanNamesForType(FileserverCleanupWorker.class).length, + output.getOut().contains("WARN") + && output.getOut().contains("app.fileserver-platform.cleanup"))) + .containsExactly(0, true)); + } + @Test void aStorageRootThatCannotBeProbedRefusesToStart() { enabled() diff --git a/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java b/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java index bbe746b1..b43ec421 100644 --- a/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java +++ b/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java @@ -65,7 +65,7 @@ public record IdempotencySettings( + responseCodecId + "'"); } - policyRevision = policyRevision == null ? 2 : policyRevision; + policyRevision = policyRevision == null ? Integer.valueOf(2) : policyRevision; if (policyRevision < 1) { throw StartupFailures.envValidation( PREFIX + ".policy-revision must be positive, was " + policyRevision); diff --git a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java index be41bed4..44156285 100644 --- a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java +++ b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java @@ -13,6 +13,7 @@ import dev.caskeleton.application.notification.platform.callback.NotificationSid import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFactory; import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; import dev.caskeleton.application.notification.platform.dispatch.DispatchOutcomeRecorder; @@ -26,6 +27,7 @@ import dev.caskeleton.application.notification.platform.dispatch.RecipientDelive import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; +import dev.caskeleton.application.notification.platform.dispatch.SuppressionSideEffect; import dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint; import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; @@ -132,6 +134,22 @@ class NotificationDeliveryConfiguration { properties.claimBatchSize()); } + /** + * What a projected hard bounce or complaint does to the contact point and the suppression list. + * + *

        An application rule over two store ports, assembled here with the other application + * services; it was a class of the persistence leaf (review 2026-11-01 04-14, r3-J). + */ + @Bean + @ConditionalOnMissingBean + NotificationSideEffectPort notificationSideEffect( + ContactPointStorePort contactPoints, + SuppressionStorePort suppressions, + NotificationIdGeneratorPort ids, + Clock clock) { + return new SuppressionSideEffect(contactPoints, suppressions, ids, clock); + } + /** Ledger projection. */ @Bean ProviderEventProjectionService providerEventProjectionService( diff --git a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java index 020d4afe..4aaf68a2 100644 --- a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java +++ b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java @@ -1,9 +1,11 @@ package dev.caskeleton.composition.notification; +import dev.caskeleton.adapter.inbound.web.notification.platform.callback.CallbackIngressUnavailableException; import dev.caskeleton.adapter.inbound.web.notification.platform.callback.ProviderCallbackHttpRequest; import dev.caskeleton.adapter.inbound.web.notification.platform.callback.ProviderCallbackIngress; import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackLimits; import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationResult; +import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationUnavailableException; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapter; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapterRegistry; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackVerificationRequest; @@ -26,6 +28,9 @@ import java.util.Objects; */ final class ProviderCallbackIngressBridge implements ProviderCallbackIngress { + private static final System.Logger LOG = + System.getLogger(ProviderCallbackIngressBridge.class.getName()); + private final ProviderCallbackAdapterRegistry adapters; private final IngestProviderCallbackUseCase ingestion; private final NotificationSecurityAuditPort securityAudit; @@ -71,7 +76,20 @@ final class ProviderCallbackIngressBridge implements ProviderCallbackIngress { request.body(), request.receivedAt()); - CallbackVerificationResult verification = adapter.verify(verificationRequest); + CallbackVerificationResult verification; + try { + verification = adapter.verify(verificationRequest); + } catch (CallbackVerificationUnavailableException unavailable) { + // Not a rejection: nothing is known about the callback yet. The provider is asked to send it + // again rather than told it was refused, which would end its retries (review 05-20). Not a + // security event either, so it is logged rather than audited. + LOG.log( + System.Logger.Level.WARNING, + "callback for profile {0} could not be verified now ({1}); asking the provider to retry", + request.providerProfileId().value(), + unavailable.reasonCode()); + throw new CallbackIngressUnavailableException(unavailable.reasonCode(), unavailable); + } if (!verification.valid()) { securityAudit.callbackSignatureRejected( request.providerProfileId(), verification.reasonCode()); 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 a628f994..959da41d 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 @@ -68,10 +68,15 @@ app: max-oldest-reconciliation-age: ${APP_NOTIFICATION_PLATFORM_MAX_OLDEST_RECONCILIATION_AGE:30m} callbacks: enabled: ${APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED:false} - # Ceiling is 65508 = the ciphertext column minus the AES-GCM nonce and tag. A larger value - # 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} + # Ceiling is 65251 = the 65536-byte ciphertext column minus the largest envelope (version + # and key-id length bytes, a key id of up to 255 bytes, the AES-GCM nonce and tag). A larger + # value is refused at binding, which stops the capability from starting; it was 65508 (nonce + # and tag only) after the envelope grew, and every lane with notification on failed to boot. + max-body-bytes: ${APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES:65251} + # SNS keeps redelivering an HTTP/S callback for up to an hour (its hard cap) with the original + # Timestamp. A shorter window drops bounces and complaints sent during an outage; a replay + # inside the window is a duplicate in the provider event ledger (review 05-20). + replay-skew: ${APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW:1h} # 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. diff --git a/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationModuleDefaultsTest.java b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationModuleDefaultsTest.java index e5b2b358..a4aa0d25 100644 --- a/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationModuleDefaultsTest.java +++ b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationModuleDefaultsTest.java @@ -2,10 +2,17 @@ package dev.caskeleton.composition.notification; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.inbound.web.notification.platform.callback.NotificationCallbackMvcController; +import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesCallbackAdapter; +import dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmCallbackPayloadProtection; import dev.caskeleton.adapter.outbound.support.startup.ModuleDefaultsEnvironmentPostProcessor; +import java.time.Duration; +import java.util.List; import java.util.Map; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; +import org.springframework.boot.convert.DurationStyle; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.StandardEnvironment; @@ -48,6 +55,71 @@ class NotificationModuleDefaultsTest { .isEqualTo("false"); } + @Test + @DisplayName("모듈 기본 콜백 replay 창은 SNS HTTP/S 재전송 최대 기간 1시간을 덮는다") + void theShippedReplayWindowCoversTheWholeSnsRetryPeriod() { + // given + StandardEnvironment environment = processed(Map.of()); + + // when + Duration window = + DurationStyle.detectAndParse( + environment.getProperty("app.notification.platform.callbacks.replay-skew")); + + // then + assertThat(window).isEqualTo(SesCallbackAdapter.SNS_HTTP_RETRY_HORIZON); + } + + @Test + @DisplayName("모듈 기본 콜백 본문 상한은 암호화 envelope를 뺀 저장 상한과 같다") + void theShippedCallbackBodyLimitIsTheLargestBodyTheColumnCanHold() { + // given + StandardEnvironment environment = processed(Map.of()); + + // when + long shipped = + Long.parseLong( + environment.getProperty("app.notification.platform.callbacks.max-body-bytes")); + + // then + assertThat(shipped) + .as( + "the settings refuse anything above the protector's ceiling, so a larger default stops" + + " the capability from starting at all") + .isEqualTo(AesGcmCallbackPayloadProtection.MAX_PLAINTEXT_BYTES); + } + + @Test + @DisplayName("콜백 endpoint의 본문 상한은 암호화 envelope를 뺀 저장 상한과 같은 수다") + void theEndpointCeilingIsTheProtectorsCeiling() { + // when + int endpointCeiling = NotificationCallbackMvcController.MAX_STORABLE_BODY_BYTES; + + // then + assertThat(endpointCeiling) + .as( + "the endpoint cannot see the protector, so this module — which assembles both — keeps" + + " the two numbers the same") + .isEqualTo(AesGcmCallbackPayloadProtection.MAX_PLAINTEXT_BYTES); + } + + @Test + @DisplayName("알림 역할 권한 매핑은 이 모듈 기본 설정과 함께 들어오고 함께 빠진다") + void theRolePermissionMappingShipsWithTheModule() { + // given + StandardEnvironment environment = processed(Map.of()); + + // when + List permissions = + List.of( + environment.getProperty("app.authz.role-permissions.notification-submit", ""), + environment.getProperty( + "app.authz.role-permissions.notification-template-publish", "")); + + // then + assertThat(permissions).containsExactly("notification:submit", "notification-template:publish"); + } + private static StandardEnvironment processed(Map deployment) { StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("deployment", deployment)); diff --git a/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridgeTest.java b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridgeTest.java index 6214dd29..fd6160b3 100644 --- a/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridgeTest.java +++ b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridgeTest.java @@ -2,10 +2,13 @@ package dev.caskeleton.composition.notification; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.adapter.inbound.web.notification.platform.callback.CallbackIngressUnavailableException; import dev.caskeleton.adapter.inbound.web.notification.platform.callback.ProviderCallbackHttpRequest; import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackLimits; import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationResult; +import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationUnavailableException; import dev.caskeleton.adapter.outbound.notification.platform.callback.MapProviderCallbackAdapterRegistry; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapter; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapterRegistry; @@ -35,6 +38,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class ProviderCallbackIngressBridgeTest { @@ -168,6 +172,27 @@ class ProviderCallbackIngressBridgeTest { assertThat(audit.limitReasons).isEmpty(); } + @Test + @DisplayName("검증 자체를 할 수 없는 콜백은 거절이 아니라 다시 보내 달라는 응답으로 바뀌고 애플리케이션에 닿지 않는다") + void aCallbackThatCannotBeVerifiedNowIsAskedForAgainAndNeverReachesTheApplication() { + // given + RecordingAdapter adapter = + RecordingAdapter.failingWith( + TWILIO, + new CallbackVerificationUnavailableException( + "SNS_CERTIFICATE_UNAVAILABLE", new java.io.IOException("unreachable"))); + RecordingAudit audit = new RecordingAudit(); + RecordingIngestion ingestion = new RecordingIngestion(); + ProviderCallbackIngressBridge bridge = bridge(adapter, ingestion, audit, 1024); + + // when + Throwable failure = catchThrowable(() -> bridge.ingest(request("application/json", "{}"))); + + // then + assertThat(List.of(failure.getClass(), audit.signatureReasons, ingestion.callbacks)) + .containsExactly(CallbackIngressUnavailableException.class, List.of(), List.of()); + } + @Test void rawHttpLimitsAreEnforcedBeforeTheProviderAdapterRuns() { RecordingAdapter adapter = new RecordingAdapter(TWILIO, true); @@ -219,6 +244,7 @@ class ProviderCallbackIngressBridgeTest { private final ProviderId providerId; private final boolean valid; + private RuntimeException failure; private int verifications; private RecordingAdapter(ProviderId providerId, boolean valid) { @@ -226,6 +252,13 @@ class ProviderCallbackIngressBridgeTest { this.valid = valid; } + /** An adapter whose verification cannot run: it throws instead of answering. */ + static RecordingAdapter failingWith(ProviderId providerId, RuntimeException failure) { + RecordingAdapter adapter = new RecordingAdapter(providerId, false); + adapter.failure = failure; + return adapter; + } + @Override public ProviderId providerId() { return providerId; @@ -234,6 +267,9 @@ class ProviderCallbackIngressBridgeTest { @Override public CallbackVerificationResult verify(ProviderCallbackVerificationRequest request) { verifications++; + if (failure != null) { + throw failure; + } return valid ? CallbackVerificationResult.valid(new VerifiedCallback(request, Map.of())) : CallbackVerificationResult.invalid("SIGNATURE_MISMATCH"); diff --git a/src/config/architecture/modules.json b/src/config/architecture/modules.json index 013dea9b..e26259d2 100644 --- a/src/config/architecture/modules.json +++ b/src/config/architecture/modules.json @@ -44,7 +44,8 @@ "gradle_path": ":application-objectstorage", "source_path": "src/application-objectstorage", "allowed_dependencies": [ - "application-core" + "application-core", + "shared-contract" ] }, { @@ -93,7 +94,8 @@ "gradle_path": ":adapter:outbound:persistence-mongo", "source_path": "src/adapter/outbound/persistence-mongo", "allowed_dependencies": [ - "application-core" + "application-core", + "shared-contract" ] }, { @@ -102,7 +104,8 @@ "source_path": "src/adapter/outbound/identifier", "allowed_dependencies": [ "domain-core", - "application-core" + "application-core", + "shared-contract" ] }, { @@ -138,7 +141,8 @@ "gradle_path": ":adapter:outbound:redis-sdk", "source_path": "src/adapter/outbound/redis-sdk", "allowed_dependencies": [ - "adapter-outbound-redis-runtime" + "adapter-outbound-redis-runtime", + "shared-contract" ] }, { @@ -215,7 +219,8 @@ "allowed_dependencies": [ "domain-core", "application-core", - "shared-contract" + "shared-contract", + "adapter-outbound-support" ] }, { @@ -364,6 +369,7 @@ "adapter-inbound-web", "shared-contract", "adapter-outbound-messaging-kafka", + "adapter-inbound-messaging", "adapter-outbound-persistence-mongo", "adapter-inbound-graphql", "adapter-outbound-httpclient", @@ -387,6 +393,7 @@ "adapter-outbound-persistence-jpa", "adapter-outbound-identifier", "adapter-outbound-objectstorage", + "adapter-outbound-support", "adapter-inbound-web", "shared-contract", "application-objectstorage", diff --git a/src/config/runtime/compose-profile-contracts.json b/src/config/runtime/compose-profile-contracts.json index a4729a4a..d0bef525 100644 --- a/src/config/runtime/compose-profile-contracts.json +++ b/src/config/runtime/compose-profile-contracts.json @@ -7,13 +7,15 @@ "local": "docker-compose.local.yml", "dev": "docker-compose.dev.yml", "prod-smoke": "docker-compose.prod-smoke.yml", - "tls": "docker-compose.tls.yml" + "tls": "docker-compose.tls.yml", + "fileserver": "infra/fileserver/compose/docker-compose.fileserver.yml" }, "$serviceRoles": "Every service a lane renders plays exactly one of three roles, and the wrapper treats them differently: longRunningServices are the only `up --wait` targets, preStartServices run with `run --rm` before the application starts because it depends on what they do, and oneShotServices run with `run --rm` after it is healthy because they exercise it. The two catalogues below name every service that is not a --wait target anywhere; a one-shot passed to `up --wait` waits forever for a container built to exit.", "preStartServices": [ "db-migrate-capabilities", "db-promote-capabilities", - "mongo-rs-init" + "mongo-rs-init", + "fileserver-storage-init" ], "oneShotServices": [ "auth-smoke", @@ -315,6 +317,9 @@ "SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_ENABLE": "true", "SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_REQUIRED": "true", "SPRING_MAIL_PROPERTIES_MAIL_SMTP_SSL_TRUST": "mailpit", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_CONNECTIONTIMEOUT": "5000", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_TIMEOUT": "10000", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_WRITETIMEOUT": "10000", "APP_NOTIFICATION_PLATFORM_SMTP_ENABLED": "true", "APP_NOTIFICATION_PLATFORM_SMTP_SENDER_IDENTITY": "no-reply@lane.test" }, @@ -381,6 +386,9 @@ "SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_ENABLE": "true", "SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_REQUIRED": "true", "SPRING_MAIL_PROPERTIES_MAIL_SMTP_SSL_TRUST": "mailpit", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_CONNECTIONTIMEOUT": "5000", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_TIMEOUT": "10000", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_WRITETIMEOUT": "10000", "APP_NOTIFICATION_PLATFORM_SMTP_ENABLED": "true", "APP_NOTIFICATION_PLATFORM_SMTP_SENDER_IDENTITY": "no-reply@lane.test" }, @@ -445,7 +453,11 @@ "activationEnv": { "APP_REDIS_ENABLED": "true", "APP_REDIS_NODES": "redis:6379", - "APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED": "true" + "APP_REDIS_NAMESPACE_ENVIRONMENT": "prod", + "APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE": "secret://ca-skeleton-application@environment/REDIS_LANE_APPLICATION_PASSWORD", + "APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE": "secret://ca-skeleton-application-advanced@environment/REDIS_LANE_ADVANCED_PASSWORD", + "REDIS_LANE_APPLICATION_PASSWORD": "fixture-application", + "REDIS_LANE_ADVANCED_PASSWORD": "fixture-advanced" }, "expectedCapabilitiesOn": [ "redis" @@ -454,17 +466,33 @@ }, { "id": "local-fileserver", + "$comment": "The Fileserver keeps its metadata in PostgreSQL through JPA (FileserverJpaPersistenceConfig needs the entityManagerFactory), so the lane without a database could never start: the application refused at startup and the lane reported an unhealthy container. PostgreSQL, the JPA module, and the fileserver schema stream installed and promoted before the application starts, the way the notification lanes get theirs.", "composeProfile": "local-fileserver", "files": [ "base", - "local" + "infra", + "local", + "fileserver" ], "springRuntime": "local", "services": [ - "app" + "app", + "db", + "db-migrate-capabilities", + "db-promote-capabilities", + "fileserver-storage-init" ], "longRunningServices": [ - "app" + "app", + "db" + ], + "preStartServices": [ + "fileserver-storage-init", + "db-migrate-capabilities", + "db-promote-capabilities" + ], + "capabilityStreams": [ + "fileserver" ], "oneShotServices": [], "blocking": true, @@ -472,12 +500,18 @@ "APP_FILESERVER_PLATFORM_ENABLED": "true", "APP_FILESERVER_PLATFORM_STORAGE_ROOT": "/var/lib/backend/files", "APP_FILESERVER_PLATFORM_SECURITY_ACCESS_POLICY": "role-based", - "APP_FILESERVER_PLATFORM_OBSERVABILITY_FINGERPRINT_KEY": "compose-contract-fileserver-key-32" + "APP_FILESERVER_PLATFORM_OBSERVABILITY_FINGERPRINT_KEY": "compose-contract-fileserver-key-32", + "APP_PERSISTENCE_JPA_ENABLED": "true", + "APP_DATASOURCE_DRIVER": "org.postgresql.Driver", + "APP_PERSISTENCE_VENDOR": "postgresql", + "APP_DATASOURCE_DDL_AUTO": "validate", + "APP_FLYWAY_ENABLED": "true" }, "expectedCapabilitiesOn": [ - "fileserver" + "fileserver", + "persistence-jpa" ], - "expectedPersistenceVendor": "none" + "expectedPersistenceVendor": "postgresql" }, { "id": "local-httpclient", @@ -643,7 +677,8 @@ "files": [ "base", "infra", - "local" + "local", + "fileserver" ], "springRuntime": "local", "services": [ @@ -652,6 +687,7 @@ "db", "db-migrate-capabilities", "db-promote-capabilities", + "fileserver-storage-init", "graphql-smoke", "kafka", "keycloak", @@ -671,12 +707,14 @@ "redis" ], "preStartServices": [ + "fileserver-storage-init", "mongo-rs-init", "db-migrate-capabilities", "db-promote-capabilities" ], "capabilityStreams": [ - "notification-platform" + "notification-platform", + "fileserver" ], "oneShotServices": [ "auth-smoke", @@ -706,12 +744,19 @@ "SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_ENABLE": "true", "SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_REQUIRED": "true", "SPRING_MAIL_PROPERTIES_MAIL_SMTP_SSL_TRUST": "mailpit", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_CONNECTIONTIMEOUT": "5000", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_TIMEOUT": "10000", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_WRITETIMEOUT": "10000", "APP_NOTIFICATION_PLATFORM_SMTP_ENABLED": "true", "APP_NOTIFICATION_PLATFORM_SMTP_SENDER_IDENTITY": "no-reply@lane.test", "APP_MESSAGING_KAFKA_BROKERS": "kafka:9092", "APP_REDIS_ENABLED": "true", "APP_REDIS_NODES": "redis:6379", - "APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED": "true", + "APP_REDIS_NAMESPACE_ENVIRONMENT": "prod", + "APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE": "secret://ca-skeleton-application@environment/REDIS_LANE_APPLICATION_PASSWORD", + "APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE": "secret://ca-skeleton-application-advanced@environment/REDIS_LANE_ADVANCED_PASSWORD", + "REDIS_LANE_APPLICATION_PASSWORD": "fixture-application", + "REDIS_LANE_ADVANCED_PASSWORD": "fixture-advanced", "APP_FILESERVER_PLATFORM_ENABLED": "true", "APP_FILESERVER_PLATFORM_STORAGE_ROOT": "/var/lib/backend/files", "APP_FILESERVER_PLATFORM_SECURITY_ACCESS_POLICY": "role-based", @@ -750,5 +795,6 @@ "redis" ], "$vendorComment": "expectedPersistenceVendor is the vendor the application must report, not the one the lane started: info.capabilities.persistence-jpa.vendor while JPA is on, none while it is off. A reported postgresql is the database the queries go to, because the JPA module refuses to start when the selected vendor is postgresql and the datasource it reaches is not PostgreSQL (JpaDataSourceProfileValidator). local-jpa passed for a while against H2 while a PostgreSQL container it never touched sat beside it, because application-local.yml pins an in-memory URL that outranks the lane's environment.", + "$redisComment": "The lanes that switch Redis on authenticate the way a deployment does. Their Redis loads infra/redis-sdk/acl/all-accounts.acl, which turns the passwordless default user off, and the application connects as the two named accounts that file provisions: ca-skeleton-application for ordinary commands and ca-skeleton-application-advanced for registered scripts. Both references use the secret://@environment/ form; without the account part the client authenticates as the disabled default user. The two REDIS_LANE_* values are that file's fixture passwords (infra/redis-sdk/acl/README.md), not deployment credentials, and deliberately carry no APP_ prefix: they are not application settings, only what these references point at. APP_REDIS_NAMESPACE_ENVIRONMENT is prod because the fixture accounts are fenced to ~prod:*, the namespace every other test against that file uses; under the default local namespace the first key a capability wrote would be refused with NOPERM after startup had reported healthy. Before this the lanes declared anonymous-access-accepted against an open Redis, and the two startup warnings that trade prints (no credential, no advanced account) failed their startup-is-silent check — which is right, because in production both are risks. scripts/verify-compose-profile-contracts.sh check 7 holds a Redis lane's references, passwords and namespace to the account lines of the file its Redis actually mounts.", "$flywayComment": "SPRING_FLYWAY_LOCATIONS is deliberately absent. Seven lanes listed every capability stream there, and it could never have worked: the db/migration/jpa/* streams each declare a V1, so one Flyway instance over all of them fails with 'Found more than one migration with version 1'. Each stream is its own stream with its own history table by design. The setting was inert until Wave 2 stopped PostgreSqlPersistenceConfig from overriding spring.flyway.locations, and the lanes passed while their own configuration was being discarded. Applying a capability stream needs a Flyway execution per stream — the operator sequence PostgreSqlNotificationPersistenceUnitIntegrationTest and FileserverRoundTripContractTest both perform in their fixtures — and that is what the notification lanes still need." } diff --git a/src/config/spotbugs/exclude.xml b/src/config/spotbugs/exclude.xml index fa2a3094..7276eb5d 100644 --- a/src/config/spotbugs/exclude.xml +++ b/src/config/spotbugs/exclude.xml @@ -84,4 +84,368 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/config/testing/container-images.properties b/src/config/testing/container-images.properties index 71a826b0..f07b29ed 100644 --- a/src/config/testing/container-images.properties +++ b/src/config/testing/container-images.properties @@ -34,6 +34,8 @@ mongo-8=mongo@sha256:4b58ebcb1dc7a7b4e84cd8ce9098d48764ae4478876898ff9551acf2ac4 mongo-7=mongo@sha256:4510cf3d7050003e958745adb25d2deb3fb907430716162d9cc1a92eda2a6047 # apache/kafka:4.1.0 kafka=apache/kafka@sha256:bff074a5d0051dbc0bbbcd25b045bb1fe84833ec0d3c7c965d1797dd289ec88f +# redis:7.4 — the cache-redis container lane; the ACL it loads is infra/redis-sdk/acl. +redis=redis@sha256:b6b6e3dc0c0952737748e55d5d885272840c7e42ba41ab1d5489f693419882f5 # ghcr.io/shopify/toxiproxy:2.12.0 toxiproxy=ghcr.io/shopify/toxiproxy@sha256:9378ed52a28bc50edc1350f936f518f31fa95f0d15917d6eb40b8e376d1a214e httpbin=kennethreitz/httpbin@sha256:599fe5e5073102dbb0ee3dbb65f049dab44fa9fc251f6835c9990f8fb196a72b diff --git a/src/grpc-advanced/CLAUDE.md b/src/grpc-advanced/CLAUDE.md index 3955a52f..12b53b24 100644 --- a/src/grpc-advanced/CLAUDE.md +++ b/src/grpc-advanced/CLAUDE.md @@ -18,6 +18,12 @@ grpc:* → grpc-advanced:* (금지 — registry가 거부한다) `grpc-spring-boot-starter`의 registry 엔트리에는 어떤 advanced id도 없다. `verifyCleanArchitectureDependencies`가 build time에 이 규칙을 강제한다. runtime 검사는 없다. +### 공용 다이제스트 헬퍼를 복사해 두는 이유 (review 2026-11-01 01-11) + +`grpc-advanced`(`GrpcDiagnosticsRedactor`)는 SHA-256 계산을 자기 안에 둔다. 의존 방향이 +`grpc-advanced:* → grpc:*`로 닫혀 있고 `shared-contract` edge가 없는 것은 의도다. `grpc/CLAUDE.md`의 +같은 절과 이유가 같다(vendored 플랫폼, MSG-023 §6.2와 같은 배치). + ## Capability grade와 feature flag capability마다 별도 flag를 갖는다. 하나의 "advanced" 스위치로 묶지 않는 이유는, gRPC-Web을 켜는 diff --git a/src/grpc/CLAUDE.md b/src/grpc/CLAUDE.md index ada4282d..19e78b30 100644 --- a/src/grpc/CLAUDE.md +++ b/src/grpc/CLAUDE.md @@ -41,6 +41,15 @@ server profile·named channel profile·method size profile·method policy 기본 `caskeleton.grpc.common.v1.generated` — 손으로 쓴 `dev.caskeleton`과 겹치지 않는다). 템플릿을 재사용할 때 바꾸는 방법은 `AGENTS.md` 「템플릿 재사용 체크리스트」에 있다. +### 공용 다이제스트 헬퍼를 복사해 두는 이유 (review 2026-11-01 01-11) + +`grpc-runtime`(`GrpcRequestFingerprint`, `GrpcResumeTokenCodec`)은 SHA-256·HMAC-SHA256 계산을 자기 +안에 둔다. 템플릿의 `shared-contract` `digest/Sha256`·`HmacSha256`을 쓰지 않는 것은 의도다. 이 +family는 optional build에 있는 vendored 플랫폼이고 registry edge는 `grpc:*` 안에서만 닫힌다(위 표). +`shared-contract` edge를 주면 플랫폼이 템플릿 계약 leaf에 묶여 따로 떼어 쓸 수 없게 된다 — messaging +family가 같은 이유로 고른 배치(MSG-023 §6.2)와 같다. 복사본을 고칠 때는 `shared-contract`의 정본과 +같은 규칙인지 함께 본다. + ## 증거 등급 — testkit이 하나의 leaf인 이유 원본 계획은 testkit을 core/in-process/netty/fault 4개 모듈로 쪼갠다. 목적은 "in-process 결과를 diff --git a/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcAdmissionController.java b/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcAdmissionController.java index a6b346c9..b0aa8e35 100644 --- a/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcAdmissionController.java +++ b/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/server/GrpcAdmissionController.java @@ -14,7 +14,10 @@ public final class GrpcAdmissionController { private final int maxQueuedCalls; // One lock for both counters: every decision reads one and changes the other, and a check on an - // atomic followed by an increment lets racing callers all pass the same check. + // atomic followed by an increment lets racing callers all pass the same check. A private object + // rather than `synchronized` methods: the controller is a shared bean, and a method that locks + // `this` waits on a monitor any holder of the reference can take, stalling every admission. + private final Object lock = new Object(); private int inFlight; private int queued; private int rejected; @@ -49,54 +52,66 @@ public final class GrpcAdmissionController { } /** Admits a call, queues it, or refuses it. */ - public synchronized Decision tryAdmit() { - if (inFlight < maxConcurrentCalls) { - inFlight++; - return new Decision(true, inFlight, queued, "within the concurrency bound"); + public Decision tryAdmit() { + synchronized (lock) { + if (inFlight < maxConcurrentCalls) { + inFlight++; + return new Decision(true, inFlight, queued, "within the concurrency bound"); + } + if (queued < maxQueuedCalls) { + queued++; + return new Decision(true, inFlight, queued, "queued within the admission bound"); + } + rejected++; + return new Decision( + false, + inFlight, + queued, + "at capacity: " + + inFlight + + " in flight and " + + queued + + " queued. Refusing is better than accepting work whose caller will have given up."); } - if (queued < maxQueuedCalls) { - queued++; - return new Decision(true, inFlight, queued, "queued within the admission bound"); - } - rejected++; - return new Decision( - false, - inFlight, - queued, - "at capacity: " - + inFlight - + " in flight and " - + queued - + " queued. Refusing is better than accepting work whose caller will have given up."); } /** Moves a queued call into execution. */ - public synchronized void promoteFromQueue() { - if (queued > 0) { - queued--; - inFlight++; + public void promoteFromQueue() { + synchronized (lock) { + if (queued > 0) { + queued--; + inFlight++; + } } } /** Releases a finished call. */ - public synchronized void release() { - if (inFlight > 0) { - inFlight--; + public void release() { + synchronized (lock) { + if (inFlight > 0) { + inFlight--; + } } } /** How many calls are executing. */ - public synchronized int inFlight() { - return inFlight; + public int inFlight() { + synchronized (lock) { + return inFlight; + } } /** How many calls are waiting. */ - public synchronized int queued() { - return queued; + public int queued() { + synchronized (lock) { + return queued; + } } /** How many calls have been refused. */ - public synchronized int rejected() { - return rejected; + public int rejected() { + synchronized (lock) { + return rejected; + } } } diff --git a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcAdmissionControllerTest.java b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcAdmissionControllerTest.java index 895fdf56..34b92609 100644 --- a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcAdmissionControllerTest.java +++ b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/server/GrpcAdmissionControllerTest.java @@ -8,6 +8,7 @@ import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; class GrpcAdmissionControllerTest { @@ -24,6 +25,27 @@ class GrpcAdmissionControllerTest { assertThat(mostAdmitted).isEqualTo(2); } + @Test + void codeHoldingTheControllersOwnMonitorDoesNotStallAdmission() throws Exception { + // given + GrpcAdmissionController controller = new GrpcAdmissionController(1, 1); + ExecutorService caller = Executors.newSingleThreadExecutor(); + Future admitted; + try { + // The controller is a shared bean: anything that holds a reference can lock it. A decision + // that waits on that monitor stalls every call the server is trying to admit. + synchronized (controller) { + // when + admitted = caller.submit(() -> controller.tryAdmit().admitted()); + + // then + assertThat(admitted.get(5, TimeUnit.SECONDS)).isTrue(); + } + } finally { + caller.shutdownNow(); + } + } + /** Races {@link #CALLERS} callers at a 1-running, 1-queued controller, round after round. */ private static int mostAdmittedOverRounds() throws Exception { ExecutorService pool = Executors.newFixedThreadPool(CALLERS); diff --git a/src/messaging/CLAUDE.md b/src/messaging/CLAUDE.md index 14c58e87..8c8d2acf 100644 --- a/src/messaging/CLAUDE.md +++ b/src/messaging/CLAUDE.md @@ -30,6 +30,16 @@ leaf의 정확한 id는 registry에서 읽는다. family는 **디렉터리 이 JDBC이고 SQL은 `jsonb` · `FOR UPDATE SKIP LOCKED` · `ON CONFLICT` · `TIMESTAMPTZ`로 PostgreSQL 전용이다. `jpa`라는 이름은 사용하지 않는 기술을 광고하고, vendor 중립 port가 어디 있는지도 숨겼다. +### 공용 다이제스트 헬퍼를 복사해 두는 이유 (review 2026-11-01 01-11) + +`messaging-admin`(`HmacApprovalVerifier`, `PlanDigest`)과 `messaging-claim-check` +(`ClaimCheckIntegrityGuard`)는 SHA-256·HMAC-SHA256 계산을 자기 안에 둔다. 템플릿의 +`shared-contract` `digest/Sha256`·`HmacSha256`을 쓰지 않는 것은 의도다. 이 family는 이 애플리케이션의 +계층이 아니라 자기 API·SPI·composition을 가진 다른 제품이고(MSG-023 §6.2), `messaging:*` leaf는 +`domain-core`·`application-core`·`shared-contract` 어느 타입에도 의존하지 않는다. 헬퍼 하나 때문에 +registry edge를 주면 그 경계가 깨진다. 복사본을 고칠 때(키 길이 검사, constant-time 비교 등)는 +`shared-contract`의 정본과 같은 규칙인지 함께 본다. + ## Public surface 정책 - **vendor 타입을 public signature에 노출하면 그 의존성은 `api`로 선언한다.** 숨긴다고 타입이 diff --git a/src/messaging/messaging-core-api/src/main/java/dev/caskeleton/messaging/api/delivery/MessageHandler.java b/src/messaging/messaging-core-api/src/main/java/dev/caskeleton/messaging/api/delivery/MessageHandler.java index 0abdc895..5e3c3c34 100644 --- a/src/messaging/messaging-core-api/src/main/java/dev/caskeleton/messaging/api/delivery/MessageHandler.java +++ b/src/messaging/messaging-core-api/src/main/java/dev/caskeleton/messaging/api/delivery/MessageHandler.java @@ -1,6 +1,8 @@ package dev.caskeleton.messaging.api.delivery; +import dev.caskeleton.messaging.api.SchemaVersion; import dev.caskeleton.messaging.api.destination.MessageDestination; +import java.util.Set; import java.util.concurrent.CompletionStage; /** @@ -28,6 +30,26 @@ public interface MessageHandler { */ MessageDestination destination(); + /** + * The schema versions of {@link #destination()}'s message type that its payload class reads. + * + *

        This declaration is the consumer's whole registration. The platform decodes a delivery only + * against a contract — message type and schema version — it knows the payload class for, and it + * builds that list from the handler beans: each version here, with the destination's message + * type, decodes into the destination's payload class. A service writes no registration code of + * its own, so a handler cannot exist while its messages are dead-lettered as undecodable for want + * of one. + * + *

        A version the handler does not name is still refused ({@code SCHEMA_VERSION_NOT_REGISTERED}) + * rather than decoded into a class written for another version. A handler that reads a second + * version says so here when the producer starts sending it. + * + * @return the versions this handler reads; version 1 unless it declares otherwise + */ + default Set schemaVersions() { + return Set.of(new SchemaVersion(1)); + } + /** * Handles one delivery. * diff --git a/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/InboxMessageHandler.java b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/InboxMessageHandler.java index 23c230f9..0bd0055a 100644 --- a/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/InboxMessageHandler.java +++ b/src/messaging/messaging-reliability/src/main/java/dev/caskeleton/messaging/inbox/InboxMessageHandler.java @@ -1,11 +1,13 @@ package dev.caskeleton.messaging.inbox; +import dev.caskeleton.messaging.api.SchemaVersion; import dev.caskeleton.messaging.api.delivery.HandleResult; import dev.caskeleton.messaging.api.delivery.MessageDelivery; import dev.caskeleton.messaging.api.delivery.MessageHandler; import dev.caskeleton.messaging.api.destination.MessageDestination; import java.time.Instant; import java.util.Objects; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; @@ -71,6 +73,11 @@ public final class InboxMessageHandler implements MessageHandler { return delegate.destination(); } + @Override + public Set schemaVersions() { + return delegate.schemaVersions(); + } + @Override public CompletionStage handle(MessageDelivery delivery) { Objects.requireNonNull(delivery, "delivery must not be null"); diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessageContracts.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessageContracts.java index 82f9721c..212ac85e 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessageContracts.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessageContracts.java @@ -1,11 +1,17 @@ package dev.caskeleton.messaging.autoconfigure; +import dev.caskeleton.messaging.api.SchemaVersion; +import dev.caskeleton.messaging.api.delivery.MessageHandler; +import dev.caskeleton.messaging.api.destination.MessageDestination; +import dev.caskeleton.messaging.api.error.MessagingConfigurationException; import dev.caskeleton.messaging.schema.MessageContractKey; +import java.util.Collection; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; /** - * What this deployment publishes: message type and schema version to payload class. + * The deployment's message contracts: message type and schema version to payload class. * *

        A named holder rather than a bare {@code Map} bean, because {@code Map} is not a neutral * injection type in Spring — a {@code Map} injection point is interpreted as "every bean of @@ -13,6 +19,12 @@ import java.util.Objects; * into something nobody wrote. A holder makes the intent unambiguous to the container and to a * reader. * + *

        A deployment registers what it publishes as a bean of this type. What it + * consumes it does not register at all: {@link #withConsumed} adds each handler bean's own + * declaration, so the codec decodes exactly what some handler said it reads (review 2026-11-01 + * 06-08 follow-up). A consumer whose payload type had to be registered here as well was a consumer + * whose messages were dead-lettered as undecodable whenever that second step was forgotten. + * *

        Empty is the default and it is fail-closed: no message type can be encoded, and every publish * is refused at preparation. A codec that accepted an unregistered type would serialise whatever * object it was handed onto a topic that consumers compiled against a different shape will read — @@ -32,4 +44,43 @@ public record MessageContracts(Map> byKey) { public static MessageContracts none() { return new MessageContracts(Map.of()); } + + /** + * These contracts plus every contract the given handlers consume. + * + *

        A handler names its message type and payload class in {@link MessageHandler#destination()} + * and the schema versions that class reads in {@link MessageHandler#schemaVersions()}; each + * version is one contract. The same contract declared twice with the same class is one entry. + * + * @param handlers the deployment's handler beans + * @return the combined contracts + * @throws MessagingConfigurationException when two declarations give one contract different + * payload classes — the codec holds one class per contract, so one of them would decode every + * message of that type into the wrong shape + */ + public MessageContracts withConsumed(Collection> handlers) { + Map> combined = new LinkedHashMap<>(byKey); + for (MessageHandler handler : handlers) { + MessageDestination destination = handler.destination(); + for (SchemaVersion version : handler.schemaVersions()) { + MessageContractKey key = new MessageContractKey(destination.messageType(), version); + Class declared = destination.payloadType(); + Class existing = combined.putIfAbsent(key, declared); + if (existing != null && !existing.equals(declared)) { + throw new MessagingConfigurationException( + "MESSAGING_CONTRACT_CONFLICT", + "contract " + + key.describe() + + " is declared as " + + existing.getName() + + " and as " + + declared.getName() + + " (handler for destination '" + + destination.name().value() + + "'); one contract decodes into one payload class"); + } + } + } + return new MessageContracts(combined); + } } diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationCompiler.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationCompiler.java index 2a24d32b..fd46dd1c 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationCompiler.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationCompiler.java @@ -24,7 +24,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.function.Supplier; /** * Turns the documented configuration into the objects the platform already validates. @@ -222,10 +221,9 @@ public final class MessagingConfigurationCompiler { broker.production(), broker.tlsEnabled(), security.hostnameVerification(), - credential(name, "producer", security.producer(), () -> true), - credential(name, "consumer", security.consumer(), () -> true), - Optional.ofNullable(security.admin()) - .map(admin -> credential(name, "admin", admin, () -> true)), + credential(name, "producer", security.producer()), + credential(name, "consumer", security.consumer()), + Optional.ofNullable(security.admin()).map(admin -> credential(name, "admin", admin)), new DestinationAccessPolicy( destinationNames(security.access().publishable()), destinationNames(security.access().consumable()), @@ -248,11 +246,11 @@ public final class MessagingConfigurationCompiler { } private static BrokerCredentialProfile credential( - String broker, - String role, - BrokerSecuritySettings.Credential credential, - Supplier required) { - if (credential == null && Boolean.TRUE.equals(required.get())) { + String broker, String role, BrokerSecuritySettings.Credential credential) { + // Every role that reaches here is required: the optional admin role is filtered out by its + // caller before the call. A "not required" branch would have nothing to return and fell + // through to dereference the missing credential. + if (credential == null) { throw configurationError( key("security", broker, role), "a configured broker needs a %s credential; the roles are separate so that a compromised " diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingEndpoint.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingEndpoint.java index 666cb4e7..79f85184 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingEndpoint.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingEndpoint.java @@ -23,7 +23,7 @@ import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; * re-identification surface too. */ @Endpoint(id = "messaging") -public class MessagingEndpoint { +public final class MessagingEndpoint { private final ValidatedDestinationRegistry registry; private final MessagingAdmissionController admission; diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingPublishConfiguration.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingPublishConfiguration.java index 79995f1b..471e32e4 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingPublishConfiguration.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingPublishConfiguration.java @@ -98,16 +98,26 @@ public class MessagingPublishConfiguration { * that accepted an unregistered type would serialise whatever object it was handed and put bytes * on a topic that consumers compiled against a different shape will read. * + *

        To those the handler beans add what they consume ({@link MessageContracts#withConsumed}): + * the decode list is what the handlers declare, so a service registers nothing to consume. The + * handlers are resolved here, so a handler whose own dependencies reach back to the publisher is + * a dependency cycle, and Spring refuses it at startup naming both beans. + * * @param contracts the declared message contracts, if the deployment registered any + * @param handlers the deployment's message handlers, whose declarations are decoded * @return the registry, defaulting to JSON */ @Bean @ConditionalOnMissingBean(dev.caskeleton.messaging.schema.MessageCodecRegistry.class) public dev.caskeleton.messaging.runtime.RegisteredMessageCodecs messagingCodecs( - ObjectProvider contracts) { + ObjectProvider contracts, + ObjectProvider> handlers) { return dev.caskeleton.messaging.runtime.RegisteredMessageCodecs.of( dev.caskeleton.messaging.schema.json.JacksonMessageCodec.of( - contracts.getIfAvailable(MessageContracts::none).byKey())); + contracts + .getIfAvailable(MessageContracts::none) + .withConsumed(handlers.orderedStream().toList()) + .byKey())); } /** diff --git a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingConsumeConfigurationTest.java b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingConsumeConfigurationTest.java index b8471f83..59766248 100644 --- a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingConsumeConfigurationTest.java +++ b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingConsumeConfigurationTest.java @@ -1,13 +1,23 @@ package dev.caskeleton.messaging.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.messaging.api.ContentType; import dev.caskeleton.messaging.api.MessageType; +import dev.caskeleton.messaging.api.SchemaVersion; import dev.caskeleton.messaging.api.delivery.HandleResult; import dev.caskeleton.messaging.api.delivery.MessageDelivery; import dev.caskeleton.messaging.api.delivery.MessageHandler; import dev.caskeleton.messaging.api.destination.DestinationName; import dev.caskeleton.messaging.api.destination.MessageDestination; +import dev.caskeleton.messaging.api.error.MessageValidationException; +import dev.caskeleton.messaging.schema.MessageCodec; +import dev.caskeleton.messaging.schema.MessageCodecRegistry; +import dev.caskeleton.messaging.schema.MessageContractKey; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.junit.jupiter.api.DisplayName; @@ -100,6 +110,122 @@ class MessagingConsumeConfigurationTest { .hasMessageContaining("IdempotentConsumer")); } + @Test + @DisplayName("handler bean이 선언한 메시지 타입과 payload class는 따로 등록하지 않아도 decode된다") + void aHandlerBeansDeclaredContractIsDecodedWithoutAnyRegistration() { + // given: a handler for order.created and no MessageContracts bean at all + var consuming = + runner + .withPropertyValues("app.messaging.destinations.order-events.consumer.group=projection") + .withBean( + "ordersHandler", + MessageHandler.class, + () -> handler(OrderCreated.class, Set.of(new SchemaVersion(1)))); + + // when + consuming.run( + context -> { + OrderCreated decoded = + json(context.getBean(MessageCodecRegistry.class)) + .decode( + new MessageType("order.created"), + new SchemaVersion(1), + "{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8), + OrderCreated.class); + + // then + assertThat(decoded).isEqualTo(new OrderCreated("o-1")); + }); + } + + @Test + @DisplayName("handler가 선언하지 않은 schema version은 그 class로 decode하지 않고 거부한다") + void aSchemaVersionTheHandlerDoesNotDeclareIsRefused() { + // given: the handler reads version 1 only + var consuming = + runner + .withPropertyValues("app.messaging.destinations.order-events.consumer.group=projection") + .withBean( + "ordersHandler", + MessageHandler.class, + () -> handler(OrderCreated.class, Set.of(new SchemaVersion(1)))); + + // when + consuming.run( + context -> { + Throwable refused = + catchThrowable( + () -> + json(context.getBean(MessageCodecRegistry.class)) + .decode( + new MessageType("order.created"), + new SchemaVersion(2), + "{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8), + OrderCreated.class)); + + // then + assertThat(refused) + .isInstanceOf(MessageValidationException.class) + .hasMessageContaining("order.created v2"); + }); + } + + @Test + @DisplayName("등록된 계약과 handler가 같은 type·version에 다른 class를 선언하면 기동을 거부한다") + void aHandlerThatDeclaresAnotherClassForARegisteredContractFailsStartup() { + // given: order.created v1 registered as String, and a handler reading it as OrderCreated + var conflicting = + runner + .withPropertyValues("app.messaging.destinations.order-events.consumer.group=projection") + .withBean( + MessageContracts.class, + () -> + new MessageContracts( + Map.of(MessageContractKey.of("order.created", 1), String.class))) + .withBean( + "ordersHandler", + MessageHandler.class, + () -> handler(OrderCreated.class, Set.of(new SchemaVersion(1)))); + + // when + conflicting.run( + context -> + // then + assertThat(context) + .hasFailed() + .getFailure() + .rootCause() + .hasMessageContaining("order.created v1") + .hasMessageContaining(OrderCreated.class.getName())); + } + + /** The payload a consumer of {@code order.created} reads. */ + record OrderCreated(String orderId) {} + + private static MessageCodec json(MessageCodecRegistry codecs) { + return codecs.find(ContentType.JSON).orElseThrow(); + } + + private static MessageHandler handler(Class payload, Set versions) { + return new MessageHandler<>() { + @Override + public MessageDestination destination() { + return new MessageDestination<>( + new DestinationName("order-events"), new MessageType("order.created"), payload); + } + + @Override + public Set schemaVersions() { + return versions; + } + + @Override + public CompletionStage handle(MessageDelivery delivery) { + return CompletableFuture.completedFuture(HandleResult.success()); + } + }; + } + private static MessageHandler handler() { return new MessageHandler<>() { @Override diff --git a/src/sample-portfolio/README.md b/src/sample-portfolio/README.md index abb91fae..fd427c76 100644 --- a/src/sample-portfolio/README.md +++ b/src/sample-portfolio/README.md @@ -48,6 +48,11 @@ 비밀번호가 문서에 적혀 있는 공개 데모 계정입니다. 비밀이 아니며, 실제 서비스는 이 방식을 쓰지 않고 `adapter:inbound:web`의 JWT 체인으로 인증합니다. +그래서 `prod` 프로필로 띄우면 기동을 거부합니다(`SampleDemoAccountsProductionGuard`, 종료 코드 71). +샘플을 복제해 운영에 올릴 때 이 계정이 남아 있으면 누구나 관리자로 들어올 수 있기 때문입니다. 운영으로 +가져가려면 `SampleDemoSecurityConfig`·`SampleDemoAccounts`를 지우고 `SamplePortfolioApplication`에서 +`WebSecurityAutoConfiguration` 제외를 풉니다. 이 규칙은 데모 설정 옆에 선언되어 있어 함께 지워집니다. + ## 샘플 데이터 (curl 예시) ```bash diff --git a/src/sample-portfolio/build.gradle b/src/sample-portfolio/build.gradle index 4b96569f..d1b079e4 100644 --- a/src/sample-portfolio/build.gradle +++ b/src/sample-portfolio/build.gradle @@ -71,6 +71,9 @@ dependencies { // extend the module's audit base types. implementation project(':adapter:outbound:persistence-jpa') implementation project(':adapter:outbound:identifier') + // The startup-rule SPI: the demo accounts refuse the prod profile through the same runner every + // module's startup rules use (SampleDemoAccountsProductionGuard). + implementation project(':adapter:outbound:support') // Object storage adapter provides the canonical staged-publication ports (declared in // application-objectstorage) the poster image publication use cases run on. runtimeOnly project(':adapter:outbound:objectstorage') 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 d9416379..1cd25fed 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 @@ -3,13 +3,13 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.controller; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; import dev.caskeleton.adapter.inbound.web.http.IdempotencyKeyHeader; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectDigest; import dev.caskeleton.application.objectstorage.model.ObjectDigestAlgorithm; import dev.caskeleton.application.objectstorage.model.ObjectMediaType; -import dev.caskeleton.application.outbound.CallBudget; import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.PosterImagePublicationResponse; import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.PosterImagePublicationStatusResponse; import dev.caskeleton.sample.portfolio.adapter.inbound.web.mapper.PosterImagePublicationWebMapper; diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntity.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntity.java index 046437fd..05dad415 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntity.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntity.java @@ -16,6 +16,7 @@ import jakarta.persistence.Table; import jakarta.persistence.Version; import java.time.LocalDate; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.UUID; import org.hibernate.annotations.JdbcTypeCode; @@ -183,12 +184,14 @@ public class WorkLogEntity extends AuditableEntity { return content; } + // Read-only views of the managed collections. They change only through replaceState, which + // leaves an unchanged collection alone; a writable getter would let a reader bypass that. public List getTechStack() { - return techStack; + return Collections.unmodifiableList(techStack); } public List getLinks() { - return links; + return Collections.unmodifiableList(links); } public LocalDate getPeriodStart() { diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/AbortPosterImageUploadCommand.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/AbortPosterImageUploadCommand.java index c1508d78..7ace7145 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/AbortPosterImageUploadCommand.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/AbortPosterImageUploadCommand.java @@ -1,9 +1,9 @@ package dev.caskeleton.sample.portfolio.application.posterimage; import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; -import dev.caskeleton.application.outbound.CallBudget; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; public record AbortPosterImageUploadCommand( diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PublishPosterImageCommand.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PublishPosterImageCommand.java index e4b67520..5114ef4d 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PublishPosterImageCommand.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PublishPosterImageCommand.java @@ -1,11 +1,11 @@ package dev.caskeleton.sample.portfolio.application.posterimage; import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectMediaType; -import dev.caskeleton.application.outbound.CallBudget; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import java.util.Objects; diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/ReconcilePosterImageRetirementCommand.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/ReconcilePosterImageRetirementCommand.java index 838925a1..adfff0a8 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/ReconcilePosterImageRetirementCommand.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/ReconcilePosterImageRetirementCommand.java @@ -1,8 +1,8 @@ package dev.caskeleton.sample.portfolio.application.posterimage; import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; -import dev.caskeleton.application.outbound.CallBudget; import java.time.Duration; /** One bounded worker claim/reconcile attempt. */ diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/ReconcilePosterImageUploadCommand.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/ReconcilePosterImageUploadCommand.java index 0792811c..9f3b3b54 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/ReconcilePosterImageUploadCommand.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/ReconcilePosterImageUploadCommand.java @@ -1,9 +1,9 @@ package dev.caskeleton.sample.portfolio.application.posterimage; import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; -import dev.caskeleton.application.outbound.CallBudget; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; public record ReconcilePosterImageUploadCommand( diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageRetirementJob.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageRetirementJob.java index f8af1304..8b68aa27 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageRetirementJob.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageRetirementJob.java @@ -1,7 +1,7 @@ package dev.caskeleton.sample.portfolio.bootstrap.objectstorage; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; -import dev.caskeleton.application.outbound.CallBudget; import dev.caskeleton.sample.portfolio.application.posterimage.ReconcilePosterImageRetirementCommand; import dev.caskeleton.sample.portfolio.application.posterimage.ReconcilePosterImageRetirementUseCase; import org.springframework.scheduling.annotation.Scheduled; diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java new file mode 100644 index 00000000..5d64db3b --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java @@ -0,0 +1,52 @@ +package dev.caskeleton.sample.portfolio.bootstrap.security; + +import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupRule; +import java.util.List; +import org.springframework.core.env.Environment; + +/** + * Refuses the {@code prod} profile while the {@link SampleDemoAccounts} authenticate requests. + * + *

        The demo accounts are published on purpose: each password is the account name and the sample + * README prints both, so a reader can watch {@code @RequiresPermission} allow one caller and refuse + * another. That is harmless in a demo and an open admin account anywhere else. The sample is also + * the code adopters copy first, so the copy that matters is the one that reaches a production + * deployment with this configuration still in it. The README says not to; this rule makes the + * deployment say so too, before any datasource, migration or listener is created. + * + *

        "Production" is the template's own answer ({@link RuntimeProfileSnapshot#isProduction()}), not + * a profile name compared here, so the sample and every module agree on what it means. The rule is + * declared beside the accounts in {@link SampleDemoSecurityConfig}: replacing the demo chain with a + * real one removes the refusal with it. + */ +final class SampleDemoAccountsProductionGuard implements StartupRule { + + @Override + public StartupPhase phase() { + return StartupPhase.PROFILE_CHECK; + } + + @Override + public String summary() { + return "the sample's demo accounts must not authenticate under the prod profile"; + } + + @Override + public String remedy() { + return "run the sample under local or dev; a production service authenticates through the JWT" + + " chain — delete SampleDemoSecurityConfig and SampleDemoAccounts and stop excluding" + + " WebSecurityAutoConfiguration in SamplePortfolioApplication"; + } + + @Override + public List violations(Environment environment) { + if (!RuntimeProfileSnapshot.from(environment).isProduction()) { + return List.of(); + } + return List.of( + "demo-user and demo-admin sign in over HTTP Basic, each password is the account name, and" + + " the sample README prints both — anyone could act as an admin"); + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java index a9b99884..0fad9aab 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java @@ -2,6 +2,7 @@ package dev.caskeleton.sample.portfolio.bootstrap.security; import dev.caskeleton.adapter.inbound.web.auth.EnvelopeAuthenticationEntryPoint; import dev.caskeleton.adapter.inbound.web.auth.SecurityErrorClassifier; +import dev.caskeleton.adapter.outbound.support.startup.StartupRule; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -23,6 +24,9 @@ import tools.jackson.databind.ObjectMapper; * decided here: method security stays on ({@code WebMethodSecurityAutoConfiguration}), so each * {@code @RequiresPermission} is checked against {@code app.authz} exactly as it is for a JWT * caller. This chain only answers who the caller is. + * + *

        The accounts are public, so they refuse the prod profile at startup ({@link + * SampleDemoAccountsProductionGuard}). */ @Configuration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @@ -43,6 +47,20 @@ public class SampleDemoSecurityConfig { return new SampleDemoAccounts(); } + /** + * Refuses to start under the prod profile while these accounts are the way in. + * + *

        Static and argument-free, as every startup rule is: the support module's runner creates it + * before any other singleton, so a production start is refused before a datasource opens or a + * migration runs. Declared here, beside the accounts, so the refusal leaves with them. + * + * @return the rule + */ + @Bean + public static StartupRule sampleDemoAccountsProductionGuard() { + return new SampleDemoAccountsProductionGuard(); + } + @Bean @Order(-100) public SecurityFilterChain sampleDemoSecurityFilterChain(HttpSecurity http, ObjectMapper json) 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 f03004d4..1777469d 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 @@ -15,7 +15,7 @@ import java.util.Objects; * store persists it. Mirrors {@code WorkLog}. */ @AggregateRoot -public class Poster { +public final class Poster { private final PosterId id; private String title; diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLog.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLog.java index c3fa7313..c5fff539 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLog.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLog.java @@ -11,7 +11,7 @@ import java.util.Objects; * WorkLogInvariantException}. See README for the design rationale. */ @AggregateRoot -public class WorkLog { +public final class WorkLog { private static final WorkLogOwner DEFAULT_OWNER = WorkLogOwner.of("sample-owner"); diff --git a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/WorkLogStatementCostSystemTest.java b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/WorkLogStatementCostSystemTest.java index 043c66da..b523fb33 100644 --- a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/WorkLogStatementCostSystemTest.java +++ b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/WorkLogStatementCostSystemTest.java @@ -113,8 +113,8 @@ class WorkLogStatementCostSystemTest { * and insert ordering, every table travels fifty rows per round trip: work_log 2 + tech-stack 4 + * link 2 = 8. The element-collection rows batch across owners because the work logs are new * entities persisted, not merged ({@code Persistable}, review 04-17); before that each owner's - * collection rows went alone and the count was 202. The number pins the whole shape: a - * regression to per-owner collection inserts shows as 202, to row-by-row as 400. + * collection rows went alone and the count was 202. The number pins the whole shape: a regression + * to per-owner collection inserts shows as 202, to row-by-row as 400. */ @Test void batchCreatingAHundredWorkLogsSendsTheWorkLogRowsInJdbcBatches() throws Exception { diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducerTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducerTest.java index a1b15cfd..7fda2bea 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducerTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducerTest.java @@ -5,12 +5,12 @@ import static org.assertj.core.api.Assertions.catchThrowable; import static org.junit.jupiter.api.Named.named; import static org.junit.jupiter.params.provider.Arguments.arguments; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.content.ObjectContentProductionContext; import dev.caskeleton.application.objectstorage.content.ObjectContentProductionException; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectDigest; -import dev.caskeleton.application.outbound.CallBudget; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntityTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntityTest.java new file mode 100644 index 00000000..8aa42679 --- /dev/null +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/WorkLogEntityTest.java @@ -0,0 +1,47 @@ +package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.entity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus; +import java.time.LocalDate; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The entity changes its element collections only through {@code replaceState}, which leaves an + * unchanged collection untouched so Hibernate does not delete and re-insert every row. A getter + * that handed out the managed collection would let any reader change it behind that rule. + */ +class WorkLogEntityTest { + + @Test + @DisplayName("getLinks()로 받은 목록으로는 엔티티의 링크를 바꿀 수 없다") + void theLinksAReaderReceivesCannotChangeTheEntity() { + // given + WorkLogEntity entity = + new WorkLogEntity( + UUID.randomUUID(), + "owner", + "title", + WorkCategory.BACKEND, + WorkLogStatus.OPEN, + "summary", + "content", + List.of("java"), + List.of("https://example.org"), + LocalDate.of(2026, 1, 1), + null, + null); + + // when + Throwable refused = catchThrowable(() -> entity.getLinks().add("https://elsewhere.org")); + + // then + assertThat(refused).isInstanceOf(UnsupportedOperationException.class); + assertThat(entity.getLinks()).containsExactly("https://example.org"); + } +} diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAbortReconcileRaceTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAbortReconcileRaceTest.java index 9817493d..04b983ac 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAbortReconcileRaceTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAbortReconcileRaceTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; @@ -34,7 +35,6 @@ import dev.caskeleton.application.objectstorage.request.ObjectHandoffReleaseRequ import dev.caskeleton.application.objectstorage.request.ObjectHandoffRenewRequest; import dev.caskeleton.application.objectstorage.request.ObjectStageRequest; import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; -import dev.caskeleton.application.outbound.CallBudget; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxAggregateSequences; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImagePublicationWorkflowTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImagePublicationWorkflowTest.java index 4882e9ee..0a6b6789 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImagePublicationWorkflowTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImagePublicationWorkflowTest.java @@ -8,6 +8,7 @@ import static org.mockito.Mockito.when; import dev.caskeleton.application.idempotency.IdempotencyExecutor; import dev.caskeleton.application.idempotency.testkit.InMemoryIdempotencyStore; import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; import dev.caskeleton.application.objectstorage.content.ObjectContentProductionContext; @@ -29,7 +30,6 @@ import dev.caskeleton.application.objectstorage.port.StagedObjectPublicationPort import dev.caskeleton.application.objectstorage.request.ObjectHandoffClaimRequest; import dev.caskeleton.application.objectstorage.request.ObjectStageRequest; import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; -import dev.caskeleton.application.outbound.CallBudget; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxAggregateSequences; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageRetirementCrashMatrixTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageRetirementCrashMatrixTest.java index 757372e6..595eab1c 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageRetirementCrashMatrixTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageRetirementCrashMatrixTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.tuple; +import dev.caskeleton.application.objectstorage.content.CallBudget; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; import dev.caskeleton.application.objectstorage.identity.ObjectOperationEpoch; @@ -14,7 +15,6 @@ import dev.caskeleton.application.objectstorage.model.ObjectMutationReceipt; import dev.caskeleton.application.objectstorage.model.ObjectOperationError; import dev.caskeleton.application.objectstorage.port.ObjectRetirementPort; import dev.caskeleton.application.objectstorage.request.ObjectRetireRequest; -import dev.caskeleton.application.outbound.CallBudget; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.sample.portfolio.application.posterimage.testkit.InMemoryPosterImageRetirementIntentStore; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/architecture/SampleArchitectureTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/architecture/SampleArchitectureTest.java index 5c30b803..5e988375 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/architecture/SampleArchitectureTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/architecture/SampleArchitectureTest.java @@ -9,6 +9,7 @@ import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.core.importer.ImportOption; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.JpaArchitectureRules; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class SampleArchitectureTest { @@ -30,6 +31,7 @@ class SampleArchitectureTest { * here as well. */ @Test + @DisplayName("샘플 엔티티의 연관관계는 한쪽에서만 매핑한다 — 운영 suite가 샘플을 못 보므로 여기서도 건다") void sampleAssociationsAreMappedFromOneSideOnly() { JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(sample); } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuardTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuardTest.java new file mode 100644 index 00000000..c56ed6d1 --- /dev/null +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuardTest.java @@ -0,0 +1,78 @@ +package dev.caskeleton.sample.portfolio.bootstrap.security; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; +import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.mock.env.MockEnvironment; + +/** + * The sample's demo accounts sign in with their own names as passwords, and the README prints both. + * The sample is the code adopters copy first, so a copy started under {@code prod} would put an + * admin account anyone can use in front of production. The refusal is a startup rule that ships + * with the demo security configuration: removing the demo accounts removes the rule with them. + */ +class SampleDemoAccountsProductionGuardTest { + + // Web, because the demo security configuration only exists in a servlet application. The rule + // runs before any singleton is created, so the prod case never needs the filter chain's beans. + private final WebApplicationContextRunner runner = + new WebApplicationContextRunner() + .withUserConfiguration( + StartupRuleAutoConfiguration.class, SampleDemoSecurityConfig.class); + + @Test + @DisplayName("prod 프로필에서는 데모 계정이 든 샘플이 기동을 거부하고, 이유와 대안을 말한다") + void theSampleRefusesToStartWithItsDemoAccountsUnderTheProdProfile() { + // when + runner + .withInitializer(context -> context.getEnvironment().setActiveProfiles("prod")) + .run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .isInstanceOfSatisfying( + StartupFailureException.class, + failure -> + assertThat(failure.errorCode()) + .isEqualTo(StartupErrorCode.PROFILE_MISMATCH)) + .hasMessageContaining("demo-user") + .hasMessageContaining("demo-admin") + .hasMessageContaining("password is the account name") + .hasMessageContaining("JWT") + .hasMessageContaining("WebSecurityAutoConfiguration"); + }); + } + + @ParameterizedTest + @ValueSource(strings = {"local", "dev", "test"}) + void theDemoAccountsAreAllowedOutsideProduction(String profile) { + // given + MockEnvironment environment = new MockEnvironment(); + environment.setActiveProfiles(profile); + + // when + List violations = new SampleDemoAccountsProductionGuard().violations(environment); + + // then + assertThat(violations).isEmpty(); + } + + @Test + void theDemoAccountsAreAllowedWithNoProfileAtAll() { + // when + List violations = + new SampleDemoAccountsProductionGuard().violations(new MockEnvironment()); + + // then + assertThat(violations).isEmpty(); + } +} diff --git a/src/shared-contract/CLAUDE.md b/src/shared-contract/CLAUDE.md index 6d8b23aa..69f3c682 100644 --- a/src/shared-contract/CLAUDE.md +++ b/src/shared-contract/CLAUDE.md @@ -28,12 +28,11 @@ envelope shape, metric cardinality bounds, tracing seam, domain-context propagat SHA-256 digest value and the one `MessageDigest.getInstance("SHA-256")`), `digest/HmacSha256` (sign and constant-time verify), `retry/Backoff` (capped exponential ceiling; "full jitter" means `U[0, ceiling]` and nothing else). Vendored `messaging:*` and the optional gRPC build do not depend - on this module and keep their own copies. A leaf that has the `shared-contract` edge uses these and - does not copy them (application-fileserver `SafeFileFingerprint` and cache-redis `RedisKeys` were - the last two). Template leaves that still copy because the registry gives them no edge — - identifier, persistence-mongo, application-objectstorage, redis-sdk — are an open decision: add the - edge (recommended for template leaves) or keep the copy and say so in that leaf's CLAUDE.md - (review 2026-11-01 01-11). + on this module and keep their own copies; each family's CLAUDE.md says why (a different product, + MSG-023). Every template leaf that needs one of these has the `shared-contract` edge and uses them + instead of copying: identifier, persistence-mongo, application-objectstorage and redis-sdk took the + edge for exactly this (review 2026-11-01 01-11, decision in the review README §15), each with a test + that pins its output to a vector computed outside the JVM. - `observability/MdcKeys`: the snake_case MDC key names (registry `docs/registries/mdc-keys.yaml`) every transport puts a request's correlation under — web, GraphQL, STOMP and gRPC alike. - Registry-rule mirrors read only by contract tests live in `testFixtures`, not `main`: From 7ef8d0b4cbb2d5e4babf8b5679832d219f18806a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:30:39 +0900 Subject: [PATCH 04/17] =?UTF-8?q?docs(review):=20=EC=84=B1=EC=88=99?= =?UTF-8?q?=EB=8F=84=20=EB=A6=AC=EB=B7=B0=20=EC=88=98=EC=A0=95=EC=9D=98=20?= =?UTF-8?q?=EC=9E=AC=EB=A6=AC=EB=B7=B0=20=EA=B2=B0=EA=B3=BC=EB=A5=BC=20?= =?UTF-8?q?=EA=B8=B0=EB=A1=9D=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 2026-11-01 성숙도 리뷰 수정(커밋 3개)은 게이트를 통과했지만, 고친 코드 자체를 독립된 리뷰어가 다시 읽은 적이 없었다. 방법: requesting-code-review 템플릿으로 영역 리뷰어 6명과 보안 리뷰어 1명을 두고, 영역마다 스킬(clean-architecture, jpa-patterns, security-and-hardening 등)을 불러 그 기준으로 봤다. 의심 결함은 별도 worktree의 임시 테스트로 확인했다. README에 결과 종합과 수정에 필요한 결정을 적었다. 위험·한계: Critical 0, 회귀 0, 모든 영역 With fixes(Important 27건, 중복 제외 22건, Minor 41건). 원래 리뷰 색인이 06 영역 발견 5건 (NN-10~14)을 빠뜨려 "모든 발견 처리"가 틀렸음을 정정했다. 이 커밋은 기록만 담고, 수정은 다음 커밋들에서 한다. 검증: 문서만. 리뷰어별 실행 명령은 각 문서 "범위" 절. Refs: docs/reviews/2026-11-03-rereview/README.md --- .../01-core-application.md | 234 ++++++++++++++ .../02-inbound-transports.md | 298 ++++++++++++++++++ .../2026-11-03-rereview/03-persistence.md | 232 ++++++++++++++ .../04-outbound-capabilities.md | 210 ++++++++++++ .../2026-11-03-rereview/05-messaging.md | 252 +++++++++++++++ .../06-bootstrap-build-ci.md | 283 +++++++++++++++++ .../2026-11-03-rereview/07-security.md | 214 +++++++++++++ docs/reviews/2026-11-03-rereview/README.md | 69 ++++ 8 files changed, 1792 insertions(+) create mode 100644 docs/reviews/2026-11-03-rereview/01-core-application.md create mode 100644 docs/reviews/2026-11-03-rereview/02-inbound-transports.md create mode 100644 docs/reviews/2026-11-03-rereview/03-persistence.md create mode 100644 docs/reviews/2026-11-03-rereview/04-outbound-capabilities.md create mode 100644 docs/reviews/2026-11-03-rereview/05-messaging.md create mode 100644 docs/reviews/2026-11-03-rereview/06-bootstrap-build-ci.md create mode 100644 docs/reviews/2026-11-03-rereview/07-security.md create mode 100644 docs/reviews/2026-11-03-rereview/README.md diff --git a/docs/reviews/2026-11-03-rereview/01-core-application.md b/docs/reviews/2026-11-03-rereview/01-core-application.md new file mode 100644 index 00000000..8992e56d --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/01-core-application.md @@ -0,0 +1,234 @@ +# 01 core·application·composition·매뉴얼 재리뷰 (2026-11-03) + +경로는 저장소 루트 기준이다. `src/`가 앞에 붙는다. + +## 범위 + +### 본 것 + +- 범위: `01a8a2a70..5786126c`(커밋 3개) 중 아래 pathspec. 365파일, +19,733 −3,474. + ```text + src/domain-core src/shared-contract src/application-core src/application-notification + src/application-fileserver src/application-objectstorage src/composition + scripts/new-feature.sh scripts/verify-feature-scaffold.sh scripts/feature-scaffold docs/manual + ``` +- 요구사항: `docs/reviews/2026-11-01-maturity-review/README.md` 2·12·13·14·15·16절과 + `01-core-and-feature-pattern.md`(완료 기준). +- 읽은 방식: diff가 커서 여러 번에 나눠 직접 읽었다. + 1. application-core main 전부(outbox·messaging.event·cache·operation·tenant·security·secret)와 testFixtures 계약 키트 전부. + 2. shared-contract main diff 전부와 README·CLAUDE.md 변경. + 3. 생성 명령(`new-feature.sh`, `verify-feature-scaffold.sh`)과 템플릿 29개 전부. + 4. 매뉴얼 13개 전부. 매뉴얼이 인용한 경로·클래스·규칙 이름이 실제로 있는지 스크립트로 전수 확인했다. + 5. application-notification main diff 전부. testFixtures는 계약 목록과 상속 관계 위주로 봤다. + 6. application-fileserver main diff 전부와 quota·move·cleanup 경로. 대응하는 persistence-fileserver 구현(`JpaFileQuota`, `JpaQuotaReclaim`)은 비교하려고 범위 밖에서 읽었다. + 7. composition: service-runtime(authorization·tracing), outbox-relay, durable-operation, fileserver-platform의 변경. +- 범위 밖에서 확인용으로 읽은 것: `ApplicationBoundaryArchitectureTest`(D4·`@SystemInvoked`), + `NamingConventionTest`·`TemplatePackageOwnership`, `DomainFeatureOnboardingContractTest`, `JpaOutboxStore.nextSequence`, + `JsonIntegrationEventEncoder`, `GlobalExceptionHandler`, sample `WorkLogRepositoryContract`·`WorkLogReservedPayload`, `docs/testing/TESTING_STRATEGY.md` 9절. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +| --- | --- | --- | +| `superpowers:requesting-code-review` | 리뷰어 템플릿(Strengths → Critical/Important/Minor → Declined → Assessment), 읽지 않은 코드에 판정 금지, 실제 심각도로 분류 | 문서 양식 전체 | +| `clean-architecture` | 의존 방향(안쪽만), 포트는 안쪽이 소유, 프레임워크는 바깥, composition root가 조립 | 생성 명령 출력의 계층별 의존, `@SystemInvoked`·권한 검사 위치, 계약 키트가 포트 소유 leaf에 있는지 | +| `domain-driven-design` | 불변식은 aggregate 안, 저장소 인터페이스는 domain, 유비쿼터스 언어 | 생성 aggregate·`*Repository`·오류 코드 위치, 이벤트 tenant 범위 규칙 | +| `codebase-design` | seam·adapter 용어, "어댑터 둘이면 진짜 seam", 인터페이스 = 호출자가 알아야 할 모든 것 | 포트 Javadoc이 약속한 것과 계약 키트가 실제로 검사하는 것의 차이, fake가 실제 adapter와 같은 interface를 지키는지 | + +### 실행한 명령과 결과 + +| 명령 | 결과 | +| --- | --- | +| `git diff --stat / --name-status 01a8a2a70..5786126c -- ` | 365파일. A 180, M 148, D 12, R 25 | +| `git worktree add /rr-01 5786126c` | 실험용. 끝나고 `git worktree remove --force`로 지웠다 | +| 변이 3개 적용 뒤 `flock … ./gradlew :application-core:test --tests TenantIdTest --tests IntegrationIdentityTest --tests InMemoryCacheRegionContractTest --continue` (load 17.4) | rc=1, 48건 중 2건 실패. M2(`TenantId` 문법에 `/` 허용) → `TenantIdTest [8] "acme/eu"` 실패(잡힘). M5(correlation 상한 128→200) → `IntegrationIdentityTest` 129자 거부 실패(잡힘). **M6(fake 캐시가 revision을 double로 비교) → 통과(살아남음)** | +| 워크트리에서 `scripts/new-feature.sh Invoice --no-format` 후, 호출자 트랜잭션을 요구하는 저장소로 생성 계약을 상속하는 실험 테스트 1개 추가, `flock … ./gradlew :domain-core:test --tests 'dev.caskeleton.domain.invoice.*'` (load 13.4) | rc=1, 18건 중 2건 실패: 실험 테스트의 `aSavedInvoiceIsFoundByItsId`, `savingTheSameIdAgainReplacesTheStoredState`. 생성된 테스트는 전부 통과 | +| 매뉴얼의 `` `src/…` `` `` `docs/…` `` 경로 존재 확인, 백틱 안 Java 식별자 109개 `git grep -w` | 없는 경로 0(glob 2개 제외), 없는 식별자 0(`V8_1` 파일명 접두어 제외) | + +### 못 본 것 + +- `:app-bootstrap:architectureTest`, 실 PostgreSQL·Redis lane은 돌리지 않았다. 게이트 결과(README 16.2)를 믿었다. +- application-notification test 디렉터리 약 60개 파일은 줄 단위로 다 읽지 않았다. 계약 상속 관계와 이름만 전수 확인했다. +- composition:notification-platform, service-runtime tracing(07-01)은 diff를 훑기만 했다. 07 영역 판단에 맡긴다. +- sample-portfolio는 범위 밖이다. 01-07·01-13·01-14 완료 기준에 필요한 줄만 읽었다. + +## Strengths + +- **트랜잭션 fake가 실제와 같은 규칙을 지킨다.** `DirectTransactionPort`가 롤백(`onRollback`), 참여 경계 실패 시 바깥 커밋 실패(doomed), 읽기 전용 표시를 갖는다(`application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java:112-155`). 같은 `TransactionPortContract` 13건을 실 PostgreSQL의 `SpringTransactionContractTest`가 상속한다. 01-05의 핵심이 닫혔다. +- **encoder fake가 서버 조립 오류를 실제와 같은 예외로 거부한다.** `FakeIntegrationEventEncoder.java:55-73`이 미등록 계약·목적지·payload 타입을 `IllegalStateException`으로 거부하고, `IntegrationEventEncoderContract`를 `JsonIntegrationEventEncoder`와 함께 상속한다. 01-04 결함이 단위 테스트에서 보이게 됐다. +- **식별자 문법이 한 곳으로 모였다.** `IntegrationIdentity.java:17-31`이 문법과 상한 3개를 갖고 `EventId`·`IntegrationEventDraft`·`ValidatedIntegrationEvent`·`AggregateIdentity`가 쓴다. draft와 저장 이벤트의 correlation 상한이 128로 같아졌다. 변이 M5를 테스트가 잡는다(위 실행). +- **relay 정지가 claim을 돌려준다.** `PublishPendingOutboxEventsUseCase.java:124-128,143-155`의 `release`와 `OutboxStorePort.releaseLease`·`markDeferred`가 생겼고, `OutboxLeaseFencingContract.java:161-213`이 in-memory와 PostgreSQL 둘 다에 같은 경우를 건다. +- **05-01 수정이 정확하다.** 호출 전 행을 `undetermined()`로 쓴다(`application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/DeliveryAttemptFactory.java:55-60`). collapse 불가 검사도 attempt 행을 만들기 전으로 옮겼다(`NotificationDispatchService.java:186-194`). +- **권한 장치 부재를 기동에서 막는다.** `composition/service-runtime/.../authorization/PermissionEnforcementGuard.java:42-61`. 실제 web advisor의 pointcut이 class·method union이라(`MethodSecurityConfig.java:55-57`) `AopUtils.canApply` 판정과 맞는다. sample이 service-runtime과 web을 함께 띄워 실제 조합에서도 통과한다. +- **생성 명령이 이름 목록 대신 실제 패키지 존재로 거절한다.** `scripts/new-feature.sh:89-105`. 목록이 갈라질 여지를 없앴다. 왕복 검사가 실제 Gradle 게이트를 돌리고 결과 XML까지 본다(`scripts/verify-feature-scaffold.sh:86-108`). +- **패키지 소유 규칙이 양방향으로 검사된다.** `TemplatePackageOwnership` + 규칙 2개 + fixture 증명 테스트(`TemplatePackageOwnershipRuleTest`). 정본 표는 `application-core/CLAUDE.md:108-167` 한 곳이다. +- **LRO 계약이 하나가 됐다.** shared-contract `operation` 패키지를 지우고 이유를 README에 남겼다(`shared-contract/README.md:298-304`). +- **캐시 revision 순서가 포트 규칙이 됐다.** `CacheSourceRevisionOrder.java`가 길이→자리 비교로 2^53 이상도 맞게 비교하고, `CacheRecordMetadata`가 모든 provider에 같은 거부를 건다. + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +| --- | --- | --- | +| 01-01 | 닫힘 | 배치 기준표 `docs/manual/03-placement.md:21-50`, 생성 명령, `verifyFeatureScaffold`(mainCheck). 생성 결과의 계약 설계 결함은 RR-01-01 | +| 01-02 | 닫힘 | fixture `CreateFeatureAggregateUseCase` non-final(`app-bootstrap/src/test/java/dev/caskeleton/onboarding/application/usecase/CreateFeatureAggregateUseCase.java:20`), `FeatureAggregateIdFactory extends IdFactory`. `DomainFeatureOnboardingContractTest.java:142-170`이 production ArchRule 전부(`RequiresPermissionProxyabilityTest` 포함)를 fixture에 적용. 변이는 직접 돌리지 않았다(E1) | +| 01-03 | 결정으로 닫힘 | experimental `TenantId` 삭제, `git ls-files '*/main/*TenantId.java'` = 정본 + notification 1개. notification 쪽은 결정 15절과 Javadoc(`application-notification/.../api/TenantId.java:4-15`), 쓰기는 `WritableTenant`가 정본 문법 강제. 변이 M2 이제 잡힘(E2) | +| 01-04 | 닫힘 | encoder의 미등록·목적지·타입 오류 → `IllegalStateException`(`adapter/outbound/support/.../JsonIntegrationEventEncoder.java:112-130`), web 400에 WARN 한 줄(`GlobalExceptionHandler.java:92-99`). 값 객체는 아직 IAE지만 WARN으로 흔적이 남는다. 매뉴얼 06장은 옛 동작을 적는다(RR-01-03) | +| 01-05 | 닫힘(application-core) | `TESTING_STRATEGY.md` 9.1 표의 포트 전부가 계약 키트와 fake·실제 상속을 가진다(직접 grep 확인). `implements TransactionPort`는 main 1 + testFixtures 2(`DirectTransactions`는 위임 래퍼). 남은 빈틈: RR-01-04(fileserver), RR-01-06(키트가 포트 약속을 다 안 봄) | +| 01-06 | 닫힘, 새 위험 있음 | 가드(`PermissionEnforcementGuard`) + relay `@SystemInvoked`. `@SystemInvoked`가 D4의 검사 없는 탈출구가 됐다(RR-01-02). 매뉴얼 07장이 "장치 없음"이라 적는다(RR-01-03) | +| 01-07 | 부분 | 문법 상수 하나 + M5 잡힘. 그러나 `sample-portfolio/.../application/worklog/WorkLogReservedPayload.java:8-9`에 같은 문법·160 상한 복사본이 남아 완료 기준("main에 한 번만")을 못 채운다(RR-01-08) | +| 01-08 | 닫힘 | `git grep shared.operation` 0건, README 기록 | +| 01-09 | 닫힘(코드), 재발 방지 없음 | `new IntegrationEventDraft<>(`가 main에서 `IntegrationEventDrafts.java:59` 한 곳. 하지만 그것을 지키는 규칙이 없고 매뉴얼은 "헬퍼 아직 없음, 기능마다 다시 쓴다"고 가르친다(RR-01-03) | +| 01-10 | 닫힘 | `outbound` 패키지 해체(`secret`, objectstorage `content.CallBudget`), 소유 표 + ArchUnit 2개 + 생성 명령 거절 | +| 01-11 | 결정으로 닫힘 | 템플릿 leaf 4곳 정본 사용, 출력 고정 테스트(`SafeFileFingerprintTest`, `ObjectIdentityDigestOutputTest`). 남은 직접 구현은 vendored `messaging:*`·`grpc*`뿐(grep) | +| 01-12 | 닫힘 | 이름 표 `application-core/CLAUDE.md:84-106`, `NamingConventionTest`가 그곳을 가리킴 | +| 01-13 | 닫힘(범위 밖 확인) | sample `UpdateWorkLogUseCase`에 소유자 검사(r2-09) | +| 01-14 | 닫힘 | README relay 설명 수정, 빈 패키지 3개 삭제, `*ValueTypesTest` 개명, `OutboxEventIdFactory`가 sample `application.event`로 이동, `TITLE_BLANK`→`WORKLOG_INVALID`(400) | +| 05-01 | 닫힘 | 위 Strengths | +| 05-07 (application 쪽) | 닫힘, 새 위험 있음 | copy가 admission·namespace 상한·예약을 거친다(`CopyFileApplicationUseCase.java:107-148`). move는 쿼터를 옮기지 않아 상한이 켜진 뒤 회계가 틀어진다(RR-01-05) | +| 04-02 (application 쪽) | 닫힘 | `ReconciliationJobStorePort.claimDue(limit, now, lease)`, `ReconciliationJob.claimFence`. fake·PG가 `ReconciliationJobStoreContract` 공유 | +| 06-01·06-03 (application 쪽) | 결정으로 닫힘 | `REJECTED_RETRYABLE`·`AMBIGUOUS`는 예산을 쓰지 않고 5분 상한 재시도(`PublishPendingOutboxEventsUseCase.java:181-193,236-260`, `OutboxBackoffPolicy.MAX_DELAY`). 결정 15절 | +| 06-02 | 닫힘 | `OutboxRelayScheduler`가 `SmartLifecycle`(phase MAX), 정지 요청 → 진행 중 발행 마무리 → 나머지 release(`OutboxRelayScheduler.java:72-170`). 경쟁 조건을 읽어 봤고 문제를 찾지 못했다 | +| 06-07 (application 쪽) | 닫힘 | `OutboxAggregateSequencePort` + `AggregateOrder.first()`, `ofOccurrence` 삭제. 계약 빈틈은 RR-01-06 | +| 02-01 (application 쪽) | 닫힘 | `OperationalError.IDEMPOTENT_IN_FLIGHT` retryable=true, 예외 Javadoc 갱신 | +| 05-02·05-03 (application 쪽) | 닫힘 | `CacheSourceRevisionOrder`, `CacheRecordMetadata` 검증. 계약에 2^53 이상 경우 없음(RR-01-06) | +| TEST-F-1 (application-core) | 닫힘 | 9.1 표 + 9.2 의도 표 | + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +#### RR-01-01 생성 명령이 만든 저장소 계약은 매뉴얼대로 만든 실제 adapter가 상속할 수 없다 + +- **위치**: `scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/__Feature__RepositoryContract.java.tmpl:26,31,48,51` +- **무엇이 틀렸나**: 생성 계약은 `repository().save(...)`를 트랜잭션 없이 바로 부른다. 계약에 트랜잭션을 여는 자리(hook)가 없다. 그런데 매뉴얼 04장은 저장 adapter가 `CallerTransaction.require`로 호출자 트랜잭션을 요구하라고 가르친다(`docs/manual/04-persistence.md:15,66-72`). 그리고 그 adapter가 같은 계약을 상속하라고 한다(`04-persistence.md:30`, `08-testing.md:14`). 둘을 같이 지키면 계약 테스트가 실패한다. 생성 fake(`InMemory__Feature__Repository.java.tmpl:19`)도 트랜잭션을 보지 않아, 유스케이스가 `tx.inWrite` 밖에서 저장해도 fake 위 테스트는 통과한다. +- **왜 중요한가**: 이 매뉴얼은 "새 기능의 예시는 생성 명령 출력 하나"라고 정했다(`docs/manual/README.md:53-63`). 생성물이 "fake와 실제가 같은 계약을 통과한다"는 규칙의 견본인데, 실제 adapter를 붙이는 첫 순간 그 규칙을 지킬 수 없다. 개발자는 계약을 고치거나(정답), adapter에서 `require`를 빼거나(트랜잭션 밖 저장이 조용히 커밋되는 원래 결함), 계약 상속을 포기한다. 같은 저장소의 다른 키트는 이미 hook을 가진다: sample `WorkLogRepositoryContract.java:50` `inTransaction(Supplier)`, `IdempotencyStoreContract.java:70`. +- **발생 조건**: 생성된 기능에 매뉴얼 04장대로 JPA adapter를 붙이고 계약을 상속한다. 모든 파생 기능이 지나는 경로다. +- **고치는 법**: 템플릿 계약에 `protected T inTransaction(Supplier work) { return work.get(); }`를 두고 모든 호출을 거치게 한다. domain-core는 `TransactionPort`를 볼 수 없으니 sample처럼 `Supplier` hook이면 된다. fake 쪽은 "트랜잭션 밖 save 거부"를 계약 경우로 넣을지 정한다(넣으려면 fake가 트랜잭션 표시를 받아야 한다). +- **심각도·우선순위**: Medium / P2. 런타임 결함은 아니다. 템플릿이 복제시키는 테스트 설계 결함이다. +- **증거**: E2. 워크트리에서 `Invoice`를 생성하고 호출자 트랜잭션을 요구하는 저장소로 생성 계약을 상속했다. `:domain-core:test` 18건 중 그 2건이 "requires an active caller transaction"으로 실패했다(트랜잭션 없이도 되는 `findById` 경우만 통과). + +#### RR-01-02 `@SystemInvoked`가 D4 권한 규칙의 검사 없는 탈출구다 + +- **위치**: `app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java:558-560`, `application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java:19-20`, `composition/service-runtime/.../authorization/PermissionEnforcementGuard.java:50` +- **무엇이 틀렸나**: D4는 쓰기 유스케이스에 `@RequiresPermission`을 강제한다. `@SystemInvoked`가 붙으면 바로 `return`해 면제한다. 면제의 전제는 "bean이 아니고 전송에서 닿지 않는다"인데 이것은 Javadoc 문장뿐이다. ArchUnit에 "inbound adapter는 `@SystemInvoked` 클래스에 의존하지 않는다" 규칙이 없다. 기동 가드는 `@RequiresPermission`만 보므로 `@SystemInvoked` bean을 그냥 지나간다. AGENTS.md와 매뉴얼 07장은 이 표시를 언급하지 않는다. +- **왜 중요한가**: 쓰기 유스케이스에 `@SystemInvoked(reason = "…")` 한 줄을 붙이고 `@Bean`으로 등록해 컨트롤러가 부르면, 권한 검사 없이 실행된다. 빌드·기동·테스트 어디서도 실패하지 않는다. 01-06이 막으려던 "조용한 인가 우회"를 다른 문으로 다시 연다. 사용자 원칙 "위험은 코드에 드러나야 한다"에 걸린다. +- **발생 조건**: 개발자가 D4 실패를 끄려고 이 표시를 쓴다. 이름이 시스템 호출용으로 보여 막을 단서가 리뷰뿐이다. +- **고치는 법**: (a) ArchUnit: `..adapter.inbound..`·`..bootstrap..`의 어떤 클래스도 `@SystemInvoked` 클래스에 의존하지 않는다(composition만 허용). (b) `PermissionEnforcementGuard`에 "`@SystemInvoked` 타입의 bean이 있으면 기동 실패"를 더한다. 둘 다 작다. (b)는 relay가 bean이 아닌 현재 구조와 맞는다. +- **심각도·우선순위**: Medium / P2. 기본 조립에는 해당 bean이 없다. 생기면 권한 우회다. +- **증거**: E1. 규칙 조건 코드와 가드 조건을 읽었다. 우회 조립을 띄워 보지는 않았다. + +#### RR-01-03 매뉴얼이 이번 수정 뒤의 코드와 반대로 말하는 곳이 세 군데 있고, 01-09의 헬퍼를 지키는 장치가 없다 + +- **위치와 내용**: + - `docs/manual/07-authorization.md:65-68` "web이 빠진 조립에서는 … 기동을 막는 장치는 아직 없다(리뷰 01-06)". 실제로는 `PermissionEnforcementGuard`가 있다. 같은 커밋 `1400dc15`에서 서로 다른 묶음이 만들었다. + - `docs/manual/09-outbox-events.md:59-60` "이 규칙은 아직 기능마다 다시 쓴다 … application-core 헬퍼로 올리는 일은 리뷰 01-09 후속이다". 실제로는 `IntegrationEventDrafts`가 있고 sample과 durable operation이 쓴다. 매뉴얼은 그 이름을 한 번도 쓰지 않는다. `application-core/CLAUDE.md` 이벤트 타입 표(:72-74)와 README에도 없다. + - `docs/manual/09-outbox-events.md:63-65` relay를 bean으로 만들지 않는 이유를 "권한 프록시가 매번 거부한다"로 적는다. 지금 relay는 `@SystemInvoked`라 권한 선언이 없다. bean이 되면 거부가 아니라 **검사 없이** 열린다(RR-01-02). 이유가 바뀌었다. + - `docs/manual/06-errors.md:44-45` "web은 그것을 로그 없이 400으로 바꿔서". 지금은 WARN 한 줄을 남긴다(`GlobalExceptionHandler.java:97`). +- **왜 중요한가**: 매뉴얼은 새 기능 작성자가 처음 읽는 문서이고 "매뉴얼과 정본이 다르면 정본이 맞다"는 규칙만으로는 독자가 차이를 알 수 없다. 특히 09장대로 하면 다음 기능이 `new IntegrationEventDraft<>(…)`를 직접 조립한다. 그것을 막는 규칙이 없으니 01-09가 고친 "기능마다 tenant·순서·correlation 규칙 재정의"가 그대로 돌아온다. 경로·식별자 전수 검사는 통과하므로(위 실행) 이 종류의 drift는 기계 검사로 안 잡힌다. +- **고치는 법**: 네 문장을 고친다. 09장 "event id·correlation·순서" 절을 `IntegrationEventDrafts.draft(…)` 사용으로 바꾸고 `SINGLE_TENANT_SCOPE`·`IntegrationIdentity`를 소개한다. `application-core/CLAUDE.md` 표에 두 타입을 넣는다. ArchUnit 한 줄: `IntegrationEventDraft` 생성자 호출은 `IntegrationEventDrafts`(와 테스트)에서만. +- **심각도·우선순위**: Medium / P2. 문서 불일치가 반복 결함(01-09)을 되살리는 경로라 Low보다 높게 본다. +- **증거**: E1. 해당 줄과 코드를 대조했다. `git grep -l IntegrationEventDrafts -- src docs` = main 2·sample 1·test 1, docs 0. + +#### RR-01-04 application-fileserver: 저장 포트 9개 중 7개는 공유 계약이 없고, 쿼터 fake는 실제와 다르게 답한다 + +- **위치**: `application-fileserver/build.gradle:12-17`, `application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java:17-20,43,57,63`, `adapter/outbound/persistence-fileserver/.../JpaFileQuota.java:62,74,91`, `docs/testing/TESTING_STRATEGY.md:192-193` +- **무엇이 틀렸나**: persistence-fileserver가 구현하는 포트는 9개다(`CleanupQueuePort`, `ContentReferenceLedgerPort`, `FileMetadataPort`, `FileQuotaPort`, `QuotaCommitPort`, `QuotaReclaimPort`, `RecoveryQueuePort`, `StagingUploadLocatorPort`, `UploadSessionPort`). 계약 키트는 `FileMetadataPortContract`, `CleanupQueuePortContract` 둘뿐이다. 나머지는 fake가 testFixtures로 옮겨졌을 뿐 계약이 없다. 그런데 build.gradle 주석은 "fake 위에서 통과한 유스케이스 테스트는 persistence-fileserver JPA adapter가 지키는 동작에 대해 통과한 것"이라 적고, TESTING_STRATEGY 9절은 fileserver 포트를 `*PortContract`가 "맡는다"고 적는다. 실제로 갈라진 예: `FakeFileQuotaService`는 Javadoc에 "durable adapter와 같은 장부"라 쓰지만 (1) 시계가 없어 만료된 예약도 `usedBytes`에 센다(실제는 `sumReservedBytes(…, now)`로 뺀다), (2) 해제된 예약의 `commit`·`extend`를 조용히 받는다(실제는 `QUOTA_EXCEEDED`로 거부). +- **왜 중요한가**: 05-07 수정으로 namespace 상한이 `usedBytes` 비교로 실제 거부를 하게 됐다. 그 판정에 쓰는 포트가 fake와 실제 사이에 묶여 있지 않다. 유스케이스 테스트가 녹색이어도 실제 상한 동작을 말해 주지 않는다. AGENTS.md 테스트 규칙 6과 capability 기준 5가 정확히 이것을 막으려는 규칙이다. +- **발생 조건**: fileserver 유스케이스를 고치거나 쿼터 규칙을 바꾸고 fake 위 테스트로 검증한다. +- **고치는 법**: 최소 `FileQuotaPortContract`(예약·연장·확정·해제·만료·`usedBytes`)를 만들어 fake와 `PostgreSqlFileserver…IntegrationTest`가 상속한다. fake에 `Clock`을 준다. 나머지 6개는 9.2처럼 "계약 없음, 이유" 표를 두거나 계약을 만든다. build.gradle 주석과 9절 문장을 사실대로 고친다. +- **심각도·우선순위**: Medium / P2. +- **증거**: E1. 두 구현을 나란히 읽었다. fake를 실 PG 테스트에 걸어 보지는 않았다. + +#### RR-01-05 파일 이동이 쿼터를 옮기지 않아, 상한을 켠 배포에서 namespace 사용량이 양쪽으로 틀어진다 + +- **위치**: `application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java:53-60`, `cleanup/DefaultCleanupService.java:311`, `adapter/outbound/persistence-fileserver/.../JpaQuotaReclaim.java:41-58`, `application-fileserver/.../quota/NamespaceQuota.java:19-25` +- **무엇이 틀렸나**: copy는 대상 namespace에 예약·확정한다. move는 `metadataStore.relocate`만 하고 쿼터를 건드리지 않는다. 확정 사용량은 namespace별 예약 행의 합이라(`JpaFileQuota.committedBytes`) 파일이 B로 가도 사용량은 A에 남는다. 나중에 그 파일을 지우면 정리 서비스가 **현재** namespace B에서 회수한다. `JpaQuotaReclaim`은 B의 행에서 빼다가 모자라면 나머지를 버린다(바닥 0). +- **왜 중요한가**: 결과는 세 가지다. B는 move로 상한을 검사 없이 넘는다. A는 없는 파일의 사용량을 영원히 들고 있어 언젠가 정상 업로드가 `QUOTA_EXCEEDED`가 된다. B의 장부는 다른 파일의 확정분까지 깎여 과소 집계된다. 05-07 이전에는 쿼터가 "기록만" 해서 틀려도 피해가 없었다. 결정 15절이 상한을 실제로 강제하게 만들면서 이 차이에 이빨이 생겼다. `NamespaceQuota`의 "Known limit"은 동시 예약 초과만 적고 move는 적지 않았다. +- **발생 조건**: `APP_FILESERVER_PLATFORM_TARGET_NAMESPACES`로 namespace를 둘 이상 열고 `APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT`을 설정한 배포에서 move를 쓴다. 기본값(대상 = 기본 namespace 하나, 상한 없음)에서는 생기지 않는다. +- **고치는 법**: move를 한 트랜잭션 안에서 "B에 `requireRoom` + 예약·확정, A에서 같은 바이트 회수"로 바꾼다. 또는 상한이 설정된 동안 namespace를 바꾸는 move를 거부하고 그 사실을 `NamespaceQuota` Javadoc과 `fileserver.yml` 주석에 적는다. 어느 쪽이든 "move 뒤 A·B `usedBytes`" 단언을 계약 테스트에 넣는다(RR-01-04와 함께). +- **심각도·우선순위**: Medium / P2. 데이터(쿼터 장부)가 조용히 틀어지지만 설정 두 개를 켠 배포에서만 생긴다. +- **증거**: E1. 코드 경로를 읽었다. 실행 재현은 하지 않았다. + +### Minor (Nice to Have) + +#### RR-01-06 계약 키트가 포트 Javadoc의 약속을 다 검사하지 않는다 + +- **위치·내용**: + - `application-core/src/main/java/dev/caskeleton/application/cache/CacheSourceRevisionOrder.java:13-18`은 "float 파싱은 2^53 위를 구분 못 한다"며 공유 `CacheRegionContract`가 Redis Lua 복사본을 맞춰 준다고 적는다. 계약의 숫자 순서 경우는 `9` 대 `10`뿐이다(`CacheRegionContract.java:168-180`). **변이 M6(fake가 revision을 `Double.parseDouble`로 비교)이 `InMemoryCacheRegionContractTest`를 통과했다(E2).** Lua가 `tonumber`로 바뀌어도 계약은 못 잡는다(현재 Lua는 문자열 비교로 맞다). + - `OutboxAggregateSequencePort.java:17-28`은 "계약이 모든 구현을 세 항목에 묶는다"고 적는다. 계약(`OutboxAggregateSequenceContract`)은 증가·독립 두 경우만 본다. "호출자 쓰기 트랜잭션 안에서만"과 "롤백된 번호는 다시 준다"는 없다. fake(`InMemoryOutboxAggregateSequences.java:14-16`)는 트랜잭션 밖 호출을 받고 롤백된 번호를 건너뛴다. JPA는 트랜잭션 밖을 거부한다(`JpaOutboxStore.java:116`). + - `IdempotencyStoreContract.java:89,340-357`의 시간 경우는 fake에서 `elapse`가 no-op이라 공짜로 통과한다. 문서에 적혀 있지만, fake 위 유스케이스 테스트는 lease 만료·넘겨받기를 영영 볼 수 없다. +- **고치는 법**: 계약에 `"9007199254740993"` 대 `"9007199254740992"` 경우, 트랜잭션 밖 `nextSequence` 거부 경우를 넣는다. 시간 경우는 fake에 시계를 주거나 `assumeTrue(hasClock())`로 건너뜀을 드러낸다. 포트 Javadoc의 "계약이 묶는다" 문장을 계약 범위에 맞춘다. +- **심각도·우선순위**: Low / P3. **증거**: E2(M6), 나머지 E1. + +#### RR-01-07 생성된 `Config`가 `TransactionPort` 공급 자동 설정 순서를 적지 않는다 + +- **위치**: `scripts/feature-scaffold/templates/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__Config.java.tmpl:30-32` +- **내용**: `@ConditionalOnBean({Repository, TransactionPort})`인데 `afterName`이 없다. `TransactionPort`는 `PersistenceJpaAutoConfiguration`이 만든다. 지금은 클래스 이름 알파벳 순서(`dev.caskeleton.adapter…` < `dev.caskeleton.bootstrap…`)로 우연히 먼저 처리된다. 같은 모양의 `DurableOperationAutoConfiguration.java:42-44`는 이름을 적었고, 매뉴얼 02장(:124)도 "안 적으면 조건이 그 bean을 못 본다"고 한다. 기능이 조용히 없어지는 실패라 찾기 어렵다. +- **고치는 법**: 템플릿에 `@AutoConfiguration(afterName = "dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaAutoConfiguration")`. 저장 adapter의 자동 설정 이름은 주석 안내대로 사람이 더한다. +- **심각도·우선순위**: Low / P3. **증거**: E1. + +#### RR-01-08 01-07 잔여 복사본 + +- **위치**: `sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedPayload.java:8-9` +- **내용**: `[A-Za-z0-9][A-Za-z0-9._:-]*`와 160 상한을 직접 갖는다. 같은 값이 `IntegrationIdentity.GRAMMAR`·`AGGREGATE_ID_MAX_LENGTH`다. 원래 리뷰의 다섯 곳 목록에 없던 여섯 번째 복사본이다. +- **고치는 법**: `IntegrationIdentity.isCanonical(workLogId, AGGREGATE_ID_MAX_LENGTH)`. +- **심각도·우선순위**: Low / P3. **증거**: E1(grep). + +#### RR-01-09 이번에 고친 문서 옆에 남은 옛 서술 + +- **내용**: 같은 파일을 이번 범위에서 고치면서 01 영역 문서 2절의 "남음" 항목을 그대로 두었다. + - `shared-contract/README.md:369` "1001번째 tenant부터 bucket folding이 자동 적용된다" — 구현 없음(A-5a). + - `shared-contract/src/main/java/dev/caskeleton/shared/runtime/RuntimeEnvironment.java:33` "app-bootstrap's RuntimeProfileSnapshot" — 실제는 support leaf(A-2d). + - `application-core/README.md:531-560` "알림 포트" 절이 application-notification의 `NotificationPort`를 설명하고, 그 아래 "Notification (값 객체)" 절 본문은 가명화 포트 설명이 섞여 있다(A-6a). +- **심각도·우선순위**: Low / P3. **증거**: E1. + +#### RR-01-10 왕복 검사가 생성 테스트 8개 중 4개만 "실행됨"을 확인한다 + +- **위치**: `scripts/verify-feature-scaffold.sh:96-101` +- **내용**: `Test`, `CreateUseCaseTest`, `ControllerTest`, `ConfigTest`의 결과 XML만 확인한다. `IdTest`, `InMemoryRepositoryContractTest`, `GetUseCaseTest`, `UuidIdFactoryTest`는 필터·태그 변경으로 실행되지 않아도 녹색이다. 스크립트 머리말이 막겠다고 한 "빈 녹색"이 절반 남는다. +- **고치는 법**: 템플릿의 `src/test/**/*Test.java.tmpl` 목록에서 기대 XML을 만들어 전부 확인한다. +- **심각도·우선순위**: Low / P3. **증거**: E1. + +## Declined to judge + +- SMTP provider adapter가 `ProviderAdapterContract`("every stable provider adapter")를 상속하지 않는 것 — 계약이 HTTP 모양이고 05 영역 판단이다. 파일 이동만 이번 범위다. +- `JpaOutboxStore`의 첫 counter 생성 경쟁(두 생성자가 PK 충돌) — persistence-jpa, 04·06 영역. +- `TracingSwitchImportFilter`가 Boot 4의 모든 tracing 자동 설정을 패키지 접두어로 덮는지 — 07 영역. +- `TemplatePackageOwnershipRuleTest`가 "목록 ⊆ 실제"만 보고 반대 방향은 안 보는 것 — 새 템플릿 패키지를 목록에 안 넣으면 기능으로 분류되지만, 다른 템플릿 패키지가 import하면 규칙 2가 잡고 생성 명령은 디스크로 거절한다. 피해가 작아 제외. +- durable operation 이벤트가 tenant가 있어도 `global` 범위로 나가는 것 — 코드 주석에 이유와 결정이 있다(`SubmitDurableOperationUseCase.java:145-147`). +- namespace 상한의 동시 예약 초과 — 결정 15절, `NamespaceQuota` Javadoc에 명시. +- relay가 진짜 인증 오류도 5분 간격으로 무한 재시도 — 결정 15절. +- 서버가 만드는 값 객체(`ValidatedIntegrationEvent` 등)가 아직 IAE를 던지는 것 — WARN 로그로 흔적이 남아 01-04 목적은 달성. 따로 올리지 않는다. +- `OutboxMetrics.refreshGauges`가 relay tick(최대 50 cycle)과 같은 스케줄러 스레드를 나눠 gauge 갱신이 늦을 수 있는 것 — 측정하지 않았다. +- sample `POSTER_INVALID_STATE`가 상태 전이 위반을 400으로 내는 것 — sample, 범위 밖. + +## 28개 관점 — 바뀐 관점만 + +01 영역 문서 8절 판정표 대비. 기호: O 충족, P 부분, X 미충족. + +| # | 관점 | 이전 | 지금 | 한 줄 이유 | +| --- | --- | --- | --- | --- | +| 2 | 구조적 성숙도 | P | O | 배치 기준표와 패키지 소유 규칙이 생기고 ArchUnit·생성 명령이 강제한다 | +| 3 | 변경 용이성 | P | O | 식별자 문법·draft 규칙이 한 곳. 남은 sample 복사본 1곳(RR-01-08)은 Low | +| 6 | 실패 성숙도 | P | O | 서버 조립 오류가 500+로그, relay 일시 거부가 DEAD 대신 재시도 | +| 8 | 디버깅 가능성 | P | O | IAE 400에도 WARN 한 줄 | +| 11 | 데이터 성숙도 | P | P | 이유가 바뀜: 이벤트 tenant 규칙은 하나가 됐고, 새로 move 쿼터 장부 drift(RR-01-05) | +| 17 | API·계약 성숙도 | P | O | LRO 계약 한 벌, Envelope null 생략 | +| 20 | 개발자 경험 | X | P | 매뉴얼·생성 명령·왕복 검사가 생겼다. 생성 계약이 실제 adapter를 못 받고(RR-01-01) 매뉴얼 일부가 코드와 반대(RR-01-03) | +| 22 | 추상화 성숙도 | P | O | `IntegrationEventDrafts`로 10필드 생성자를 직접 다루지 않는다 | +| 23 | 일관성 | X | P | TenantId·LRO·문법·이름 규칙이 정리됐다. 매뉴얼과 코드 불일치, sample 복사본이 남았다 | +| 24 | 네이밍·의미 | P | O | 이름 규칙 정본 표, `*ValueTypesTest` 개명, 예외는 "따라 하지 말 것"으로 명시 | +| 25 | 조직 확장성 | P | O | 기능 패키지가 템플릿 패키지와 섞이지 않게 생성 명령과 ArchUnit이 막는다 | +| 27 | 삭제 가능성 | P | O | sample 전용 LRO 타입이 sample로 내려갔다 | + +10 테스트·15 보안·21 Guardrail은 기호가 그대로 P다. 키트가 크게 늘었지만 RR-01-01·02·04·06이 남는다. + +## Assessment + +**Ready to merge?** With fixes + +**Reasoning:** 01 영역 발견 14건 중 12건이 닫히거나 결정으로 닫혔고, Critical·회귀는 없다. 다만 이번 수정이 새로 만든 탈출구(`@SystemInvoked`, RR-01-02)와, 따라 할 예시인 생성 계약이 실제 adapter를 못 받는 문제(RR-01-01), 매뉴얼이 고친 코드와 반대로 말하는 곳(RR-01-03)은 파생 서비스로 그대로 복제되므로 병합 전에 고치는 편이 싸다. diff --git a/docs/reviews/2026-11-03-rereview/02-inbound-transports.md b/docs/reviews/2026-11-03-rereview/02-inbound-transports.md new file mode 100644 index 00000000..89b92c7e --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/02-inbound-transports.md @@ -0,0 +1,298 @@ +# 02 inbound 전송(HTTP·GraphQL·WebSocket·gRPC) 재리뷰 (2026-11-03) + +리뷰 대상: Base `01a8a2a70` → Head `5786126c`, 영역 번호 02(slug `inbound-transports`). 원래 영역 문서는 +`docs/reviews/2026-11-01-maturity-review/02-inbound-web.md`, `03-inbound-realtime-graphql-grpc.md`다. + +## 범위 — 본 pathspec, 불러온 스킬과 적용한 기준, 실행한 명령과 결과, 못 본 것 + +### 본 pathspec + +```text +src/adapter/inbound src/grpc src/grpc-advanced docs/web +docs/architecture/graphql-api-surface.txt docs/runbooks/grpc-platform-operations.md +docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md +``` + +`git diff --stat` 기준 188파일 +9,378 −614. 여러 번에 나눠 직접 읽었다(하위 에이전트 없음). + +- 꼼꼼히 읽은 것: web main 전체 diff(인증·CORS·Envelope·오류 핸들러·멱등 키·rate limit·설정), + `docs/web/http-contract.md` 전문, web README·runbook diff, web-advanced 오류 enum, web-fileserver CORS 기여, + GraphQL 복잡도 scorer·calculator·deadline·per-parent instrumentation·interceptor 전문, WebSocket writer·handler· + STOMP 연결 상한·구독 상한 전문, gRPC 어댑터 admission·deadline interceptor·runner·settings 전문, gRPC ledger + port·JPA adapter·repository·entity·V002·interceptor·retention·starter 전문, ADR-GRPC-004·runbook diff. +- 경로만 따라간 것: pathspec 밖이지만 판단에 필요한 `IdempotencyExecutor`(application-core), + `OperationalError`·`Envelope` 계열(shared-contract), `docs/registries/error-codes.yaml`, `security.yml`, + `IdempotencySettings`(composition:idempotency), spring-graphql 2.0.5 jar의 `BlockingHandlerMethodPredicate`(javap). +- 훑기만 한 것: `src/adapter/inbound/messaging`(새 leaf, 06 영역 소관), web-notification 콜백 503(05-20), + web-fileserver tus PATCH(05-12). 이 셋은 「Declined to judge」에 적었다. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +| --- | --- | --- | +| `superpowers:requesting-code-review` | 리뷰어 템플릿 — 계획 정렬(README 12~16절·영역 문서 완료 기준), 코드 품질, 아키텍처, 「Declined to judge」, 읽기 전용, 하위 에이전트 금지 | 발견마다 완료 기준을 코드로 대조, 수정 diff 자체의 결함 탐색 | +| `api-and-interface-design` | 한 가지 오류 모양(Consistent Error Semantics), Hyrum's Law(관찰되는 wire 변화는 계약), Idempotency-Key 절(원자적 claim, 처리 중 중복에 대한 의도된 응답 409, 다른 본문 422, 결과 불명 3분류, 보존 기간 ≥ 재시도 경로) | `http-contract.md`와 실제 응답 대조(Tomcat 실행), 409/422/Retry-After, gRPC ledger claim·takeover·commit·purge 경쟁 | +| `security-and-hardening` | STRIDE의 DoS(입력 크기·복잡도·연결 수 상한, timeout), CORS는 명시 목록, 인증/인가(JWT aud·role 범위), 오류 본문이 입력을 되돌려 쓰지 않음 | GraphQL 복잡도 우회, WebSocket·gRPC 한도와 종료, CORS 노출 헤더, JWT audience 필수·client role 범위, `/error` 본문의 path echo | + +### 실행한 명령과 결과 + +모두 `git worktree add /rr-02 5786126c`로 만든 worktree에서 `flock heavy.lock`으로 감싸 돌렸다. +끝난 뒤 `git worktree remove --force`로 지웠다. 임시 테스트 원본은 scratchpad `rr-02-notes/probes/`에 남겼다. +메인 체크아웃에는 이 문서 말고 바꾼 파일이 없다. + +| 명령 | 실행 직전 load | 결과 | +| --- | --- | --- | +| `git diff --stat / git diff 01a8a2a70..5786126c -- ` | — | 188파일 | +| `./gradlew :adapter:inbound:graphql:test --tests '*Rr02UnionProbeTest'` (임시 테스트) | 6.14 | rc=0. `plainNested score=3368410`, `unionNested score=20`, `unionSingleNested score=20`, `unionPageOverMax score=20`(거부 안 됨), `unionFragmentSpread score=20`, `plainPageOverMax rejected=page size exceeds maximum` → RR-02-01 | +| `./gradlew :adapter:inbound:web:test --tests '*Rr02ErrorDispatchProbeTest'` (임시 테스트, 실제 Tomcat) | 17.95 | rc=0. `GET /probe/item;x=1` → `400 {"success":true,"data":{"timestamp":…,"status":400,"error":"Bad Request","path":"/probe/item;x=1"},"meta":{…}}` → RR-02-02. 대조군 `/probe/item` 200 정상 Envelope, `/probe/missing` 404 `ROUTE_NOT_FOUND` 실패 Envelope | +| `./gradlew -p optional-platforms :grpc:grpc-core-api:test --tests '*Rr02StaleOwnerProbeTest'` (임시 테스트, 공유 계약 fake) | 22.27 | rc=0. `bTookOver=true staleOwnerMarkFailed=accepted state=FAILED_TERMINAL cReclaimed=true` → RR-02-04 | +| `javap` spring-graphql 2.0.5 `AnnotatedControllerDetectionSupport$BlockingHandlerMethodPredicate` | — | `CompletableFuture`를 돌려주는 resolver는 blocking으로 보지 않아 호출 스레드에서 돈다. per-parent instrumentation이 README 예시를 N+1로 오인하지 않는다(문제 없음 확인) | + +게이트(ci·mainCheck·integrationCheck·optional·performanceCheck·releaseCheck)는 README 16.2대로 이미 통과했고 +다시 돌리지 않았다. + +### 못 본 것 + +- 짝 프론트를 실제로 붙여 실행하지 않았다(프론트 분류기·strict 스키마의 반응은 판단하지 않음). +- 기본 JWT 체인에서 `/error` 디스패치가 401로 바뀌는지는 코드로 추론만 했다(실행은 permit-all 체인으로 함). +- gRPC ledger의 동시 commit 경쟁은 실 PostgreSQL로 재현하지 않았다(순차 경로만 fake로 실행). +- Jetty·nginx WebSocket lane, gRPC Netty·fault lane, GraphQL systemTest는 다시 돌리지 않았다. + +## Strengths + +- **wire 모양을 원문 키로 단언한다.** `EnvelopeWireShapeTest.java:36-41,186-189`가 `doesNotExist`(null도 통과) 대신 + 응답 원문의 키 집합을 비교한다. 02-02가 숨어 있던 바로 그 맹점을 막는다. Boot `JsonMapper`를 쓰는 + `@WebMvcTest`라 mix-in 등록 경로까지 함께 검증한다. +- **JWT audience가 두 겹으로 닫혀 있다.** `SecuritySettings.java:62`(기동 거부), `JwtDecoderConfig.java:78`(검증기 + 조립 거부), 미해결 `${…}` 자리표시자를 값으로 쓰지 않는 `SecuritySettings.java:87`. role은 audience client만 + 읽는다(`JwtToAuthenticatedPrincipalConverter.java:94`). 다른 client role 무시 테스트가 있다. +- **컨버터 밖 거부 응답의 writer가 하나다.** `EnvelopeResponseWriter.java:34-41`. Tomcat 기본 문자셋을 흉내 낸 + `RateLimitInterceptorTest`의 `ContainerDefaultCharsetResponse`가 02-04를 실제로 다시 잡는다(mock의 관대함에 기대지 않음). +- **gRPC 과부하 거부가 "정상 close"다.** `GrpcCallAdmission.java:65-118`이 executor 선택 단계에서 permit을 정하고, + 거부된 호출은 handler 없이 `RESOURCE_EXHAUSTED`로 닫으며, permit은 `onComplete`/`onCancel`에서 한 번만 돌려준다. + bounded pool reject가 스트림을 매달아 두는 io.grpc 동작을 정확히 피했다. 서버 deadline close도 + `GrpcServerDeadlineInterceptor.java:94-144`에서 직렬화했다. +- **WebSocket 경쟁 두 건을 같은 lock 아래 재확인으로 닫았다.** `SerializedOutboundWriter.java:107`(close 뒤 offer + 예약 금지), `PlatformWebSocketHandler.java:93-124`(stop 전후 연결 1001), 큐 거부 시 구독 슬롯 반환 + `WebSocketInboundAuthorizationInterceptor.java:78`. +- **ledger 회수·정리가 SQL 한 문장씩이다.** `GrpcOperationLedgerRepository.java:106-156` — takeover는 조건부 UPDATE, + purge는 `FOR UPDATE SKIP LOCKED` 부분 질의 + 바깥 `state <> 'IN_PROGRESS'` 이중 조건, V002 부분 인덱스. +- **GraphQL deadline이 값 하나다.** `GraphQlPlatformWebInterceptor.java:132-138`이 요청 context의 deadline으로 + timer를 걸고, 실행 스레드 모델별 한계를 테스트 두 개로 고정했다(README 「요청 deadline」). +- **복잡도 scorer가 변수 기본값·포화 산술을 다룬다.** `GraphQlDocumentComplexityScorer.java:385-405`, + `GraphQlComplexityCalculator.java:148`. 03-01 완료 기준의 네 쿼리는 모두 고쳐졌다. + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +| --- | --- | --- | +| 02-01 | 닫힘(백엔드) | `OperationalError.java:47` retryable=true, `RetryAfterAdvisor.java:19` 2초, `http-contract.md:73`, `runbook.md:41-44`, `error-codes.yaml:402-408`이 같은 문장. 짝 프론트 §6 반영은 15절 결정대로 프론트 세션 인계. 단 같은 표의 503 행이 거짓 → RR-02-03 | +| 02-02 | 닫힘(MVC 경로) | `EnvelopeWireFormatConfig.java:33-38` mix-in, `EnvelopeWireShapeTest`. MVC 밖 `/error` 디스패치는 여전히 `success:true`+`data` → RR-02-02로 따로 | +| 02-03 | 닫힘 | 위 Strengths 두 번째 항목. `.env.example:97` 빈 값은 기동 실패(15절 결정대로) | +| 02-04 | 닫힘 | `EnvelopeResponseWriter.java:34-41`, `RateLimitInterceptor` reject가 이를 씀 | +| 02-05 | 닫힘 | `CorsExposedHeaders.PLATFORM`, `SecurityConfig` 합집합, `FileserverHttpSurfaceConfiguration` 기여 bean, `CorsSecurityFilterIntegrationTest` 2건 | +| 02-06 | 닫힘 | `EnvelopeBodyAdvice.java:77-80`(String 컨버터면 같은 mapper로 직렬화), `EnvelopeBodyAdviceTest` 3건 | +| 02-07 | 닫힘 | `WebAdvancedError` enum + 10종 carrier, `WebAdvancedErrorMappingTest`, `RetryAfterHint` | +| 02-08 | 닫힘 | `GlobalExceptionHandler.handleHandlerMethodValidationException`, 503→`REQUEST_TIMEOUT`, `TransportErrorHandlingTest` 2건 | +| 02-09 | 결정으로 닫힘 | 15절(JSON 아닌 본문은 엔드포인트가 직접). 변이 ①② 대응 테스트 `JsonBodyLimitFilterTest` 2건 추가 | +| 02-10 | 닫힘 | `WebAdapterAutoConfiguration` import 목록에서 제거, `WebMvcPlatformAutoConfigurationTest` 3건 | +| 02-11 | 닫힘 | `WebMvcRequestIdFilter.resolveCorrelationId`가 요청 id 규칙으로 교체, 테스트 3건 | +| 02-12 | 닫힘 | `IdempotencyKeyHeader`, sample `PosterImagePublicationController.java:64`, `FaultFixtureController.java:58` | +| 03-01 | **부분** | 완료 기준 네 쿼리는 통과. 그러나 union 타입 필드 아래는 점수 0·page 상한 미검사(실행 확인) → RR-02-01 | +| 03-02 | 닫힘(한계 문서화) | interceptor timer + `GraphQlDeadlineInstrumentation`, 두 실행 모델 테스트. 실행 중 resolver는 끊지 않음을 README가 명시 | +| 03-03 | 닫힘 | README 절 + 컴파일되는 예시 `OrderCustomerBatchLoading`, `GraphQlPerParentFetchInstrumentation`, `GraphQlPerParentFetchTest` | +| 03-04 | 닫힘 | registry 삭제, `graphql-api-surface.txt` 갱신 | +| 03-05 | 닫힘 | `GraphQlPlatformContextMissingException`(INTERNAL + `PLATFORM_CONTEXT`) + WARN | +| 03-06 | 닫힘 | STOMP 전송 한도 4개 키, `StompConnectionLimit`(1013), 세션당 구독 1, library handler `maxConnections` 필수. principal별 상한·토큰 재검증 없음은 README 한계로 명시 | +| 03-07 | 닫힘 | `SerializedOutboundWriter.java:107` 재확인 + 결정적 경합 테스트 | +| 03-08 | 닫힘 | `accepting` 플래그와 등록 뒤 재확인, `TomcatWebSocketShutdownIT` 재접속 케이스 | +| 03-09 | 닫힘 | `GrpcServerSettings` 상한, fixed pool + admission, 서버 deadline, drain. `GrpcP1BoundaryWireTest` 1 MiB·deadline·과부하 케이스 | +| 03-10 | 닫힘(완료 기준) | `reclaimStale`·purge·V002, 계약 테스트 fake·PG. 다만 takeover가 새 위험을 만들었다 → RR-02-04 | +| 03-11 | **부분** | 옵션 (b)로 interceptor·retention을 조립하고 ledger bean이 없으면 기동 거부. 그래도 플래그만 켜면 검증기는 통과하고 key를 실제로 처리하는 호출자는 여전히 없다. 「소유자가 (b)를 골랐다」는 기록이 15절에 없다 → RR-02-07 | +| 03-12 | > 08 영역 | `release.yml`은 이 pathspec 밖. README 13절 08-01+08-04+03-12 충족 | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +#### RR-02-01 · union 타입 필드 아래는 복잡도 점수 0이고 page 상한 검사도 건너뛴다 + +- **위치**: `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorer.java:154-156`, + `:250-260`, `:361-364` +- **무엇이 틀렸나**: `fieldCost`는 자식 비용을 `fieldsContainer(definition.getType())`로 구한다. 필드 타입이 + union이면 `GraphQLUnionType`은 `GraphQLFieldsContainer`가 아니라 `null`이 된다. 그러면 + `selectionSetCost(… parent=null …)`가 첫 줄에서 0을 돌려준다. union 아래의 inline fragment·fragment spread는 + 한 번도 방문되지 않는다. 그 안의 목록 곱셈도, `first`/`last` 상한 검사도 일어나지 않는다. 이 동작은 수정 전에도 + 있었고, 03-01 수정이 건드리지 않았다. 스코어러 단위 테스트에도 union 케이스가 없다. +- **왜 중요한가**: 검색 결과·피드처럼 union을 돌려주는 필드는 흔하다. 그런 필드가 하나라도 있으면 + `search { ... on Post { comments(first: 100000) { … } } }`가 점수 20으로 통과한다. 예산(기본 10,000)과 page 상한 + (기본 100)이 그 아래에서 꺼진다. resolver가 `GraphQlConnectionPolicy`를 직접 부르지 않으면 `first: 100000`이 + 그대로 DB까지 간다. 03-01과 같은 결함 종류이고, README 1절의 "GraphQL 공개 — 사용 보류" 판단을 그대로 남긴다. +- **고치는 법**: 부모가 union이어도 선택 집합은 내려간다. 직접 필드(union에는 `__typename`만 허용)만 건너뛰고, + type condition이 있는 inline fragment·fragment spread는 그 타입으로 계속 점수를 매긴다. union 목록 필드 자체는 + 지금처럼 `listCost`로 곱한다. scorer 테스트에 union·interface 각각 "중첩 목록 곱셈", "page 상한 초과 거부" 케이스를 넣는다. +- **심각도·우선순위**: High · P1 +- **증거**: E2 — 임시 테스트(스키마 `search: [SearchResult!]!`, `union SearchResult = Item`). + 같은 4단 중첩이 일반 목록이면 3,368,410점, union 아래면 20점. union 아래 `paged(first: 100000)`은 20점으로 통과, + 같은 값을 일반 목록에 쓰면 `page size exceeds maximum`으로 거부. + +#### RR-02-02 · 서블릿 오류 디스패치(`/error`) 응답이 `success:true` Envelope로 나간다 + +- **위치**: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java:68-81`, + `docs/web/http-contract.md:18-26,54-55`, `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java:87-94` +- **무엇이 틀렸나**: 컨트롤러 밖에서 생긴 오류(Spring Security firewall의 `RequestRejectedException`, 컨테이너 + `sendError`)는 서블릿 오류 디스패치로 Boot의 `BasicErrorController`에 간다. 그 컨트롤러가 돌려주는 `Map`을 + `EnvelopeBodyAdvice`가 그대로 `Envelope.ok(...)`로 감싼다. 결과는 HTTP 400인데 본문은 + `{"success":true,"data":{"timestamp":…,"status":400,"error":"Bad Request","path":"/probe/item;x=1"},"meta":{…}}`다. + 새 정본 `http-contract.md` 1절은 "실패 응답은 `success=false`, `error`, `meta`이고 `data` 키가 없다"고 약속하고, + 필터 체인 밖 오류는 "id 키가 빠질 수 있다"고만 적는다. `EnvelopeWireShapeTest`는 MockMvc라 오류 디스패치를 타지 + 않아 이 경로를 못 본다. 기본 JWT 체인은 `/error`를 공개 경로에 두지 않으므로, 익명 오류 디스패치가 인증에 걸려 + 원래 400 대신 401이 나갈 것으로 보인다(추론, 미실행). 샘플 체인은 GET을 모두 허용하므로 실행 결과와 같은 + `success:true` 모양이 나갈 것으로 보인다(추론). +- **왜 중요한가**: `success`를 판별자로 쓰라는 계약을 클라이언트가 그대로 따르면 4xx를 성공으로 읽는다. 짝 프론트의 + strict 스키마는 상태 코드와 모양이 어긋난 응답을 계약 위반으로 처리한다. 본문의 `path`는 요청 경로 원문을 + 되돌려 쓴다(02 영역 4.3이 404에서 막았다고 적은 것과 같은 종류). 기본 체인에서는 400이 401로 바뀌어 원인이 + 인증 문제로 오진된다. +- **고치는 법**: web leaf에 `ErrorController`(또는 `/error` 처리)를 두어 상태 코드를 `errorCodeFor`와 같은 표로 + 코드에 매핑하고 `ErrorResponseFactory`로 실패 Envelope를 쓴다. `EnvelopeBodyAdvice`는 응답 status가 4xx·5xx면 + 감싸지 않는다. 보안 체인에 `dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()`을 더해 원래 status가 나가게 + 한다. 실제 서버 테스트(오류 디스패치는 MockMvc로 재현되지 않는다)에 `;` 경로 케이스를 넣고 원문 키를 단언한다. +- **심각도·우선순위**: Medium · P2 (동작은 수정 전부터 있었다. 새 정본 계약이 반대로 약속한다) +- **증거**: E3 — 실제 Tomcat 임시 테스트(permit-all 체인 + `EnvelopeBodyAdvice` + `EnvelopeWireFormatConfig` + + `WebMvcPlatformAutoConfiguration`). 기본 JWT 체인의 401 전환은 E1(코드 읽기). + +#### RR-02-03 · 정본 계약이 `IDEMPOTENCY_UNAVAILABLE`을 "작업 실행 전에 거부"라고 적지만, complete 단계에서는 작업이 이미 돌았다 + +- **위치**: `docs/web/http-contract.md:94`, `src/adapter/inbound/web/README.md:243`, + `src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyUnavailableException.java:7`, + `src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java:193,203,233` +- **무엇이 틀렸나**: `runStarted`는 `action.run()`(193행)이 성공한 뒤 `complete`(203행)를 부른다. 저장소가 + `UNAVAILABLE`을 돌려주면 233행이 같은 `IdempotencyUnavailableException`을 던진다. 그런데 새 정본 표는 이 코드를 + "작업 실행 전에 거부됐다. 같은 키로 나중에 다시 보낸다"로만 적는다. 02 영역 문서 2절이 P6-new-2로 이미 지적했고 + 결정 24는 "현재 동작 유지 + 문서화"였다. 이번에 만든 정본 문서가 그 거짓 문장을 다시 실었다. +- **왜 중요한가**: 클라이언트는 이 문장을 보고 사용자에게 "적용되지 않았다"고 알린다. `inWrite` 안의 DB 효과는 + 예외로 롤백되지만, action 안의 비트랜잭션 효과(외부 호출 등)는 이미 일어났다. 같은 키 재전송은 Redis 저장소에서 + claim이 `EXECUTING`으로 남아 있으면 409를 반복하다 lease 뒤 다른 판정을 받는다. "결과 불명"을 "확실히 안 함"으로 + 기록하는 것은 README 4절의 반복 원인 1번과 같은 모양이다. +- **고치는 법**: 최소한 정본 표·README 표·예외 Javadoc을 "claim 단계면 실행 전, complete 단계면 실행했을 수 있음 + (같은 트랜잭션의 DB 효과는 롤백)"으로 나눠 적는다. 더 낫게는 complete 단계에 별도 코드(예: + `IDEMPOTENCY_COMPLETION_UNKNOWN`)를 주고 클라이언트 행동을 따로 정한다. `IdempotencyExecutorTest`에 "action 뒤 + complete UNAVAILABLE" 케이스를 넣어 어느 예외·코드가 나가는지 고정한다. +- **심각도·우선순위**: Medium · P2 +- **증거**: E1 — 코드 경로(193→203→233)와 문서 대조 + +#### RR-02-04 · ledger에 시도(owner) 구분이 없어, takeover 뒤 옛 owner의 실패·완료 기록이 새 시도를 덮는다 + +- **위치**: `src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java:75-101`, + `GrpcOperationLedgerEntity.java:123-139`, `GrpcOperationLedgerRepository.java:106-123`, + `src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java:182-202`, + `docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md:61-69` +- **무엇이 틀렸나**: takeover(`tryReclaimStale`)는 `claimed_at`만 바꾼다. `markCommitted`·`markFailed`는 identity만 + 받고 "어느 시도의 기록인지"를 받지 않는다. 엔티티 검사는 `state == IN_PROGRESS` 하나다. 그래서 TTL(5분)을 넘긴 + 옛 owner A가 나중에 `markFailed`를 부르면, B가 넘겨받아 실행 중인 claim이 `FAILED_TERMINAL`이 된다. 그다음 재시도 + C가 `reclaimFailed`로 다시 claim하면 B와 C가 동시에 실행된다. 또 JPA `markCommitted`는 `findById` → 상태 확인 → + `save`라 행 잠금·`@Version`이 없다. 두 시도가 같은 순간 commit하면 둘 다 IN_PROGRESS를 읽고 둘 다 커밋한다. + ADR은 "느린 owner의 commit"만 위험으로 적고, 옛 owner의 `markFailed` 덮어쓰기는 적지 않는다. 버린 대안 목록에도 + heartbeat 없는 fence(commit 시 claim 시각 비교)가 없다. 공유 계약 테스트에 "takeover 뒤 옛 owner의 기록" 케이스가 없다. + - 같은 묶음의 작은 경쟁: purge가 지운 직후 같은 key의 claim은 `INSERT … ON CONFLICT`가 0을 받고 `findById`가 비어 + `IllegalStateException("… Retry the claim.")`을 던진다(`JpaGrpcOperationLedger.java:53-65`). `decide()`는 다시 + 시도하지 않아 호출자는 내부 오류를 받는다. 보존 기간(24h)보다 오래된 key에서만 열리는 좁은 창이다. +- **왜 중요한가**: 03-10 수정은 "key가 영구히 막힘"을 "TTL 뒤 넘겨받음"으로 바꿨다. 넘겨받는 순간이 바로 하류가 + 멈춘 때라 옛 owner가 늦게 깨어나 기록하는 경우가 생긴다. 그때 기록이 새 시도를 덮어 같은 operation이 두 번 + 돌 수 있다. 멱등성 ledger가 막으려던 결과다. 플랫폼이 아직 어디에도 채택되지 않아 지금 노출은 없다(채택 전 차단 항목). +- **고치는 법**: claim·reclaimFailed·reclaimStale이 claim 토큰(그 시도의 `claimed_at`이나 attempt id)을 돌려주게 + 한다. `markCommitted`·`markFailed`는 `UPDATE … WHERE state='IN_PROGRESS' AND claimed_at=:token`으로 바꿔 0행이면 + 호출자가 롤백한다. 계약 테스트에 "takeover 뒤 옛 owner의 commit·fail은 거부", PG lane에 "동시 commit은 하나만"을 + 더한다. ADR 버린 대안에 fence 안을 적거나 고른다. purge 경쟁은 claim이 행 소실을 보면 insert를 한 번 더 시도하게 한다. +- **심각도·우선순위**: Medium · P2 (채택 전에 고친다) +- **증거**: E2 — 공유 계약 fake로 순차 경로 실행: `bTookOver=true staleOwnerMarkFailed=accepted state=FAILED_TERMINAL cReclaimed=true`. + JPA 동시 commit 경쟁은 E1(코드 읽기, 실 PG 미실행). + +### Minor (Nice to Have) + +#### RR-02-05 · `Retry-After: 2`를 "lease에 맞춰 다시 정하라"고 하지만 고칠 손잡이가 없다 + +- **위치**: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java:14-19`, + `docs/web/http-contract.md:80-83`, `src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java:47-50` +- **무엇이 틀렸나**: 정본은 "lease를 2초보다 짧게 설정한 서비스는 값을 다시 정한다"고 적는다. 그런데 2초는 web leaf의 + 정적 표에 박혀 있고 설정 키가 없다. `IdempotencySettings`도 lease 하한을 2초 위로 막지 않는다. +- **왜 중요한가**: 개발자가 따로 기억해야 하는 숨은 규칙이다. lease를 1초로 둔 서비스는 클라이언트를 lease 뒤에 + 다시 오게 만든다. +- **고치는 법**: `IdempotencySettings`에서 lease가 `IDEMPOTENT_IN_FLIGHT`의 Retry-After보다 길어야 기동하게 하거나, + 문장을 "lease를 2초 이하로 두지 않는다"로 바꾼다. +- **심각도·우선순위**: Low · P3 · **증거**: E1 + +#### RR-02-06 · in-flight `retryable` 변경이 gRPC·GraphQL wire에도 나가는데 문서·테스트·호환성 표시가 없다 + +- **위치**: `src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapper.java:59-64`, + `docs/registries/error-codes.yaml:404-414` +- **무엇이 틀렸나**: `IDEMPOTENT_IN_FLIGHT`가 retryable=true가 되면서 gRPC trailer `error-retryable`(status ABORTED)와 + GraphQL extension `retryable`도 true로 바뀌었다. README 13절이 "테스트 없음"으로 남긴 상태 그대로다. registry는 + `compatibility_impact: none`이다. 같은 코드 이름 `REQUEST_TIMEOUT`이 web에서는 503·`TRANSIENT_DEPENDENCY`(이번에 + 새로 만듦), GraphQL에서는 category `TIMEOUT`이다. +- **왜 중요한가**: 관찰되는 wire 값이 바뀌면 소비자가 의존한다(Hyrum's Law). 클라이언트가 전송마다 다른 뜻을 배운다. +- **고치는 법**: gRPC·GraphQL 매핑 테스트에 in-flight 케이스를 넣고 각 README에 한 줄 적는다. registry의 + `compatibility_impact`를 `behavior-change`로 고친다. web 쪽 timeout 코드 이름과 category를 GraphQL과 맞추거나 차이를 적는다. +- **심각도·우선순위**: Low · P3 · **증거**: E1 + +#### RR-02-07 · 03-11: 플래그만 켜면 검증기는 통과하고, key를 처리하는 호출자는 여전히 adopter 몫이다 + +- **위치**: `src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java:149-155`, + `GrpcPlatformAutoConfiguration.java`(interceptor bean Javadoc "nothing calls this yet"), `src/grpc/CLAUDE.md:168` +- **무엇이 틀렸나**: 검증기 문구는 "플래그가 false면 key가 받아들여지고 처리되지 않는다"고 한다. 플래그를 true로 + 두면 결정 함수 bean은 생기지만 그것을 부르는 서버 단계가 없어도 기동한다. 원래 지적("운영자가 멱등 처리가 켜졌다고 + 믿는다")이 좁아졌을 뿐 남는다. 또 `src/grpc/CLAUDE.md:168`의 "The owner chose (b)"는 리뷰 README 15절 결정 기록에 없다. +- **고치는 법**: 15절(또는 ADR)에 (b) 결정과 이유를 기록한다. 검증기가 `IDEMPOTENCY` 단계 interceptor가 조립됐는지까지 + 보거나, 문구를 "플래그는 결정 함수만 조립한다. 서버 단계 연결은 별도"로 고친다. +- **심각도·우선순위**: Low · P3 · **증거**: E1 + +#### RR-02-08 · GraphQL 작은 불일치 두 건 + +- **위치**: `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlComplexityCalculator.java:124-127` + 대 `:56-60`, `context/GraphQlDeadline.java:11-22` 대 `README.md:298` +- **무엇이 틀렸나**: ① `effectivePageSize(first, last)`는 둘 다 있으면 `first`를 고른다. 같은 클래스의 + `connectionCost`는 이번 수정으로 큰 쪽을 고른다. main 호출자는 없다. 갈라진 복사본이다. ② `GraphQlDeadline` Javadoc은 + "지금 읽는 곳은 이것뿐"이라며 셋을 나열하지만 이번에 추가한 `GraphQlDeadlineInstrumentation`이 빠졌다. README는 넷이다. +- **고치는 법**: `effectivePageSize`를 지우거나 `connectionCost`와 같은 규칙으로 맞춘다. Javadoc 목록에 instrumentation을 넣는다. +- **심각도·우선순위**: Low · P3 · **증거**: E1 + +## Declined to judge + +- 짝 프론트의 분류기·strict 스키마가 `retryable=true` 409와 `meta.page.sort: null`을 어떻게 받는지 — 다른 repo이고 + 15절에서 프론트 세션에 인계했다. +- `src/adapter/inbound/messaging`(inbox 자동 설정·마이그레이션 스트림) — 06 영역 발견(06-08)의 수정이다. + `TransactionTemplate`에 timeout이 없다는 점만 눈에 띄었다. +- web-notification 콜백 503+`Retry-After`(05-20)와 본문 상한 계산, web-fileserver tus PATCH(05-12) — 05 영역 소관. +- Keycloak 기본 토큰의 `aud=account`를 audience로 넣는 운영 실수 — 코드는 설정한 값을 정확히 검사한다. 운영 문서 문제로 보고 판단하지 않았다. +- `GlobalExceptionHandler`가 503 상태 전체를 `REQUEST_TIMEOUT`으로 읽는 것 — 지금 Spring MVC에서 503을 내는 예외가 async timeout 하나라 문제는 없다. 미래 Spring 변경 위험은 추측이라 올리지 않았다. +- `PlatformWebSocketHandler`가 `final`이 되고 생성자 인자가 늘어난 API 변경 — 라이브러리 소비자가 템플릿 안에 없고 README가 새 시그니처를 적는다. +- WebSocket 연결 상한 기본 1000 × send buffer 512 KiB = 최악 512 MiB — README가 노드 heap에 맞추라고 적었다. 실측하지 않았다. +- GraphQL over WebSocket 구독에 interceptor timeout이 어떻게 걸리는지 — 이 템플릿에서 구독을 켜는 경로를 확인하지 못했다. +- `DurableOperationController`의 id factory 교체 — 01·07 영역 결정(UUIDv7)의 일부다. + +## 28개 관점 — 바뀐 관점만 + +| # | 관점 | 영역 | 이전 → 지금 | 이유 | +| --- | --- | --- | --- | --- | +| 5 | 위험 가시성 | 02 | X → P | audience 필수·String·null 생략이 코드에 드러남. `/error` 모양(RR-02-02)과 503 문장(RR-02-03)이 남음 | +| 5 | 위험 가시성 | 03 | X → P | deadline·STOMP 한도·ledger 플래그가 코드와 문서에 맞음. union 점수 구멍(RR-02-01)이 드러나지 않음 | +| 7 | 운영 성숙도 | 03 | P → O | gRPC drain, WebSocket stop 뒤 1001, ledger 증가 runbook | +| 8 | 디버깅 가능성 | 03 | P → O | batch context 누락이 `PLATFORM_CONTEXT`+WARN, per-parent N+1이 WARN+metric | +| 13 | 확장성 | 03 | X → P | WebSocket 노드 연결·구독 상한, gRPC bounded pool+admission. principal별 상한은 없음(문서화) | +| 15 | 보안 성숙도 | 02 | X → P | JWT audience 필수·client role 범위. `/error` 본문의 path echo와 상태 왜곡(RR-02-02) | +| 17 | API·계약 | 02 | X → P | 정본 `http-contract.md`와 원문 키 테스트. `/error`·503 행이 계약과 어긋남(RR-02-02·03) | +| 19 | 설정 성숙도 | 03 | P → O | STOMP·gRPC 한도가 검증되는 명시 키, ledger TTL·보존 키 | +| 25 | 조직 확장성 | 02 | P → O | KEYED 헤더 추출이 `IdempotencyKeyHeader` 하나(02-12) | +| 28 | 회복 가능성 | 03 | X → P | stale claim 회수·writer 예산 누수 해소. takeover 뒤 옛 owner 기록 fence 없음(RR-02-04) | + +## Assessment + +**Ready to merge? With fixes.** Critical은 없다. 02·03 발견 24건 중 21건이 닫혔고(결정으로 닫힘 1건 포함), 2건(03-01·03-11)은 부분, 1건(03-12)은 08 영역이다. RR-02-01(union 아래 복잡도 우회, +High)이 GraphQL 공개 보류를 그대로 남기므로 GraphQL을 켜기 전에, RR-02-04는 gRPC ledger 채택 전에, RR-02-02·03은 +짝 프론트가 정본 계약을 따르기 전에 고쳐야 한다. diff --git a/docs/reviews/2026-11-03-rereview/03-persistence.md b/docs/reviews/2026-11-03-rereview/03-persistence.md new file mode 100644 index 00000000..04f2581a --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/03-persistence.md @@ -0,0 +1,232 @@ +# 03 persistence 재리뷰 (2026-11-03) + +## 범위 + +- 리뷰 범위: Base `01a8a2a70` → Head `5786126c`. +- 본 pathspec: `src/adapter/outbound/persistence-jpa`, `persistence-mongo`, `persistence-fileserver`, + `persistence-notification`, `docs/jpa`, `docs/mongodb`, `docs/architecture/jpa-api-surface.txt`, + `docs/adr/ADR-JPA-003-completion-unknown.md`. 224파일, +8,176 −2,138. +- 판단에 필요해서 pathspec 밖에서 읽은 것: + - `application-core`: `AggregateOrder`, `OutboxAggregateSequenceContract`, `SubmitDurableOperationUseCase`, `PublishPendingOutboxEventsUseCase`의 트랜잭션 경계. + - `adapter/outbound/messaging`: `PlatformIntegrationEventPublishAdapter`(순서 번호가 소비자에게 나가는 곳). + - `application-notification` testFixtures: `OverlappingWrites`, `SuppressionStoreContract`, `ReconciliationJobStoreContract`. + - `app-bootstrap`: `JpaProductionArchitectureTest`, `build.gradle`(ArchUnit 규칙이 보는 leaf 범위). + - `docs/runbooks/outbox-dead-letter.md` §8, `docs/jpa/migration-guide.md`, `src/config/architecture/modules.json`. + - 15절이 이 영역에 묶은 마이그레이션: grpc-ledger `V002`와 그 삭제 쿼리, sample `V8_1`과 `PosterRepositoryAdapter`. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +|---|---|---| +| `superpowers:requesting-code-review` | 리뷰어 템플릿: 요구사항 정합, mock이 아닌 실제 동작 테스트, 마이그레이션 전략·하위 호환, Declined to judge, 심각도 보정 | 발견별 완료 기준 대조, 테스트가 단언하는 범위, 마이그레이션의 기존 데이터 영향 | +| `jpa-patterns` | assigned id와 `Persistable`, 짧은 트랜잭션·readOnly, bulk UPDATE와 `@Version`, JDBC batch(`batch_size`, `order_inserts`), Flyway additive 마이그레이션 | 04-05·04-07·04-10·04-17·09-07. 연관관계는 **사용자 원칙(양방향 금지)을 스킬의 `mappedBy` 예시보다 우선**해서 규칙의 빈틈을 찾았다(RR-03-04) | +| `supabase-postgres-best-practices` | `lock-skip-locked`(claim은 CTE + `FOR UPDATE SKIP LOCKED` + `UPDATE … RETURNING` 한 문장), `data-upsert`(check-then-insert 금지, `ON CONFLICT`), `schema-constraints`(제약 추가의 재실행 안전성), `lock-short-transactions`(트랜잭션 시간 제한), `query-partial-indexes`·인덱스 | 04-02·04-08·04-13의 claim·upsert, 새 counter(RR-03-01), V20·V21·V11~V13·V002의 잠금·재실행·기존 데이터 영향(RR-03-02·05) | + +### 실행한 명령 + +모두 별도 worktree `scratchpad/rr-03`(@`5786126c`)에서 `flock heavy.lock`으로 감싸 실행했다. 끝난 뒤 `git worktree remove --force`로 지웠다. 메인 작업 트리는 바꾸지 않았다. + +| 명령 | 실행 직전 부하 | 결과 | +|---|---|---| +| `./gradlew :adapter:outbound:persistence-jpa:test --tests '*RrScratchTest*'` (임시 테스트 1클래스·엔티티 3개 추가) | load 23.79 | rc=0, 3개 실행. 관찰은 RR-03-03·RR-03-04 | +| `./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxAggregateSequenceIntegrationTest` (기존 클래스에 임시 메서드 2개 추가) | load 17.43 | rc=0, 6개 실행·skip 0. 관찰은 RR-03-01·RR-03-02 | + +임시 테스트는 결과를 출력만 하고 실패시키지 않게 썼다. rc=0은 "결함 없음"이 아니다. 관찰값은 각 발견의 증거 칸에 적었다. + +### 못 본 것 + +- Mongo 컨테이너 lane(`MongoTransactionWriteConflictLaneTest`)은 직접 돌리지 않았다. 04-11은 코드로만 봤다. +- 알림 정산 claim을 실제 2개 인스턴스로 돌리지 않았다. 공용 계약(`ReconciliationJobStoreContract`)을 읽었다. +- V20의 CHECK 추가가 테이블을 한 번 읽는지 실측하지 않았다. +- optional-platforms build(grpc-ledger)는 실행하지 않았다. +- 전체 게이트는 README 16.2 결과를 그대로 썼다. + +## Strengths + +- **커밋 단계를 따로 분류한다.** `SpringTransaction.java:195-215`는 본문이 끝난 뒤 자기가 연 쓰기 트랜잭션을 커밋하는 동안 난 실패만 `translateCommitFailure`로 보낸다. 실 PostgreSQL 테스트가 `pg_terminate_backend`로 커밋 중 연결을 끊고 `DB_COMPLETION_UNKNOWN`·`retryable=false`를 단언한다(`PostgreSqlTransactionIntegrationTest.java:211-214`). +- **SQLState 표가 한 벌이 됐다.** `PostgreSqlSqlStateErrorMapping.java:60-90`은 행을 직접 쓰지 않고 `PostgreSqlFailureClassifier` → `FailureCategory.operationalError()`에서 만든다. `SqlStateClassificationParityTest`가 두 경로의 결과를 모든 상태에 대해 비교한다. +- **정산 job claim이 한 문장이다.** `JdbcReconciliationJobStore.java:56-72`는 CTE + `SKIP LOCKED` + `UPDATE … RETURNING`으로 lease와 fence를 같은 문장에서 쓴다. 이후 쓰기는 fence 조건이다. 같은 계약을 fake와 실 PG가 상속한다(`ReconciliationJobStoreContract.java:54,70`). +- **upsert를 DB가 판정한다.** `JpaSuppressionStore.java:59-100`은 `ON CONFLICT DO NOTHING` 뒤 managed entity로 갱신한다. `OverlappingWrites.java:42`는 첫 트랜잭션을 열어 둔 채 두 번째를 시작해 경쟁을 운에 맡기지 않는다. +- **계약 테스트가 실제 결함을 찾았다.** 선호 설정이 `jsonb` 열에 쉼표 문자열을 넣어 실 PG에서 항상 실패하던 것을 PG 계약 테스트가 드러냈고 고쳤다(`JpaPolicyStores.java:104`). +- **bulk UPDATE 규칙이 운영 그래프에 걸린다.** `JpaVersionedBulkUpdateRule.java:51,78`은 `@Version` 엔티티 이름을 검사 대상 그래프에서 계산한다. `JpaProductionArchitectureTest.java:135`가 notification·fileserver를 포함한 운영 클래스에 적용한다. +- **격리 수준 왕복 제거를 실측으로 고정했다.** 서버 기본값을 `repeatable read`로 둔 풀에서 `getTransactionIsolation()` 호출 0회와 `read committed` 실행을 함께 단언한다(`PostgreSqlTransactionIntegrationTest.java:322`). +- **V21 runbook SQL을 실 PG에서 실행한다.** `PostgreSqlOutboxOrderKeyRunbookIntegrationTest`가 runbook 문서에서 SQL 블록을 읽어 돌린다. 문서가 lane의 입력으로 선언돼 있다(`persistence-jpa/build.gradle`). +- **Mongo URI 경로 기본값의 순서가 맞다.** `MongoProfileClientSettingsAutoConfiguration.java:99`는 기본값을 가장 먼저 적용해 URI 값이 이긴다. 테스트가 Boot 표준 connection-string customizer와 함께 순서를 확인한다. +- **V12가 남길 행의 규칙을 SQL 주석에 적었다.** 삭제 마이그레이션에 생존 규칙 4단계와 이유가 있다. 같은 규칙이 leaf `CLAUDE.md`에 적혀 있다. + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +|---|---|---| +| 04-01 | 닫힘 | `SpringTransaction.java:195-215`, `PersistenceExceptionTranslator.java:157-182`, PG IT `:211-214`. 한계: IT는 `DataSourceTransactionManager`로 돈다. 운영은 `JpaTransactionManager`다. cause chain을 걷는 구현이라 같은 결과로 보지만 실행 확인은 안 했다 | +| 04-02 | 닫힘 | `JdbcReconciliationJobStore.java:56-90`, 계약 `ReconciliationJobStoreContract.java:54,70`. 남은 것: RR-03-08 | +| 04-03 | 부분 | 규칙(`SingleSidedAssociationCondition`), 가이드(`entity-mapping-guide.md:52-95`), 단방향 fixture는 들어왔다. `mappedBy` 없는 양방향이 규칙을 통과한다(RR-03-04, E3) | +| 04-04 | 닫힘(이 영역 몫) | persistence-fileserver 테스트 4클래스(activation, caller transaction, `AssignedIdEntity`, claim SQL). 새 lane 2개가 `readinessLanes`에 등록됐다. workflow 실행은 08 영역 | +| 04-05 | 닫힘 | `PersistenceExceptionTranslator.java:128-141`. PG IT `aVersionRaceLostAtCommitIsAnOptimisticConflict`가 `JpaTransactionManager`로 409 코드를 단언한다 | +| 04-06 | 닫힘 | `PostgreSqlSqlStateErrorMapping.java:60-90`, `SqlStateClassificationParityTest`. 남은 이름 문제: RR-03-10 | +| 04-07 | 닫힘 | `InboxItemJpaRepository`·`RecipientClaimSql.EXPIRE_OVERDUE`에 `version + 1`과 `clearAutomatically`. PG `InboxBulkReadVersionContractTest`·`RecipientExpiryVersionContractTest`. 한계: 규칙은 `@Modifying @Query`만 본다(Declined 참고) | +| 04-08 | 닫힘 | `JpaSuppressionStore.java:59-100`, `JpaPolicyStores.Preferences.save`, V12, `SuppressionStoreContract.java:150`(실 PG 겹침) | +| 04-09 | > | sample 영역. 이 리뷰에서 확인하지 않았다 | +| 04-10 | 부분 | 쓰기·읽기 30초. JDBC 경로는 PG IT로 확인됐다. Hibernate 문장 직전 마감 초과는 분류되지 않는다(RR-03-03, E3) | +| 04-11 | 닫힘(E1) | `SpringMongoTransactionSessionFactory.java:141-151`. 소항목(commit 재시도 대기 중 인터럽트)은 `MongoTransactionRetryCoordinator.java:150-156`. lane은 직접 돌리지 않았다 | +| 04-12 | 닫힘 | `MongoUriOnlyClientDefaults`, customizer 순서(`:99`), `MongoUriOnlyClientDefaultsTest`, `mongo.yml` 주석 정정 | +| 04-13 | 닫힘 | `JpaCleanupQueue`에 정책 상수·`heldClaims` 없음. lease는 인자, 토큰은 `CleanupItem`. claim 한 문장(`CleanupClaimSql`). PG `PostgreSqlFileserverReclamationIntegrationTest.java:174` | +| 04-14 | 부분 + 결정으로 닫힘 | notification 포트 계약 대부분을 PG가 상속한다. `ConsentStorePort`·`NotificationInbox`는 15절 결정으로 닫았다. fileserver `*PortContract` 상속 | +| 04-15 | 닫힘 | 테스트 소스 예시(`mongo/example`), `docs/mongodb/consumer-leaf-guide.md`. 가이드의 레지스트리 주장(app-bootstrap에 mongo edge가 이미 있음 등)을 `modules.json`과 대조해 맞음을 확인했다 | +| 04-16 | 닫힘 | 두 leaf `CLAUDE.md`, notification `entity`·`repository` 분할. 부작용: RR-03-09 | +| 04-17 | 닫힘 | `AssignedIdEntity`(`Persistable`), `AssignedIdEntityTest` | +| 09-02 | 닫힘(E1, 일부만 봄) | `V8_1`이 중복 사전 검사 뒤 `uq_poster_title_ci` 생성. adapter가 `saveAndFlush` 뒤 제약 이름으로 변환한다. 동시성 실측은 README 13절 기록 | +| 09-05 | 닫힘 | 템플릿 `ISOLATION_DEFAULT` + Hikari `transaction-isolation` + 기동 검사. PG IT `:322` | +| 09-07 | 닫힘 | `persistence-jpa.yml` batch 50·`order_inserts/updates` true, `ModuleDefaultJdbcBatchingTest` | +| 09-09 | 닫힘 | `build.gradle`이 H2를 `testRuntimeOnly`로. lockfile의 `runtimeClasspath`에서 H2가 빠졌다 | +| 05-01 | 닫힘(persistence 쪽) | `PostgreSqlNotificationBackgroundPassIntegrationTest`가 `DeliveryAttemptFactory`로 만든 행을 `LeaseRecoveryService`에 넣는다. 개명한 `WorkerCrashRecoveryContractTest` 테스트는 동어반복이다(RR-03-07) | +| 06-07 | 부분 | 순서 번호를 DB counter로 바꿨다(`JpaOutboxStore.nextSequence`). 순서 키 유일 인덱스(V21)가 들어왔다. counter가 새 결함 두 개를 만들었다(RR-03-01, RR-03-02) | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +#### RR-03-01 첫 counter 생성이 겹치면 정상 쓰기가 409로 거절된다 + +- **위치**: `persistence-jpa/.../outbox/jpa/JpaOutboxStore.java:114-124`, `OutboxEventJpaRepository.java:122-145`, Javadoc `JpaOutboxStore.java:108-112`. +- **무엇이 틀렸나**: counter가 없으면 `UPDATE`가 0행을 돌려주고 `INSERT … SELECT`로 만든다. 두 트랜잭션이 같은 aggregate에서 동시에 0행을 보면 둘 다 INSERT한다. 두 번째는 첫 번째의 커밋을 기다린 뒤 PK 위반(23505)으로 실패한다. Javadoc은 "a rollback the caller retries"라고 쓰지만 재시도하는 호출자는 없다. +- **증거**: 첫 트랜잭션이 `nextSequence` 뒤 커밋을 미루고, 두 번째가 같은 새 aggregate로 `nextSequence`를 불렀다. 첫째는 `1`. 둘째는 `PersistenceFailureException DB_UNIQUE_VIOLATION retryable=false`. +- **왜 중요한가**: + - 발생 조건: counter가 없는 aggregate에 쓰기 두 개가 겹칠 때. V21 배포 직후에는 기존 aggregate 전부가 counter가 없다. + - 영향: 정상 요청이 재시도 불가 409로 거절되고 그 업무 쓰기 전체가 롤백된다. + - 같은 leaf에 맞는 모양이 이미 있다: `JpaLiveEventReplay.java:41-48`의 `INSERT … ON CONFLICT (stream_id) DO UPDATE SET last_position = last_position + 1 RETURNING`. notification `CLAUDE.md`의 "Insert-or-update is decided by the database" 규칙과도 다르다. 같은 일을 하는 두 갈래 구현이다. +- **고치는 법**: 한 문장으로 바꾼다. + ```sql + INSERT INTO outbox_aggregate_sequence (tenant_scope, aggregate_type, aggregate_id, last_sequence) + SELECT :t, :a, :i, COALESCE(MAX(e.aggregate_sequence), 0) + 1 + FROM outbox_event e WHERE e.tenant_scope = :t AND e.aggregate_type = :a AND e.aggregate_id = :i + ON CONFLICT (tenant_scope, aggregate_type, aggregate_id) + DO UPDATE SET last_sequence = outbox_aggregate_sequence.last_sequence + 1 + RETURNING last_sequence; + ``` + 두 번째 쓰기는 첫째 커밋을 기다린 뒤 `DO UPDATE`로 2를 받는다. 행 잠금이라 커밋 순서도 그대로다. `OutboxAggregateSequenceContract`에 `OverlappingWrites` 같은 겹침 테스트를 더한다. +- **가이드 심각도·우선순위**: Medium · P2. **증거**: E3. + +#### RR-03-02 V21 이행 뒤 aggregate 순서 번호가 이미 내보낸 번호보다 작아진다 + +- **위치**: seed `OutboxEventJpaRepository.java:130-145`(`COALESCE(MAX(e.aggregate_sequence), 0) + 1 FROM outbox_event`), V21 주석 `V21__outbox_aggregate_sequence.sql:8-11`, 소비자로 나가는 곳 `PlatformIntegrationEventPublishAdapter.java:102,124`, 계약 `AggregateOrder` Javadoc("consumers read it as 'which change came last'"). +- **무엇이 틀렸나**: + - seed는 outbox에 남은 행만 본다. + - `OutboxReaper`는 retention이 지난 PUBLISHED 행을 지운다. + - 그래서 옛 벽시계 방식(epoch 마이크로초, 약 1.7×10¹⁵)으로 이미 발행한 aggregate도 counter가 1부터 시작한다. + - rolling 배포 중 옛 인스턴스가 벽시계 번호를 계속 쓰면, 새 인스턴스의 counter(옛 최대+1부터)는 나중 커밋에 더 작은 번호를 준다. + - V21 주석이 가리키는 `JpaOutboxAggregateSequences` 클래스는 없다(실제는 `JpaOutboxStore.nextSequence`). +- **증거**: 번호 1,761,955,200,000,000인 행을 append하고 지운 뒤(reaper 흉내) `nextSequence` → `1`(E3). 소비자 영향은 추론이다. 템플릿 안에는 번호를 비교하는 소비자가 없다(E1). +- **왜 중요한가**: + - `AggregateOrder.ofOccurrence`는 삭제된 공개 API다. 쓰던 파생 서비스는 업데이트하면서 `nextSequence`로 옮겨야 한다. + - 그 서비스의 소비자가 "마지막 번호보다 작으면 버린다"로 구현했다면 V21 이후 해당 aggregate의 이벤트를 모두 버린다. + - runbook §8은 중복 키만 다루고 이 단절은 말하지 않는다. + - V21 주석의 "rows numbered by the old clock scheme still come first"는 outbox 안에서만 참이다. +- **고치는 법(대안)**: + - (a) seed에 하한을 둔다. 다음 마이그레이션이 이행 시점 하한을 한 행 테이블에 기록하고, 새 counter는 `GREATEST(MAX, 하한) + 1`에서 시작한다. 벽시계를 쓴 적 없는 서비스는 하한 0. 코드로 막으므로 권한다. + - (b) runbook에 "V21 전 모든 옛 writer 종료(mixed version 금지)"와 "소비자의 마지막 번호 초기화" 절차를 적는다. + - (c) 계약 문서에 번호 단절을 명시하고 현상 유지. + - V21 파일은 해시가 고정돼 주석을 고칠 수 없다. 정정은 다음 마이그레이션 주석이나 runbook에 둔다. +- **가이드 심각도·우선순위**: Medium · P2. **증거**: E3(seed 동작), E1(소비자 영향). + +#### RR-03-03 JPA 경로에서 트랜잭션 마감 초과가 분류되지 않고 500이 된다 + +- **위치**: `PersistenceExceptionTranslator.java:128-141`(Spring `TransactionTimedOutException`만 본다), `SpringTransaction.java:121-126` Javadoc, `persistence-jpa/CLAUDE.md:237-238,305`, 테스트 `PostgreSqlTransactionIntegrationTest.java:273-290`(`DataSourceTransactionManager` + `JdbcTemplate`만). +- **무엇이 틀렸나**: 마감이 지난 뒤 Hibernate가 다음 문장을 준비하면 Hibernate가 직접 `org.hibernate.TransactionException("Transaction timeout expired")`를 던진다. SQLState도 없고 Spring 타입도 아니다. 번역기는 비운다. web catch-all이 500 `INTERNAL_ERROR`로 답한다. +- **증거**: H2 + `JpaTransactionManager` + `Timeouts(1s, 1s)`, 본문에서 1.3초 기다린 뒤 `persist`. + - 본문 안 `flush` → `org.hibernate.TransactionException`, 번역 안 됨. + - 커밋 시 flush → `JpaSystemException`(cause `TransactionException`), 번역 안 됨. + - 이 예외는 JDBC 호출 전에 Hibernate가 만든다. 벤더와 무관하다. +- **왜 중요한가**: 운영 조합은 `JpaTransactionManager`다. 문서와 Javadoc은 "마감이 지나면 `DB_QUERY_CANCELED`"를 약속하지만 주 경로에서는 500과 error 로그가 나간다. 테스트는 옆 경로(JDBC)만 본다. 롤백은 되므로 데이터 손상은 없다. +- **고치는 법**: `SpringTransaction`이 시작 시각과 마감을 안다. 실패가 분류되지 않았고 실패 시점이 마감을 넘었으면 `DB_QUERY_CANCELED`로 분류한다. 예외 메시지를 읽지 않아도 된다. `JpaTransactionManager`로 같은 시나리오를 도는 PG 테스트를 하나 더한다. +- **가이드 심각도·우선순위**: Medium · P2. **증거**: E3. + +#### RR-03-04 `mappedBy` 없는 양방향 연관관계가 금지 규칙을 통과한다 + +- **위치**: `testFixtures/.../arch/SingleSidedAssociationCondition.java:30,50`(`mappedBy` 속성만 본다), `docs/jpa/entity-mapping-guide.md:52,72,81`. +- **무엇이 틀렸나**: 부모 `@OneToMany @JoinColumn(name = "parent_id")`와 자식 `@ManyToOne @JoinColumn(name = "parent_id", insertable = false, updatable = false)`는 한 FK를 두 필드가 가진 양방향이다. Hibernate 문서에 있는 `@JoinColumn` 양방향 모양이다. `mappedBy`가 없어 규칙은 위반 0을 낸다. +- **증거**: 두 엔티티를 `ClassFileImporter`로 넣고 `associationsAreMappedFromOneSideOnly().check(...)` → 통과. +- **왜 중요한가**: 사용자 원칙은 "양방향 금지"다. 가이드도 "one side only"라고 말한다. 가이드가 허용한 예외(단방향 `@OneToMany @JoinColumn`)에 자식 쪽 `@ManyToOne` 하나만 더하면 금지된 모양이 빌드를 통과한다. 읽기 전용 쪽은 같은 영속성 컨텍스트에서 바뀌지 않는다. 규칙 Javadoc이 막겠다는 "메모리와 DB 불일치"가 그대로 생긴다. +- **고치는 법**: 규칙을 클래스 하나가 아니라 그래프로 본다. A의 연관이 B를 가리키고 B의 연관이 A를 가리키면 위반이다(같은 join column이든 `mappedBy`든). 최소한 `@ManyToOne`·`@OneToOne`에 `insertable = false, updatable = false`인 `@JoinColumn`이 있으면 위반으로 본다. 가이드 81행 문장을 실제 범위에 맞춘다. 위반 fixture로 red/green 테스트를 둔다. +- **가이드 심각도·우선순위**: Medium · P2. **증거**: E3. + +### Minor (Nice to Have) + +#### RR-03-05 V21 유일 인덱스를 잠금 아래 만들고, 고른 이유가 없다 + +- **위치**: `V21__outbox_aggregate_sequence.sql:26`, `docs/jpa/migration-guide.md:35-46`, 비교 대상 grpc-ledger `V002`. +- **무엇**: 비동시 `CREATE UNIQUE INDEX`는 빌드 동안 `outbox_event`에 SHARE 잠금을 건다. 그동안 모든 append, 즉 outbox를 쓰는 업무 쓰기가 멈춘다. `lock_timeout`이 없어 잠금을 기다리는 동안 뒤 요청이 줄을 선다. migration-guide는 `CONCURRENTLY` + `executeInTransaction=false`를 정형으로 둔다. grpc `V002`는 비동시를 고른 이유를 적었다. V21에는 고른 방법·버린 대안이 없다. "중복이면 롤백"을 위해 트랜잭션 안을 골랐을 수 있지만 기록이 없다. +- **고치는 법**: runbook §8에 한 줄을 더한다. "outbox가 크면 같은 정의를 `CREATE UNIQUE INDEX CONCURRENTLY`로 먼저 만든다. V21의 `IF NOT EXISTS`가 그것을 건너뛴다." 이유도 같이 적는다. +- Low · P3 · E1. + +#### RR-03-06 쓰는 곳 없는 `positional` helper가 두 벌이다 + +- **위치**: `persistence-fileserver/.../repository/CleanupClaimSql.java:53`(새로 복사), `persistence-notification/.../repository/RecipientClaimSql.java:80`. +- **무엇**: 같은 정규식 helper다. 두 벌 모두 자기 단위 테스트 말고 호출자가 없다. 04-14로 bare `Connection` 테스트가 없어졌기 때문이다. `CleanupClaimSql.java:17-19` Javadoc은 "a test in this package that runs the identical text on a bare Connection"이라는 없는 소비자를 말한다. +- **고치는 법**: 둘 다 지운다. 필요하면 persistence-jpa testFixtures 한 곳에 둔다. +- Low · P3 · E1. + +#### RR-03-07 테스트 이름이 단언보다 크다 + +- **위치**: `WorkerCrashRecoveryContractTest.java:94-112`, `CleanupClaimSqlTest.java:18,28`. +- **무엇**: + - `WorkerCrashRecoveryContractTest`의 개명 테스트는 "reconcile 대상이 된다"고 말한다. 실제로는 recovery를 돌리지 않는다. 방금 직접 insert한 evidence 값을 다시 읽어 같은지 본다. factory도 거치지 않는다. + - 같은 클래스의 나머지 `@DisplayName` 5개는 영어다(소유자 결정 5는 한국어). + - `CleanupClaimSqlTest`는 "잠그고 건너뛴다"를 문자열 `contains`로 단언한다. + - 실제 동작은 `PostgreSqlNotificationBackgroundPassIntegrationTest`와 `PostgreSqlFileserverReclamationIntegrationTest.java:174`가 본다. +- **고치는 법**: 이름을 단언 범위로 줄이거나, 동어반복 테스트를 지운다. +- Low · P3 · E1. + +#### RR-03-08 정산 job을 다시 claim해도 시도 횟수가 오르지 않는다 + +- **위치**: `JdbcReconciliationJobStore.java:56-72`(claim은 fence만 올린다), `:77`(`attempts`는 reschedule에서만 오른다). +- **무엇**: 워커가 같은 job에서 매번 죽으면 lease(2분)마다 다시 claim된다. 시도 한도에 닿지 않는다. 같은 라운드의 fileserver reclaim은 시도 횟수를 올린다(`FileserverCleanupRepository.java:101`, "bounded by the same retry budget"). +- **고치는 법**: 만료된 lease를 다시 잡을 때 `attempts + 1`, 또는 `claim_fence`와 `attempts`의 차로 한도를 판단한다. +- Low · P3 · E1. + +#### RR-03-09 notification 엔티티의 변경 메서드가 public이 됐다 + +- **위치**: `persistence-notification/.../entity/DeliveryAttemptEntity.java:133,199,288`, `persistence-notification/CLAUDE.md:16`, 비교 `persistence-fileserver/.../entity/AssignedIdEntity.java:23`. +- **무엇**: 04-16 패키지 분할로 생성자·`completeWith`·`claimSuppressionSideEffect` 등이 public이 됐다. "entity never leaves the leaf"는 글로만 있다. 같은 라운드의 fileserver는 "leaf's public surface is a ceiling"으로 반대로 했다. 두 leaf가 "같은 규칙"이라 했지만 공개 범위 규칙은 다르다. +- **고치는 법**: `..notification.platform.entity..`를 leaf 밖에서 쓰지 못하게 ArchUnit 규칙을 둔다. +- Low · P3 · E1. + +#### RR-03-10 `FailureCategory.TRANSACTION_TIMEOUT`의 이름과 뜻이 다르다 + +- **위치**: `persistence-jpa/.../api/error/FailureCategory.java:46-52`. +- **무엇**: 이 범주는 이제 25P03(idle 세션 종료)만 뜻하고 재시도 가능 코드로 간다. 실제 트랜잭션 시간 초과(Spring 마감)는 `QUERY_TIMEOUT`/`DB_QUERY_CANCELED`다. 이름만 보면 "트랜잭션 timeout은 재시도 가능"으로 읽힌다. 라이브러리 예외 `TransactionTimeoutException`도 같은 뜻이다. +- **고치는 법**: 공개 API(`jpa-api-surface.txt`)라 이름 변경은 호환성 비용이 있다. 지금은 Javadoc 첫 문장에 "Spring 트랜잭션 timeout이 아니다"를 적고, 다음 호환성 깨짐 때 `IDLE_IN_TRANSACTION_TIMEOUT`으로 바꾼다. +- Low · P3 · E1. + +## Declined to judge + +- V20의 `ADD COLUMN … CHECK`가 기존 행 검사를 위해 테이블을 한 번 읽는지 — 실측하지 않았다. outbox는 reaper로 크기가 묶여 있어 영향이 작을 것으로 본다. +- V12 생존 규칙이 `scope`·`notification_category`를 보지 않는 것 — 중복은 같은 webhook 경쟁에서 생겨 두 행의 scope가 같을 것으로 보지만 실제 데이터로 확인하지 않았다. 키는 수정 전 finder와 같은 `(tenant, target, reason)`이다. +- V11 배포 중 옛 인스턴스의 autocommit claim이 잠시 남는 것 — 배포 절차 문제이고 모든 인스턴스가 바뀌면 사라진다. +- `JpaTransactionManager`에서 커밋 중 연결 단절 — cause chain을 걷는 구현이라 같은 결과로 보지만 실행하지 않았다(04-01 한계로 적음). +- `afterCommit` 콜백 실패가 커밋 단계로 분류돼 "결과 불명"이 되는 경우 — 실제로는 커밋된 뒤라 안전한 쪽이다. +- `JpaVersionedBulkUpdateRule`이 `JdbcTemplate` 문자열 SQL을 보지 않는 것 — 지금 `JdbcTemplate` UPDATE 대상(정산 job 등)에는 `@Version` 엔티티가 없어 위반이 없다. +- 30초 기본 제한이 긴 작업을 끊는지 — outbox relay는 publish를 트랜잭션 밖에서 한다(`PublishPendingOutboxEventsUseCase.java:109,148,202,241,264`). 나머지 `inWrite` 호출처 약 50곳은 전수 확인하지 않았다. +- `HikariPoolConstraintValidator`가 `"2"` 같은 숫자 표기를 거부하는 것 — 엄격한 쪽이라 결함으로 보지 않는다. +- grpc-ledger `V002` — 읽기만 했다. 빈 테이블 전제와 `CONCURRENTLY` 수동 절차가 주석에 있고 삭제 쿼리 조건과 부분 인덱스 조건이 맞다. +- 04-09·09-02의 sample 코드 — sample 영역이라 마이그레이션과 예외 변환만 봤다. + +## 28개 관점 — 바뀐 관점만 + +| 관점 | 원래 | 지금 | 이유 | +|---|---|---|---| +| 5 위험 가시성 | X | P | claim 잠금·bulk version·`mappedBy` 양방향이 코드와 규칙으로 드러났다. 남음: 두-owner 양방향 통과(RR-03-04), 없는 재시도를 약속하는 Javadoc(RR-03-01) | +| 6 실패 성숙도 | X | P | 커밋 결과 불명·버전 충돌·시간 제한이 처리됐다. 남음: Hibernate 마감 초과 500(RR-03-03), counter 경쟁 409(RR-03-01) | +| 26 Ownership | P | O | 분리 leaf 두 곳에 가까운 `CLAUDE.md`가 생겼다. PG 테스트가 persistence-jpa에 남은 이유와 위치가 문서에 있다 | + +## Assessment + +**Ready to merge? With fixes.** + +원래 High(04-01·04-02)와 P1(04-03·04-04)은 코드와 실 DB 테스트로 닫혔다(04-03은 빈틈 하나). 다만 06-07 수정으로 들어온 순서 번호 counter가 첫 생성 경쟁에서 정상 쓰기를 409로 거절하고(RR-03-01, E3) 이행 때 번호를 되돌리므로(RR-03-02, E3), 벽시계 번호를 쓰던 서비스에 배포하기 전에 두 건을 고친다. RR-03-03·04는 같은 묶음에서 고치는 것이 싸다. diff --git a/docs/reviews/2026-11-03-rereview/04-outbound-capabilities.md b/docs/reviews/2026-11-03-rereview/04-outbound-capabilities.md new file mode 100644 index 00000000..4237c994 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/04-outbound-capabilities.md @@ -0,0 +1,210 @@ +# 04 outbound capability 재리뷰 (2026-11-03) + +## 범위 + +- 리뷰 범위: Base `01a8a2a70` → Head `5786126c`. 경로는 `src/`를 생략한다. +- 본 pathspec: `adapter/outbound/{support, identifier, redis-runtime, redis-sdk, cache-redis, httpclient, objectstorage, notification, fileserver}`, `docs/{httpclient, notification, fileserver}`, `infra/redis-sdk`, `infra/minio`. 238파일, +8,942 −1,682. +- 발견 ID: 원 리뷰 `05-outbound-capabilities.md`의 05-01~05-23. 고친 코드가 pathspec 밖(`application-notification`, `application-fileserver`, `web-fileserver`, `persistence-fileserver`)에 있는 발견은 그 줄을 읽어 상태만 판정했다. 그 파일의 diff 전체는 다른 영역 몫이다. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 리뷰어 템플릿(계획 정렬, 새 결함, Declined to judge, 읽기 전용, 하위 에이전트 금지) | 출력 양식 전체 | +| `performance-optimization` | 연결 pool 고갈 신호, "pool을 키우기 전에 누가 연결을 잡는지 찾는다", timeout이 대기열을 숨기는지 | Redis SCRIPT lane 공유(RR-04-02), 실패 뒤 연결 폐기로 생기는 재연결, rate-limit 대기 상한 | +| `observability-and-instrumentation` | 실패 원인이 신호에 맞게 남는지, health 상태 순서, 원인이 다른 실패를 같은 신호로 세지 않는지 | breaker가 호출자 deadline 중단을 상대 장애로 셈(RR-04-01), `DEGRADED` 순서, MinIO 공급 실패 메시지, JDK 스트림의 미분류 `IOException`(RR-04-03) | +| `security-and-hardening` | 자원 남용 상한(DoS), 인가 회귀 방지, 비밀값, replay 창, 공급망 | 파일 서버 쿼터·소유자 검사(RR-04-04), SNS replay 창 1h, MinIO 커뮤니티 fork digest·mirror override, ACL probe | + +### 실행한 명령 + +| 명령 | 결과 | +|---|---| +| `git diff --stat/--numstat 01a8a2a70..5786126c -- ` | 238파일. leaf별 변경 규모 확인 | +| `git worktree add /rr-04 5786126c` 후 임시 테스트 3개를 넣고 `flock … ./gradlew :adapter:outbound:httpclient:test --tests '…Rr*ProbeTest' --console=plain -i` | 아래 세 줄. 모두 BUILD SUCCESSFUL | +| `RrStreamingBodyProbeTest`: 헤더 즉시, 본문 30바이트를 100ms마다 1바이트(약 3초), 기본 timeout(response-header 2s, read-idle 3s, total 4s) | APACHE `bytesRead=30 elapsedMs=2994 COMPLETED`. **JDK `bytesRead=20 elapsedMs=2010 FAILED IOException: closed`** | +| `RrDeadlineBreakerProbeTest`: 600ms 뒤 200을 주는 건강한 서버, breaker 창 5, 호출자 deadline 200ms로 5회 → 예산 넉넉한 호출 1회 | APACHE·JDK 모두 5회 `HttpDeadlineExceededException` 뒤 **`HttpCircuitOpenException`**, 서버 요청 수 5 | +| `RrDeadlinePostProbeTest`: 비멱등 POST, 서버 800ms 지연, 호출자 deadline 300ms | APACHE·JDK 모두 `HttpAmbiguousExecutionException`, evidence `SENT_NO_RESPONSE` (기대대로) | +| `javap -c` Spring 7.0.9 `JdkClientHttpRequest$TimeoutHandler`(Gradle cache jar) | timeout이 끝나면 응답 future를 취소하고 본문 stream을 닫는다. timer는 stream `close()`에서만 취소된다 | +| `git worktree remove --force /rr-04` | 임시 테스트와 함께 삭제 | + +### 못 본 것 + +- 전체 게이트는 다시 돌리지 않았다(README 16.2 결과를 읽기만 했다). +- Redis 컨테이너 lane, Redis topology lane, MinIO 계약·fault lane, Toxiproxy lane, PostgreSQL lane은 실행하지 않았다. +- SCRIPT lane 경합(RR-04-02)과 move 쿼터 우회(RR-04-04)는 코드와 설정 숫자로만 판정했다(E1). +- 다중 인스턴스 경쟁, 실제 SES/SMTP 발송, TLS 소켓을 공용 타이머 스레드에서 닫을 때의 지연은 보지 않았다. +- `application-*`, `web-fileserver`, `persistence-fileserver`의 diff 전체는 읽지 않았다. 발견 판정에 필요한 줄만 읽었다. + +## Strengths + +- Redis 연결 실패가 "보내지 않음"으로 분류된다. 연결을 여는 단계의 실패를 `RedisLaneUnavailableException`으로 감싼다(`redis-runtime/.../RedisRuntimeOwner.java:245`). 대기가 끝난 lease는 pool에 돌려주지 않고 버린다(`cache-redis/.../SemanticRedisCall.java:146-155`). +- renew가 자기 Lua 프로그램을 갖는다(`IdempotencyScripts.java:145-181`). 잃어버린 응답의 재시도는 "시작 revision + 요청 lease"가 같을 때만 `ALREADY`다. lease가 다르면 `OPERATION_CONFLICT`라 호출자가 갖지 않은 lease를 가졌다고 믿지 않는다. +- revision 순서가 포트(`CacheRecordMetadata`)에서 정해지고, Lua 사본(`CacheScripts.java:56`)과 fake 사본을 `CacheRegionContract`가 fake와 실 Redis 양쪽에서 같은 표로 묶는다. +- HTTP 결과 불명 판정이 재시도 규칙보다 먼저다(`DefaultRetryEligibilityEngine.java:32`). 비멱등 POST가 호출자 deadline으로 잘려도 `HttpAmbiguousExecutionException`이 난다(위 probe, E3). +- Apache가 쓰기 시작 시점을 알린다(`SignallingRequestExecutor`). TLS·connect 실패가 더는 "보냈을 수 있음"이 되지 않는다. 401 토큰 갱신은 재시도가 허락될 때만 한다(`DefaultGenericHttpGateway.java:258`). +- 설정 실수를 기동에서 막는다. 0 timeout(`ClientProfileValidator.java:138`), `max-attempts` 상한 5(`:265`), breaker 범위 검사, 동작 없던 키 6개 삭제, 이름 없는 예산도 profile 단위로 제한(`RestClientRuntimeFactory`). +- MinIO 이미지 참조가 evidence 파일 한 곳이다. mirror override는 같은 digest만 받는다(`MinioQualificationImage.java`). compose 기본값을 테스트가 대조한다(`ComposeMinioImageMatchesEvidenceTest`). evidence의 측정 4줄을 lane이 매번 단언한다(`MinioManagedObjectContractTest.java:125,212`). +- S3 mutation의 5xx를 `INDETERMINATE`로 바꿨다(`S3ProviderErrorMapper.java:69`). 쓰기 뒤 5xx를 "반영 안 됨 확정"으로 읽지 않는다. +- SMTP 실패가 reply code·연결 거절·인증 실패로 나뉜다(`JavaMailSenderSmtpDispatch.java:68-104`). 근거가 없으면 보수적으로 "commit됨"을 유지한다. +- module-defaults 파일명·키 중복이 기동을 멈춘다(`ModuleDefaultsEnvironmentPostProcessor.java:65,84`). strict binder가 list 원소 둘째 단계 이하 오타도 거부한다(`StrictSettingsBinder.java:281-389`). 낮은 우선순위 출처의 list 원소는 예전처럼 봐준다. +- 파일 copy가 업로드와 같은 admission·쿼터 예약·대상 namespace 허용 목록을 거친다(`CopyFileApplicationUseCase.java:91-136`). + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +|---|---|---| +| 05-01 | 닫힘 | factory가 `ProviderExecutionEvidence.undetermined()`로 행을 만든다(`DeliveryAttemptFactory.java:60`). requeue는 PROVEN+false만(`LeaseRecoveryService.java:101-144`) | +| 05-02 | 닫힘 | 전용 `RENEW` Lua(`IdempotencyScripts.java:145-181`), `RedisIdempotencyStoreAdapter.java:185-210`. 실 Redis renew는 `LiveRedisSemanticPortsTest.java:452`가 mainCheck lane에서 본다. 계약 클래스 전체는 게이트 밖(RR-04-05) | +| 05-03 | 닫힘 | `REPLACE_IF_REVISION_NEWER`(`CacheScripts.java:56`), 의도별 분기(`RedisCacheRegionAdapter.java:268-338`), `CacheRegionContract.java:151-195` | +| 05-04 | 닫힘 | 무효화 marker(`RedisCacheRegionAdapter.java:356,409-425`), miss도 condition 반환, stampede 보호 없음 문서화, CLAUDE.md jitter 문장 삭제. 새 부작용은 RR-04-02 | +| 05-05 | 닫힘 | `CircuitBreakerStatusPolicy`(5xx·408·429만), RETURN_RESULT 5xx 집계, profile별 breaker 키. 새 결함 RR-04-01 | +| 05-06 | 닫힘 | `AttemptDeadline` scope, Apache cancel(`DeadlineAwareApacheRequestFactory.java:30`), JDK·Jetty 상한, Toxiproxy lane을 mainCheck에(`httpclient/build.gradle` mainCheck). JDK 스트리밍 본문 문제는 RR-04-03 | +| 05-07 | 닫힘 | copy에 admission·쿼터·허용 목록(`CopyFileApplicationUseCase.java:91-136`), `namespace-limit` 신설. move 경로 우회는 RR-04-04 | +| 05-08 | 닫힘 | `FakeFileAccessPolicy`가 descriptor 소유자를 검사(`FakeFileAccessPolicy.java:38-46`), copy·move 소유자 거부 테스트(`FileLifecycleUseCasesTest.java:321,434`) | +| 05-09 | 결정으로 닫힘 | 15절 결정(`pgsty/minio` digest). 참조 한 곳, digest 고정 mirror override, `PinnedImageUnavailableException`, compose 대조 테스트 | +| 05-10 | 닫힘 | collapse 검사가 attempt 전 `failBeforeAttempt` 경로(`NotificationDispatchService.java:186-191`) | +| 05-11 | 닫힘 | SMTP 분류(`JavaMailSenderSmtpDispatch.java:76-104`), SES 사전 오류를 `ProviderCallNotStartedException`으로(`SesNotificationProviderAdapter.java:147-155`, `SesRequestMapper.java:93`). 작은 결함 RR-04-11 | +| 05-12 | 닫힘 | PATCH가 append 결과로 응답, status 재조회 삭제(`TusController.java:183-198`) | +| 05-13 | 닫힘 | cleanup 기본 on(`FileserverPlatformSettings.java` Cleanup, `fileserver.yml:101`), 끄면 WARN(`FileserverCleanupDisabledConfiguration.java:36`) | +| 05-14 | 닫힘 | 결과 불명 우선(`DefaultRetryEligibilityEngine.java:32`), `RequestWriteSignal`, 더 구체적 evidence 유지(`BlockingAttemptExecutor` `withMoreSpecificEvidence`). probe로 POST deadline 중단도 확인(E3) | +| 05-15 | 닫힘 | 키 6개 삭제, 0 timeout 거부, `max-attempts` 상한, 이름 없는 예산 제한, binder list 원소 검사 | +| 05-16 | 부분 | 계약이 포트 소유 testFixtures로 이동(notification·fileserver·objectstorage·cache·idempotency), Redis 컨테이너 lane·Toxiproxy lane이 mainCheck에. 남음: `LiveRedisIdempotencyStoreContractTest`가 어느 게이트 lane에도 없음(RR-04-05), SES/SMTP 실제 벤더 테스트 없음(GreenMail 등 0건) | +| 05-17 | 부분 | 연결 실패 → notSent, 실패 lease 폐기, rate-limit 대기 상한. 남음: 새 연결 열기는 caller deadline이 아니라 connect timeout 2s로 묶임(코드 주석에 명시, `RedisEdgeRateLimitAdapter.java:123-127`). 폐기가 SCRIPT lane 재연결을 늘린다(RR-04-02) | +| 05-18 | 부분 | Redis prefix 예외는 결정으로 닫힘(`cache-redis/CLAUDE.md` 예외 절). notification `@Value` 기본값 중복은 남음: `NotificationCallbackMvcController.java:59`(`65251`), `NotificationSubmissionConfiguration.java:91`(`ko-KR`). 같은 값이 settings·yml에도 있다(세 벌) | +| 05-19 | 닫힘 | 권한 매핑이 각 module-defaults로(`notification.yml:29-33`, `fileserver.yml:24-27`), `security.yml:32`에는 설명만 | +| 05-20 | 닫힘 | replay 창 기본 1h(`SesCallbackAdapter.SNS_HTTP_RETRY_HORIZON`), 인증서 실패는 `CallbackVerificationUnavailableException` | +| 05-21 | 부분 | README·CLAUDE.md 갱신, RFC 4231 벡터 테스트, 안 쓰는 edge 삭제. 합친 뒤 `package-info.java`가 다시 내용과 어긋남(RR-04-06) | +| 05-22 | 닫힘 | finalize가 writer lease를 잡고 token으로 해제(`FinalizeUploadApplicationUseCase.java:56-62`) | +| 05-23a | 닫힘 | 선언 길이 0이면 첫 바이트 거절(`LocalBlockingContentStore.java:146-147`) | +| 05-23b | 닫힘 | mutation 5xx → `INDETERMINATE`, PUT 재시도 불가 이유 주석(`S3AsyncClientFactory.java:38-42`) | +| 05-23c | 닫힘 | DROP 결과 저장(`NotificationSubmissionService.java:208,231`) | +| 05-23d | 닫힘 | 파일명·키 중복 기동 실패(`ModuleDefaultsEnvironmentPostProcessor.java:60-93`) | +| 05-23e | 닫힘(조건부) | `management.endpoint.health.status.order`(`cache-redis.yml:86`). 순서는 cache-redis가 싣고 상태는 redis-runtime이 낸다(RR-04-10) | +| 05-23f | 닫힘 | dedup 기본 off, 켜면 조립 거부(`RateLimitPolicy.java:36-38`, `RedisEdgeRateLimitAdapter.java:76-89`) | +| 05-23g | 닫힘 | 재시도 허락 뒤에만 토큰 갱신(`DefaultGenericHttpGateway.java:258-262`) | + +회귀로 판정한 발견은 없다. 다만 수정이 새 결함을 만든 발견이 넷이다(05-04·05-17 → RR-04-02, 05-05+05-06 → RR-04-01, 05-06 → RR-04-03, 05-07 → RR-04-04). + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +#### RR-04-01 호출자 deadline으로 끊은 시도를 breaker가 상대 장애로 센다 + +- 위치: `httpclient/.../resilience/AttemptResiliencePipeline.java:111-113`, `restclient/BlockingAttemptExecutor.java:114`(pipeline 호출), `:218-235`(`finish`), `apache/DeadlineAwareApacheRequestFactory.java:30`. +- 무엇이 틀렸나: 05-06 수정으로 진행 중 시도가 deadline에서 취소된다. 취소된 시도는 엔진 예외로 pipeline을 빠져나간다. pipeline은 모든 예외를 `circuitBreaker.onError`로 기록한다. `finish()`가 결과를 `DEADLINE_EXCEEDED`로 바꾸는 것은 그 뒤다. 그래서 breaker는 "상대 장애"로 이미 셌다. `finish()` 주석 자신이 "deadline 중단을 transport 장애로 보고하면 건강한 상대를 오판한다"고 적는데, breaker에는 그 구분이 없다. +- 왜 중요한가: `HttpOperation.deadline()`으로 남은 요청 시간을 넘기는 호출자가 있으면, 정상 응답 시간보다 예산이 짧은 호출이 쌓여 circuit이 열린다. 열리면 그 profile의 모든 호출이 기본 60초 동안 거절된다. 05-05와 같은 피해(상대는 정상인데 기능 전체가 멈춤)다. 05-06 전에는 응답이 늦게라도 도착해 성공으로 기록됐다. 이 수정이 만든 동작이다. +- 증거: E3. `RrDeadlineBreakerProbeTest` — 600ms에 답하는 서버, 창 5, deadline 200ms 호출 5회 뒤 예산 넉넉한 호출이 Apache·JDK 모두 `HttpCircuitOpenException`. 서버는 요청 5개만 받았다. +- 고치는 법: 시도 scope가 만료돼 끝난 실패는 breaker에 기록하지 않는다(Resilience4j `releasePermission()` 또는 ignore). 판정은 `AttemptDeadline.Scope.expired()`로 pipeline 안에서 한다. profile `total-call`로만 끝난 경우를 계속 실패로 셀지는 따로 정해 주석에 남긴다. 위 probe를 회귀 테스트로 둔다. +- 가이드 심각도·우선순위: Medium / P1 (호출자가 deadline을 넘길 때만 도달, 도달하면 High와 같은 피해). + +#### RR-04-02 캐시 조건부 쓰기가 멱등성·rate-limit·lease와 8개짜리 SCRIPT lane을 나눠 쓴다 + +- 위치: `cache-redis/.../cache/RedisCacheRegionAdapter.java:135-136,262-268`, `README.md:183-187`. lane 공유: `RedisIdempotencyStoreAdapter.java:88`, `RedisEdgeRateLimitAdapter.java:71`, `RedisDistributedLeaseAdapter.java:85`. 크기: `redis-runtime/.../RedisRuntimeSettings.java:458`(`maximum-script-connections` 8). 실패 lease 폐기: `SemanticRedisCall.java:146-155`. +- 무엇이 틀렸나: 05-03·05-04 수정 뒤 write condition이 있는 기록은 모두 SCRIPT lane으로 간다. README가 권하는 정상 사용(조회가 준 condition으로 기록)이 곧 모든 캐시 채우기다. 그 lane은 pod당 연결 8개이고, 같은 lane에서 멱등성 claim과 요청 경로의 rate-limit이 돈다. lease는 호출마다 연결 하나를 독점한다. 또 05-17 수정으로 시간 초과(캐시 200ms)된 lease는 버려진다. 다음 호출은 새 연결을 연다. 새 연결은 caller deadline이 아니라 connect timeout 2s로 묶인다. +- 왜 중요한가: Redis가 느려지거나 region 무효화로 미스가 몰리면 캐시 채우기가 8개 연결을 차지한다. 그동안 멱등성 claim은 최대 2s 기다리다 `UNAVAILABLE`로, rate-limit은 deadline까지 기다리다 실패 정책으로 간다. 시간 초과마다 연결을 닫고 다시 열어 느린 Redis에 재연결 부하가 더해진다. 캐시는 "끊겨도 되는" 기능인데 정확성 기능을 굶긴다. README·CLAUDE.md 어디에도 이 공유가 적혀 있지 않다. 개발자가 따로 기억해야 하는 숨은 위험이다. +- 증거: E1(코드와 기본값). 실측하지 않았다. +- 고치는 법: 셋 중 하나를 고르고 버린 대안을 README에 남긴다. (a) 캐시 전용 script lane(별도 permit), (b) 캐시 조건부 쓰기에 SCRIPT lane permit 상한을 따로 둔다(예: 8 중 2), (c) 캐시 계정에 해당 script 권한만 주고 REGULAR lane에서 돈다. 어느 쪽이든 lane 대기·거절 수를 lane별 metric으로 낸다. 시간 초과 lease 폐기는 유지하되 재연결 횟수를 metric으로 본다. +- 가이드 심각도·우선순위: Medium / P2. + +#### RR-04-03 JDK transport 스트리밍 본문이 response-header timeout(2s)에서 잘린다 — 문서와 반대 + +- 위치: `httpclient/.../jdk/DeadlineAwareJdkRequestFactory.java:41`, `restclient/BlockingStreamingGateway.java:76-82`, `README.md:42-44`, `docs/httpclient/configuration-reference.md:103-105`. +- 무엇이 틀렸나: JDK factory는 Spring `JdkClientHttpRequest`의 read timeout을 `min(response-header, 남은 deadline)`으로 둔다. Spring 7.0.9의 이 timeout은 교환 전체에 걸린다. 끝나면 응답 future를 취소하고 본문 stream을 닫는다. timer는 stream을 닫을 때만 멈춘다. 그래서 스트리밍 다운로드는 헤더를 받은 뒤에도 2s(또는 남은 예산)에 끊긴다. 이번 diff가 추가한 문서는 "넘겨받은 뒤 본문은 gap마다 read-idle로만 묶인다, 긴 다운로드를 임의의 총 시간에서 자르지 않는다"고 적는다. Apache에서만 참이다. 끊길 때 호출자는 분류되지 않은 `IOException: closed`를 받는다. +- 왜 중요한가: JDK profile로 2초 넘는 다운로드는 항상 실패한다. 오류도 `HttpClientException` 계층이 아니라 원인 분류·로그 필드가 없다. 길이가 2초 근처인 다운로드는 간헐적으로 실패해 원인을 찾기 어렵다. +- 증거: E3. `RrStreamingBodyProbeTest` — Apache 30/30바이트 2,994ms 완료, JDK 20/30바이트 2,010ms `IOException: closed`. `javap`로 Spring `TimeoutHandler` 동작 확인. 기존 `StreamingSetupDeadlineTest`는 setup만 보고 본문 길이는 보지 않는다. +- 고치는 법: (a) JDK 스트리밍 요청은 read timeout을 걸지 않고 setup은 `AttemptDeadline` abort(응답 future 취소)로 묶는다. 본문 gap은 JDK가 못 재므로 "JDK 스트리밍은 gap 상한 없음"을 문서에 적는다. (b) JDK profile의 스트리밍을 기동에서 거부한다. 어느 쪽이든 README·configuration-reference의 문장을 transport별로 고치고, 위 probe를 transport별 계약 테스트로 둔다. 본문 stream 실패는 stable 예외로 감싼다. +- 가이드 심각도·우선순위: Medium / P2. + +#### RR-04-04 파일 move가 namespace 쿼터 상한을 우회하고, 쿼터 장부를 어긋나게 한다 + +- 위치: `application-fileserver/.../lifecycle/MoveFileApplicationUseCase.java:36-60`(쿼터 의존 없음, `relocate`만), `cleanup/DefaultCleanupService.java:311`(삭제 때 현재 namespace에서 회수), `persistence-fileserver/.../JpaFileQuota.java:85-96`(사용량 = 예약 장부 합), `docs/fileserver/configuration.md:131-136`. +- 무엇이 틀렸나: 쿼터 사용량은 namespace별 예약 장부의 합이다. move는 레코드의 namespace만 바꾸고 장부는 옮기지 않는다. 그래서 (1) 목적지 B는 옮겨 온 바이트를 세지 않는다. 상한 B를 꽉 채운 뒤에도 기본 namespace에 올리고 B로 옮기면 B가 상한을 넘는다. (2) 출발지 A는 떠난 파일을 계속 센다. (3) 옮긴 파일을 지우면 cleanup이 B 장부에서 회수한다. B의 다른 행이 깎이고(바닥 0), A는 영영 줄지 않는다. +- 왜 중요한가: 이번 diff가 `namespace-limit`을 "한 namespace가 가질 수 있는 최대 바이트"로 문서화했다. `target-namespaces`와 `namespace-limit`을 함께 켜는 배포에서 그 약속이 깨진다. 시간이 지나면 A는 실제로 비었는데 `QUOTA_EXCEEDED`로 업로드를 거절하고, B는 상한을 넘는다. 05-07의 목적(쓰기 자원 남용 상한)이 move로 빠져나간다. +- 증거: E1. `MoveFileApplicationUseCase` 생성자에 `FileQuotaPort`가 없다. 실행 재현은 하지 않았다. +- 고치는 법: move를 한 트랜잭션에서 "B에 `requireRoom` + 예약·commit, A에서 같은 바이트 reclaim"으로 바꾼다. 또는 move를 같은 namespace 안의 이름 변경으로 좁히고 namespace 간 이동은 copy+delete로 하게 한다. 고른 쪽을 문서에 적고, "B 상한을 move로 넘을 수 없다"와 "옮긴 뒤 A 사용량이 준다" 테스트를 둔다. +- 가이드 심각도·우선순위: Medium / P2 (두 설정을 함께 켤 때만 도달). + +#### RR-04-05 Redis 멱등성 계약의 실서버 실행이 어느 게이트에도 없다 + +- 위치: `cache-redis/build.gradle:57-64`(topology lane에만), `:76-86`(`redisContainerContractTest`의 `requires`에 없음), `cache-redis/CLAUDE.md:131-137`. +- 무엇이 틀렸나: `requires`는 lane이 돌릴 클래스를 거르는 필터다(`StrictTestLanePlugin.java:216-219`). 컨테이너 lane은 캐시·lease 계약, `LiveRedisSemanticPortsTest`, ACL probe만 돈다. `LiveRedisIdempotencyStoreContractTest`는 explicit-only topology lane에만 있다. r3-B(계약 추가)와 r3-C(컨테이너 lane 추가)가 따로 작업하고 합쳐진 틈으로 보인다. +- 왜 중요한가: 05-02의 원인은 "fake가 Lua의 버그를 따라 함"이었다. fake에는 Lua 상태 기계의 Java 사본이 있다(`InMemorySemanticRedisCommands.java:284-322`). 지금 실서버로 게이트에서 확인되는 멱등성 경로는 claim 경합·서버 시간·renew 정상 경로 세 개뿐이다. stale handle의 `NOT_OWNER`, `CLAIMED` 상태 renew 거부, complete·markFailed·release 재시도 같은 계약 케이스는 fake 사본에서만 돈다. 두 사본이 갈라져도 ci·mainCheck·integrationCheck가 초록이다. +- 증거: E1(빌드 파일과 lane 필터). +- 고치는 법: `redisContainerContractTest`의 `requires`에 `LiveRedisIdempotencyStoreContractTest`를 넣고 CLAUDE.md 목록을 맞춘다. 계약이 실서버에서 1초 lease를 기다리므로 lane 시간이 늘어나는지 한 번 잰다. +- 가이드 심각도·우선순위: Medium / P2. + +### Minor (Nice to Have) + +#### RR-04-06 identifier leaf 문서가 합친 뒤 다시 내용과 어긋난다 + +- 위치: `identifier/src/main/java/.../package-info.java:2`, `identifier/CLAUDE.md:27-33`, `README.md` HmacUserPrincipalPseudonymizer 절. +- 무엇: package-info는 "식별자 생성은 여기 없다"고 하는데 `UuidV7DurableOperationIdFactory`가 있다. CLAUDE.md Allowed에 `:domain-core`와 `uuid-creator`가 없다. README의 "checked exception을 `IllegalStateException`으로 감싼다"는 `HmacSha256` 위임 뒤 이 클래스 이야기가 아니다. 05-21 문서 수정(r2-05b)과 UUIDv7 추가(r2-06)가 따로 합쳐졌다. +- 고치는 법: 세 문서를 지금 두 클래스·세 의존에 맞춘다. +- 심각도·우선순위: Low / P3. 증거 E1. + +#### RR-04-07 캐시 전용 ACL probe가 연결 중 끊김을 "권한 설정 오류"로 보고 기동을 멈춘다 + +- 위치: `cache-redis/.../capability/RedisSemanticScriptAclProbe.java:92-109,137`. +- 무엇: "닿지 못함" 판정이 `RedisLaneUnavailableException`·`TimeoutException`뿐이다. 연결은 열렸지만 probe 중 끊김, Redis 재시작 중 `LOADING` 응답, Lettuce 재연결 중 거절은 `ExecutionException`이라 설정 오류로 간다. README는 "캐시 장애는 pod 기동을 멈추지 않는다"고 적는다. +- 고치는 법: `NOPERM`·`NOSCRIPT` 같은 권한 응답만 치명으로 보고 나머지 실패는 경고로 낮춘다. 테스트로 `LOADING` 응답 케이스를 둔다. +- 심각도·우선순위: Low / P3. 증거 E1. + +#### RR-04-08 Redis renew가 lease만 늘리고 key TTL은 늘리지 않는다 + +- 위치: `IdempotencyScripts.java:177-180`(RENEW에 `PEXPIRE` 없음), claim의 `PEXPIRE ARGV[7]`(`:44,77`, replay TTL). +- 무엇: renew로 lease를 replay TTL(`APP_IDEMPOTENCY_TTL`, 기본 24h, 짧게 둘 수 있음) 너머까지 늘리면 실행 중 key가 사라진다. 다음 요청은 새 claim(`ACQUIRED`)을 받아 같은 부작용을 다시 실행한다. PostgreSQL store에는 이 제약이 없어 두 구현의 계약이 다르다. 지금 템플릿 안 호출자는 없다. +- 고치는 법: RENEW에서 `PTTL < 새 leaseUntil - now`이면 `PEXPIRE`를 늘리거나, renew 요청을 거부한다. 계약에 "renew한 lease는 replay TTL보다 오래 살 수 있다" 케이스를 둔다. +- 심각도·우선순위: Low / P3. 증거 E1. + +#### RR-04-09 startup rule을 일찍 만드는 전제("static, 의존 없음")를 막는 장치가 없다 + +- 위치: `support/.../startup/StartupRuleRunner.java:65-66`, `StartupRule.java` Javadoc. +- 무엇: runner는 bean factory post-processor 단계에서 모든 rule bean을 `getBean`한다. 지금 rule은 모두 `static @Bean`이다. 파생 서비스가 non-static `@Bean` rule을 쓰면 그 설정 클래스와 생성자 의존(datasource 등)이 그 시점에 만들어진다. 07-02가 막은 "검사 전에 DB 연결"이 조용히 되살아난다. 규칙은 Javadoc에만 있다. +- 고치는 법: runner가 rule의 bean definition에 `getFactoryBeanName() != null`(non-static factory method)이면 기동을 실패시킨다. 테스트 1건. +- 심각도·우선순위: Low / P3. 증거 E1. + +#### RR-04-10 `DEGRADED` 정렬 순서를 상태를 내지 않는 leaf가 싣는다 + +- 위치: `cache-redis/src/main/resources/config/module-defaults/cache-redis.yml:78-87`, `redis-runtime/.../RedisRuntimeAutoConfiguration.java:71-72,276-286`. +- 무엇: `redisOptional`(`DEGRADED`)은 `app.redis.enabled=true`면 redis-runtime이 만든다. 순서 설정은 cache-redis에만 있다. redis-runtime을 `api`로 끌어오는 redis-sdk만 쓰는 조립에서는 05-23e가 그대로다. +- 고치는 법: 순서 키를 redis-runtime 쪽 기본값으로 옮긴다. redis-runtime에는 module-defaults가 없으니 `EnvironmentPostProcessor` 또는 문서화된 예외로 둔다. +- 심각도·우선순위: Low / P3. 증거 E1. + +#### RR-04-11 SMTP reply code 범위가 2xx·3xx까지 "거절"로 받는다 + +- 위치: `notification/.../smtp/JavaMailSenderSmtpDispatch.java:115`. +- 무엇: `200 <= code < 600`을 받는다. Angus `sendpartial` 경로의 `SMTPSendFailedException`은 마지막 성공 코드(250)를 싣는다. 이 값이 `SmtpFailureClassifier`에서 영구 거절로 기록된다. 지금은 수신자 1명이라 도달하기 어렵다(`SmtpMimeMessageFactory.java:69`). +- 고치는 법: `400 <= code < 600`만 reply code로 쓴다. 그 밖은 보수적 경로로 보낸다. +- 심각도·우선순위: Low / P3. 증거 E1. + +## Declined to judge + +- `AttemptDeadline`의 abort가 JVM 공용 `CompletableFuture` delay 스레드에서 Apache `cancel()`(소켓 닫기)을 돈다. TLS 소켓 닫기가 막히면 JVM 안 다른 timeout이 늦어질 수 있다. JDK·Apache 구현 확인과 실측이 필요해 판단하지 않았다. +- `pgsty/minio`(커뮤니티 fork)를 qualification 기준으로 삼는 공급망 위험. 15절 소유자 결정이고, digest 고정과 같은 digest mirror override로 완화돼 있다. +- SES replay 창 1h. 15절 결정이고 ledger 유일 제약이 중복을 막는다. 재전송 공격 면이 넓어진 정도는 판단하지 않았다. +- `namespace-limit`의 동시 예약 초과 허용. 15절 결정이며 문서에 적혀 있다. +- 시스템 env가 list 원소 하나를 덮으면 yml에 있던 같은 원소의 다른 필드가 조용히 사라지는 Spring의 list 통째 교체. 이번 diff 전부터 있던 동작이라 범위 밖으로 뒀다. +- 캐시 `invalidate`의 GET→SET 비원자성. 코드 주석에 고른 이유(덮어써도 무효화 의미가 같음, REGULAR lane 권한)가 있다. +- notification evidence verifier가 상위 계약 클래스를 따라가 테스트를 찾게 바뀐 것. 지정 root 밖은 따라가지 않아 fail-closed다. 문제 없다고 봤다. +- `application-*`·`web-fileserver`·`persistence-fileserver` diff 중 발견 판정에 쓰지 않은 부분. + +## 28개 관점 — 바뀐 관점만 + +| # | 관점 | 전 → 후 | 한 줄 이유 | +|---|---|---|---| +| 8 | 디버깅 가능성 | P → O | MinIO 공급 실패가 `PinnedImageUnavailableException`으로 구분되고, deadline 중단·evidence가 구체적으로 남는다. 예외: JDK 스트림의 미분류 `IOException`(RR-04-03) | +| 12 | 동시성 성숙도 | P → O | 발송 중 crash 재발송(05-01), renew(05-02), finalize lease(05-22)가 닫혔다. 쿼터 동시 초과는 결정으로 문서화 | +| 16 | 의존성 성숙도 | P → O | MinIO 공급원이 digest 고정 + mirror override로 복구됐고, Jackson 2는 결정으로 닫혔다 | +| 27 | 삭제 가능성 | P → O | 권한 매핑이 각 모듈 기본값으로 옮겨져 모듈 한 줄을 지우면 함께 사라진다(05-19) | +| 28 | 회복 가능성 | P → O | 증거 오기로 인한 재발송이 닫히고 정리 worker가 기본 on이다 | + +1·6·11·14·15·17·21번은 기호는 P 그대로이고 이유가 바뀌었다. 원래 이유는 대부분 닫혔고, 새 이유는 각각 RR-04-03(17), RR-04-01(6), RR-04-04(11·15), RR-04-02(14), RR-04-05(21)다. + +## Assessment + +**Ready to merge: With fixes.** 원 리뷰의 High·P1(05-01~05-09)은 모두 코드와 테스트로 닫혔고 회귀는 없다. 다만 05-06 수정이 breaker를 호출자 deadline으로 열게 만들었고(RR-04-01, E3), JDK 스트리밍이 문서와 반대로 잘린다(RR-04-03, E3). 이 둘과 RR-04-02·04·05는 파생 서비스가 HTTP client·Redis·파일 쿼터를 켜기 전에 고쳐야 한다. diff --git a/docs/reviews/2026-11-03-rereview/05-messaging.md b/docs/reviews/2026-11-03-rereview/05-messaging.md new file mode 100644 index 00000000..a2e1982b --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/05-messaging.md @@ -0,0 +1,252 @@ +# 05 messaging 재리뷰 (2026-11-03) + +- 리뷰 범위: Base `01a8a2a70` → Head `5786126c`, 이 영역 pathspec 62파일(+3,798 −274). +- 원래 발견: `docs/reviews/2026-11-01-maturity-review/06-messaging.md`(06-01~06-09, NN-10~NN-14). +- 판정 기준: 리뷰 가이드 35절(심각도·우선순위·통제·증거), 36.3 양식, `AGENTS.md`·`CLAUDE.md`, `src/messaging/CLAUDE.md`, `src/adapter/inbound/messaging/CLAUDE.md`. + +## 범위 + +### 본 pathspec + +`src/messaging`, `src/adapter/outbound/messaging`, `src/adapter/outbound/messaging-kafka`, +`src/adapter/inbound/messaging`, `src/composition/outbox-relay`, `docs/messaging`, +`docs/runbooks/outbox-dead-letter.md`, `docs/runbooks/outbox-publish-failed.md`, +`docs/runbooks/migration-failed.md`, `docs/manual/09-outbox-events.md`. + +발견을 확인하려고 pathspec 밖의 다음 코드도 읽었다. 이 파일들의 diff 전체를 리뷰한 것은 아니다. + +- application-core: `application/outbox/**`(relay use case, outcome, backoff, `ClaimedOutboxEvent`, `OutboxStorePort`, `OutboxAggregateSequencePort`), `application/messaging/event/**`(`EventId`, `IntegrationIdentity`, `IntegrationEventDrafts`, `AggregateOrder`), `SubmitDurableOperationUseCase`. +- persistence-jpa: `JpaOutboxStore`, `OutboxEventJpaRepository`, `V20`, `V21`. +- support: `JsonIntegrationEventEncoder`(봉투·partition key). +- sample: `PortfolioEventOutbox`, `OutboxEventIdFactory`. +- `docs/registries/metrics.yaml` outbox 항목. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 본 것 | +| --- | --- | --- | +| `superpowers:requesting-code-review` | 리뷰어 템플릿: Strengths → Issues(심각도별) → Assessment, Declined to judge, 읽기 전용, 하위 에이전트 금지 | 문서 구조 전체 | +| `domain-driven-design` | Anti-Corruption Layer는 바깥 모델의 의미를 안쪽 어휘로 번역한다. 통합 이벤트의 식별자·순서는 소비자 계약이다. 경계 맥락은 서로의 모델을 알지 않는다 | bridge의 `retryable` 번역(06-01), event id ↔ `MessageId`(06-06), aggregate 순서 번호가 소비자에게 보이는 계약인지(06-07), vendored 제품이 앱을 아는지(MSG-023) | +| `observability-and-instrumentation` | on-call 질문부터 정한다("이 행은 왜 계속 재시도하나", "인증 오류인가 종료 중 거부인가", "적체가 느는가"). 지표 label 집합은 고정한다. runbook의 첫 확인 절차가 실제로 동작해야 한다 | relay 실패 보고의 원인 정보, 게이지 갱신 경로, `outcome` label 값, DEAD runbook SQL | +| `doubt-driven-development` | 결과 불명 판단을 주장(CLAIM)으로 적고 반증을 시도한다 | 아래 다섯 주장. 하위 에이전트 금지(브리프)라 새 맥락 리뷰어 대신 자기 반증으로 했다(축소 적용). 비대화 실행이라 교차 모델 검토는 건너뛰었다 | + +반증을 시도한 주장과 결과: + +1. "retryable 거부·결과 불명은 DEAD가 되지 않으니 안전하다" → 일부 반증. 끝나지 않는 행을 구분·처분할 수단이 없다(RR-05-03). +2. "종료 중 claim된 행은 PUBLISHED 또는 lease 해제 상태로 남는다" → 반증 못 함. Spring 7.0.9 종료 순서와 맞는다(닫힘). +3. "V21 카운터는 옛 벽시계 번호 뒤에서 시작한다" → 반증. 옛 행이 지워졌거나 identity가 바뀌면 1부터 다시 시작한다(RR-05-02, 실 PG 재현). +4. "DEAD runbook 재발행 SQL로 행이 다시 발행된다" → 반증. `deferred_attempt_count`가 2 이상이면 행이 DEAD로 되돌아간다(RR-05-01, 실 PG 재현). +5. "게이지가 relay와 무관한 자기 주기로 갱신된다" → 일부 반증. relay와 같은 단일 스레드에서 줄을 선다(RR-05-05). + +### 실행한 명령과 결과 + +| 명령 | 결과 | +| --- | --- | +| `git diff --stat 01a8a2a70..5786126c -- `, `git diff ...` | 62파일. 나눠서 전부 읽었다 | +| `git worktree add /rr-05 5786126c` 후 worktree에서만 `PostgreSqlOutboxClaimAndMaintenanceIntegrationTest`에 실험 메서드 2개 추가 | 메인 작업 트리는 건드리지 않았다. 끝나고 `git worktree remove --force` | +| `flock ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformContractTest --tests '*PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.rr05RunbookRedrive*'` | 실 PostgreSQL. 예상대로 실패. `claimed=[] status=DEAD counts={attempt_count=1, deferred_attempt_count=2}`, WARN `outbox claim moved a row it cannot read to DEAD`, 원인 `deferredAttemptCount must be between 0 and attemptCount (1), was 2` (29초) | +| 같은 lane, `--tests '*rr05CounterSeed*'` | 통과(17초). `a(옛 행 남음)=1788000000000001`, `b(tenant scope 바뀜)=1`, `c(옛 행 지워짐)=1`, 옛 번호 `1788000000000000` | +| `javap -c -p` spring-context 7.0.9 `SimpleAsyncTaskScheduler`, spring-boot-autoconfigure 4.0.8 `TaskSchedulingConfigurations$TaskSchedulerConfiguration` | virtual thread가 켜지면(템플릿 기본 `true`, `app-bootstrap/.../application.yml:58`) Boot가 `SimpleAsyncTaskScheduler`를 만든다. fixed-delay 작업은 `fixedDelayExecutor`(core pool 1)에서 돈다. `ContextClosedEvent`에서는 `shutdown()`(실행 중 작업은 계속)이다 | + +게이트(`ci`·`mainCheck`·`integrationCheck` 등)는 README 16.2 기록을 따랐고 다시 돌리지 않았다. + +### 못 본 것 + +- Kafka lane(`messagingKafkaRelayIntegrationTest`, `messagingInboxRedeliveryIntegrationTest`)을 직접 실행하지 않았다. 코드와 README 16절 기록만 봤다. +- 실제 SIGTERM 종료 순서, 다중 인스턴스 동시 기동, 처리량을 측정하지 않았다. +- vendored admin·claim-check·schema·observability 내부, starter-kafka `KafkaConsumerRegistrar`는 이번 diff에 없어 보지 않았다. + +## Strengths + +- **종료 순서를 relay가 직접 소유한다.** `OutboxRelayScheduler`가 SmartLifecycle(phase `Integer.MAX_VALUE`)이 되어 platform admission(`MessagingShutdownLifecycle.PHASE`)보다 먼저 멈춘다(`composition/outbox-relay/.../OutboxRelayScheduler.java:40,150`). 진행 중 발행 하나만 끝내고 남은 claim은 `releaseLease`로 시도 횟수 없이 돌려준다(`application-core/.../PublishPendingOutboxEventsUseCase.java:123-127,143-155`). Spring 7.0.9의 `ContextClosedEvent → shutdown()` → lifecycle stop 순서와 맞는다. +- **순서 테스트가 platform 상수를 직접 쓴다.** `OutboxRelayShutdownOrderTest`가 MAX-1024를 복사하지 않고 `MessagingShutdownLifecycle.PHASE`를 compile-only로 참조한다(`composition/outbox-relay/build.gradle:32-39`). platform phase가 바뀌면 테스트가 깨진다. +- **ACL 번역이 정확해졌다.** bridge가 platform `retryable`을 `REJECTED_RETRYABLE`로 옮긴다(`PlatformIntegrationEventPublishAdapter.java:189`). AMBIGUOUS로 뭉개지 않은 이유(중복 경고 오염)가 README에 남아 있다. +- **재전송 id가 바뀌지 않는다.** bridge가 대문자·축약 표기 UUID를 다른 id로 바꿔 보내지 않고 거부한다(`PlatformIntegrationEventPublishAdapter.java:154-163`). 소비자 중복 제거 키가 깨지는 경로를 막았다. +- **시도 예산을 일시 실패와 분리했다.** `deferred_attempt_count`(V20)와 `budgetedAttemptCount()`(`ClaimedOutboxEvent.java:55`)로 예산은 분류되지 않은 예외에만 쓴다. 재시도 시각은 실패 시점 기준이다(`PublishPendingOutboxEventsUseCase.java:179,187,193`). V20은 기본값으로 기존 행을 다시 쓰지 않는다. +- **소비 경로를 실제 의존성으로 검증한다.** `InboxRedeliveryIntegrationTest`는 앱 relay → Kafka → platform consumer → inbox+JPA 한 트랜잭션을 실 Kafka·PostgreSQL로 돌린다. offset 되감기와 실패 재처리 둘 다 본다. inbox 중복 검사를 지우는 변이를 잡았다는 기록도 있다. +- **이 lane이 실제 결함을 찾았다.** inbound/outbound messaging leaf가 같은 Gradle 좌표라 bridge가 빠지던 문제를 group·jar 이름으로 고쳤다(`adapter/inbound/messaging/build.gradle:19-28`). +- **decode 등록을 코드가 막는다.** handler 선언으로 decode 목록을 만들고, 같은 계약에 다른 class를 선언하면 기동을 막는다(`MessageContracts.java:61-85`). 서비스가 등록을 잊어 메시지가 조용히 DLQ로 가는 숨은 위험이 사라졌다. +- **inbox 마이그레이션 위치를 고른 이유가 남아 있다.** primary location에 넣으면 V22가 out-of-order로 거부되는 이유와 explicit baseline을 쓴 이유가 코드 주석에 있다(`MessagingInboxSchemaStream.java:20-31`). + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +| --- | --- | --- | +| 06-01 | 닫힘 | retryable REJECTED → `REJECTED_RETRYABLE`(`PlatformIntegrationEventPublishAdapter.java:188-190`). relay는 `markDeferred`로 예산 없이 재시도(`PublishPendingOutboxEventsUseCase.java:189-194`). Kafka 인증·인가는 retryable(`KafkaPublishFailureClassifier.java:43,75-76`). `PUBLISH_RUNTIME_UNAVAILABLE`·`KAFKA_TRANSPORT_CLOSED`도 retryable(`DefaultMessagePublisher.java:266-276`, `KafkaMessagingTransport.java:121-131`). 남은 위험은 RR-05-03 | +| 06-02 | 닫힘 | SmartLifecycle phase `MAX_VALUE`, `stop(Runnable)`이 진행 중 회차를 기다림(`OutboxRelayScheduler.java:150-162`). 남은 claim 해제(`OutboxStorePort.releaseLease`, `OutboxEventJpaRepository` `releaseLease`). 13절의 "lease 해제 없음"·"phase 하드코딩"도 해결 | +| 06-03 | 닫힘 | AMBIGUOUS·retryable 거부는 예산을 쓰지 않음. 지연 상한 5분(`OutboxBackoffPolicy.MAX_DELAY`). runbook 차단 범위 조회가 현재 FIFO 키(`outbox-dead-letter.md:27`). 단 같은 runbook의 재발행 SQL이 V20과 어긋난다(RR-05-01) | +| 06-04 | 닫힘 | 발행이 있으면 한 tick 안에서 다시 claim, 상한 50회차(`OutboxRelayScheduler.java:47,102-112`). README에 처리량 상한 숫자(`composition/outbox-relay/README.md` "한 tick이 claim 한 번이 아니다"). PG 카운트 테스트 대신 fake store 테스트(`OutboxRelaySchedulerDrainTest`) | +| 06-05 | 닫힘 | 게이지 갱신을 `@Scheduled refreshGauges`로 분리(`OutboxMetrics.java:91-94`). relay 꺼짐 WARN(`OutboxRelayOffWarning`). 실제 스케줄러로 relay-off 게이지 값을 단언(`OutboxMetricsTest.java:40-66`). 단 relay와 같은 스레드를 쓴다(RR-05-05) | +| 06-06 | 부분 | bridge는 정규 소문자 UUIDv7만 받게 엄격해졌다. 완료 기준인 "append(draft·encode) 시점 거부"는 없다. `EventId`는 여전히 `[A-Za-z0-9][A-Za-z0-9._:-]*`(`EventId.java:9`), durable operation digest 경로는 UUID가 아닌 id를 만든다(`SubmitDurableOperationUseCase.java:168-173`). bridge 주석·README도 "until it does"라고 미완을 인정한다(RR-05-04) | +| 06-07 | 닫힘 | sample이 `OutboxAggregateSequencePort`로 번호를 받는다(`PortfolioEventOutbox.java` append). V21 유일 인덱스로 같은 번호 두 번 append를 거부. 업그레이드 연속성은 RR-05-02 | +| 06-08 | 닫힘 | 새 leaf `adapter:inbound:messaging`(registry 등록), inbox 부품 조립, decode 목록 자동, V1101 별도 stream, 실 Kafka+PG 중복 전달 lane. application 소비 포트는 버린 대안으로 이유와 함께 기록(`adapter/inbound/messaging/README.md` "고른 방법과 버린 대안"). 예시 handler는 sample이 아니라 테스트에 있다 | +| 06-09 | 닫힘 | `messagingKafkaRelayIntegrationTest`(strict lane, `integration()`, skip 거부)가 relay → bridge → 실 Kafka 레코드 바이트를 비교. `:integrationCheck`는 `.github/workflows/integration-main.yml`에서 main push·nightly로 돈다 | +| NN-10~NN-14 | 미조치(색인 누락) | README 12절 색인에 06-01~06-09만 있다. NN-13은 부분(스케줄러·use case Javadoc은 고침, `OutboxLeaderElectionToken` 설명과 `CLAUDE.md` 부재는 남음). NN-10·11·12·14는 diff에 조치가 없다(RR-05-10) | + +회귀로 판정한 발견: 없음. RR-05-01은 06-03 자체의 회귀가 아니라 V20이 같은 변경 안에서 runbook SQL을 낡게 만든 새 결함이다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +#### RR-05-01 — DEAD runbook의 재발행 SQL이 `deferred_attempt_count`를 되돌리지 않아 행이 다시 DEAD가 된다 + +- 위치: `docs/runbooks/outbox-dead-letter.md:46,48`. 관련 코드는 `application-core/.../ClaimedOutboxEvent.java:35-41`, `persistence-jpa/.../JpaOutboxStore.java:150-155`. +- 무엇이 틀렸나: + - runbook SQL은 `attempt_count = 0`만 쓴다. + - V20이 더한 `deferred_attempt_count`는 그대로 남는다. + - 다음 claim에서 `attempt_count`는 1이 된다. + - `ClaimedOutboxEvent`는 `deferredAttemptCount > attemptCount`이면 생성을 거부한다. + - claim은 그 예외를 "읽을 수 없는 행"으로 보고 행을 다시 DEAD로 옮긴다. +- 왜 중요한가: + - 발생 조건: DEAD 행의 `deferred_attempt_count`가 2 이상이다. 장애 중 두 번 이상 미뤄진 뒤 확정 거부나 예산 소진으로 DEAD가 된 행이 해당한다. 운영자가 장애 뒤 일괄 재구동할 행이 바로 이런 행이다. + - 영향: P1 incident의 유일한 복구 절차가 실패한다. aggregate는 계속 막힌다. + - 탐지가 어렵다. 로그는 `outbox claim moved a row it cannot read to DEAD`라고 말해 원인을 행 손상으로 오해하게 한다. 이 경로는 failure reporter를 거치지 않아 `OUTBOX_DEAD_LETTER` 보고와 `outcome=DEAD` 카운터도 다시 나오지 않는다. + - 증거: 실 PostgreSQL에서 runbook SQL을 그대로 실행해 재현했다. 결과는 `claimed=[]`, `status=DEAD`, `attempt_count=1`, `deferred_attempt_count=2`다. +- 고치는 법: + 1. runbook §4 두 SQL에 `deferred_attempt_count = 0`을 넣는다. + 2. V21 확인 쿼리처럼 §4 SQL에 `runbook-sql` 표지를 달고, PG lane(`PostgreSqlOutboxOrderKeyRunbookIntegrationTest`와 같은 방식)이 runbook에서 읽어 실행하게 한다. "재발행한 행이 claim된다"를 단언한다. + 3. 선택: DB에 `CHECK (deferred_attempt_count <= attempt_count)`를 둔다. 잘못된 수동 SQL이 claim 때 조용히 DEAD가 되는 대신 UPDATE 시점에 바로 실패한다. +- 가이드 심각도: Medium · 우선순위 P1 · 증거 E3(실 PG 재현) · 통제 M0(runbook SQL을 검사하는 장치 없음). + +#### RR-05-02 — 새 aggregate 카운터가 1부터 시작해 소비자가 보는 순서 번호가 업그레이드 때 뒤로 간다 + +- 위치: `persistence-jpa/.../OutboxEventJpaRepository.java:137`(`COALESCE(MAX(e.aggregate_sequence), 0) + 1`), `JpaOutboxStore.java:114-124`, `V21__outbox_aggregate_sequence.sql:9-11`, `sample-portfolio/.../PortfolioEventOutbox.java:38`(scope가 `portfolio` → `global`). +- 무엇이 틀렸나: + - 카운터가 없는 aggregate의 첫 번호는 "지금 outbox에 남은 행"의 최댓값 + 1이다. + - 옛 sample은 번호로 epoch 마이크로초(약 1.7×10^15)를 썼다. + - reaper가 PUBLISHED 행을 7일 뒤 지운다. 7일 넘게 조용했던 aggregate는 남은 행이 없다. 그래서 다음 번호가 1이다. + - sample은 같은 diff에서 tenant scope를 `portfolio`에서 `global`로 바꿨다. 옛 행은 다른 identity라 최댓값 계산에 들어가지 않는다. 모든 sample aggregate가 1부터 다시 시작한다. + - scope는 Kafka partition key 해시에도 들어간다(`JsonIntegrationEventEncoder.java:258-264`). 배포 전에 남은 `portfolio` 미발행 행과 배포 뒤 `global` 행은 서로 막지 않고 다른 partition으로 간다. +- 왜 중요한가: + - `AggregateOrder` 문서는 소비자가 이 번호를 "어느 변경이 마지막인가"로 읽는다고 적는다(`AggregateOrder.java:7`). 봉투에도 `aggregate.sequence`로 실린다. + - "마지막으로 본 번호보다 작으면 버린다"로 구현한 소비자는 업그레이드 뒤 그 aggregate의 이벤트를 모두 버린다. 템플릿이 권한 패턴이다. + - V21 주석의 의도("rows numbered by the old clock scheme still come first")가 옛 행이 남아 있을 때만 성립한다. 포트 계약(`OutboxAggregateSequencePort` Javadoc "greater than any number an earlier outbox row carries")도 지워진 행은 다루지 않는다. + - 증거: 실 PostgreSQL에서 `nextSequence`를 불렀다. 옛 행이 남은 경우 1788000000000001, scope가 바뀐 경우 1, 옛 행이 지워진 경우 1이다. + - scope를 `global`로 바꾼 것은 15절 결정(r2-01)이다. 결정을 뒤집자는 것이 아니라, 그 결정과 V21이 합쳐져 생긴 업그레이드 위험이다. +- 고치는 법: + - 새 카운터의 시작값을 `GREATEST(COALESCE(MAX(e.aggregate_sequence), 0), <현재 epoch 마이크로초>) + 1`로 둔다. 번호는 양수이고 커지기만 하면 되므로 비용이 없다. 옛 벽시계 번호는 그 시각 이전 값이라 새 번호가 항상 뒤에 온다. + - sample scope 변경은 "배포 전 `portfolio` 미발행 행을 비운다"는 절차를 sample README나 manual 09에 적는다. 또는 sample만 `portfolio`를 유지한다. + - 파생 서비스가 벽시계 번호에서 포트로 옮길 때의 주의를 manual 09 "event id·correlation·순서" 절에 한 줄 적는다. +- 가이드 심각도: Medium · 우선순위 P2 · 증거 E3(실 PG에서 번호 확인) · 소비자 쪽 피해는 E1(소비자 구현에 달림). + +#### RR-05-03 — 끝나지 않는 재시도 행을 운영자가 구분하거나 처분할 수단이 없다 + +- 위치: `PlatformIntegrationEventPublishAdapter.java:188-190`, `application-core/.../OutboxPublishRefusedException.java:39-41`, `PublishPendingOutboxEventsUseCase.java:181-194`, `messaging-kafka/.../KafkaPublishFailureClassifier.java:55-63`, `docs/runbooks/outbox-publish-failed.md:43-45,60`. +- 무엇이 틀렸나: + - AMBIGUOUS와 `REJECTED_RETRYABLE`은 이제 예산을 쓰지 않는다. 그래서 끝 상태가 없다. 이것은 15절 결정이다. + - 결정 기록과 runbook이 다루는 남은 위험은 "진짜 인증 오류" 하나다. + - 실제로 영원히 재시도하는 행은 하나 더 있다. Kafka classifier가 이름을 모르는 브로커 거부는 기본값으로 AMBIGUOUS다. 예: topic의 timestamp 정책에 걸린 `InvalidTimestampException`, 없는 topic의 metadata 대기 시간 초과. 예전에는 3회 뒤 DEAD와 P1 경보로 끝났다. 지금은 5분 간격으로 끝없이 FAILED가 되고 그 aggregate를 막는다. + - runbook은 원인을 "인증/인가면"으로 가르라고 한다. 그런데 bridge가 platform의 실패 code·category를 버리고 `REJECTED_RETRYABLE`만 넘긴다. relay 보고의 원인 문장은 "shutting down, saturated, transport closed or credentials refused" 넷을 한 문장에 묶는다. platform 발행 지표 label도 completion뿐이다(`DefaultMessagePublisher.java` `observe`). 그래서 앱 로그와 지표로는 원인을 가를 수 없다. + - FAILED 행을 건너뛰는 절차가 없다. skip SQL은 `status = 'DEAD'`만 대상으로 한다(`outbox-dead-letter.md:51`). publish-failed runbook은 "즉시 수동 개입 불필요"라고 한다. + - 영원히 재시도하는 행을 찾는 쿼리·지표가 없다. `deferred_attempt_count`가 있는데도 runbook이 쓰지 않는다. +- 왜 중요한가: + - 발생 조건: 레코드 하나에만 해당하는 영구 거부를 classifier가 모르는 경우, 또는 인증·ACL이 실제로 틀린 경우. + - 영향: 그 aggregate의 뒤 이벤트가 무기한 멈춘다. `outbox.publisher.lag` 경보는 울린다. 하지만 운영자는 원인을 알 수 없고 처분 절차도 없다. + - 사용자 판단 원칙 "위험은 코드에 드러나야 한다"에 걸린다. AMBIGUOUS 분기 주석(`PublishPendingOutboxEventsUseCase.java:182-186`)은 broker 정지만 말하고 이 경우를 말하지 않는다. +- 고치는 법: + 1. bridge가 platform `FailureDescriptor.code()`를 잃지 않게 한다. 예: `OutboxPublishOutcome`은 그대로 두고 `publishForOutcome` 결과에 sanitized code를 함께 실어 relay 보고 필드(`error.reason` 등)로 남긴다. 번역 경계(ACL) 안에서 끝나는 변경이다. + 2. runbook에 "끝나지 않는 재시도" 절을 둔다. 확인 쿼리는 `status='FAILED' AND deferred_attempt_count >= N`이다. 처분은 원인 해소 또는 FAILED 행 skip(DEAD skip과 같은 승인 조건)이다. + 3. 선택: 결정을 유지하면서 상한을 하나 둔다. 예: `deferred_attempt_count`가 아주 크거나 행 나이가 기준을 넘으면 별도 경보를 낸다. 예산 키를 만들지 않는다는 결정과 충돌하지 않는다. + 4. 15절 결정 기록의 "남은 위험" 칸에 classifier 미분류 영구 거부를 더한다. +- 가이드 심각도: Medium · 우선순위 P2 · 증거 E1 · 통제 M1(runbook이 인증 오류만 기술). + +#### RR-05-04 — 06-06이 "완료"로 기록됐지만 완료 기준(append 시점 거부)이 채워지지 않았다 + +- 위치: `application-core/.../EventId.java:9`, `IntegrationIdentity.java:18`, `SubmitDurableOperationUseCase.java:168-173`, `PlatformIntegrationEventPublishAdapter.java:133-151`, `adapter/outbound/messaging/README.md:45-51`. README 14절 r2-06 행("06-04~06-07 ... 완료"). +- 무엇이 틀렸나: + - application `EventId` 문법은 그대로 넓다. + - bridge만 정규 소문자 UUIDv7로 더 좁아졌다. 두 계약의 차이는 오히려 커졌다. + - `canonicalIdentity`는 문법 밖 operation id를 `operation-`로 바꾼다. 이 id는 append를 통과하고 relay에서 DEAD가 된다. + - bridge Javadoc과 README가 "append 쪽에서 먼저 실패해야 한다 — 별도 작업"이라고 적는다. 그런데 조치 현황은 완료다. +- 왜 중요한가: + - 지금은 HTTP가 서버에서 UUIDv7을 만들어 도달하지 않는다(`DurableOperationController.java:91`). + - 새 inbound adapter, 클라이언트 지정 id, 다른 id 생성기를 쓰는 기능이 생기면 원래 06-06과 같다. 업무 트랜잭션은 커밋되고, 실패는 나중에 relay에서 DEAD로 나타나 aggregate를 막는다. + - 상태 기록이 실제와 달라 후속 작업 목록에서 빠진다. +- 고치는 법: 원래 권고 (a)를 따른다. `EventId`를 정규 소문자 UUIDv7로 좁힌다. 또는 encoder가 encode 단계에서 같은 검사를 한다. `canonicalIdentity`의 digest 경로는 UUIDv5/v7 파생으로 바꾸거나 없앤다. 조치 현황의 06-06을 "부분"으로 고친다. +- 가이드 심각도: Medium · 우선순위 P2(원래 등급 유지) · 증거 E1 · 통제 M2(bridge에서만 강제). + +### Minor (Nice to Have) + +#### RR-05-05 — 게이지 갱신이 relay와 같은 단일 스레드에서 줄을 선다 + +- 위치: `composition/outbox-relay/.../OutboxMetrics.java:21-29,91-94`, `OutboxRelayScheduler.java:47,102-112`. +- 무엇: Javadoc은 게이지가 "relay와 무관한 자기 주기"로 갱신된다고 적는다. 실제로는 fixed-delay `@Scheduled` 작업이 모두 한 스레드를 쓴다. virtual thread 켬(템플릿 기본)이면 `SimpleAsyncTaskScheduler.fixedDelayExecutor`(core 1)이고, 끄면 `ThreadPoolTaskScheduler` pool 1이다. relay tick은 이제 최대 50회차라 한 tick 동안 게이지·reaper가 기다린다. +- 왜: broker가 느린데 발행은 성공할 때(예: 발행당 0.5초면 50×20×0.5초 ≈ 8분) 게이지가 갱신되지 않는다. 적체를 봐야 할 바로 그때다. relay-off·매 회차 실패 경우(06-05의 완료 기준)는 맞게 동작한다. +- 고치는 법: tick 상한을 회차 수가 아니라 시간(예: poll 주기의 몇 배)으로 둔다. 또는 게이지를 Micrometer의 지연 조회 gauge나 별도 executor로 옮긴다. 최소한 Javadoc을 "relay tick 사이에 갱신"으로 고친다. +- 심각도 Low · P3 · 증거 E1(Spring 7.0.9·Boot 4.0.8 바이트코드). + +#### RR-05-06 — 새 결과 `RELEASED`가 지표 registry에 없다 + +- 위치: `docs/registries/metrics.yaml:353`(`allowed_values: [PUBLISHED, FAILED, DEAD, IN_FLIGHT, STALE]`), `OutboxMetrics.java:65`(Javadoc에 RELEASED 없음), `OutboxMessagePublishAdapter.java:16`("four-valued outcome", 지금은 다섯). +- 무엇: relay는 종료 때 `outbox.publisher.published.total{outcome=RELEASED}`를 기록한다. registry 허용 값에는 없고, 실제로 나오지 않는 `IN_FLIGHT`는 남아 있다. `OutboxStatusRegistryContractTest`는 `outbox.pending.size` status만 비교해서 이 차이를 잡지 못한다. +- 고치는 법: 허용 값을 `OutboxRelayResult.Outcome`과 맞추고, 같은 계약 테스트에 이 label도 비교하게 한다. +- 심각도 Low · P3 · 증거 E1. + +#### RR-05-07 — vendored 제품 안에 두 개의 재시도 규칙이 생겼고, 고른 이유가 제품 쪽에 없다 + +- 위치: `messaging-core-api/.../FailureDescriptor.java:57-75`, `messaging-kafka/.../KafkaPublishFailureClassifier.java:19-25,62-77`, `messaging-runtime-core/.../DefaultMessagePublisher.java:266-268`, `messaging-spring-boot-starter/.../MessagingShutdownLifecycle.java:33-38,121-127`. +- 무엇: + - platform의 category 기본 규칙은 "인증·인가 실패는 자동 재시도하지 않는다"이다(`defaultRetryable(AUTHENTICATION)=false`, Javadoc). + - publish classifier는 이제 같은 category에 `retryable=true`를 붙인다. consumer 재시도 엔진은 두 값을 AND하므로 지금 동작은 안 바뀐다. 하지만 같은 제품이 같은 category를 두 의미로 쓴다. + - vendored 주석 세 곳이 "the application's outbox relay", `composition:outbox-relay OutboxRelayScheduler`를 이름으로 부른다. `PHASE`는 앱 테스트를 위해 public이 됐다. + - registry 간선은 그대로라 MSG-023의 의존 방향은 지켰다. 하지만 제품 문서가 소비자를 알게 됐다. + - "bridge(ACL)에서 category를 보고 번역하고 vendored는 그대로 둔다"는 대안을 왜 버렸는지가 `src/messaging/CLAUDE.md`에 없다. 같은 파일의 digest 헬퍼 절(01-11)처럼 남기는 관례가 이미 있다. +- 고치는 법: `FailureDescriptor` Javadoc에 "publish 거부의 retryable은 category 기본값과 다를 수 있다(인증·인가)"를 적는다. vendored 주석은 "a publisher that trusts the flag"처럼 소비자 이름 없이 쓴다. `src/messaging/CLAUDE.md`에 06-01 vendored 수정 목록과 ACL 대안을 버린 이유를 적는다. +- 심각도 Low · P3 · 증거 E1. + +#### RR-05-08 — `MessagingShutdownLifecycle`에 주인 없는 Javadoc이 남았다 + +- 위치: `messaging-spring-boot-starter/.../MessagingShutdownLifecycle.java:32`. +- 무엇: `POLL` 필드의 Javadoc("How often the drain is re-checked")이 새 `PHASE` Javadoc 바로 위에 붙어 떨어져 있다. `POLL`(40행)에는 설명이 없어졌다. +- 고치는 법: 32행 주석을 `POLL` 선언 위로 옮긴다. +- 심각도 Low · P3 · 증거 E1. + +#### RR-05-09 — 문서·주석이 이번 변경을 따라오지 못했다 + +- `V21__outbox_aggregate_sequence.sql:10`이 없는 클래스 `JpaOutboxAggregateSequences`를 가리킨다. 실제는 `JpaOutboxStore.nextSequence`다. +- `docs/manual/09-outbox-events.md:59-60`은 "application-core 헬퍼로 올리는 일은 01-09 후속"이라고 한다. 같은 diff에 `IntegrationEventDrafts`가 이미 있다. +- `OutboxRelayAutoConfiguration.java:96`과 README 트리의 "SKIP LOCKED 리더 선출" 설명이 남았다(NN-13). +- `docs/runbooks/outbox-publish-failed.md`·`outbox-dead-letter.md` 머리말의 `last_updated: 2026-06-11`이 내용 변경 뒤에도 그대로다. +- 고치는 법: 위치마다 현재 이름과 상태로 고친다. +- 심각도 Low · P3 · 증거 E1. + +#### RR-05-10 — 06 영역 발견 5건(NN-10~NN-14)이 조치 추적에서 빠졌다 + +- 위치: `docs/reviews/2026-11-01-maturity-review/README.md` 12절 색인(06-01~06-09만), 14·16절. +- 무엇: 영역 문서는 14건(High 2·Medium 10·Low 2)을 적는다. 색인·조치 현황·남은 것 어디에도 NN-10(payload 버전 호환성, Medium/P2), NN-11(outbox 두 모델 문서, Medium/P3), NN-12(batch×deadline vs lease 미검사, Medium/P3), NN-13(낡은 설명, Low/P3), NN-14(DLQ 사유 한 값, Low/P3)이 없다. 코드도 NN-13 일부만 바뀌었다. +- 고치는 법: 색인에 06-10~06-14로 올리고, 각 항목을 "남음" 또는 결정으로 닫는다. +- 심각도 Low · P3 · 증거 E1. + +## Declined to judge + +- V21의 `CREATE UNIQUE INDEX`(CONCURRENTLY 아님)가 큰 `outbox_event`에서 쓰기를 막는 시간 — 표 크기를 모르고, 마이그레이션 잠금 정책은 04 영역 몫이다. +- `MessagingInboxSchemaStream`의 `info()` → `baseline()` 사이 다중 인스턴스 동시 기동 경쟁 — Flyway가 같은 baseline marker면 건너뛴다고 보지만 실행으로 확인하지 않았다. +- `PUBLISH_RUNTIME_UNAVAILABLE`을 retryable로 바꾼 것이 "그 broker의 runtime이 영영 없는" 설정 오류를 무한 재시도로 숨기는지 — 기동 검증이 그 조합을 막는지 추적하지 않았다. +- `createAggregateSequence`의 PK 충돌로 실패한 쓰기 트랜잭션을 호출자가 재시도하는지·어떤 HTTP 응답이 되는지 — sample·persistence 영역 경로다. +- relay가 레코드 timestamp를 `occurredAt`으로 보내서, 오래 밀린 행이 topic 보존·timestamp 정책에 걸리는 문제 — 기존 동작이고 broker 설정에 달린다. 무한 재시도와 겹치는 부분만 RR-05-03에 적었다. +- relay를 끈 모든 인스턴스도 poll 주기마다 게이지 질의 2개를 돈다 — 부하는 작다고 보지만 재지 않았다. +- `messagingCodecs`가 handler bean을 일찍 만들어 생기는 순환 의존 — Javadoc이 알리고 Spring이 기동에서 거부한다. 실제 순환 사례로 시험하지 않았다. +- `OutboxRelayShutdownOrderTest`는 platform 대역(같은 phase)을 쓴다. 실제 `MessagingShutdownLifecycle` drain과 실제 SIGTERM은 확인하지 않았다. + +## 28개 관점 — 바뀐 관점만 + +| 번호 | 관점 | 이전 → 지금 | 한 줄 이유 | +| --- | --- | --- | --- | +| 2 | 구조적 성숙도 | P → O | 소비 경로에 application leaf(`adapter:inbound:messaging`)가 생겼다. application 소비 포트는 이유를 남기고 버렸다 | +| 6 | 실패 성숙도 | X → P | 일시 거부·종료·짧은 장애가 더는 DEAD가 되지 않는다. 끝나지 않는 재시도 행의 처분 수단이 없다(RR-05-03) | +| 13 | 확장성 | P → O | aggregate 하나가 poll 주기에 묶이지 않는다(tick당 최대 50회차) | +| 18 | 배포 성숙도 | X → P | 종료 순서를 relay가 소유하고 앱 경로 실연 lane이 main·nightly 게이트에 있다. 업그레이드 때 순서 번호가 1로 돌아간다(RR-05-02) | +| 22 | 추상화 성숙도 | P → O | outcome 어휘가 platform의 "지금만 거부"를 담는다(`REJECTED_RETRYABLE`) | +| 25 | 조직 확장성 | P → O | 소비 기능을 registry 간선을 새로 만들지 않고 정해진 leaf에 둔다 | +| 28 | 회복 가능성 | X → P | broker 장애 뒤 자동 재개된다. DEAD 수동 재구동 SQL은 일부 행에서 실패한다(RR-05-01) | + +## Assessment + +**Ready to merge? With fixes.** + +06-01~06-05·06-07~06-09의 수정은 코드와 테스트로 확인했고, 종료 순서와 재시도 분리는 설계대로 동작한다. 다만 DEAD runbook 재발행 SQL(RR-05-01)은 실 PG에서 실패가 재현됐고 고치기 쉬우므로 먼저 고친다. 업그레이드 때 순서 번호가 1로 돌아가는 문제(RR-05-02)는 파생 서비스가 이 변경을 받기 전에 시작값이나 절차를 정한다. diff --git a/docs/reviews/2026-11-03-rereview/06-bootstrap-build-ci.md b/docs/reviews/2026-11-03-rereview/06-bootstrap-build-ci.md new file mode 100644 index 00000000..62662716 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/06-bootstrap-build-ci.md @@ -0,0 +1,283 @@ +# 06 bootstrap·build·CI 재리뷰 (2026-11-03) + +리뷰 대상: Base `01a8a2a70` → Head `5786126c`, 영역 번호 06(slug `bootstrap-build-ci`). 원래 영역 문서는 +`docs/reviews/2026-11-01-maturity-review/07-bootstrap-composition-config.md`, +`08-build-ci-test.md`, `09-performance-measurement.md`(샘플 쪽)다. 경로는 저장소 루트 기준이다. + +## 범위 — 본 pathspec, 불러온 스킬과 적용한 기준, 실행한 명령과 결과, 못 본 것 + +### 본 pathspec + +```text +src/app-bootstrap src/sample-portfolio src/build-logic src/build.gradle src/settings.gradle src/gradle +src/gradle.properties src/optional-platforms src/config src/Dockerfile src/Dockerfile.sample +src/.env.example .github docker-compose*.yml infra/postgres infra/fileserver +scripts/run-compose-runtime-smoke.sh scripts/verify-compose-profile-contracts.sh AGENTS.md CLAUDE.md +docs/registries docs/testing docs/capability-status.md +``` + +`git diff --stat` 기준 259파일 +8,251 −2,008. 하위 에이전트 없이 여러 번에 나눠 직접 읽었다. + +- 전부 읽은 것: build-logic main diff 전체(`StrictLaneStagesPlugin`, `WorkflowGradleInvocations`, + `StrictTestLanePlugin`, `JavaConventionsPlugin`, `QualityConventionsPlugin`, `ModuleRegistry`, + `ArchitecturePlugin`, `ConfigContractPlugin`·`EnvContractVerifier`), 루트 `build.gradle`, optional-platforms의 + `settings.gradle`·`gradle.properties`·`build.gradle`, workflow diff 전체(`integration-main.yml` 전문, + `ci-quality-gates.yml`, `release.yml`), `config/spotbugs/exclude.xml` 전문, `container-images.properties`, + compose 파일·`compose-profile-contracts.json`·검사 스크립트 diff, app-bootstrap main diff 전체와 + `build.gradle` 전문, sample main diff 전체와 `application.yml` 전문, AGENTS.md·CLAUDE.md diff. +- 표본으로 읽은 것: repository-contract 태그 16개 클래스가 읽는 파일 목록(입력 선언과 대조), 새 system·integration + 테스트의 단언부, `env-keys.yaml` diff 앞부분, `docs/testing/TESTING_STRATEGY.md` 9절, `docs/capability-status.md` diff. +- pathspec 밖에서 확인용으로 읽은 것: support `StartupRuleRunner`·`StartupRule`·`StartupRuleAutoConfiguration`, + persistence-jpa `JpaStartupAutoConfiguration`의 rule bean 선언, `grpc/grpc-testkit/build.gradle`, + objectstorage `build.gradle`, SpotBugs 제외 표본 확인용 `JdbcOutboxRepository`·`MessageHeaders`·`AuthorizationPrincipal`. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +| --- | --- | --- | +| `superpowers:requesting-code-review` | 리뷰어 템플릿(Strengths → severity별 Issues → Declined → Assessment), "테스트가 mock이 아닌 실제 동작을 보는가", "읽지 않은 코드에 좋다고 하지 않는다" | 새 system 테스트가 실제 서버·실 PostgreSQL·실 OTLP 수신기를 쓰는지 확인. 의심 가는 것은 worktree에서 실행해 확인 | +| `ci-cd-and-automation` | "No gate can be skipped", Red flag "CI failures ignored or silenced", 캐시 최적화가 결과를 바꾸면 안 된다, CI 설정 안 비밀값 | strict lane 단계 연결(`verifyStrictLaneStages`), `--continue`, build cache가 실패해야 할 lane을 녹색으로 돌려주는지, Redis lane fixture 비밀번호 | +| `refactor` | 동작 보존, 중복 코드, 죽은 코드 | 샘플을 그대로 복제해도 안전한가 — 죽은 설정 블록, 두 갈래 충돌 변환, 같은 lane 중복 실행 | +| `documentation-and-adrs` | "Rules files are current and accurate", "Known gotchas documented inline", 결정에 이유가 남아 있는가 | AGENTS.md·CLAUDE.md·build-logic README·capability-status·env 레지스트리를 코드와 대조. 숨은 제약이 Javadoc에만 있는지 | + +### 실행한 명령과 결과 + +worktree `scratchpad/rr-06`(HEAD `5786126c`)에서 `flock heavy.lock`으로 감싸 실행했다. 시작 부하 6~23. 끝난 뒤 +`git worktree remove --force`로 지웠다. 메인 체크아웃은 건드리지 않았다. + +| # | 명령 | 결과 | +| --- | --- | --- | +| 1 | `MessagingEnvelopeSchemaResourceTest`에 `@Disabled` 테스트 1개 추가, `shared-contract/build.gradle`의 `rejectSkipped = false` → `./gradlew :shared-contract:messagingSharedSchemaQualificationTest` | SUCCESS, 결과 XML `skipped="1"` | +| 1-b | 같은 lane에서 `rejectSkipped = true`로만 바꾸고 같은 명령 | **`UP-TO-DATE`, BUILD SUCCESSFUL** | +| 1-c | `--rerun` | FAILED: "forbids skipped tests but observed 1 skipped test(s)" | +| 1-d | lane 결과 폴더를 지우고 다시 실행 | **`FROM-CACHE`, BUILD SUCCESSFUL** | +| 2 | support test에 probe 추가: JavaBean `@ConfigurationProperties("probe")` + non-static `@Bean StartupRule probeRule(ProbeSettings)`, `probe.name=bound` → `./gradlew :adapter:outbound:support:test --tests '*RR06EarlyRuleProbeTest*'` | runner 없음: `name=bound`. runner 있음: 기동 성공, **`name=null`**, 경고 없음. rule이 null을 위반으로 보면 "probe.name is missing"으로 기동 실패. 설정을 생성자 주입하는 변형은 "No default constructor found" | +| 3 | `./gradlew :sample-portfolio:spotbugsMain`(현재 exclude) | BugInstance 0 | +| 3-b | exclude에서 EI 패턴 1과 `~.*SecurityConfig` CSRF Match를 빼고 sample·application-core·domain-core·shared-contract·web·app-bootstrap·service-runtime·support `spotbugsMain --continue` | EI 23건 전부 협력 객체(리포지토리·유스케이스·`EntityManager`·예외 cause·`BeanFactory`). CSRF 4건: web `SecurityConfig`, `ManagementSecurityConfig`, `SampleManagementSecurityConfig`, `SampleDemoSecurityConfig` | +| 4 | `./gradlew :verifyStrictLaneStages --dry-run` | "every strict lane is in an executed stage" | +| 4-b | `integration-main.yml`의 `:integrationCheck` 줄에 `-x :adapter:outbound:persistence-jpa:postgresqlIdempotencyIntegrationTest` 추가 후 같은 명령 | **여전히 통과** | + +돌리지 않은 것: `ci`·`mainCheck`·`integrationCheck` 전체(README 16.2의 오케스트레이터 실행을 근거로 삼았다), +`docker build`, compose 실제 기동, GitHub Actions 실행. + +### 못 본 것 + +- 실제 CI runner에서의 workflow 실행과 `gradle/actions/setup-gradle`의 캐시 복원 범위. RR-06-02의 CI 전파는 action 설정 + (`cache-read-only`)에서 추론했다. +- app-bootstrap document-contract 21개 클래스 본문, `env-keys.yaml` diff 뒷부분(키 이름·주석만 훑음). +- sample posterimage 경로(application 클래스 45개)는 diff 표본만 봤다. + +## Strengths + +- **lane 도달성을 Gradle 자신의 계획으로 판정한다.** `src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java:104-145`. + 문자열 contains가 아니라 `--dry-run` task graph를 읽는다. `--dry-run`·`-p` 명령은 실행으로 세지 않는다. TestKit 6건과 reader 테스트 8건이 있다. +- **YAML folded block의 빈 줄 결함(22곳)을 검사로 고정했다.** `WorkflowGradleInvocations.java:95-131`, workflow 5개 diff. +- **캐시 허용을 lane 범주로 나누고 이유를 코드에 적었다.** `StrictTestLanePlugin.java:223-231, 307-333`. `StrictTestLaneConventionTest`가 FROM_CACHE와 SUCCESS를 TestKit으로 단언한다. +- **저장소를 읽는 테스트를 두 lane으로 나눴다.** `src/app-bootstrap/build.gradle:316-387`. 저장소 루트를 두 lane에만 준다. 그래서 태그 없이 저장소를 읽는 테스트는 `test`에서 실패한다. repository-contract 16개 클래스가 읽는 파일을 표본 대조했고 모두 선언된 입력 안에 있었다. +- **기동 rule이 DB 연결·마이그레이션 전에 돈다.** `src/adapter/outbound/support/.../startup/StartupRuleRunner.java:51-67`(BFPP). `StartupRuleRunnerTest`가 "다른 빈이 하나도 만들어지기 전"을 단언한다. +- **트레이스 수출을 실제 수신기로 검증한다.** `src/app-bootstrap/src/systemTest/.../TracingExportSystemTest.java:40-92`. OTLP 본문 바이트 안에서 응답의 trace id를 찾는다. mock이 아니다. +- **샘플 인가를 실행본 그대로 검증한다.** `SampleWorkLogAuthorizationSystemTest`는 `SamplePortfolioApplication` 전체를 RANDOM_PORT + 실 PostgreSQL로 띄워 401·403·204·201을 확인한다. +- **SQL 비용을 실제 서버에서 숫자로 고정한다.** `src/sample-portfolio/src/systemTest/.../WorkLogStatementCostSystemTest.java:85-131`(목록 20·100건 모두 2문장, batch 100건 8왕복, 제목 PATCH 시 컬렉션 쓰기 0). +- **중복 규칙을 DB가 지킨다.** `src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql`은 기존 중복이 있으면 이유와 함께 실패한다. adapter는 제약 이름이 일치할 때만 409로 바꾼다(`PosterRepositoryAdapter.java:72-91`). +- **SpotBugs 제외에 이유가 붙어 있고 넓은 패턴은 필드 타입으로 좁혔다.** `src/config/spotbugs/exclude.xml:94-149`. 실험 3-b에서 EI 패턴 1을 빼고 8개 leaf를 돌렸다. 나온 EI 23건은 모두 협력 객체였다. 이 패턴이 진짜 결함을 가린 표본은 찾지 못했다. +- **Redis lane이 운영과 같은 인증 모양이다.** `docker-compose.infra.yml:140-180`이 ACL 파일을 그대로 마운트한다. `scripts/verify-compose-profile-contracts.sh` check 7이 계정·비밀번호·key pattern을 실제 마운트 파일과 대조한다. +- **복사본이 갈라지면 실패한다.** `src/optional-platforms/settings.gradle:23-36`이 `gradle.properties` 두 벌의 동일성을 검사한다. +- **미등록 leaf를 잡는다.** `ModuleRegistry.unregisteredBuildScripts`(`ModuleRegistry.java:189-246`) + `VerifyCleanArchitectureDependenciesTask`. + +## 발견 재확인 표 + +상태: 닫힘 / 부분 / 회귀 / 결정으로 닫힘. `>`는 다른 영역 소관. + +| ID | 상태 | 근거 | +| --- | --- | --- | +| 07-01 | 닫힘 | Boot tracing 모듈로 교체. `TracingExportSystemTest.java:58-92`가 실제 OTLP 수신과 trace id 일치를 본다. endpoint가 비면 exporter bean 0개(`:95-108`) | +| 07-02 | 닫힘(새 위험 RR-06-01) | `StartupRuleRunner.java:51-67` BFPP. `SecretSourceValidator`·`StartupSafetyValidator`가 rule로 옮겼다. rule을 static으로 선언해야 한다는 제약은 강제되지 않는다 | +| 07-03 | 닫힘 | `SampleDemoSecurityConfig.java:33-86` + 메서드 보안 유지(`SamplePortfolioApplication.java:31`). 실서버 테스트 `SampleWorkLogAuthorizationSystemTest` | +| 07-04 | 닫힘(대안 검증) | `Dockerfile.sample:56-63`에 `gradle.properties`·`build-logic/`. `DeveloperExperienceContractTest.java:384-401`이 두 Dockerfile 의존성 단계 COPY 줄 동일성을 단언. 실제 `docker build`는 이번에 다시 돌리지 않았다 | +| 07-05 | 닫힘(02-03과 묶음) | audience 필수. `application.yml:45-47` 주석 갱신. 본체는 02 영역 | +| 07-06 | 닫힘 | `logback-spring.xml:21-60`이 `app.logging.*`을 읽는다. `LoggingSettings` 삭제. `LoggingConfigurationRule`·`LoggingSettingsSourceSystemTest` | +| 07-07 | 닫힘(잔여 RR-06-08) | compose `stop_grace_period: 60s`(`docker-compose.yml:88`), `AWAIT_TERMINATION_SECONDS` 공개 상수, 합계 단언 테스트. drain 30초는 테스트에 리터럴로 남음 | +| 07-08 | 부분(RR-06-10) | durable-operation 모듈 분리, 권한 매핑 모듈 이동, fileserver 볼륨 overlay, dev/prod 프로필 정리 완료. 원래 항목 (6) `ConfigContractPlugin.java:24`가 redis-runtime을 이름으로 아는 것은 그대로 | +| 07-09 | 닫힘(01 영역과 공유) | AGENTS.md 기능 개발 프로토콜에 "sample은 배치 예시가 아니다" 추가, `scripts/new-feature.sh`·`verifyFeatureScaffold`(mainCheck). 표본만 확인 | +| 07-10 | 부분(RR-06-06, RR-06-07) | bootstrap 설정 strict 바인딩(`AsyncExecutorSettings`·`RuntimeSafetySettings`·`BootstrapSettings`·`SecretSourceSettings`), compose·logback이 `verifyEnvKeys` 입력. sample yml 죽은 블록과 smoke 래퍼·lane json의 키는 남음 | +| 07-11 | 닫힘(새 drift RR-06-11) | 지목된 줄은 모두 고침. 같은 종류의 새 drift가 생김 | +| 07-12 | 닫힘(문서) | `config/server.yml:15-22` 주석. 실측은 없음(주석이 그렇게 말함) | +| 07-13 | 닫힘 | `docker-compose.yml:61`, `docker-compose.dev.yml:67` loopback. `DeveloperExperienceContractTest.java:428-` 단언 | +| 07-14 | 닫힘 | `RuntimeEnvironmentProfileValidator.java:86` class literal | +| 08-01 | 부분(RR-06-03, RR-06-04) | main build는 닫힘: `integration-check`·`performance-check` 잡(`integration-main.yml:165-212`), sample systemTest가 mainCheck(`src/build.gradle:192`), `verifyStrictLaneStages`가 PR 게이트. optional-platforms build는 검사 밖이고 `grpcPerformanceTest`가 여전히 어디서도 돌지 않는다 | +| 08-02 | 닫힘(새 위험 RR-06-02) | `StrictTestLanePlugin.java:223-231`. app-bootstrap이 `systemTestCheck`에서 빠짐(`src/build.gradle:124-131`). lane 정책(`rejectSkipped`)이 캐시 키에 없다 | +| 08-03 | 닫힘 | `app-bootstrap/build.gradle:316-387`, `test`가 `repository-contract` 제외 | +| 08-04 | 부분(RR-06-09) | main-check `--continue`(`integration-main.yml:85`), 이미지 목록 한 파일(MinIO는 결정으로 objectstorage 소유), mirror prefix 안내. 원래 (d) MinIO lane 중복은 오히려 늘었다 | +| 08-05 | 닫힘 | `ModuleRegistry.java:189-246`, `VerifyCleanArchitectureDependenciesTask.java:65-72`, `ModuleRegistryTest` | +| 08-06 | 닫힘 | optional `gradle.properties` + 동일성 검사, ARCHITECTURE lane이 실서버 슬롯을 잡지 않음(`StrictTestLanePlugin.java:187-201`) | +| 08-07 | 결정으로 닫힘(잔여 RR-06-05) | MEDIUM으로 내림, 제외마다 이유. sample은 어떤 단계도 분석하지 않는다 | +| 09-01 | 닫힘 | 목록이 요약 projection을 쓴다. `WorkLogStatementCostSystemTest.java:85-94` | +| 09-02 | 닫힘 | `V8_1` 유일 인덱스 + adapter 변환 + `CreatePosterConcurrencyIntegrationTest`(integrationCheck) | +| 09-03 | 닫힘 | 07-03과 같은 수정 | +| 09-04 | 닫힘 | `SampleApiDocsSystemTest`(sample systemTest, mainCheck) | +| 09-05 | > 04 | persistence-jpa 소관 | +| 09-06 | 닫힘 | `WorkLogRepositoryAdapter.java:56-71` 관리 엔티티 갱신, `WorkLogEntity.replaceState`. 테스트 `:97-108` | +| 09-07 | 닫힘 | sample `application.yml:61-71` batch 50 + order_inserts. 테스트 `:120-131`(8왕복) | +| 09-08 | 부분(RR-06-06) | `SampleRuntimeDefaultsContractTest`는 키 3개만 본다. sample yml 머리말의 "읽는 설정만"은 사실이 아니다 | +| 09-09 | > 04 | persistence-jpa 소관 | +| 09-10 | 닫힘 | `application-local.yml:118` `${APP_SERVER_PORT:8080}` | +| 09-11 | 결정으로 닫힘 | 15절: Jackson 2 유지 | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +#### RR-06-01 · 기동 rule을 static이 아닌 `@Bean`으로 선언하면 설정이 조용히 바인딩되지 않는다 + +- **위치**: `src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java:51-67`(pathspec 밖, 07-02 수정), 제약 설명은 `StartupRule.java:12-22`와 `src/app-bootstrap/CLAUDE.md:88-90`뿐. 같은 방식으로 기대는 곳: `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java:33-35`(`RequiredProductionSecrets`를 rule 실행 때 꺼냄). +- **무엇이 틀렸나**: runner가 `BeanFactoryPostProcessor`가 되면서 rule bean은 어떤 `BeanPostProcessor`보다 먼저 만들어진다. rule을 non-static `@Bean` 메서드로 선언하고 설정 bean을 인자로 받으면, 그 설정 bean도 BPP 없이 먼저 만들어진다. JavaBean 방식 `@ConfigurationProperties`의 바인딩은 BPP가 하므로 값이 들어가지 않는다. singleton이라 앱이 끝날 때까지 그 상태로 남는다. +- **증거 (E3)**: 실험 2. 같은 설정(`probe.name=bound`)으로 runner가 없으면 `bound`, runner가 있으면 `null`이었다. 기동은 성공했고 경고는 없었다. 생성자 주입 변형은 "No default constructor found"라는 엉뚱한 메시지로 실패했다. +- **왜 중요한가**: 이 제약은 Javadoc과 CLAUDE.md 한 줄에만 있다. 새 capability 작성자가 흔한 모양(설정 bean을 받는 `@Bean` 메서드)으로 rule을 쓰면, 그 rule은 기본값을 검사한다. 같은 설정 bean을 쓰는 다른 코드도 기본값으로 동작한다. 사용자 원칙 "개발자가 따로 기억해야 하는 숨은 위험은 결함"에 해당한다. 템플릿 자신도 CLAUDE.md의 "parameterless"를 지키지 않는다(`StartupSafetyValidator(ListableBeanFactory)`, `SecretSourceValidator(ObjectProvider)`). 현재 선언 13곳은 모두 static이라 지금 터지는 곳은 없다. +- **고치는 법**: runner가 rule을 꺼내기 전에 정의를 검사해 거절한다. `beanFactory.getBeanDefinition(name)`이 `AnnotatedBeanDefinition`이면 `getFactoryMethodMetadata().isStatic()`과 인자 타입(`Environment`·`ListableBeanFactory`·`ObjectProvider`만 허용)을 확인하고, 아니면 이름을 대며 기동을 실패시킨다. 더 단순한 대안은 rule 생성 전후 `getSingletonCount()`를 비교해 rule 말고 다른 singleton이 생겼으면 실패시키는 것이다. 둘 다 위 probe를 RED 테스트로 쓸 수 있다. `RequiredProductionSecrets`에도 같은 검사를 건다. +- **가이드 심각도·우선순위**: Medium · P2. + +#### RR-06-02 · build cache가 지금의 lane 정책이라면 실패했을 결과를 녹색으로 돌려준다 + +- **위치**: `src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java:223-231`(캐시 허용), `:277`(`isRejectSkipped()`는 `doLast`에서만 읽는다). CI 전파 경로: `.github/actions/setup-gradle-java/action.yml`(`cache-read-only: github.ref != main`). +- **무엇이 틀렸나**: 08-02 수정으로 TEST·ARCHITECTURE lane은 up-to-date와 build cache를 쓴다. 그런데 `rejectSkipped`는 task 입력이 아니다. lane이 skip을 포함한 채 통과해 캐시에 들어간 뒤 `rejectSkipped = true`로 바꾸면, 입력이 같아서 이전 결과를 그대로 쓴다. `doLast` 검사는 돌지 않는다. +- **증거 (E3)**: 실험 1. `rejectSkipped`를 true로 바꾼 직후 `UP-TO-DATE` 성공, 결과 폴더를 지우면 `FROM-CACHE` 성공. `--rerun`에서만 "forbids skipped tests"로 실패했다. 실패한 실행은 캐시에 저장되지 않으므로 녹색 항목이 계속 남는다. +- **왜 중요한가**: 정책을 강화하는 PR이 자기 효과를 보지 못하고 merge된다. main에서 저장한 캐시를 PR이 읽으므로(action 설정 기준, 실측 아님) CI에서도 같다. 테스트 클래스가 바뀔 때까지 강화가 적용되지 않는다. ci-cd 스킬의 "CI failures silenced"에 해당한다. 같은 변경으로 release 증거 잡(`release.yml` `webAdvancedTest`, gRPC 3 lane)도 캐시 결과를 증거로 올릴 수 있게 됐다. 원래 08-02 권고는 증거 잡에 `--rerun-tasks`였다. +- **고치는 법**: lane 정책을 입력으로 등록한다. `test.getInputs().property("strictLane.rejectSkipped", lane.isRejectSkipped())`, 그리고 `requires` 목록과 `explicitOnly` 여부도 같은 방식으로. TestKit에 "정책만 바꾼 두 번째 실행은 SUCCESS가 아니라 다시 실행한다"를 추가한다. release 증거 잡은 `--rerun-tasks`를 붙이거나 그 lane을 `doNotCacheIf`로 뺀다. +- **가이드 심각도·우선순위**: Medium · P2. + +#### RR-06-03 · `verifyStrictLaneStages`는 optional-platforms build를 보지 않는다 — `grpcPerformanceTest`가 여전히 어디서도 돌지 않는다 + +- **위치**: `StrictLaneStagesPlugin.java:129-137`(`root.getAllprojects()` — main build만), `src/optional-platforms/build.gradle:1-3`(`ca.strict-lane-stages` 미적용, `performanceCheck` 없음), `src/grpc/grpc-testkit/build.gradle:27-32`(`performance()`, `explicitOnly` 아님). 문서: `AGENTS.md:79-83`, `CLAUDE.md:40-42`, `src/build-logic/README.md:19`. +- **무엇이 틀렸나**: 문서는 "`explicitOnly`가 아닌 모든 strict lane"을 검사한다고 말한다. 실제로는 main build의 lane만 본다. optional build의 `grpcPerformanceTest`는 performance lane인데 어느 workflow도 부르지 않는다(release.yml은 다른 3 lane만 이름으로 부른다). 08-01이 찾은 모양 그대로다. +- **증거 (E2·E1)**: 실험 4에서 검사가 "every strict lane is in an executed stage"로 통과했다. 같은 시점에 `grpcPerformanceTest`를 부르는 run 줄은 workflow 15개에 없다(`grep`). optional build의 lane 연결은 아직 문자열 contains 테스트(`DeveloperExperienceContractTest.java:360-381`) 하나에 기댄다 — 원래 08-01이 기각한 방식이다. +- **왜 중요한가**: lane을 추가하는 사람은 "검사가 막아 준다"고 믿는다. optional build에서는 그 믿음이 틀린다. 지금 1개 lane이 그 상태다. +- **고치는 법**: optional build 루트에도 `ca.strict-lane-stages`를 적용하고 stage를 `ci`·`integrationCheck`·(신설) `performanceCheck` 또는 `explicitOnly`로 선언한다. workflow 쪽은 `-p optional-platforms `를 그 build의 실행으로 세도록 reader에 build 디렉터리 인자를 준다. `grpcPerformanceTest`는 주석의 의도대로 `explicitOnly("a measurement on a shared runner is a flaky test; run by name")`로 바꾼다. 문서의 "모든"을 범위에 맞게 고친다. +- **가이드 심각도·우선순위**: Medium · P2. + +### Minor (Nice to Have) + +#### RR-06-04 · stage 검사는 `-x` 제외·job 조건·`continue-on-error`를 보지 않는다 + +- **위치**: `WorkflowGradleInvocations.java:59-64`(`executesInStartBuild`), `:239-240`(`-x` 값을 건너뛰기만 함). +- **무엇이 틀렸나**: run 줄에 stage 이름만 있으면 실행으로 센다. `-x `으로 lane을 빼도, job이 `continue-on-error: true`나 `if:`로 막혀 있어도 통과한다. +- **증거 (E3)**: 실험 4-b. `:integrationCheck`에 `-x :adapter:outbound:persistence-jpa:postgresqlIdempotencyIntegrationTest`를 붙여도 통과했다. 그 lane은 integrationCheck에만 있으므로 어디서도 돌지 않게 된다. 지금 workflow에는 이런 줄이 없다. +- **고치는 법**: `-x` 값을 모아 plan에서 빼고 판정한다. `continue-on-error: true` job의 명령은 실행으로 세지 않는다. 둘 다 reader 단위 테스트 1건씩. +- **심각도·우선순위·증거**: Low · P3 · E3. + +#### RR-06-05 · sample은 SpotBugs를 한 번도 거치지 않는데 exclude에는 sample 항목이 있다. CSRF 제외 이유가 sample 데모 체인에는 맞지 않는다 + +- **위치**: `src/build.gradle:85-93`(`qualityCheck`는 `leafPaths` = sample 제외, `runOnCheck=false`), `src/config/spotbugs/exclude.xml:24-27`(`~.*SecurityConfig`), `:335`(sample `PosterImageUploadIntent`), `QualityConventionsPlugin.java:99-101`("A new finding fails qualityCheck"). +- **무엇이 틀렸나**: (1) 어떤 단계도 sample의 `spotbugsMain`을 부르지 않는다. 그래서 sample의 새 코드는 분석되지 않는다. exclude의 sample 항목은 닿지 않는 규칙이다. (2) `~.*SecurityConfig` 제외의 이유는 "stateless JWT, no ambient cookie auth"다. 새 `SampleDemoSecurityConfig`는 HTTP Basic이다. 브라우저는 Basic 자격 증명을 기억해 같은 origin 요청에 자동으로 붙인다. 이유가 이 클래스에는 거짓이다. +- **증거 (E3)**: 실험 3·3-b. 현재 exclude로 0건, Match를 빼면 `SampleDemoSecurityConfig`에 `SPRING_CSRF_PROTECTION_DISABLED`. +- **왜 중요한가**: 데모 계정 비밀번호가 공개이고 prod는 기동을 거부하므로 sample 자체의 피해는 없다. 문제는 복제되는 예시다. dev에서 실제 계정으로 이 체인을 복제하면 CSRF가 열린다. 그리고 그 사실을 알려 줄 도구가 sample에서는 꺼져 있다. +- **고치는 법**: sample job에 `:sample-portfolio:qualityCheck`를 넣거나 sample 항목을 지운다. CSRF Match는 클래스 이름 목록으로 좁히고, `SampleDemoSecurityConfig`는 이유("공개 데모 계정, prod 거부")를 단 별도 Match로 둔다. +- **심각도·우선순위·증거**: Low · P3 · E3. + +#### RR-06-06 · sample `application.yml` 머리말은 "읽는 설정만"이라고 말하지만 읽는 곳이 없는 블록이 남아 있다 + +- **위치**: `src/sample-portfolio/src/main/resources/application.yml:3`(머리말), `:210-211`(`app.messaging.broker`), `:212-216`(`app.notification.*`), `:217-235`(`app.outbound.http.*` 17키). +- **무엇이 틀렸나**: `app.outbound.http.*`는 저장소 어디에도 읽는 코드가 없다(`src/README.md:357`이 "canonical 설정이 아니다"라고 적는다). messaging·notification 모듈은 sample의 classpath에 없다(`sample-portfolio/build.gradle:66-88`). sample yml은 `verifyEnvKeys`의 설정 파일 입력도 아니다(`ConfigContractPlugin.java:26-45`). +- **왜 중요한가**: sample은 가장 먼저 복제된다. 복제한 사람은 이 키로 HTTP 타임아웃·재시도를 조정한다고 믿는다. 07-10의 (3)과 09-08이 노린 결함이다. +- **고치는 법**: 세 블록을 지운다. `SampleRuntimeDefaultsContractTest`에 "sample yml의 `app.*` 최상위 키는 sample classpath의 설정 prefix 중 하나"를 단언하거나, sample yml을 `verifyEnvKeys` 설정 입력에 넣는다. +- **심각도·우선순위·증거**: Low · P3 · E1. + +#### RR-06-07 · compose lane 계약 json과 smoke 래퍼의 `APP_*` 키는 env 계약 검사 밖이다 + +- **위치**: `scripts/run-compose-runtime-smoke.sh:41-53`(`CAPABILITIES_OFF`), `src/config/runtime/compose-profile-contracts.json`(각 lane `activationEnv`), `ConfigContractPlugin.java:46-57`(compose yml·logback만 operator 파일). +- **무엇이 틀렸나**: r3-f가 손으로 찾은 `CASKELETON_GRPC_ENABLED`(아무도 읽지 않는 키)와 같은 결함이 다시 생겨도 게이트가 모른다. 고친 키 `APP_GRPC_SERVER_ENABLED`와 기존 `APP_OBJECTSTORAGE_ENABLED`는 relaxed binding으로 동작하지만 레지스트리에 없다. +- **고치는 법**: `verifyEnvKeys`의 operator 입력에 lane json의 `activationEnv` 키와 스크립트의 `CAPABILITIES_OFF`를 더한다. 레지스트리에 없는 capability 끄기 키는 등록한다. +- **심각도·우선순위·증거**: Low · P3 · E1. + +#### RR-06-08 · 종료 예산의 web drain 30초가 테스트에 리터럴로 있고, runbook은 옛 예산을 말한다 + +- **위치**: `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java:410`(`webDrainSeconds = 30`), `docs/runbooks/job-timeout.md:51`(pathspec 밖, "shutdown 예산(20s) vs k8s 30s"). +- **무엇이 틀렸나**: drain은 `APP_SERVER_SHUTDOWN_TIMEOUT`으로 바뀌는 값이다. 레지스트리 기본값이 바뀌어도 테스트는 30으로 계산한다. 원래 완료 기준 "숫자는 한 곳"을 채우지 못했다. runbook의 20초는 이제 30+19초다. k8s grace 30초면 async 대기 중 SIGKILL이다. +- **고치는 법**: 테스트가 `env-keys.yaml`의 `APP_SERVER_SHUTDOWN_TIMEOUT` 기본값을 읽는다. runbook 문장을 49초 + preStop 기준으로 고친다. +- **심각도·우선순위·증거**: Low · P3 · E1. + +#### RR-06-09 · MinIO lane이 main push마다 두 잡에서 돈다 + +- **위치**: `src/adapter/outbound/objectstorage/build.gradle:162`(leaf `mainCheck` → MinIO 2 lane), 같은 lane이 `integration()`이라 `:integrationCheck`에도 들어간다. `integration-main.yml:67-85`와 `:165-176`이 같은 push에서 병렬로 돈다. PR 경로 필터 workflow `object-storage-qualification.yml:36,46`도 있다. +- **무엇이 틀렸나**: 원래 08-04 (d) "중복은 하나만"이 처리되지 않았다. 08-01 수정 뒤 실행 위치가 세 곳이 됐다. +- **고치는 법**: objectstorage `mainCheck`의 의존을 지운다. 컨테이너 lane은 integrationCheck가 소유한다는 규칙과도 맞는다. +- **심각도·우선순위·증거**: Low · P3 · E1. + +#### RR-06-10 · env 계약 태스크가 여전히 특정 leaf를 안다 (07-08 항목 6) + +- **위치**: `src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java:24`(`dependsOn(':adapter:outbound:redis-runtime:compileJava')`), `:58-62`(그 leaf의 metadata 경로). +- **무엇이 틀렸나**: capability 기준 7("이 모듈을 아는 곳은 모듈 자신뿐")의 남은 한 곳이다. redis-runtime을 지우거나 옮기면 `verifyEnvKeys`가 깨진다. 14·16절 어디에도 이 항목의 처리나 보류 이유가 없다. +- **고치는 법**: metadata를 내보내는 leaf가 자기 산출물을 등록하는 방식(예: 각 leaf의 `spring-configuration-metadata.json`을 configuration으로 노출하고 app-bootstrap이 runtime classpath에서 모음)으로 바꾸거나, 보류 이유를 결정 기록에 남긴다. +- **심각도·우선순위·증거**: Low · P3 · E1. + +#### RR-06-11 · 이번 수정 뒤 새로 어긋난 문서·주석 + +- **무엇이 틀렸나** (모두 E1): + - `src/build-logic/README.md:64` "a lane never reports up-to-date" — 08-02 뒤 TEST·ARCHITECTURE lane은 up-to-date다. + - `src/grpc/grpc-testkit/build.gradle:7-9` "none of them can serve an up-to-date result" — 같은 이유로 거짓(pathspec 밖). + - `CLAUDE.md:134-137`, `AGENTS.md:205` — mainCheck 구성에 `:sample-portfolio:systemTest`와 `verifyFeatureScaffold`가 빠져 있다(`src/build.gradle:192,197`). + - `src/app-bootstrap/src/main/resources/config/runtime.yml:22`, `config/observability.yml:114` — "@ConfigurationProperties로 바인딩"이라고 말한다. 이제 `StrictSettingsBinder`이고, `app.logging`은 settings record가 없다. + - `src/sample-portfolio/.../bootstrap/management/SampleManagementSecurityConfig.java:24` "order 0으로 main chain보다 먼저" — 데모 체인은 `@Order(-100)`에 `/**`라 먼저 매칭된다. actuator 체인은 닿지 않는다(이전부터 있던 상태지만 이번 diff가 이 흐름을 바꿨다). + - `docs/capability-status.md:34` — "`postgresqlIdempotencyIntegrationTest`, but no workflow runs it"는 이제 거짓이다(integrationCheck). 같은 행의 `IdempotencyProviderSelectionConfig`·`SampleIdempotencyConfig`는 main 소스에 없다. + - `src/sample-portfolio/build.gradle:199` — jvmArgs를 지운 뒤 "Pin UTC" 주석만 남았다. +- **고치는 법**: 위 줄을 코드에 맞춘다. 문서 대조 parser를 두지 않는 방침이므로 이번 리뷰 목록으로 처리한다. +- **심각도·우선순위·증거**: Low · P3 · E1. + +#### RR-06-12 · 샘플의 "DB가 지키는 유일 규칙" 예시가 계약을 산문으로만 두고, 두 흐름이 충돌을 다르게 바꾼다 + +- **위치**: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterRepository.java:8-13`(domain 포트 Javadoc이 application 예외를 약속), `PosterRepositoryAdapter.java:6,72-91`(adapter가 `application.poster.PosterTitleAlreadyExistsException`을 던짐), 비교: `WorkLogRepositoryAdapter.java:63-66`(Spring `ObjectOptimisticLockingFailureException`을 그대로 던짐). +- **무엇이 틀렸나**: domain 포트의 계약이 application 타입을 가리킨다. 코드로는 표현할 수 없어 Javadoc에만 있다. PosterRepository에는 fake도 공유 계약도 없어(단위 테스트는 Mockito mock) 이 약속을 실제 adapter만 지킨다. 같은 sample 안에서 WorkLog는 프레임워크 예외를, Poster는 application 예외를 adapter가 던진다. +- **왜 중요한가**: 이 sample은 09-02 수정의 따라 할 예시다. 복제하는 사람은 두 모양 중 하나를 고른다. AGENTS.md 테스트 규칙(fake와 adapter가 한 계약을 상속)도 이 포트에는 적용되지 않았다. +- **고치는 법**: 포트 옆(domain)에 `DuplicatePosterTitleException` 같은 타입을 두고 use case가 application 예외로 바꾸거나, 포트가 결과 타입을 돌려주게 한다. `PosterRepositoryContract`(fake + adapter)에 "같은 제목 두 번째 save는 거절"을 둔다. 매뉴얼에 충돌 변환 위치를 하나로 적는다. +- **심각도·우선순위·증거**: Low · P3 · E1. + +## Declined to judge + +- `AuthenticationModeCompositionConfig`가 여전히 `SmartInitializingSingleton`(모든 singleton 뒤)이다 — 빈 이름만 보므로 rule로 옮길 수 있지만, 바뀌는 것은 Redis 연결 하나라 피해가 작고 CLAUDE.md "빈이 필요한 검사는 빈으로 남는다"와 맞아 판단을 미룬다. +- Redis lane이 `APP_REDIS_NAMESPACE_ENVIRONMENT=prod`(local 프로필)를 쓴다 — 15절 결정(r3-K)이다. 새 위험은 문서화돼 있어 뒤집지 않았다. +- `performance-check` 잡의 `GRADLE_OPTS=-Dorg.gradle.project.performance.assertions.enabled=true`가 daemon까지 전달되는지 — 실행하지 않았다. +- `configuration-cache` 잡이 `performanceCheck`를 저장 가능성 검사에 넣지 않은 것 — 영향을 측정하지 않았다. +- `exclude.xml` CT group 1이 `@Configuration(proxyBeanMethods = false)` 클래스까지 덮는다. 이유("CGLIB 서브클래스")는 그 클래스에는 맞지 않는다. 다만 finalizer 공격 위험이 사실상 없어 결함으로 세지 않았다. +- `UNSAFE_HASH_EQUALS`의 `PostgreSqlIdempotencyStore` 제외 — 멱등 키가 주체별로 범위가 나뉘는지에 따라 판단이 달라진다. 02·04 영역 소관이라 미뤘다. +- `JdbcOutboxRepository.transition`이 `failureCode == null`이고 `now != null`이면 timestamp를 `last_failure_code` 자리에 묶는다 — SQL 주입 제외 표본을 보다 발견했다. messaging 영역(05) 소관이고 이번 diff가 아니다. +- sample 관리 포트에서 데모 체인이 GET을 모두 허용해 health 상세가 Basic 인증 시 보인다 — 공개 데모 계정이라 의미 있는 노출이 아니다. +- `.env.example`이 `APP_FILESERVER_PLATFORM_CLEANUP_ENABLED=true` 등 기본값을 바꾼 것 — 05 영역 결정(15절)이다. + +## 28개 관점 — 바뀐 관점만 + +원래 판정은 07 영역(`07-…md` 8절), 08 영역(`08-…md` 10절), 09 영역(README 11절)의 값이다. + +| 관점 | 영역 | 이전 → 지금 | 이유 | +| --- | --- | --- | --- | +| 2 구조적 성숙도 | 07 | P → O | durable operation·권한 매핑·볼륨이 모듈로 이동. 남은 것은 build-logic 한 곳(RR-06-10) | +| 5 위험 가시성 | 07 | X → P | 트레이스·인가·검사 순서가 고쳐지고 테스트로 보인다. rule static 제약은 숨어 있다(RR-06-01) | +| 5 위험 가시성 | 08 | P → P | 단계 검사가 생겼지만 optional build와 `-x`는 안 보인다(RR-06-03·04) | +| 5 위험 가시성 | 09 | X → P | 동시 중복·대표 쓰기·N+1이 실서버 테스트로 보인다. sample SpotBugs는 꺼져 있다(RR-06-05) | +| 6 실패 성숙도 | 08 | P → O | main-check `--continue`, 이미지 실패는 실패로 남는다 | +| 7 운영 성숙도 | 07 | P → O | span 수출, 종료 예산 합계 검사, 관리 포트 loopback. runbook drift는 Minor(RR-06-08) | +| 10 테스트 성숙도 | 09 | X → P | 실서버·실 PG 테스트가 대표 위험을 잡는다. Poster 포트는 공유 계약이 없다(RR-06-12) | +| 10 테스트 성숙도 | 08 | P → P | lane이 실제로 돈다. 캐시가 강화된 정책을 건너뛴다(RR-06-02) | +| 11 데이터 성숙도 | 09 | X → O | 유일 인덱스 + 기존 중복 시 마이그레이션 실패 | +| 12 동시성 성숙도 | 09 | X → O | 16 동시 생성에서 1행(동시성 integration 테스트) | +| 13 확장성 | 08 | P → P | main build는 lane 추가가 workflow를 몰라도 된다. optional build는 아직 이름 나열 | +| 14 성능 성숙도 | 08 | P → O | hermetic lane 캐시, 중복 systemTest 제거. `ci` 434→51초(캐시 있는 측정) | +| 16 의존성 성숙도 | 08 | P → O | 테스트 이미지 한 파일·digest, mirror prefix, 효과 없는 netty override 삭제 | +| 18 배포 성숙도 | 07 | P → O | `Dockerfile.sample` COPY 동일성 검사, 기본 이미지에서 VOLUME 제거, fileserver overlay | +| 19 설정 성숙도 | 07 | P → P | bootstrap strict 바인딩·로그 단일 출처는 됨. sample yml 죽은 키, lane 키 미검사(RR-06-06·07) | +| 20 개발자 경험 | 08 | P → O | 문서만 바꾼 커밋이 app-bootstrap `test`를 무효화하지 않는다 | +| 21 Guardrail 성숙도 | 07 | P → P | `@RequiresPermission` 실행본 검증은 생겼고, rule 선언 제약은 장치가 없다(RR-06-01) | +| 21 Guardrail 성숙도 | 08 | P → P | lane 도달성 M3(main build), optional build M0 | +| 26 Ownership | 07 | P → O | 권한 매핑·볼륨을 capability가 소유 | +| 27 삭제 가능성 | 07 | P → O | capability 한 줄을 지우면 bootstrap·compose·이미지에 흔적이 없다(주석 제외) | +| 28 회복 가능성 | 08 | P → O | 이미지 공급원이 사라지면 mirror prefix로 돌릴 수 있고, 다른 결과를 가리지 않는다 | + +## Assessment + +**Ready to merge? With fixes.** + +원래 07·08·09 발견은 대부분 코드와 실제 실행 테스트로 닫혔고 회귀는 없다. 다만 07-02·08-02 수정이 새 숨은 위험 두 개(rule 조기 생성, 캐시가 강화된 lane 정책을 건너뜀)를 만들었고, 08-01의 재발 방지 검사가 optional build를 덮지 못하므로 RR-06-01~03은 merge 전에 고치거나 결정 기록으로 받아들이는 것이 맞다. diff --git a/docs/reviews/2026-11-03-rereview/07-security.md b/docs/reviews/2026-11-03-rereview/07-security.md new file mode 100644 index 00000000..703ce010 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/07-security.md @@ -0,0 +1,214 @@ +# 07 보안 재리뷰 (2026-11-03) + +## 범위 + +### 본 pathspec + +브랜치 전체 `01a8a2a70..5786126c` 중 보안에 닿는 변경만 봤다. 영역이 여러 leaf에 걸쳐 있어서 파일 단위로 골랐다. + +- 인증·인가: `src/adapter/inbound/web/src/main/java/**/{auth,authz,settings,mvc/autoconfigure}/`, `src/composition/service-runtime/**/authorization/`, `src/application-core/**/security/`, `src/app-bootstrap/**/{security,runtime}/`, `src/app-bootstrap/src/main/resources/{config/security.yml,application*.yml}`, `src/sample-portfolio/**/bootstrap/security/`, `src/sample-portfolio/**/{controller,application/worklog}/`, `src/adapter/outbound/support/**/startup/` +- 파일 서버 소유자·대상: `src/application-fileserver/**/{lifecycle,upload}/`, `src/application-fileserver/src/testFixtures/**/FakeFileAccessPolicy.java`, `src/adapter/outbound/fileserver/**/RoleBasedFileAccessPolicy.java`, `src/adapter/inbound/web-fileserver/src/main/` +- 입력 상한: `src/adapter/inbound/graphql/**/cost/`, `src/adapter/inbound/web/**/mvc/filter/`, `src/adapter/inbound/websocket/**/stomp/`, `src/adapter/inbound/grpc/**/GrpcServer*.java`, `src/grpc/grpc-runtime/**/idempotency/` +- 헤더: `CorsExposedHeaders.java`, `SecurityConfig.java`, `WebMvcRequestIdFilter.java`, `IdempotencyKeyHeader.java`, `InvalidIdempotencyKeyException.java` +- 비밀값·compose: `SecretSource*.java`, `src/application-core/**/secret/`, `docker-compose*.yml`, `infra/redis-sdk/acl/`, `infra/fileserver/compose/`, `src/.env.example`, `src/config/runtime/compose-profile-contracts.json` +- SES 콜백: `src/adapter/outbound/notification/**/{callback,provider/ses,autoconfigure/NotificationCallbackProviderConfig.java,security/AesGcmCallbackPayloadProtection.java}`, `src/adapter/inbound/web-notification/**/callback/`, `src/composition/notification-platform/**/ProviderCallbackIngressBridge.java` +- 의존성·공급망: 모든 `gradle.lockfile`, `src/gradle/libs.versions.toml`, `JavaConventionsPlugin.java`, `src/adapter/outbound/objectstorage/src/test/**/MinioQualificationImage.java`, `minio-provider-evidence.json` +- 정적 분석: `src/config/spotbugs/exclude.xml`, `QualityConventionsPlugin.java` + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +|---|---|---| +| `superpowers:requesting-code-review` | 리뷰어 템플릿(Strengths → severity별 Issues → Declined to judge → Assessment), 읽기 전용, 하위 에이전트 금지 | 이 문서의 형식. 칭찬은 읽은 줄에만 붙였다 | +| `security-and-hardening` | 신뢰 경계마다 STRIDE, Always/Never 목록(비밀값 커밋 금지, CORS `*` 금지, 입력 상한), 공급망 4단계(lockfile·새 의존성·출처) | 아래 경계 표, CORS 노출 목록, 비밀값 fixture, lockfile 좌표 비교, MinIO 이미지 출처 | +| `security-review` | 발견마다 공격 경로와 신뢰도, 거짓 양성 걸러내기(DoS·하드닝 부족·테스트 전용 파일 제외) | 하위 작업 분할 지시는 brief의 "하위 에이전트 금지"를 따라 쓰지 않고, 걸러내기 기준만 직접 적용했다. 그래서 High로 올릴 만한 직접 악용 경로는 없었고, 남은 발견은 개발자·운영자 행동이 조건인 Medium·Low다 | + +신뢰 경계와 STRIDE로 본 것: + +| 경계 | 들어오는 것 | 본 위협 | +|---|---|---| +| HTTP API (JWT·세션) | bearer token, 헤더, 본문 | S(다른 client 토큰), E(role 범위, 권한 검사 누락), D(본문 상한) | +| 샘플 HTTP Basic | 공개 데모 계정 | S·E(운영 복제) | +| SES/SNS 콜백 | 서명된 SNS envelope | S(인증서 URL), T, R(감사), replay | +| WebSocket·gRPC·GraphQL | 프레임, 메시지, 쿼리 | D(크기·연결·복잡도) | +| 설정·env·compose | env 값, ACL 파일 | T·I(fixture 비밀번호, 오타 키) | +| 공급망 | Maven 좌표, 컨테이너 이미지 | T(새 라이브러리, 커뮤니티 이미지) | + +### 실행한 명령과 결과 + +- `git diff --stat` / `git diff 01a8a2a70..5786126c -- <위 pathspec>`: 읽기. +- lockfile 좌표 비교(base·head의 모든 `gradle.lockfile`을 합쳐 `group:artifact:version` 집합 차이): 새 좌표 4개, 지운 좌표 0개. 넷 다 1차 공급자 것이다(`spring-boot-micrometer-tracing`, `spring-boot-micrometer-tracing-opentelemetry`, `spring-boot-opentelemetry` 4.0.8, `opentelemetry-exporter-sender-jdk` 1.55.0). `io.netty:*`는 base와 같은 4.2.17.Final이다. +- 별도 worktree(`scratchpad/rr-07`, 5786126c)에 probe 테스트 2개를 넣고 실행: + `flock .../heavy.lock ./gradlew :composition:service-runtime:test --tests '*Rr07SystemInvokedProbeTest' :sample-portfolio:test --tests '*Rr07DemoGuardProbeTest' --console=plain -i` + → `BUILD SUCCESSFUL in 16s`(실행 직전 load 27.65). 출력은 RR-07-01, RR-07-02 증거에 적었다. worktree는 `git worktree remove --force`로 지웠다. + +### 못 본 것 + +- 실제 IdP(Keycloak) 토큰으로 audience·role 범위를 확인하지 않았다. 단위 테스트와 코드만 읽었다. +- 게이트(ci·mainCheck·integrationCheck)는 다시 돌리지 않았다. README 16.2 결과를 그대로 둔다. +- compose lane(`local-redis`, `all-adapters`, notification)을 직접 띄우지 않았다. +- 의존성 CVE 데이터베이스 대조(OSV·dependency-check)는 하지 않았다. 새 좌표가 1차 공급자 것뿐이라는 것까지만 확인했다. +- 보안과 관계없는 나머지 diff(성능·메시징 재시도·JPA 매핑 등)는 보지 않았다. + +## Strengths + +- **JWT audience가 닫힌 기본값이 됐다.** `SecuritySettings.java:44`가 풀리지 않은 `${...}` 자리표시자를 "값 없음"으로 읽는다. `SecuritySettings.java:62`가 JWT 모드에서 빈 audience를 기동 거부한다. `JwtDecoderConfig.java:77-88`도 빈 목록이면 예외를 던져 두 번째 방어선이 된다. 목록 중 하나만 맞으면 통과한다(`JwtDecoderConfig.java:106-116`). +- **role 범위가 자기 client로 좁혀졌다.** `JwtToAuthenticatedPrincipalConverter.java:92-100`은 audience로 설정한 client의 `resource_access`만 읽는다. "다른 client role은 권한이 되지 않는다" 테스트가 있다(`JwtToAuthenticatedPrincipalConverterTest.java:81-82`). +- **`app.security`가 엄격 바인딩이다.** 오타 키와 아무 설정도 아닌 `APP_SECURITY_*` env가 기동을 막는다(`SecuritySettingsTest.java:59-79`). 같은 prefix를 느슨하게 두 번 바인딩하던 `AuthenticationModeSettings`가 지워졌다. +- **메서드 보안이 인증 체인과 분리됐다.** `WebMethodSecurityAutoConfiguration`이 따로 있어서 JWT 체인을 빼도 `@RequiresPermission`이 남는다. web 어댑터가 없는 조립은 `PermissionEnforcementGuard.java:41-61`이 기동 실패로 막는다. +- **샘플 권한이 실서버로 검증된다.** `SampleWorkLogAuthorizationSystemTest`가 실제 PostgreSQL과 RANDOM_PORT 서버로 익명 401, 권한 없는 삭제 403, 권한 있는 삭제 204, 남의 기록 수정 403을 본다. mock이 아니다. +- **prod 기동 규칙이 DB 연결 전에 돈다.** `StartupRuleRunner`가 BeanFactoryPostProcessor가 됐다. `SecretSourceValidator`, TLS `verify-full`, H2 금지, 데모 계정 거부가 datasource·Flyway보다 먼저 돈다. 기여 bean은 모두 `static`이다(`JpaStartupAutoConfiguration.java:163`, `RedisCapabilityConfig.java:91`). +- **SNS 인증서 실패가 "거절"이 아니라 "다시 보내라"다.** `NotificationCallbackMvcController.java:124`가 503과 `Retry-After`를 준다. replay 창은 근거가 있는 상수다(`SesCallbackAdapter.java:49`, SNS HTTP 재시도 상한 3600초). 중복은 `(provider_profile_id, event_fingerprint)` 유일 인덱스가 막는다. +- **전송 상한이 코드에 드러났다.** gRPC는 메시지 1 MiB·메타데이터 8 KiB·연결당 동시 호출·고정 크기 executor·기본 deadline을 builder에 건다(`GrpcServerRunner.java:99-110`). WebSocket은 메시지·버퍼·첫 메시지 시간·노드 연결 수(`WebSocketConfig.java:72-78`)와 세션당 구독 1개를 건다. session id가 없으면 구독을 받지 않는다(`WebSocketInboundAuthorizationInterceptor.java:92-96`). +- **GraphQL 점수가 우회 경로를 막는다.** 변수 기본값, 스키마 인자 기본값, 크기 없는 list, 중첩 list 곱셈을 모두 계산하고, 범위 밖 정수는 최대값으로 읽어 거부한다(`GraphQlDocumentComplexityScorer.java:262-327`). +- **헤더 처리가 한 규칙이다.** correlation ID는 요청 ID와 같은 문법이고 틀리면 고치지 않고 새로 만든다(`WebMvcRequestIdFilter.java:189`). `Idempotency-Key`는 응답에 되돌려 쓰지 않는다(`InvalidIdempotencyKeyException.java`). CORS 노출 목록은 코드가 소유하고 `*`를 거부한다(`CorsExposedHeaders.java:27-47`). +- **compose 관리 포트가 loopback이다.** `docker-compose.yml:61`, `docker-compose.dev.yml`. compose Redis는 `default` 사용자를 끄고 ACL 계정으로만 붙는다. +- **SpotBugs MEDIUM의 보안 제외가 위치 단위다.** 표본으로 확인했다. `JdbcOutboxRepository`의 SET 절은 모두 문자열 리터럴이고 값은 바인딩이다. `IdempotencyCapabilityGuard`의 SQL은 상수다. `GraphQlRequestBodyLimitFilter.reject`는 고정 본문을 쓴다. `SnsSignatureVerifier`의 호스트 정규식은 선형이다. `ContentType`은 정규식 전에 160자로 자른다. +- **MinIO 이미지가 digest로만 바뀐다.** 운영자 override도 같은 digest가 아니면 거부한다(`MinioQualificationImage.java:73`). compose 기본값과 evidence가 다르면 `ComposeMinioImageMatchesEvidenceTest`가 실패한다. 기각한 후보와 이유가 evidence 파일에 남아 있다. +- **파일 서버 소유자 회귀가 이제 잡힌다.** fake 정책이 소유자 규칙을 지키므로 05-08 변이(descriptor 제거)가 use case 테스트에서 죽는다. copy·move 대상 namespace는 허용 목록이다(`CopyFileApplicationUseCase.java:96`, `MoveFileApplicationUseCase.java:53`). + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +|---|---|---| +| 02-03 | 닫힘 | `SecuritySettings.java:44,62`, `JwtDecoderConfig.java:77-88`, `JwtToAuthenticatedPrincipalConverter.java:92-100`. 완료 기준 2개(빈 audience 기동 실패, 다른 client role 무시) 모두 테스트가 있다 | +| 07-05 | 닫힘 | 02-03과 같은 코드. 결정 A대로 prod만이 아니라 JWT 모드 전체에서 거부한다 | +| 07-03 | 닫힘 | `SamplePortfolioApplication`이 JWT 체인만 빼고 `WebMethodSecurityAutoConfiguration`은 남긴다. 실서버 테스트가 403·204를 본다. 결정이 만든 새 위험은 RR-07-02 | +| 09-03 | 닫힘 | 익명 생성이 500이 아니라 401(`SampleWorkLogAuthorizationSystemTest`) | +| 01-06 | 닫힘, 새 결함 1 | 완료 기준 2개(web 없는 조립 기동 실패, relay의 장식용 권한 선언 제거)는 채웠다. 대신 들어온 `@SystemInvoked` 면제가 코드로 묶여 있지 않다 → RR-07-01 | +| 05-08 | 닫힘 | `FakeFileAccessPolicy.java:45-50`, `DownloadUseCasesTest.java:91,110`, `FileLifecycleUseCasesTest.java:340`. 규칙이 두 벌이다 → RR-07-06 | +| 05-12 | 닫힘 | `TusController.java:185`가 status 재조회(`file:read`) 없이 append 결과로 판단한다. 자동 finalize도 `file:upload`와 소유자 검사를 거친다 | +| 05-07 (대상·쿼터) | 결정으로 닫힘 | `TargetNamespacePolicy`(기본은 업로드 기본 namespace 하나). 동시 예약이 상한을 넘을 수 있는 것은 15절 결정 | +| 05-20 | 닫힘 | 창 1시간(`SesCallbackAdapter.java:49`), 인증서 실패 503(`ProviderCallbackIngressBridge.java:82`). 분류·중복 방지에 작은 틈 → RR-07-03, RR-07-07 | +| 05-09 | 결정으로 닫힘 | `pgsty/minio` digest 고정, 참조 한 곳(evidence), override digest 검사 | +| 03-01 | 닫힘 | `GraphQlDocumentComplexityScorer.java:262-295`, `PageVariables`(:385-) | +| 03-06 | 닫힘 | `StompConnectionLimit`, `WebSocketInboundAuthorizationInterceptor.java:55`, `WebSocketConfig.java:72-78` | +| 03-09 | 닫힘 | `GrpcServerRunner.java:99-110`, `GrpcServerSettings` 기본값 | +| 02-05 | 닫힘 | `SecurityConfig.corsConfigurationSource`가 `CorsExposedHeaders` 합집합을 노출, fileserver가 tus 헤더를 기여 | +| 02-09 | 결정으로 닫힘 | JSON 두 갈래를 테스트가 고정(`JsonBodyLimitFilterTest.java:47-77`). JSON 아닌 본문은 엔드포인트 몫(15절) | +| 02-11 | 닫힘 | `WebMvcRequestIdFilter.java:189` | +| 02-12 | 닫힘 | `IdempotencyKeyHeader`, 유일한 운영 KEYED 컨트롤러가 사용(`PosterImagePublicationController.java:64`) | +| 07-10 (보안 prefix) | 닫힘 | `SecuritySettings.bind`, `SecretSourceSettings.bind`. 다른 prefix는 이 영역 밖이라 보지 않았다 | +| 07-13 | 닫힘 | `docker-compose.yml:61`, `docker-compose.dev.yml` | +| 08-07 | 닫힘 | `QualityConventionsPlugin`에 MEDIUM과 측정 수, 제외마다 이유. 이유가 맞지 않게 된 기존 제외 1건 → RR-07-05 | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +#### RR-07-01 `@SystemInvoked`의 권한 검사 면제 조건이 Javadoc에만 있다 + +- 위치: `src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java:19-20`, `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java:558`, `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java:41-61` +- 무엇이 틀렸나: ArchUnit D4는 쓰기 유스케이스에 `@RequiresPermission`을 요구한다. 클래스에 `@SystemInvoked`가 붙으면 이 검사를 건너뛴다(:558). 면제의 전제는 "transport가 닿는 Spring 빈이 되면 안 된다"인데, 이 문장은 Javadoc(:19-20)과 `application-core/CLAUDE.md`에만 있다. 기동 검사(`PermissionEnforcementGuard`)는 `@RequiresPermission`이 붙은 빈만 본다. `@SystemInvoked` 빈은 보지 않는다. +- 왜 중요한가: D4가 실패하면 개발자(또는 에이전트)가 가장 쉽게 고르는 해법이 `@SystemInvoked(reason = "...")` 한 줄이다. 그 유스케이스를 컨트롤러가 부르면 모든 게이트가 통과한다. + - 누가: 그 서비스의 인증된 사용자 누구나(role 무관). + - 무엇으로: `@SystemInvoked`가 붙은 채 빈으로 등록된 쓰기 엔드포인트. + - 무엇을 얻나: role→permission 검사 없이 쓰기를 실행한다(권한 상승). 사용자 원칙 "개발자가 따로 기억해야 하는 숨은 위험은 결함"에 해당한다. +- 고치는 법: `PermissionEnforcementGuard`가 이미 모든 빈 정의를 훑는다. 같은 루프에서 클래스에 `@SystemInvoked`가 있으면 기동을 실패시킨다. 메시지는 "system-invoked use case must be constructed by its composition, not registered as a bean". 아래 probe를 RED 테스트로 쓴다. 보조로 ArchUnit "inbound adapter는 `@SystemInvoked` 클래스에 의존하지 않는다"를 둘 수 있다. +- 가이드 심각도·우선순위: Medium · P2. 개발자 실수가 조건이라 High가 아니다. +- 증거: E3. worktree에서 `@SystemInvoked` 클래스를 빈으로 등록하고 `PermissionEnforcementConfig`와 함께 띄웠다. 출력 `RR07 systemInvokedBean failed=false`(기동 성공). + +#### RR-07-02 데모 계정 거부가 정확히 `prod`일 때만 걸리고, 샘플에는 프로필 검증기가 없다 + +- 위치: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java:44-46`, `src/sample-portfolio/src/main/resources/application.yml:30`(`${SPRING_PROFILES_ACTIVE:local}`), `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java:84-86`, `src/config/architecture/modules.json:387-390`, `src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuardTest.java:70` +- 무엇이 틀렸나: 15절 결정의 이유는 "샘플을 복제해 운영에 올리는 위험을 코드로 막는다"이다. 구현은 금지 목록 방식이다. `RuntimeEnvironment.fromProfile`은 정확히 `prod`만 production으로 읽는다. 앱의 "환경 프로필 정확히 하나" 검사는 main class가 `CaSkeletonApplication`일 때만 돈다(:84-86). 샘플은 app-bootstrap에 의존하지 않아서 이 검사가 아예 없다(modules.json). 그래서 프로필 없음(yml 기본 `local`로 바뀜), `production`, `staging`으로 띄우면 데모 계정이 열린 채 기동한다. `Dockerfile.sample`도 프로필을 정하지 않는다. 테스트가 "프로필 없음이면 허용"을 고정해 둔다(:70). +- 왜 중요한가: + - 누가: 그 배포에 네트워크로 닿는 누구나. + - 무엇으로: README에 공개된 `demo-admin` / `demo-admin` HTTP Basic. + - 무엇을 얻나: admin role(`worklog:close` 삭제 등). 샘플을 베낀 서비스라면 그 서비스가 `admin`에 매핑한 권한 전부. + 결정 자체(prod 거부)는 그대로 지켰다. 문제는 결정이 막으려던 경로(복제 후 운영 배포)가 `prod`라는 이름 하나에만 걸려 있다는 것이다. +- 고치는 법: 결정을 넓히는 방향이라 뒤집지 않는다. + 1. 거부 조건을 허용 목록으로 바꾼다. `local`·`dev`·`test` 중 정확히 하나가 명시적으로 켜져 있을 때만 데모 계정을 허용한다. + 2. 샘플 yml의 `SPRING_PROFILES_ACTIVE:local` 기본값을 지운다. 기본값이 남아 있으면 1번만으로는 "프로필 없음"이 `local`로 바뀌어 통과한다. 대안은 데모 계정을 `app.sample.demo-accounts.enabled` 같은 명시 키로 켜고 이미지 기본값을 false로 두는 것이다. + 3. `theDemoAccountsAreAllowedWithNoProfileAtAll`을 반대 단언으로 바꾸고 `production`·`staging` 케이스를 더한다. +- 가이드 심각도·우선순위: Medium · P2. +- 증거: E3. worktree probe에서 `violations()` 결과: `production` 0건, `staging` 0건, `prd` 0건, `PROD ` 1건. + +### Minor (Nice to Have) + +#### RR-07-03 SNS 인증서 URL의 HTTP 4xx를 "검증 불가(503)"로 분류해서 위조 콜백이 거절도 감사도 되지 않는다 + +- 위치: `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java:74-77`, `src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java:82-92` +- 무엇이 틀렸나: 진짜 SNS 메시지의 `SigningCertURL`은 존재하는 인증서를 가리킨다. 호스트·경로 검사를 통과한 URL이 404·403을 주면 그 envelope은 위조다. 지금은 2xx가 아닌 모든 응답이 IOException·인터럽트와 같은 "일시 장애"로 묶인다. 결과는 503과 `Retry-After`이고, `securityAudit.callbackSignatureRejected`에 남지 않는다(WARNING 로그만). 주석은 "Not a security event"라고 단정한다. +- 왜 중요한가: + - 누가: 콜백 URL과 구독 topic ARN을 아는 외부인. + - 무엇으로: 허용 topic, 현재 `Timestamp`, `https://sns..amazonaws.com/SimpleNotificationService-<없는 id>.pem`을 넣은 envelope. + - 무엇을 얻나: 이벤트는 기록되지 않아 데이터 변조는 없다. 얻는 것은 서명 위조 시도가 감사 기록에서 빠지는 것(R)이다. 이전(500)에도 감사되지 않아서 회귀는 아니다. +- 고치는 법: 4xx는 `IllegalArgumentException`("SNS 서명 인증서가 아님") 쪽으로 보내 invalid + 감사로 처리한다. IOException·5xx·인터럽트만 `CallbackVerificationUnavailableException`으로 둔다. +- 가이드 심각도·우선순위: Low · P3. +- 증거: E1(코드 읽기). + +#### RR-07-04 Redis ACL fixture 파일이 "배포가 싣는 파일"로 소개되는데 공개 비밀번호의 `+@all` 계정을 담고 있다 + +- 위치: `infra/redis-sdk/acl/all-accounts.acl:8`(`ca-skeleton-cluster-bootstrap on >fixture-bootstrap ~* &* +@all`), `infra/redis-sdk/acl/README.md:23`, `docker-compose.infra.yml:140`, `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java:33` +- 무엇이 틀렸나: README 표(:23)는 이 파일을 "the four accounts concatenated … this is what a deployment loads"라고 쓴다. 실제 파일은 8줄이고 superuser 1개가 들어 있다. 이번 브랜치가 compose 주석(:140)에 "with the accounts a deployment loads"를 새로 썼다. README 11-13행은 반대로 "배포는 파일 전체를 바꾼다"고 쓴다. prod 비밀 검사는 `__LOCAL_DEV_` 접두만 거부하고 `fixture-*` 값은 모른다. 이번 브랜치는 lane에서 앱을 fixture 비밀번호와 namespace `prod`로 붙이기 시작했다. +- 왜 중요한가: + - 누가: 이 파일을 그대로 운영 Redis에 올린 배포에서, Redis에 닿는 누구나(같은 클러스터의 다른 pod 등). + - 무엇으로: `AUTH ca-skeleton-cluster-bootstrap fixture-bootstrap`. + - 무엇을 얻나: 모든 키 읽기·삭제, `CONFIG`·`MODULE`을 포함한 서버 장악. + 운영자가 fixture를 복사해야 성립하므로 Low다. +- 고치는 법: README 표와 compose 주석을 "lane이 싣는 fixture. 배포는 같은 모양의 파일을 비밀 저장소 비밀번호로 새로 만든다"로 고친다. 계정 수를 실제와 맞춘다. prod `SecretSourceValidator`가 `fixture-` 접두 값도 sentinel처럼 거부한다. +- 가이드 심각도·우선순위: Low · P3. +- 증거: E1. + +#### RR-07-05 CSRF 제외 규칙의 이유가 새 샘플 보안 설정에는 맞지 않는다 + +- 위치: `src/config/spotbugs/exclude.xml:19-27`, `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java:71-73` +- 무엇이 틀렸나: `SPRING_CSRF_PROTECTION_DISABLED`를 `~.*SecurityConfig` 패턴으로 제외한다. 이유는 "stateless JWT bearer, ambient cookie auth 없음"이다. 새 `SampleDemoSecurityConfig`가 이름 패턴에 걸린다. 이 클래스는 CSRF를 끄고 HTTP Basic을 쓴다. HTTP Basic은 브라우저가 한 번 받은 자격을 자동으로 붙이는 수단이라 이유가 성립하지 않는다. 08-07이 정한 규칙("A pattern-wide Match needs a reason that holds for every class it can ever match", `QualityConventionsPlugin`)과 어긋난다. +- 왜 중요한가: 지금 실제 영향은 없다. 401이 `WWW-Authenticate: Bearer`라 브라우저가 Basic 자격을 저장하지 않고, 계정도 공개다. 다만 샘플을 베낀 서비스가 실제 Basic 계정을 넣으면 CSRF 경고가 조용히 사라진다. +- 고치는 법: 매치를 정확한 클래스 이름으로 좁힌다. 샘플용 Match를 따로 두고 "공개 계정이라 CSRF가 지킬 자격이 없다"는 이유를 단다. +- 가이드 심각도·우선순위: Low · P3. +- 증거: E1. + +#### RR-07-06 파일 소유자 규칙이 fake와 실제 정책에 두 벌 있고 공유 계약이 없다 + +- 위치: `src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java:45-50`, `src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/security/RoleBasedFileAccessPolicy.java:74-91` +- 무엇이 틀렸나: 05-08 변이를 잡는 장치는 fake가 실제 정책의 소유자 규칙을 베낀 것이다. 둘을 묶는 `FileAccessPolicyPort` 계약 테스트가 없다(`docs/testing/TESTING_STRATEGY.md` 9절에도 없음). 비교 방식도 다르다. fake는 `owner == subject.asOwner()` 하나로 비교하고, 실제 정책은 principalId와 tenant를 따로 비교한다. +- 왜 중요한가: 실제 정책이 바뀌면(예: 관리자 우회 추가) fake는 그대로 남는다. use case 테스트는 운영과 다른 소유자 규칙을 검증하게 된다. 다른 사용자 파일 접근(IDOR) 회귀를 막는 장치가 갈라진 복사본에 기대고 있다. +- 고치는 법: application-fileserver testFixtures에 `FileAccessPolicyPortContract`를 둔다. 케이스는 남의 파일 거부, 다른 tenant 거부, 소유자 없는 파일 거부, descriptor 없음은 역할만 확인. fake와 `RoleBasedFileAccessPolicyTest`가 상속한다(AGENTS.md의 공유 계약 규칙). +- 가이드 심각도·우선순위: Low · P3. +- 증거: E1. + +#### RR-07-07 replay 창 1시간의 중복 방지가 fingerprint 키 회전에 깨지고, Javadoc은 다른 유일 키를 말한다 + +- 위치: `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java:36-40`, `SesEventNormalizer.java:78`, `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/security/AesGcmCallbackPayloadProtection.java:130`, `src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V1__notification_platform_core.sql:174-179` +- 무엇이 틀렸나: Javadoc은 "ledger가 `(provider_profile_id, provider_event_id)`로 유일하다"고 쓴다. SES 이벤트는 `provider_event_id`가 항상 비어 있다(:78). 실제로 막는 것은 `(provider_profile_id, event_fingerprint)` 유일 인덱스다. fingerprint는 현재 활성 HMAC 키로 만든다(:130). 키를 회전하면 같은 콜백이 다른 fingerprint가 된다. +- 왜 중요한가: 창이 5분에서 1시간으로 12배 늘었다. 회전 전에 받은 콜백을 SNS가(또는 그 메시지를 가진 사람이) 회전 뒤 다시 보내면 두 번 기록된다. 서명이 필요해서 위조는 아니다. 같은 bounce·complaint·delivery가 두 행이 된다. +- 고치는 법: Javadoc을 실제 인덱스로 고친다. SES 콜백은 서명 문자열에 포함된 SNS `MessageId`를 `provider_event_id`로 넣는다. 그러면 키와 무관한 유일성이 생긴다. +- 가이드 심각도·우선순위: Low · P3. +- 증거: E1. + +## Declined to judge + +- Keycloak은 사용자가 어떤 client의 role을 가지면 그 client를 `aud`에 넣는다. 그래서 다른 client(`azp`)가 받은 토큰도 이 서비스 audience를 담을 수 있다. `azp` 검사는 02-03 결정 범위 밖이고 IdP 설정에 달려 있어 판단을 미룬다. +- `realm_access.roles`와 최상위 `roles` claim은 client 구분 없이 읽는다. realm role은 15절 결정으로 유지됐다. 최상위 `roles`는 IdP mapper 설정에 달려 있다. +- `PermissionEnforcementGuard`는 pointcut이 맞는 아무 advisor나 "강제한다"로 인정한다. Javadoc이 이 한계를 적었고, 지금 템플릿에는 `@RequiresPermission` 빈에 맞는 다른 advisor bean이 없다. +- 들어온 `traceparent`가 trace id와 sampled 플래그를 정한다(Boot 기본 ParentBased 샘플러). 기존 설계이고, 영향이 비용·로그 상관 쪽이라 보안 결함으로 보지 않았다. +- `pgsty/minio`는 커뮤니티 fork이고 서명 검증(cosign 등)이 없다. digest 고정과 테스트·로컬 전용이라는 점, 소유자 결정(15절)을 보고 판단을 미룬다. +- 의존성 CVE 대조는 도구를 돌리지 않아 판단하지 않았다. +- fileserver 저장소 초기화 컨테이너가 root로 `chown`만 한다(`network_mode: none`, `read_only`). capability를 더 줄일 수 있지만 하드닝 제안이라 발견으로 올리지 않았다. +- 파일 쿼터 동시 예약이 상한을 넘을 수 있는 것은 15절 결정이다. +- HTTP client의 `PLAINTEXT_FALLBACK_FORBIDDEN`이 비운영에서 풀린 것은 설정 문서와 `ClientProfileValidator`의 prod 검사(:246)와 일치해서 결함으로 보지 않았다. + +## 28개 관점 — 바뀐 관점만 + +README 11절 종합 판정 대비, 보안 범위 안에서 바뀐 것만 적는다. + +| 관점 | 전 | 후 | 이유 | +|---|---|---|---| +| 5 위험 가시성 | X | P | 빈 audience가 기동 거부로 드러난다. `@SystemInvoked` 조건(RR-07-01)과 데모 거부 범위(RR-07-02)는 아직 코드 밖에 있다 | +| 10 테스트 성숙도 | X | P | 05-08 변이가 죽고, 샘플 권한을 실서버로 본다. 소유자 규칙의 공유 계약은 없다(RR-07-06) | +| 13 확장성 | X | P | WebSocket 연결·구독, gRPC 동시 호출·메시지 크기 상한이 생겼다. principal별 상한은 서비스 몫으로 문서화됐다 | +| 15 보안 성숙도 | X | P | 02-03이 닫혔다. Medium 2건(RR-07-01, RR-07-02)이 남았다 | + +## Assessment + +**Ready to merge? With fixes** + +Critical·High는 없고 보안 영역의 원래 발견은 모두 닫히거나 결정으로 닫혔다. 남은 Important 2건은 권한 검사를 비켜 가는 경로(`@SystemInvoked` 빈, `prod`가 아닌 이름의 데모 배포)를 코드가 막지 못하는 것이고, 각각 기동 검사 한 군데를 고치면 된다. diff --git a/docs/reviews/2026-11-03-rereview/README.md b/docs/reviews/2026-11-03-rereview/README.md new file mode 100644 index 00000000..b6dee03d --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/README.md @@ -0,0 +1,69 @@ +# 재리뷰 — 2026-11-03 + +> 대상: 브랜치 `refactor/maturity-review-2026-11`, `01a8a2a70..5786126c`(커밋 3개, 1,323파일 +60k −9.6k). 2026-11-01 성숙도 리뷰(`../2026-11-01-maturity-review/README.md`)의 수정 전체를 다시 봤다. +> 방법: `superpowers:requesting-code-review`의 리뷰어 템플릿으로 영역 리뷰어 6명과 보안 리뷰어 1명(`security-auditor`)을 띄웠다. 리뷰어마다 영역 스킬을 불러 그 기준을 적용했다(각 문서 "범위" 절). 읽기 전용, 하위 에이전트 금지, 의심 결함은 별도 worktree의 임시 테스트로 확인. + +## 1. 결론 + +- **Critical 0, 회귀 0.** 원래 리뷰의 High·P1 수정은 모든 영역에서 닫혔다고 판정됐다. +- **모든 영역 판정: With fixes.** 수정이 새로 만든 결함과 덜 끝난 완료 기준이 있다. Important 27건(중복을 빼면 22건), Minor 41건. +- **정정 — 원래 리뷰의 발견 수는 119건이 아니라 124건이다.** 06 영역 문서의 `NN-10`~`NN-14` 5건이 색인에 들어가지 않아 어떤 수정 묶음에도 배정되지 않았다(오케스트레이터가 `NN-0x`만 `06-0x`로 바꾼 실수). 원래 README 14.3·16절의 "모든 발견 처리"는 이 5건에 대해 틀렸다. 이번 수정에서 `06-10`~`06-14`로 다시 매기고 처리한다. + +## 2. 영역별 + +| 문서 | 리뷰 스킬 | Important | Minor | 판정 | 부분으로 판정한 원래 발견 | +|---|---|---|---|---|---| +| [01 core·application](01-core-application.md) | clean-architecture, domain-driven-design, codebase-design | 5 | 5 | With fixes | 01-07 | +| [02 inbound](02-inbound-transports.md) | api-and-interface-design, security-and-hardening | 4 | 4 | With fixes | 03-01, 03-11 | +| [03 persistence](03-persistence.md) | jpa-patterns, supabase-postgres-best-practices | 4 | 6 | With fixes | 04-03, 04-10, 06-07 | +| [04 outbound](04-outbound-capabilities.md) | performance-optimization, observability-and-instrumentation, security-and-hardening | 5 | 6 | With fixes | 05-16, 05-17, 05-18, 05-21 | +| [05 messaging](05-messaging.md) | domain-driven-design, observability-and-instrumentation, doubt-driven-development | 4 | 6 | With fixes | 06-06, 06-10~14(미조치) | +| [06 bootstrap·build·CI](06-bootstrap-build-ci.md) | ci-cd-and-automation, refactor, documentation-and-adrs | 3 | 9 | With fixes | 07-08, 07-10, 08-01, 08-04 | +| [07 보안](07-security.md) | security-and-hardening, security-review | 2 | 5 | With fixes | — | + +## 3. Important (중복 묶음) + +| 묶음 | ID | 내용 | 증거 | +|---|---|---|---| +| 권한 탈출구 | RR-01-02 = RR-07-01 | `@SystemInvoked`가 쓰기 유스케이스 권한 선언 규칙을 면제하는데, "bean 금지"는 주석뿐 | 탐침 테스트(bean으로 기동됨) | +| 데모 계정 | RR-07-02 | 거부가 정확히 `prod`에서만. 프로필 없음·`production`·`staging`이면 `demo-admin` 로그인 가능 | 탐침 테스트 | +| 순서 번호 | RR-03-01 | counter 첫 생성이 겹치면 두 번째 쓰기가 409 | 실 PG | +| 순서 번호 | RR-03-02 = RR-05-02 | counter가 없으면 1부터 시작 → 옛 벽시계 번호(~1.7e15)보다 작아져 소비자 순서가 뒤로 감 | 실 PG | +| 트랜잭션 | RR-03-03 | JPA 경로에서 트랜잭션 마감 초과가 미분류 500 | H2 재현 | +| JPA 규칙 | RR-03-04 | `mappedBy` 없이 양쪽 매핑한 양방향이 금지 규칙 통과 | 임시 fixture | +| GraphQL | RR-02-01 | union 아래 복잡도 0·page 상한 미검사(03-01 부분) | 임시 테스트 | +| wire 계약 | RR-02-02 | 서블릿 `/error` 디스패치가 `success:true` + 요청 경로 원문 | 실 Tomcat | +| wire 계약 | RR-02-03 | `IDEMPOTENCY_UNAVAILABLE` 503을 "실행 전 거부"라 적지만 complete 단계에선 작업이 이미 돎 | 코드 | +| gRPC ledger | RR-02-04 | 시도(owner) 구분이 없어 takeover 뒤 옛 owner 기록이 새 시도를 덮음 | 계약 fake | +| HTTP client | RR-04-01 | 호출자 deadline으로 끊은 시도를 breaker가 상대 장애로 셈 | 임시 테스트 | +| HTTP client | RR-04-03 | JDK 스트리밍 본문이 2초 response-header timeout에서 잘림(문서와 반대) | 임시 테스트 | +| Redis | RR-04-02 | 캐시 조건부 쓰기가 멱등성·rate-limit·lease와 8개짜리 SCRIPT lane 공유 | 코드·기본값 | +| Redis | RR-04-05 | Redis 멱등성 계약의 실서버 실행이 어느 게이트에도 없음 | 코드 | +| 파일 쿼터 | RR-01-05 = RR-04-04 | move가 namespace 쿼터를 옮기지 않아 상한 우회·장부 어긋남 | 코드 | +| 파일 계약 | RR-01-04 (+RR-07-06) | fileserver 저장 포트 9개 중 7개 공유 계약 없음, 쿼터 fake가 실제와 다름, 소유자 규칙 두 벌 | 코드 | +| 생성 명령 | RR-01-01 | 생성된 저장소 계약에 트랜잭션 hook이 없어 매뉴얼대로 만든 adapter가 상속 불가 | 생성 후 실험 | +| 매뉴얼 | RR-01-03 | 매뉴얼 3곳이 수정 뒤 코드와 반대, `IntegrationEventDrafts`를 지키는 장치 없음 | 코드 대조 | +| outbox 운영 | RR-05-01 | DEAD 재발행 SQL이 `deferred_attempt_count`를 안 되돌려 다시 DEAD | 실 PG | +| outbox 운영 | RR-05-03 | 끝나지 않는 재시도 행을 구분·처분할 수단 없음, bridge가 원인 코드를 버림 | 코드 | +| 이벤트 ID | RR-05-04 | 06-06 완료 기준(append 시점 거부) 미충족 | 코드 | +| 기동 rule | RR-06-01 (≈RR-04-09) | 기동 rule을 non-static `@Bean`으로 쓰면 설정 bean이 조용히 바인딩 안 됨 | 탐침 테스트 | +| build cache | RR-06-02 | `rejectSkipped`가 캐시 입력이 아니라 실패해야 할 lane이 FROM-CACHE 통과 | 실행 | +| CI | RR-06-03 | `verifyStrictLaneStages`가 optional-platforms를 안 봄 — `grpcPerformanceTest` 미실행 | 실행 | + +Minor 41건은 각 문서에 있다. + +## 4. 결정 (2026-11-03, 사용자 위임) + +| 항목 | 결정 | 이유 | +|---|---|---| +| 순서 번호 seed (RR-03-02) | counter가 없으면 전역 floor부터 시작한다. floor는 V21 적용 시각의 마이크로초(옛 벽시계 번호의 상한)로 마이그레이션이 한 번 기록한다. V21은 남은 행이 있는 aggregate의 counter를 그 최대값으로 미리 만든다 | 정리(reaper)로 행이 사라진 aggregate도 소비자가 본 번호보다 작게 시작하지 않는다. 새 aggregate의 첫 번호가 커지는 비용은 순서 보장보다 작다 | +| 데모 계정 (RR-07-02) | 거부 목록(`prod`)이 아니라 허용 목록: `local`·`test`·`demo` 프로필이 명시적으로 켜졌을 때만 데모 계정을 만든다 | 프로필 이름이 하나 다르면 열리는 구조가 사용자 원칙("위험은 코드에 드러나야")과 반대다 | +| `@SystemInvoked` (RR-01-02) | 기동 시 `@SystemInvoked` 유스케이스가 bean으로 등록돼 있으면 실패, ArchUnit으로 inbound adapter가 직접 부르지 못하게 한다 | 주석뿐인 규칙을 코드로 | +| 멱등성 complete 단계 실패 (RR-02-03) | complete 단계의 저장소 실패는 "결과 불명"으로 따로 알린다(실행 전 503과 구분). 같은 키 재전송 시 서버가 replay·in-flight·회복 필요로 판정한다는 것을 계약에 적는다 | 클라이언트가 "실행 안 됨"으로 믿고 새 키로 다시 보내는 위험을 막는다 | +| Redis SCRIPT lane (RR-04-02) | 캐시 조건부 쓰기는 멱등성·lease와 다른 연결 예산을 쓴다 | 캐시는 성능 기능이고 멱등성·lease는 정합성 기능이다. 캐시 부하가 정합성을 굶기면 안 된다 | +| build cache와 lane 정책 (RR-06-02) | lane 정책 값(`rejectSkipped` 등)을 모두 캐시 입력으로 | 정책을 바꿨는데 옛 결과가 통과하면 게이트가 아니다 | +| 끝나지 않는 재시도 (RR-05-03) | bridge가 원인 코드를 행에 남기고, 오래 재시도 중인 행 수·나이를 지표로 내고, runbook에 park(수동 보류)·재개 절차와 테스트된 SQL을 둔다 | 무한 재시도(15절 결정)를 유지하되 운영자가 보고 멈출 수 있어야 한다 | + +## 5. 다음 + +위 Important 전부, Minor 41건, 06-10~14를 영역별 수정 묶음으로 고친다. 각 묶음은 `5786126c`에서 만든 worktree에서 RED→GREEN, 오케스트레이터가 합쳐 전체 게이트 후 커밋·push한다. 결과는 이 문서 6절. From bbe944bd3c332c04be8d7af5eeef8f48bee1f2f8 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 23:29:35 +0900 Subject: [PATCH 05/17] =?UTF-8?q?fix!:=20=EC=9E=AC=EB=A6=AC=EB=B7=B0?= =?UTF-8?q?=EA=B0=80=20=EC=B0=BE=EC=9D=80=20=EA=B2=B0=ED=95=A8=EA=B3=BC=20?= =?UTF-8?q?=EC=83=89=EC=9D=B8=EC=97=90=EC=84=9C=20=EB=B9=A0=EC=A1=8C?= =?UTF-8?q?=EB=8D=98=20=EB=B0=9C=EA=B2=AC=205=EA=B1=B4=EC=9D=84=20?= =?UTF-8?q?=EA=B3=A0=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 성숙도 리뷰 수정을 다시 읽은 재리뷰(Critical 0, 회귀 0)가 Important 27건·Minor 41건을 찾았다. 수정이 새로 만든 결함이 많았다. @SystemInvoked가 권한 규칙의 탈출구가 됐고, 데모 계정 거부가 정확히 prod일 때만 걸렸고, outbox 순서 번호가 업그레이드 때 뒤로 갔고, GraphQL union 아래 복잡도가 0이었고, 서블릿 오류 응답이 success:true로 나갔고, 호출자 deadline이 breaker를 열었다. 원래 리뷰 색인이 06 영역 발견 5건(06-10~14)을 빠뜨려 그동안 처리되지 않았다. 방법: 영역별 7묶음이 test-driven-development 절차로 실패 테스트를 먼저 쓰고 고쳤다. 결정은 재리뷰 README 4절에 적었다: 순서 번호는 V21이 기록한 전역 floor부터, 데모 계정은 local·test·demo 허용 목록, @SystemInvoked bean은 기동 실패, complete 단계 실패는 IDEMPOTENCY_COMPLETION_UNKNOWN(결과 불명), 캐시 조건부 쓰기는 별도 SCRIPT lane, strict lane 정책은 build cache 입력, 끝나지 않는 재시도 행은 원인 코드·지표·PARKED 절차. 레지스트리가 선언만 하고 아무 코드도 내보내지 않던 redis.capability.* 지표 6개는 빼고 runbook을 실제 지표(redis.lane.*) 기준으로 고쳤다. 위험·한계: V21을 V22 없이 직접 고쳤다(어느 배포에도 아직 없음). 이 브랜치의 V21을 적용한 개발 DB는 다시 만들어야 한다. 서블릿 오류 디스패치를 보안 체인이 허용한다. 발행·저장소 포트 시그니처가 바뀌어 파생 서비스 코드가 깨진다. prod에서 fixture-로 시작하는 설정값은 기동을 막는다. httpclient failure-injection lane의 main 단계 중복 실행은 이전 결정대로 남겼다. 실제 CI runner 실행은 확인하지 못했다. 검증: ci, mainCheck, :integrationCheck, -p optional-platforms ci integrationCheck performanceCheck, :performanceCheck, :releaseCheck (-PgitRevision), verify-compose-profile-contracts(18 lane) 통과. 첫 실행의 실패 2건(FindSecBugs 1, sample 동시 생성 테스트의 v4 event id)은 고친 뒤 ci·integrationCheck·mainCheck를 다시 돌려 통과했다. Refs: docs/reviews/2026-11-03-rereview/README.md 3·4·6·7절 BREAKING CHANGE: outbox 발행 포트와 저장소 포트 시그니처, 순서 번호 첫 값(V21 floor 다음), 샘플 데모 계정 프로필 허용 목록, 새 오류 코드 IDEMPOTENCY_COMPLETION_UNKNOWN, prod의 fixture- 값 거부, 기동 rule은 static·의존 없음이어야 한다. --- .github/workflows/ci-quality-gates.yml | 10 +- .github/workflows/integration-main.yml | 6 + .github/workflows/release.yml | 14 +- AGENTS.md | 15 +- CLAUDE.md | 14 +- docker-compose.infra.yml | 12 +- ...retry-ownership-and-durable-idempotency.md | 30 ++ docs/capability-status.md | 6 +- docs/fileserver/configuration.md | 6 +- docs/fileserver/http-contract.md | 2 +- docs/httpclient/configuration-reference.md | 16 +- docs/jpa/entity-mapping-guide.md | 16 +- docs/manual/04-persistence.md | 10 + docs/manual/05-idempotency.md | 1 + docs/manual/06-errors.md | 5 +- docs/manual/07-authorization.md | 23 +- docs/manual/09-outbox-events.md | 42 +- docs/messaging/configuration-reference.md | 4 +- docs/messaging/outbox-inbox.md | 20 + docs/notification/configuration-reference.md | 2 +- docs/notification/evidence-manifest.json | 3 +- docs/notification/support-matrix.md | 11 +- docs/registries/env-keys.yaml | 57 ++- docs/registries/error-codes.yaml | 21 +- docs/registries/metrics.yaml | 318 ++++++-------- docs/registries/secrets-classification.yaml | 3 + .../06-messaging.md | 42 +- .../2026-11-01-maturity-review/README.md | 9 +- docs/reviews/2026-11-03-rereview/README.md | 43 ++ docs/runbooks/grpc-platform-operations.md | 4 +- docs/runbooks/idempotency-unavailable.md | 12 +- docs/runbooks/job-timeout.md | 7 +- docs/runbooks/outbox-dead-letter.md | 108 ++++- docs/runbooks/outbox-publish-failed.md | 84 +++- docs/runbooks/redis-capability-incident.md | 32 +- docs/testing/TESTING_STRATEGY.md | 45 +- docs/web/http-contract.md | 39 +- infra/redis-sdk/README.md | 2 +- infra/redis-sdk/acl/README.md | 30 +- ...accounts.acl => lane-fixture-accounts.acl} | 0 infra/redis-sdk/cluster/compose.yml | 2 +- infra/redis-sdk/sentinel/compose.yml | 2 +- infra/redis-sdk/standalone/compose.yml | 2 +- infra/redis-sdk/tls/compose.yml | 2 +- ..._Feature__RepositoryContractTest.java.tmpl | 51 +++ .../__feature__/__Feature__Config.java.tmpl | 13 +- .../__Feature__RepositoryContract.java.tmpl | 30 +- scripts/verify-feature-scaffold.sh | 75 +++- src/.env.example | 6 +- src/adapter/inbound/graphql/README.md | 7 +- .../graphql/context/GraphQlDeadline.java | 3 + .../cost/GraphQlComplexityCalculator.java | 5 - .../cost/GraphQlDocumentComplexityScorer.java | 38 +- .../GraphQlDocumentComplexityScorerTest.java | 98 ++++- .../error/GraphQlWireErrorMapperTest.java | 23 ++ src/adapter/inbound/grpc/README.md | 3 +- .../inbound/grpc/GrpcStatusMapperTest.java | 19 + src/adapter/inbound/web/README.md | 18 + .../inbound/web/auth/SecurityConfig.java | 6 + .../web/envelope/EnvelopeBodyAdvice.java | 16 + .../envelope/EnvelopeWireFormatConfig.java | 2 +- .../web/error/EnvelopeErrorController.java | 72 ++++ .../web/error/GlobalExceptionHandler.java | 23 +- .../web/error/HttpStatusErrorCodes.java | 38 ++ .../WebMvcPlatformAutoConfiguration.java | 28 +- .../web/observability/RetryAfterAdvisor.java | 32 +- .../testkit/mvc/JwtChainErrorDispatchIT.java | 91 ++++ .../web/envelope/EnvelopeBodyAdviceTest.java | 26 ++ .../IdempotencyExceptionMappingTest.java | 21 + .../testkit/mvc/WebContractAssertions.java | 54 +++ .../ContractFixtureApplication.java | 11 +- src/adapter/outbound/cache-redis/CLAUDE.md | 24 +- src/adapter/outbound/cache-redis/README.md | 61 ++- src/adapter/outbound/cache-redis/build.gradle | 20 +- .../outbound/cache-redis/gradle.lockfile | 6 +- .../cache/redis/cache/CacheScriptLane.java | 34 ++ .../redis/cache/RedisCacheRegionAdapter.java | 8 +- .../redis/capability/RedisCacheConfig.java | 22 + .../capability/RedisCapabilitySettings.java | 22 + .../RedisSemanticScriptAclProbe.java | 53 ++- .../redis/idempotency/IdempotencyScripts.java | 10 + .../config/module-defaults/cache-redis.yml | 15 +- .../cache/redis/LiveRedisRuntime.java | 4 + .../cache/redis/RedisTestContainer.java | 2 +- .../cache/RedisCacheRegionAdapterTest.java | 36 +- .../cache/RedisCacheRegionContractTest.java | 1 + .../RedisCapabilityCompositionTest.java | 65 +++ .../RedisSemanticScriptAclProbeTest.java | 79 ++++ .../security/RoleBasedFileAccessPolicy.java | 21 +- ...RoleBasedFileAccessPolicyContractTest.java | 31 ++ src/adapter/outbound/httpclient/README.md | 10 +- .../jdk/DeadlineAwareJdkRequestFactory.java | 15 +- .../jdk/JdkBlockingTransportProvider.java | 3 +- .../jdk/JdkStreamingClientHttpRequest.java | 128 ++++++ .../jdk/JdkStreamingClientHttpResponse.java | 63 +++ .../httpclient/jdk/ReadIdleInputStream.java | 90 ++++ .../resilience/AttemptCircuitBreaker.java | 17 + .../resilience/AttemptResiliencePipeline.java | 29 +- .../httpclient/resilience/Deadline.java | 27 +- .../resilience/DeadlineCalculator.java | 8 +- .../restclient/BlockingAttemptExecutor.java | 9 +- .../restclient/BlockingStreamingGateway.java | 26 +- .../restclient/ClassifiedBodyInputStream.java | 64 +++ .../httpclient/transport/AttemptDeadline.java | 37 +- .../resilience/DeadlineCalculatorTest.java | 9 +- .../resilience/RetryCoordinatorTest.java | 4 +- .../CircuitBreakerStatusAccountingTest.java | 119 ++++++ .../restclient/StreamingBodyLifetimeTest.java | 124 ++++++ .../RecordingResilienceComponents.java | 5 + src/adapter/outbound/identifier/CLAUDE.md | 15 +- src/adapter/outbound/identifier/README.md | 15 +- .../outbound/identifier/package-info.java | 6 +- .../outbound/messaging-kafka/CLAUDE.md | 14 + .../ApplicationRelayKafkaIntegrationTest.java | 20 +- src/adapter/outbound/messaging/CLAUDE.md | 2 +- src/adapter/outbound/messaging/README.md | 35 +- .../outbox/OutboxMessagePublishAdapter.java | 18 +- .../Slf4jOutboxRelayFailureReportAdapter.java | 4 + ...latformIntegrationEventPublishAdapter.java | 66 ++- .../messaging/MessagingConfigTest.java | 4 +- ...4jOutboxRelayFailureReportAdapterTest.java | 15 +- ...ormIntegrationEventPublishAdapterTest.java | 113 ++++- .../NotificationCallbackProviderConfig.java | 30 +- .../provider/ses/SesCallbackAdapter.java | 14 +- .../provider/ses/SesEventNormalizer.java | 58 ++- .../smtp/JavaMailSenderSmtpDispatch.java | 7 +- .../SnsCertificateFetchTest.java | 104 +++++ .../provider/ses/SesCallbackAdapterTest.java | 24 ++ .../smtp/JavaMailSenderSmtpDispatchTest.java | 34 ++ .../outbound/objectstorage/build.gradle | 12 +- .../outbound/persistence-fileserver/CLAUDE.md | 12 +- .../persistence/fileserver/JpaFileQuota.java | 7 +- .../repository/CleanupClaimSql.java | 14 +- .../repository/CleanupClaimSqlTest.java | 27 +- .../outbound/persistence-jpa/CLAUDE.md | 10 +- .../outbound/persistence-jpa/README.md | 18 +- .../outbound/persistence-jpa/build.gradle | 22 +- .../api/error/FailureCategory.java | 11 +- .../error/TransactionTimeoutException.java | 9 +- .../PersistenceExceptionTranslator.java | 38 ++ .../outbox/jpa/JpaOutboxStore.java | 94 ++++- .../outbox/jpa/OutboxEventJpaRepository.java | 62 ++- .../OutboxAggregateSequenceFloorEntity.java | 32 ++ .../outbox/jpa/entity/OutboxEventEntity.java | 16 + .../transaction/SpringTransaction.java | 23 +- .../V21__outbox_aggregate_sequence.sql | 75 +++- .../V22__outbox_event_last_failure_code.sql | 21 + .../WorkerCrashRecoveryContractTest.java | 50 ++- ...rationSubmissionOutboxIntegrationTest.java | 11 +- .../readiness/FileserverPostgreSqlStack.java | 159 +++++++ .../readiness/OutboxRunbookSql.java | 80 ++++ ...SqlContentReferenceLedgerContractTest.java | 54 +++ ...PostgreSqlFileQuotaLedgerContractTest.java | 92 +++++ .../PostgreSqlMigrationIntegrationTest.java | 2 +- ...utboxAggregateSequenceIntegrationTest.java | 90 +++- ...lOutboxConcurrentRelayIntegrationTest.java | 7 + ...tboxDispositionRunbookIntegrationTest.java | 279 +++++++++++++ ...lOutboxOrderKeyRunbookIntegrationTest.java | 184 ++++++++- .../PostgreSqlRecoveryQueueContractTest.java | 60 +++ ...reSqlStagingUploadLocatorContractTest.java | 73 ++++ .../PostgreSqlTransactionIntegrationTest.java | 52 +++ .../PostgreSqlUploadSessionContractTest.java | 66 +++ .../outbox/jpa/JpaOutboxStoreTest.java | 70 +++- .../FlywayProdSafetyValidatorTest.java | 2 +- .../HikariPoolConstraintValidatorTest.java | 2 +- .../OpenInViewSafetyValidatorTest.java | 2 +- ...sistenceVendorProdSafetyValidatorTest.java | 2 +- ...tgreSqlTransportSecurityValidatorTest.java | 2 +- .../RequiredEnvironmentValidatorTest.java | 2 +- .../arch/JpaArchitectureRulesTest.java | 64 +++ .../arch/entity/JoinColumnChildEntity.java | 36 ++ .../arch/entity/JoinColumnParentEntity.java | 38 ++ .../testkit/outsider/OrderEntityReader.java | 18 + .../SpringTransactionDeadlineTest.java | 152 +++++++ .../resources/db/applied-migrations.sha256 | 3 +- .../testkit/arch/JpaArchitectureRules.java | 35 ++ .../arch/SingleSidedAssociationCondition.java | 174 ++++++-- .../persistence-notification/CLAUDE.md | 7 +- .../platform/JdbcReconciliationJobStore.java | 9 +- .../repository/RecipientClaimSql.java | 16 +- .../repository/RecipientClaimSqlTest.java | 14 - .../outbound/redis-runtime/build.gradle | 5 + .../outbound/redis-runtime/gradle.lockfile | 3 + .../runtime/config/RedisLaneMetrics.java | 161 ++++++++ .../config/RedisRuntimeAutoConfiguration.java | 33 +- .../runtime/connection/RedisLaneListener.java | 77 ++++ .../runtime/connection/RedisRuntimeOwner.java | 124 +++++- .../config/module-defaults/redis-runtime.yml | 13 + .../runtime/config/RedisLaneMetricsTest.java | 388 ++++++++++++++++++ .../RedisRuntimeAutoConfigurationTest.java | 25 ++ .../RedisRuntimeHealthStatusOrderTest.java | 51 +++ .../config/RedisScriptLaneAdmissionTest.java | 4 +- .../config/RedisScriptLaneCapacityTest.java | 4 +- .../outbound/redis-sdk/gradle.lockfile | 3 + .../outbound/support/startup/StartupRule.java | 5 + .../support/startup/StartupRuleRunner.java | 83 +++- .../JsonIntegrationEventEncoderTest.java | 4 +- .../startup/StartupRuleRunnerTest.java | 143 +++++++ src/app-bootstrap/CLAUDE.md | 4 +- src/app-bootstrap/README.md | 6 +- src/app-bootstrap/build.gradle | 11 +- .../ApplicationBoundaryArchitectureTest.java | 42 ++ .../ArchRuleDiscoveryContractTest.java | 2 + .../ArchitectureViolationFixtureTest.java | 32 ++ .../JpaProductionArchitectureTest.java | 24 ++ ...SystemInvokedCallingControllerFixture.java | 17 + ...HandBuiltIntegrationEventDraftFixture.java | 40 ++ .../SystemInvokedFixtureUseCase.java | 16 + .../runtime/SecretSourceValidator.java | 57 ++- .../main/resources/config/observability.yml | 5 +- .../src/main/resources/config/runtime.yml | 3 +- ...strapCapabilityReachabilitySystemTest.java | 2 +- .../DeveloperExperienceContractTest.java | 21 +- .../SampleRuntimeDefaultsContractTest.java | 110 ++++- .../OutboxStatusRegistryContractTest.java | 47 ++- ...rrorDetailExposureSafetyValidatorTest.java | 3 +- .../RuntimeNumericBoundsValidatorTest.java | 2 +- .../runtime/SecretSourceValidatorTest.java | 47 +++ src/application-core/CLAUDE.md | 20 +- src/application-core/README.md | 117 +++--- src/application-core/build.gradle | 3 +- ...IdempotencyCompletionUnknownException.java | 32 ++ .../idempotency/IdempotencyExecutor.java | 22 +- .../IdempotencyInFlightException.java | 3 +- .../IdempotencyUnavailableException.java | 7 +- .../event/IntegrationEventDraft.java | 26 +- .../event/IntegrationEventPublishPort.java | 21 +- .../messaging/event/IntegrationIdentity.java | 25 ++ .../SubmitDurableOperationUseCase.java | 36 +- .../outbox/OutboxAggregateSequencePort.java | 14 +- .../application/outbox/OutboxEventStatus.java | 21 +- .../application/outbox/OutboxLongRetries.java | 24 ++ .../outbox/OutboxMessagePublishPort.java | 25 +- .../outbox/OutboxPublishAttempt.java | 103 +++++ .../outbox/OutboxPublishOutcome.java | 12 +- .../outbox/OutboxRelayFailureReport.java | 24 +- .../application/outbox/OutboxRelayResult.java | 18 +- .../application/outbox/OutboxStorePort.java | 43 +- .../PublishPendingOutboxEventsUseCase.java | 73 +++- .../application/security/SystemInvoked.java | 9 +- .../idempotency/IdempotencyExecutorTest.java | 94 +++++ .../IdempotencyFailureCodeTest.java | 3 + .../ApplicationPayloadSchemaReleaseTest.java | 18 + .../event/IntegrationEventDraftTest.java | 75 +++- .../event/IntegrationEventDraftsTest.java | 2 +- .../event/IntegrationIdentityTest.java | 2 +- .../SubmitDurableOperationUseCaseTest.java | 52 ++- .../outbox/OutboxPublishOutcomeTest.java | 2 +- .../outbox/OutboxRelayFailureReportTest.java | 52 ++- ...PublishPendingOutboxEventsUseCaseTest.java | 23 +- .../TransientPublishFailureRelayTest.java | 52 +++ ...akeOutboxMessagePublisherContractTest.java | 4 +- ...ryOutboxAggregateSequenceContractTest.java | 6 +- ...ryOutboxStoreLeaseFencingContractTest.java | 5 + .../contracts/released-payload-schemas.sha256 | 4 + .../cache/testkit/CacheRegionContract.java | 19 + .../testkit/IdempotencyStoreContract.java | 40 +- .../ReleasedPayloadSchemaContract.java | 115 ++++++ .../FakeIntegrationEventPublisher.java | 33 +- .../IntegrationEventEncoderContract.java | 2 +- .../IntegrationEventPublishContract.java | 24 +- .../testkit/FakeOutboxMessagePublisher.java | 37 +- .../InMemoryOutboxAggregateSequences.java | 49 ++- .../outbox/testkit/InMemoryOutboxStore.java | 59 ++- .../OutboxAggregateSequenceContract.java | 107 ++++- .../testkit/OutboxLeaseFencingContract.java | 123 +++++- .../testkit/OutboxMessagePublishContract.java | 20 +- .../testkit/OverlappingWrites.java | 9 +- src/application-fileserver/build.gradle | 9 +- .../api/security/FileAccessSubject.java | 18 + .../fileserver/cleanup/QuotaReclaimPort.java | 4 +- .../lifecycle/MoveFileApplicationUseCase.java | 60 ++- .../cleanup/CleanupServiceTest.java | 4 +- .../lifecycle/FileLifecycleUseCasesTest.java | 65 ++- .../FileReconciliationServiceTest.java | 4 +- .../FakeFileAccessPolicyContractTest.java | 25 ++ ...oryContentReferenceLedgerContractTest.java | 19 + .../InMemoryQuotaLedgerContractTest.java | 58 +++ .../InMemoryRecoveryQueueContractTest.java | 20 + ...emoryStagingUploadLocatorContractTest.java | 40 ++ ...nMemoryUploadSessionStoreContractTest.java | 34 ++ .../FinalizeUploadApplicationUseCaseTest.java | 4 +- .../ContentReferenceLedgerPortContract.java | 123 ++++++ .../testkit/FakeFileAccessPolicy.java | 7 +- .../testkit/FakeFileQuotaService.java | 200 +++++++-- .../testkit/FakeQuotaCommitGateway.java | 39 +- .../testkit/FileAccessPolicyPortContract.java | 175 ++++++++ .../testkit/FileQuotaLedgerContract.java | 346 ++++++++++++++++ .../testkit/InMemoryFileMetadataStore.java | 15 +- .../testkit/InMemoryRecoveryQueue.java | 10 +- .../testkit/InMemoryUploadSessionStore.java | 32 +- .../testkit/RecordingQuotaReclaimGateway.java | 19 +- .../testkit/RecoveryQueuePortContract.java | 137 +++++++ .../StagingUploadLocatorPortContract.java | 92 +++++ .../testkit/UploadSessionPortContract.java | 367 +++++++++++++++++ src/application-notification/build.gradle | 3 + .../dispatch/ReconciliationJobStorePort.java | 4 +- .../testkit/AdminOperationStoreContract.java | 2 +- .../InMemoryReconciliationJobStore.java | 4 + .../NotificationRequestStoreContract.java | 2 +- .../ReconciliationJobStoreContract.java | 24 +- .../testkit/DeduplicationStoreContract.java | 1 + .../testkit/PreferenceStoreContract.java | 1 + .../testkit/SuppressionStoreContract.java | 1 + src/build-logic/README.md | 5 +- .../config/ConfigContractPlugin.java | 20 +- .../ConfigurationMetadataClasspath.java | 87 ++++ .../config/EnvContractVerifier.java | 45 +- .../buildlogic/config/VerifyEnvKeysTask.java | 57 ++- .../strictlane/StrictLaneStagesExtension.java | 9 + .../strictlane/StrictLaneStagesPlugin.java | 57 ++- .../strictlane/StrictTestLanePlugin.java | 14 + .../strictlane/WorkflowGradleInvocations.java | 221 +++++++++- .../ConfigurationMetadataClasspathTest.java | 48 +++ .../config/EnvContractVerifierTest.java | 54 +++ .../StrictLaneStagesFunctionalTest.java | 129 ++++++ .../StrictTestLaneConventionTest.java | 36 ++ .../WorkflowGradleInvocationsTest.java | 52 +++ .../FileserverFileUseCaseConfiguration.java | 7 +- .../idempotency/IdempotencySettings.java | 15 +- .../idempotency/IdempotencySettingsTest.java | 25 ++ src/composition/outbox-relay/CLAUDE.md | 21 + src/composition/outbox-relay/README.md | 62 +-- .../outbox/OutboxLeaderElectionToken.java | 21 - .../composition/outbox/OutboxMetrics.java | 146 ++++++- .../outbox/OutboxRelayAutoConfiguration.java | 25 +- .../composition/outbox/OutboxSettings.java | 35 ++ .../composition/outbox/OutboxMetricsTest.java | 89 +++- .../OutboxRelayAutoConfigurationTest.java | 32 ++ .../outbox/OutboxRelaySchedulerDrainTest.java | 3 +- .../outbox/OutboxRelayShutdownOrderTest.java | 9 +- .../outbox/OutboxSettingsTest.java | 45 ++ src/composition/service-runtime/README.md | 4 +- .../PermissionEnforcementGuard.java | 26 +- .../PermissionEnforcementGuardTest.java | 30 ++ .../runtime/compose-profile-contracts.json | 2 +- src/config/spotbugs/exclude.xml | 46 ++- src/grpc/CLAUDE.md | 13 +- .../grpc/api/ledger/GrpcClaimToken.java | 35 ++ .../grpc/api/ledger/GrpcOperationLedger.java | 47 ++- .../api/ledger/GrpcOperationLedgerRecord.java | 25 +- .../ledger/GrpcOperationLedgerContract.java | 202 +++++++-- .../api/ledger/InMemoryOperationLedger.java | 104 +++-- .../ledger/GrpcOperationLedgerMigrations.java | 3 +- .../JpaGrpcOperationLedgerContractIT.java | 48 ++- .../ledger/GrpcOperationLedgerEntity.java | 54 ++- .../ledger/GrpcOperationLedgerRepository.java | 95 ++++- .../grpc/ledger/JpaGrpcOperationLedger.java | 141 +++++-- ...dd_grpc_operation_ledger_claim_attempt.sql | 20 + .../GrpcOperationLedgerRepositoryTest.java | 121 +++++- .../idempotency/GrpcIdempotencyDecision.java | 51 ++- .../GrpcIdempotencyInterceptor.java | 62 ++- .../GrpcCompletionReconcilerTest.java | 10 +- .../GrpcIdempotencyInterceptorTest.java | 86 +++- .../GrpcOperationLedgerRetentionTest.java | 4 +- .../boot/GrpcPlatformStartupValidator.java | 10 +- ...cPlatformAutoConfigurationContextTest.java | 4 +- .../GrpcPlatformStartupValidatorTest.java | 38 ++ src/grpc/grpc-testkit/build.gradle | 9 +- src/messaging/CLAUDE.md | 25 ++ .../api/error/FailureDescriptor.java | 8 + .../kafka/KafkaConsumerRegistrar.java | 43 +- .../kafka/KafkaPublishFailureClassifier.java | 12 +- .../kafka/KafkaQuarantinePublisher.java | 18 +- .../kafka/KafkaConsumerRegistrarTest.java | 89 +++- .../runtime/DefaultMessagePublisher.java | 2 +- .../KafkaDeadLetterQuarantine.java | 8 +- .../MessagingShutdownLifecycle.java | 17 +- src/optional-platforms/build.gradle | 34 ++ src/sample-portfolio/README.md | 9 +- src/sample-portfolio/build.gradle | 9 +- .../PosterRepositoryAdapterContractTest.java | 71 ++++ ...osterRepositoryAdapterIntegrationTest.java | 2 +- ...reatePosterConcurrencyIntegrationTest.java | 4 +- .../web/error/DomainExceptionHandler.java | 2 +- .../repository/PosterRepositoryAdapter.java | 6 +- .../poster/CreatePosterUseCase.java | 1 + .../PosterTitleAlreadyExistsException.java | 11 - .../poster/UpdatePosterUseCase.java | 1 + .../worklog/WorkLogReservedPayload.java | 15 +- .../SampleManagementSecurityConfig.java | 7 +- .../SampleDemoAccountsProductionGuard.java | 48 ++- .../security/SampleDemoSecurityConfig.java | 16 +- .../domain/poster/PosterRepository.java | 18 +- .../PosterTitleAlreadyExistsException.java | 20 + .../domain/worklog/WorkLogRepository.java | 7 + .../src/main/resources/application.yml | 40 +- .../SampleWorkLogAuthorizationSystemTest.java | 38 ++ .../controller/PosterControllerWireTest.java | 2 +- .../web/error/DomainExceptionHandlerTest.java | 2 +- .../event/SamplePayloadSchemaReleaseTest.java | 18 + .../worklog/WorkLogUseCasesTest.java | 2 +- ...SampleDemoAccountsProductionGuardTest.java | 25 +- .../SampleDemoSecurityConfigTest.java | 8 +- .../InMemoryPosterRepositoryContractTest.java | 19 + .../contracts/released-payload-schemas.sha256 | 10 + .../testkit/InMemoryPosterRepository.java | 114 +++++ .../testkit/PosterRepositoryContract.java | 119 ++++++ .../contract/OpenApiDriftContractTest.java | 4 + .../web/date/DateHeaderContractTest.java | 4 + .../web/filter/VirtualThreadMdcE2ETest.java | 4 + .../web/openapi/OpenApiSnapshotTest.java | 4 + src/shared-contract/README.md | 3 +- .../shared/error/OperationalError.java | 2 + .../shared/runtime/RuntimeEnvironment.java | 10 +- .../shared/error/OperationalErrorTest.java | 15 + 406 files changed, 13493 insertions(+), 1656 deletions(-) rename infra/redis-sdk/acl/{all-accounts.acl => lane-fixture-accounts.acl} (100%) create mode 100644 scripts/feature-scaffold/probes/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/testkit/CallerTransaction__Feature__RepositoryContractTest.java.tmpl create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorController.java create mode 100644 src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java create mode 100644 src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/mvc/JwtChainErrorDispatchIT.java create mode 100644 src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScriptLane.java create mode 100644 src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/security/RoleBasedFileAccessPolicyContractTest.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpRequest.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpResponse.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ClassifiedBodyInputStream.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingBodyLifetimeTest.java create mode 100644 src/adapter/outbound/messaging-kafka/CLAUDE.md create mode 100644 src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateFetchTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxAggregateSequenceFloorEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V22__outbox_event_last_failure_code.sql create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlContentReferenceLedgerContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileQuotaLedgerContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecoveryQueueContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlStagingUploadLocatorContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlUploadSessionContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinColumnChildEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinColumnParentEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/outsider/OrderEntityReader.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionDeadlineTest.java delete mode 100644 src/adapter/outbound/persistence-notification/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientClaimSqlTest.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetrics.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLaneListener.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/resources/config/module-defaults/redis-runtime.yml create mode 100644 src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetricsTest.java create mode 100644 src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeHealthStatusOrderTest.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemInvokedCallingControllerFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/HandBuiltIntegrationEventDraftFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/SystemInvokedFixtureUseCase.java create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompletionUnknownException.java create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxLongRetries.java create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishAttempt.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/ApplicationPayloadSchemaReleaseTest.java create mode 100644 src/application-core/src/test/resources/contracts/released-payload-schemas.sha256 create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/contract/testkit/ReleasedPayloadSchemaContract.java rename src/{application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy => application-core/src/testFixtures/java/dev/caskeleton/application/transaction}/testkit/OverlappingWrites.java (89%) create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicyContractTest.java create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryContentReferenceLedgerContractTest.java create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryQuotaLedgerContractTest.java create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueueContractTest.java create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryStagingUploadLocatorContractTest.java create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStoreContractTest.java create mode 100644 src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/ContentReferenceLedgerPortContract.java create mode 100644 src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileAccessPolicyPortContract.java create mode 100644 src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileQuotaLedgerContract.java create mode 100644 src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/RecoveryQueuePortContract.java create mode 100644 src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/StagingUploadLocatorPortContract.java create mode 100644 src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/UploadSessionPortContract.java create mode 100644 src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigurationMetadataClasspath.java create mode 100644 src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/ConfigurationMetadataClasspathTest.java create mode 100644 src/composition/outbox-relay/CLAUDE.md delete mode 100644 src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxLeaderElectionToken.java create mode 100644 src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcClaimToken.java create mode 100644 src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V003__add_grpc_operation_ledger_claim_attempt.sql create mode 100644 src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterContractTest.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PosterTitleAlreadyExistsException.java create mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTitleAlreadyExistsException.java create mode 100644 src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/SamplePayloadSchemaReleaseTest.java create mode 100644 src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/InMemoryPosterRepositoryContractTest.java create mode 100644 src/sample-portfolio/src/test/resources/contracts/released-payload-schemas.sha256 create mode 100644 src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/InMemoryPosterRepository.java create mode 100644 src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/PosterRepositoryContract.java diff --git a/.github/workflows/ci-quality-gates.yml b/.github/workflows/ci-quality-gates.yml index 6c25d1a3..83986f9e 100644 --- a/.github/workflows/ci-quality-gates.yml +++ b/.github/workflows/ci-quality-gates.yml @@ -65,9 +65,12 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java + # `qualityCheck` too: the root one covers the production leaves only, so the sample — the code + # adopters copy first — was analysed by no stage, and its SpotBugs exclusions matched nothing + # (review 2026-11-03 RR-06-05). - name: Verify the standalone sample application working-directory: src - run: ./gradlew :sample-portfolio:check --stacktrace + run: ./gradlew :sample-portfolio:check :sample-portfolio:qualityCheck --stacktrace optional-platforms: runs-on: ubuntu-latest @@ -77,6 +80,11 @@ jobs: - name: Verify the optional gRPC platform build working-directory: src run: ./gradlew -p optional-platforms ci --stacktrace + # The optional build's own lane-reachability check: the main build's cannot see these lanes + # (review 2026-11-03 RR-06-03). + - name: Require every optional-platform strict lane to be in an executed stage + working-directory: src + run: ./gradlew -p optional-platforms :verifyStrictLaneStages --dry-run --stacktrace # gRPC schema policy (owner decision 18). protoc compiles src/grpc/grpc-contract inside the # optional-platforms build above; lint and breaking-change policy belong to Buf, configured by diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml index 79090826..7bd70230 100644 --- a/.github/workflows/integration-main.yml +++ b/.github/workflows/integration-main.yml @@ -203,6 +203,12 @@ jobs: - name: Run every performance-category strict lane working-directory: src run: ./gradlew :performanceCheck --continue --stacktrace + # The optional gRPC build's performance lanes (grpcPerformanceTest). A separate build, so a + # separate command; its own verifyStrictLaneStages counts this line (review 2026-11-03 RR-06-03). + - name: Run every optional-platform performance-category strict lane + if: always() + working-directory: src + run: ./gradlew -p optional-platforms performanceCheck --continue --stacktrace - name: Publish the performance lane reports if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 43d2ff14..8cdecab9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -120,9 +120,10 @@ jobs: # container and no fixed cadence — grpcNettyContractTest opens an ephemeral socket, not a broker — # so the guard is worth asserting once per tag and is not worth a runner every night. # - # grpcPerformanceTest is deliberately absent. The leaf excludes it from `test` and says why: "a - # measurement in the release gate is a flaky test on a shared CI runner; it runs when somebody asks - # for it, by name." It is recorded as a manual entrypoint in the repository README instead. + # The optional build's `releaseCheck` is those hermetic lanes, so a lane added there is here + # without a workflow edit. grpcPerformanceTest is deliberately absent: a measurement is not release + # evidence on a shared runner. It runs in integration-main.yml's performance-check job (the + # optional build's `performanceCheck`). grpc-stable-release-gate: runs-on: ubuntu-latest timeout-minutes: 45 @@ -131,12 +132,7 @@ jobs: - uses: ./.github/actions/setup-gradle-java - name: Run the gRPC Stable certification lanes working-directory: src - run: >- - ./gradlew -p optional-platforms - :grpc:grpc-testkit:grpcInProcessContractTest - :grpc:grpc-testkit:grpcNettyContractTest - :grpc:grpc-testkit:grpcFaultTest - --stacktrace + run: ./gradlew -p optional-platforms releaseCheck --stacktrace # The operation ledger's real-PostgreSQL lane ran only on main and nightly # (integration-main.yml), so a tag could be cut from a main whose ledger lane was red. It needs # Docker, which a release runner has (review 2026-11-01 03-12). diff --git a/AGENTS.md b/AGENTS.md index 27b27f35..0b68af7d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,10 +77,13 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 `ca.config-contract`다. `src/build-tools/` included build는 비워서 삭제했다. - `src/build.gradle`: 루트 라이프사이클(`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, `releaseCheck`, `qualityCheck`, `configContractCheck`)과 버전/리비전. `verifyStrictLaneStages - --dry-run`(PR 게이트)은 `explicitOnly`가 아닌 모든 strict lane이 workflow가 실제로 실행하는 단계 - (`ci`·`sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) - 중 하나에 들어 있는지, 그리고 workflow의 접힌(`>`) run 블록이 빈 줄 때문에 옵션을 별개 명령으로 - 떼어 내지 않는지 검사한다. + --dry-run`(PR 게이트)은 그 빌드에서 `explicitOnly`가 아닌 strict lane이 workflow가 실제로 실행하는 + 단계(main 빌드: `ci`·`sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`· + `releaseCheck`, optional-platforms 빌드: `-p optional-platforms`로 부르는 `ci`·`integrationCheck`· + `performanceCheck`·`releaseCheck`) 중 하나에 들어 있는지, 그리고 workflow의 접힌(`>`) run 블록이 빈 + 줄 때문에 옵션을 별개 명령으로 떼어 내지 않는지 검사한다. 두 빌드가 각자 검사를 돌린다. `-x`로 뺀 + lane, `continue-on-error` 아래 명령, 상태 함수(`always()`·`success()`·`!cancelled()`)가 아닌 `if:` + 아래 명령은 실행으로 세지 않는다. 작업 파일의 소유 leaf는 registry의 `source_path`로 판단하고 가장 가까운 `src/**/CLAUDE.md`를 함께 읽는다. focused test는 registry의 `gradle_path`에서 @@ -202,10 +205,10 @@ cd src ./gradlew architectureCheck # 의존 방향·domain-core/shared-contract/application-* 순수성·ArchUnit ./gradlew qualityCheck # SpotBugs + FindSecBugs (leaf check에는 없다) ./gradlew ci # PR 게이트 = leaf check + architecture + quality -./gradlew mainCheck # main 단계 = env 계약·전체 기동·public path·전송/메시징 레인·leaf 문서 대조 레인 +./gradlew mainCheck # main 단계 = env 계약·전체 기동(샘플 포함)·public path·전송/메시징 레인·leaf 문서 대조 레인·기능 생성 왕복(verifyFeatureScaffold) ./gradlew integrationCheck # 실제 컨테이너 integration 레인 전체(main·nightly, Docker 필요) ./gradlew performanceCheck # 부하·종료·자원 한계 레인(main·nightly) -./gradlew verifyStrictLaneStages --dry-run # 모든 strict lane이 workflow가 실행하는 단계에 속하는지 +./gradlew verifyStrictLaneStages --dry-run # 이 빌드의 strict lane이 workflow가 실행하는 단계에 속하는지(optional 빌드는 -p optional-platforms로 따로) ./gradlew verifyPublicPathSnapshot ./gradlew :app-bootstrap:verifyEnvKeys ``` diff --git a/CLAUDE.md b/CLAUDE.md index d749111f..facf5c12 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,8 +38,10 @@ If this summary drifts from `AGENTS.md`, `AGENTS.md` wins and this summary must `ca.config-contract`. The `src/build-tools/` included build was emptied and removed. - `src/build.gradle`: the root lifecycle (`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, `releaseCheck` and the named repository-wide gates). `verifyStrictLaneStages --dry-run` (pull - request) fails when a non-`explicitOnly` strict lane is in no stage a workflow executes, or a - folded workflow `run:` block splits an option off its command. + request; the main build and, as `-p optional-platforms`, the optional build each run their own) + fails when a non-`explicitOnly` strict lane is in no stage a workflow executes — a lane the + command removes with `-x` and a command under `continue-on-error` or a non-status `if:` do not + count — or a folded workflow `run:` block splits an option off its command. Commit policy is `human-only`: agents do not stage, commit, amend, or push implementation changes. @@ -132,9 +134,11 @@ declared strict integration lanes; a lane that needs an input the build was not and named), `performanceCheck` (the declared performance lanes; main and nightly). `ci` (pull request) is leaf checks (API surfaces included, owner decision 20) + architectureCheck + qualityCheck, and the workflow also runs `verifyStrictLaneStages --dry-run`; `mainCheck` (main branch) is configContractCheck + -qualificationCheck + the sample web contract + the public-path snapshot + the transport and -messaging qualification lanes + every leaf's `mainCheck` (document-contract lanes, MinIO lanes); -`releaseCheck` is the tag-only checks: release provenance and the public-path snapshot. +qualificationCheck + the sample web contract + the sample full boot (`:sample-portfolio:systemTest`) ++ the public-path snapshot + the transport and messaging qualification lanes + the feature +generator round trip (`verifyFeatureScaffold`) + every leaf's `mainCheck` (document-contract lanes +and any lane the leaf adds). `releaseCheck` is the tag-only checks: release provenance and the +public-path snapshot. Test-writing rules (behavior-sentence names that assert what they promise, `@DisplayName` in Korean only when the name cannot say it (owner decision 5), given/when/then comments, one `// when`, one diff --git a/docker-compose.infra.yml b/docker-compose.infra.yml index 93de6c85..4ae89ea3 100644 --- a/docker-compose.infra.yml +++ b/docker-compose.infra.yml @@ -137,10 +137,12 @@ services: start_period: 30s # ---- Redis — local compose contract for the shipped Redis runtime ---------------- - # Authenticated, with the accounts a deployment loads: infra/redis-sdk/acl/all-accounts.acl, the - # same file the Redis topology lanes use, mounted as it is rather than copied. Its first line turns - # the passwordless `default` user off, so the application connects as the named accounts the lane - # contract gives it (compose-profile-contracts.json, $redisComment). + # Authenticated the way a deployment authenticates, with the lanes' test-fixture accounts: + # infra/redis-sdk/acl/lane-fixture-accounts.acl, the same file the Redis topology lanes use, mounted + # as it is rather than copied. It is not a deployment file — its passwords are public and it carries + # a lane-only `+@all` account (infra/redis-sdk/acl/README.md). Its first line turns the passwordless + # `default` user off, so the application connects as the named accounts the lane contract gives it + # (compose-profile-contracts.json, $redisComment). # # This Redis was open and the lanes declared app.redis.authentication.anonymous-access-accepted. # The application then logged that trade, and the missing advanced account, as two startup @@ -162,7 +164,7 @@ services: - --save - "" - --aclfile - - /etc/redis/acl/all-accounts.acl + - /etc/redis/acl/lane-fixture-accounts.acl volumes: - type: bind source: ./infra/redis-sdk/acl diff --git a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md index 495d3480..7307c654 100644 --- a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md +++ b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md @@ -69,6 +69,36 @@ method can run longer than any fixed TTL; revisit when one exists. A sweeper job rows — it needs a scheduler this family does not have, and deleting a claim makes the next retry a fresh claim with no record that an attempt was abandoned. +**A taken-over owner is fenced by a claim token** (re-review 2026-11-03, RR-02-04). The owner a +takeover presumes dead may only be slow. Without knowing which attempt held the claim, its late +`markFailed` turned the new attempt's claim `FAILED_TERMINAL`, the next retry re-claimed it, and two +attempts ran the mutation at once; its late `markCommitted` committed beside the new attempt. Every +claim now carries a `GrpcClaimToken` (`claim_attempt`, migration V003): 1 for the first claim, one more +for each `reclaimFailed` or `reclaimStale`. `decide` returns it on `PROCEED`, and `recordCommit` / +`recordFailure` hand it back. A commit or a failure is one conditional +`UPDATE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt`: a commit by an attempt that lost +the claim is refused with an exception, so its business transaction rolls back; a failure by one is +ignored (`markFailed` returns false). The same conditional update closes the JPA commit race — +load-check-save let two commits that both read `IN_PROGRESS` both write; now exactly one matches. +A claim whose conflicting row is purged between insert and read retries the insert once instead of +failing the call. + +Chosen over the claim moment as the token (`WHERE claimed_at = :claimedAt`), which needs no column: +PostgreSQL stores microseconds while `Instant` carries nanoseconds, so the token a caller holds and +the one stored can differ by rounding, and two processes' clocks can give two attempts the same +moment. The counter has neither problem. The heartbeat lease above stays rejected for the same reason +as before; the token fences without one. + +**What `operation-ledger-enabled=true` promises (03-11 (b), recorded 2026-11-03, RR-02-07).** The +2026-11-01 review offered (a) delete the flag and judge by whether a ledger bean exists, or (b) keep the +flag and have the starter assemble the decision function from it. (b) is kept: the assembly and the +TTL validation live in one place instead of in every adopter. (a) was rejected because it removes the +false promise only by removing the assembly with it. The limit stays and is stated where an operator +meets it: the starter builds no server, so the flag assembles the decision function only, and keys are +honoured once the adopter's `IDEMPOTENCY` stage interceptor or service adapter calls `decide` and +`recordCommit`. `GrpcPlatformStartupValidator`'s refusal for a keyed method says exactly that; a running +process cannot see whether the stage exists, so the validator does not claim to check it. + **Finished rows are purged after a retention; in-progress rows never are** (03-10 follow-up). `GrpcOperationLedger.purgeCompletedBefore(cutoff, limit)` deletes at most `limit` `COMMITTED` or `FAILED_TERMINAL` rows that completed before the cutoff, oldest first — on PostgreSQL one bounded diff --git a/docs/capability-status.md b/docs/capability-status.md index ab9f8972..7b701ff0 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -30,14 +30,14 @@ lanes and CI; it is not a deployment artifact. | Relational persistence (JPA/PostgreSQL) | `ca-skeleton.persistence-jpa.enabled` / `APP_PERSISTENCE_JPA_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-jpa')`) | yes | Not in the default composition. The one line brings everything — its own `AutoConfiguration.imports` (`PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig`, `JpaStartupAutoConfiguration`), its environment handling (`JpaActivationEnvironmentPostProcessor`, `spring.factories`: readiness `db` while on; with `false` it also excludes Boot's JDBC, Hibernate, Spring Data JPA and Flyway auto-configuration, so no DataSource is bound), the startup guards (Flyway strategy, datasource/OSIV/DDL/pool/TLS/vendor checks, exit codes unchanged) and its settings (`config/module-defaults/persistence-jpa.yml`). `persistence-jpa:PersistenceJpaCapabilityAssemblyTest` proves the module assembles on its own; the `postgresql*IntegrationTest` readiness lanes, run by `integration-main.yml` → `integration-check` (`:integrationCheck`), qualify it against PostgreSQL. `sample-portfolio` selects it by its build dependency and the module's auto-configuration (no broad scan of the persistence package). `bootRunH2` adds the module to its own classpath only. | | Document persistence (MongoDB) | `ca-skeleton.persistence-mongo.enabled` / `APP_PERSISTENCE_MONGO_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-mongo')`) | yes | On when present; `false` also excludes Boot's Mongo auto-configuration (`MongoCapabilityActivationTest`). The connection-source rule (`SPRING_MONGODB_URI` or the selected profile's `uri-secret`) is checked by the module's own `MongoDefaultsEnvironmentPostProcessor`. Six container lanes (`mongoReplicaSetTest`, `mongoFailoverTest`, …), run by `integration-main.yml` → `integration-check` (`:integrationCheck`) | | Messaging (Kafka) | `app.messaging.enabled` / `APP_MESSAGING_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:messaging-kafka')`, which brings the application bridge, the legacy `KafkaSender` seam and the vendored platform with its Kafka transport) | Kafka only | On when present (`KafkaCapabilityActivationTest`). `messaging-kafka:messagingCertificationTest` behind `verifyMessagingCertificationEvidence`, run by `messaging-certification.yml`; the starter's `integrationTest` is the live Kafka round trip. Kafka is the only registered broker; the RabbitMQ broker keys were removed (no transport). | -| Redis capabilities (cache / rate-limit / lease / idempotency) | `app.redis.enabled` / `APP_REDIS_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:cache-redis')`, which brings `redis-runtime`) | yes | `cache-redis:redisContainerContractTest` (Testcontainers Redis, `integrationCheck` and `mainCheck`); `cache-redis:redisTopologyTest`, run by `redis-sdk-topology.yml`. Not in the default composition. On when present; `false` contributes no Redis bean — no settings, client, connection, thread or health contributor. The module owns its readiness contribution (`RedisReadinessGroupPostProcessor`, `spring.factories`) and its settings (`config/module-defaults/cache-redis.yml`: `app.redis.enabled`, `app.rate-limit.*`, the Redis `ca-skeleton.capabilities.*`). No `app-bootstrap` main source names a Redis type. | -| Request idempotency | `APP_IDEMPOTENCY_PROVIDER` (`disabled` \| `redis` \| `postgresql`; a selector, not an on/off key) | yes | yes | Redis only | One generation: the application `IdempotencyExecutor`, built once by `app-bootstrap` `IdempotencyProviderSelectionConfig` over the one store the selected provider contributes (`cache-redis` or `persistence-jpa`); startup is refused unless exactly one store exists. `sample-portfolio` cannot depend on `app-bootstrap`, so its own `SampleIdempotencyConfig` builds its one executor from the same keys. Redis is covered by the row above. PostgreSQL has `persistence-jpa:postgresqlIdempotencyIntegrationTest`, but no workflow runs it. The `postgresql` provider refuses a non-PostgreSQL data source, so `bootRunH2` uses `disabled` or `redis`.. The executor stays in the composition root on purpose — it needs only application-core and its settings — while each store comes with its module: `postgresql` needs the persistence-jpa line, `redis` the cache-redis one. | +| Redis capabilities (cache / rate-limit / lease / idempotency) | `app.redis.enabled` / `APP_REDIS_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:cache-redis')`, which brings `redis-runtime`) | yes | `cache-redis:redisContainerContractTest` (Testcontainers Redis, `integrationCheck`); `cache-redis:redisTopologyTest`, run by `redis-sdk-topology.yml`. Not in the default composition. On when present; `false` contributes no Redis bean — no settings, client, connection, thread or health contributor. The module owns its readiness contribution (`RedisReadinessGroupPostProcessor`, `spring.factories`) and its settings (`config/module-defaults/cache-redis.yml`: `app.redis.enabled`, `app.rate-limit.*`, the Redis `ca-skeleton.capabilities.*`). No `app-bootstrap` main source names a Redis type. | +| Request idempotency | `APP_IDEMPOTENCY_PROVIDER` (`disabled` \| `redis` \| `postgresql`; a selector, not an on/off key) | yes | yes | Redis and PostgreSQL | One generation: the application `IdempotencyExecutor`, built once by `composition:idempotency` (`IdempotencyAutoConfiguration`) over the one store the selected provider contributes (`cache-redis` or `persistence-jpa`); startup is refused unless exactly one store exists. `app-bootstrap` and `sample-portfolio` both take that module with one `runtimeOnly` line, so there is no second assembly. Redis is covered by the row above. PostgreSQL has `persistence-jpa:postgresqlIdempotencyIntegrationTest`, run by `integration-main.yml` → `integration-check` (`:integrationCheck`). The `postgresql` provider refuses a non-PostgreSQL data source, so `bootRunH2` uses `disabled` or `redis`. Each store comes with its module: `postgresql` needs the persistence-jpa line, `redis` the cache-redis one. | | Transactional outbox relay | `ca-skeleton.outbox.enabled` / `APP_OUTBOX_ENABLED`, `false` (+ `APP_OUTBOX_RELAY_ENABLED`, `false`; persistence-jpa settings) | yes | yes (with the persistence-jpa line; the scheduler also needs the messaging-kafka line) | yes | The store and its settings are persistence-jpa's; the relay (`OutboxConfig`) is application composition in `app-bootstrap` because a driven adapter must not build or call a use case. It turns on only when an `OutboxStorePort` bean exists, and the scheduler only when an `OutboxMessagePublishPort` does (the messaging bridge), each ordered after its contributor by `afterName` — so an environment with no publisher keeps its PENDING rows. The bridge registers no stand-in publisher: a present-and-enabled bridge with a blank broker and no canonical transport is refused at startup. `postgresqlLegacyOutboxConcurrentRelayIntegrationTest` qualifies claim/fencing against PostgreSQL. | | Notification platform | `ca-skeleton.notification.platform.enabled` / `APP_NOTIFICATION_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:notification-platform')`, plus the persistence-jpa line) | claim-scoped | Not in the default composition. The one line brings the use-case assembly, `adapter:outbound:notification`, the HTTP surface `adapter:inbound:web-notification` and its own settings (`config/module-defaults/notification.yml`), each registered through the module's own `AutoConfiguration.imports`; `adapter:inbound:web` no longer depends on `application-notification`. `verifyNotificationEvidence` refuses a grade in `docs/notification/support-matrix.md` that no proven claim backs; run by `notification-platform.yml`. There is no real-SMTP lane, and the matrix says so rather than implying one. | | File server platform | `app.fileserver-platform.enabled` / `APP_FILESERVER_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:fileserver-platform')`, plus the persistence-jpa line) | yes | On when present; module-owned `config/module-defaults/fileserver.yml` also carries the servlet multipart ceiling. `app-bootstrap:integrationTest` → `FileserverCompositionIntegrationTest` (required by the strict lane), run by `integration-main.yml` → `integration-check` (`:integrationCheck`) | | Outbound HTTP client | `app.httpclient.enabled` / `APP_HTTPCLIENT_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:httpclient')`) | yes | On when present (`HttpClientPlatformActivationTest`). `httpclient:httpClientFailureInjectionTest` against a faulted upstream, run by `integration-main.yml` → `integration-check` (`:integrationCheck`) | | GraphQL transport | `backend.graphql.enabled` / `APP_GRAPHQL_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:graphql')`) | leaf-level | On when present; `false` also excludes Spring GraphQL's own auto-configuration, so no `/graphql` (`GraphQlCapabilityActivationTest`). `graphqlTransportQualificationTest` runs the HTTP boundary. The deployment-mode/runtime-profile rule is the module's own `GraphQlPlatformStartupValidator`. The default jar does not ship GraphQL, so a compose lane that exercises it runs the qualification jar. | -| Object storage | `app.object-storage.enabled` (no `APP_*` row), `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:objectstorage')`) | MinIO only | Own `ObjectStorageAutoConfiguration` (was bound through bootstrap's properties scan); on when present, `false` leaves only the explicit legacy seam (`ObjectStorageAutoConfigurationTest`). `app-bootstrap:integrationTest` assembles it against digest-pinned MinIO. | +| Object storage | `app.object-storage.enabled` / `APP_OBJECTSTORAGE_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:objectstorage')`) | MinIO only | Own `ObjectStorageAutoConfiguration` (was bound through bootstrap's properties scan); on when present, `false` leaves only the explicit legacy seam (`ObjectStorageAutoConfigurationTest`). `app-bootstrap:integrationTest` assembles it against digest-pinned MinIO. | | gRPC platform | — (build-level) | yes | **no** | yes | Absent from the main build entirely: `optional-platforms` is a separate Gradle build, so the switch is the `include`, not an environment variable. `-p optional-platforms ci` runs on every PR and `integrationCheck` certifies the operation ledger against real PostgreSQL. | | gRPC transport (`adapter:inbound:grpc`) | `ca-skeleton.grpc.server.enabled` (no `APP_*` row), `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:grpc')`) | leaf-level | Own `AutoConfiguration.imports` (`GrpcServerConfig`); on when present, and the loopback plaintext listener still needs `ca-skeleton.grpc.server.allow-insecure-local=true` (`GrpcSafeActivationTest`, `grpcTransportQualificationTest`). | | WebSocket transport | `app.websocket.enabled` / `APP_WEBSOCKET_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:websocket')`) | — | Own `AutoConfiguration.imports` (`WebSocketConfig`), on in a servlet app when present (`WebSocketAutoConfigurationTest`); `ConditionalTransportBuildContractTest` asserts it has no default production edge. | diff --git a/docs/fileserver/configuration.md b/docs/fileserver/configuration.md index 2cd42562..60af6511 100644 --- a/docs/fileserver/configuration.md +++ b/docs/fileserver/configuration.md @@ -128,13 +128,17 @@ Set `inline-safe-profile: true` only when downloads are never served inline from | `direct-download-permits` | `64` | concurrent non-delegated downloads | | `soft-high-water` | `0.70` | storage fraction at which pressure is reported | | `hard-high-water` | `0.85` | storage fraction at which uploads and copies are refused | -| `namespace-limit` | unset (unlimited) | most bytes one namespace may hold, live reservations plus committed usage; a create or copy that would pass it is refused with `QUOTA_EXCEEDED` (413) before any record or byte exists | +| `namespace-limit` | unset (unlimited) | most bytes one namespace may hold, live reservations plus committed usage; a create, copy or move that would pass it is refused with `QUOTA_EXCEEDED` (413) before any record, byte or namespace changes | `namespace-limit` is checked against the usage the quota ledger reports and then reserved, in one transaction but without a per-namespace lock: reservations admitted at the same moment can overshoot the limit by at most their own size, and the next one is refused. A service that needs an exact cap adds that lock in its persistence adapter. +A move to another namespace carries the file's bytes in the ledger: in the transaction that relocates +the record it checks the target's limit, books the bytes as committed usage there and reclaims them +from the source. A refused move leaves the file, and both namespaces' usage, as they were. + When the storage fraction cannot be read, admission treats it as unknown and does not apply the high-water rule — a synthetic `0` would silently disable the guard, and a synthetic `1` would take the capability down over a failed syscall. diff --git a/docs/fileserver/http-contract.md b/docs/fileserver/http-contract.md index 08cbb87b..84034bfd 100644 --- a/docs/fileserver/http-contract.md +++ b/docs/fileserver/http-contract.md @@ -15,7 +15,7 @@ and fails if one is missing, so this file cannot silently fall behind the code. | HEAD | `/v1/files/{fileId}/content` | `200`, `304` | identical headers, no body | | DELETE | `/v1/files/{fileId}` | `202`, `204` | logical delete first | | POST | `/v1/files/{fileId}:copy` | `202` | create-only target | -| POST | `/v1/files/{fileId}:move` | `200` | logical namespace change only | +| POST | `/v1/files/{fileId}:move` | `200` | namespace change only, bytes stay; the file's quota moves with it, and a target namespace past its `namespace-limit` is `413` | | OPTIONS | `/v1/uploads` | `204` | tus capability discovery | | POST | `/v1/uploads` | `201` | tus creation | | HEAD | `/v1/uploads/{uploadId}` | `204` | tus offset | diff --git a/docs/httpclient/configuration-reference.md b/docs/httpclient/configuration-reference.md index d4ff4823..206d81f7 100644 --- a/docs/httpclient/configuration-reference.md +++ b/docs/httpclient/configuration-reference.md @@ -102,7 +102,13 @@ greater than zero (`TIMEOUT_NOT_POSITIVE`): both engines read zero as "wait fore `total-call` also bounds the setup of a streaming download — connect, send, and the wait for response headers. Once the stream is handed over, each gap of the body is bounded by `read-idle` -instead, so a long download is not cut at an arbitrary total (design §15.3). +instead, so a long download is not cut at an arbitrary total (design §15.3). This holds on both +transports. The JDK transport keeps its exchange-wide timeout off a streamed body and bounds each +read with its own `read-idle` timer, because the JDK client has no socket read timeout; before +review 2026-11-03 RR-04-03 every JDK download longer than `response-header` was cut mid-body. A body +failure after hand-over is thrown as `HttpResponseTimeoutException` (a gap longer than `read-idle`) +or `HttpResponseTruncatedException` (the connection ended early), stage `RESPONSE_BODY`, evidence +`PARTIAL_RESPONSE`. ### Removed settings @@ -126,6 +132,14 @@ it as a result — and every transport failure. Every other 4xx is a healthy ans only say how many failures, out of how many calls, open the circuit. Defaults are Resilience4j's own, which every profile ran with before the keys existed. +Two deadlines can end an attempt in flight, and they are counted differently (review 2026-11-03 +RR-04-01): + +| Ended by | Breaker | Why | +|---|---|---| +| The caller's own deadline (`HttpOperation.deadline()`, when earlier than `total-call`) | Not recorded; the permission is given back | The caller ran out of time. Counting it opened the circuit on a healthy upstream whenever callers passed short budgets | +| The profile's `timeout.total-call` | Recorded as a failure | `total-call` is the operator's statement of how long a healthy upstream may take; a slow-drip upstream that never trips a per-gap timeout is seen only through it | + | Property | Default | Meaning | |---|---|---| | `failure-rate-threshold` | `50` | Percent of failed calls in the window that opens the circuit, 1–100 | diff --git a/docs/jpa/entity-mapping-guide.md b/docs/jpa/entity-mapping-guide.md index 9aec101d..4d3aa55e 100644 --- a/docs/jpa/entity-mapping-guide.md +++ b/docs/jpa/entity-mapping-guide.md @@ -72,17 +72,23 @@ What to use, in order of preference: A unidirectional `@OneToMany` with its own `@JoinColumn` is the exception, not the default. Use it only for child entities the root genuinely owns and changes only through itself (the testkit's `LifecycleParent` and `PagedParent` are this shape). It still costs an `UPDATE` per child when the -join column is nullable, and the collection still loads as a unit. +join column is nullable, and the collection still loads as a unit. The child then has no +association back to the root — not even a read-only `@ManyToOne` on the same join column +(`insertable = false, updatable = false`): that is the bidirectional pair again, without the +`mappedBy` that names it. If the child needs the root, it holds the root's ID. `CascadeType.ALL` with `orphanRemoval` is correct only for a child the aggregate genuinely owns. Between independent aggregates it deletes rows another part of the system still owns — another reason those are ID references. -`JpaArchitectureRules.associationsAreMappedFromOneSideOnly()` (testkit) fails the build on any -`@OneToMany`, `@OneToOne` or `@ManyToMany` that declares `mappedBy`, on `@Entity`, -`@MappedSuperclass` and `@Embeddable` types. `JpaProductionArchitectureTest` (app-bootstrap +`JpaArchitectureRules.associationsAreMappedFromOneSideOnly()` (testkit) fails the build on every +bidirectional pair, on `@Entity`, `@MappedSuperclass` and `@Embeddable` types: an association that +declares `mappedBy` (only that inverse half is reported), and two entities whose associations point +at each other without `mappedBy` (both halves are reported — the `@JoinColumn` form above, review +RR-03-04). A class that links to itself is a pair only when a second member points back the other +way (`@ManyToOne parent` with `@OneToMany children`). `JpaProductionArchitectureTest` (app-bootstrap `architectureTest`) runs it over the production graph and `SampleArchitectureTest` over the sample. -The failure message names the field and these alternatives. +The failure message names the fields and these alternatives. Chosen and rejected: diff --git a/docs/manual/04-persistence.md b/docs/manual/04-persistence.md index 4b40ee6e..4d5faddd 100644 --- a/docs/manual/04-persistence.md +++ b/docs/manual/04-persistence.md @@ -28,6 +28,9 @@ use case ── tx.inWrite ──▶ XRepository (domain 포트) 3. 엔티티·Spring Data repository·mapper·adapter를 쓴다. adapter는 aggregate만 주고받는다 (`OUTBOUND_ADAPTER_METHOD_RETURNS_ONLY_DOMAIN_OR_PRIMITIVES`). 4. `JpaXRepositoryContractTest extends XRepositoryContract`를 실 PostgreSQL lane에 둔다(08장 lane). + adapter는 호출자 트랜잭션 밖의 호출을 거부하므로(아래 「트랜잭션 안에서만 쓴다」), 계약의 + `inTransaction(Supplier)`을 재정의해 거기서 트랜잭션을 열고 커밋한다. 계약은 모든 저장소 호출을 그 + hook으로 부른다. fake는 기본값(그냥 실행)을 쓴다. 예: `src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterContractTest.java`. 5. adapter를 bean으로 등록하는 자동 설정을 쓰고, 기능의 `XConfig`에 `afterName`으로 그 순서를 적는다. @@ -80,6 +83,13 @@ store는 자기 트랜잭션을 열지 않는다. 유스케이스가 연 트랜 예: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapter.java` (`DataIntegrityViolationException` → 제약 이름 확인 → `PosterTitleAlreadyExistsException` 409), 제약은 `src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql`. + - **충돌을 바꾸는 곳은 하나다.** 업무 규칙 충돌(같은 제목)은 포트 옆 domain 패키지의 예외 타입이고, + 포트가 `@throws`로 선언하고 adapter가 던진다. 유스케이스의 사전 조회도 같은 타입을 던져 두 경로가 같은 + 409가 된다. application 예외를 domain 포트가 Javadoc으로만 가리키면 fake·mock은 그 약속을 지킬 수 없다. + 기술 충돌(버전 불일치·교착)은 adapter가 프레임워크 예외 그대로 두고 아래 `PersistenceExceptionTranslator`가 + `DB_*` 코드로 바꾼다(WorkLog의 `ObjectOptimisticLockingFailureException` → `DB_OPTIMISTIC_CONFLICT`). + - 그 약속은 포트 소유자 testFixtures의 공유 계약 테스트로 고정한다. fake와 adapter가 같은 계약을 상속한다. + 예: `PosterRepositoryContract`(`InMemoryPosterRepository`, `PosterRepositoryAdapterContractTest`). - 여러 인스턴스가 집는 작업 → `FOR UPDATE SKIP LOCKED`는 **트랜잭션 안에서**, 그리고 lease(만료 시각)와 fence 값을 함께 저장한다. 예: `ReconciliationJobStorePort.claimDue`(application-notification), gRPC operation ledger의 claim. diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md index 8ffd3d4f..1883f5a7 100644 --- a/docs/manual/05-idempotency.md +++ b/docs/manual/05-idempotency.md @@ -50,6 +50,7 @@ DB 커밋 중 연결 끊김 ───────────────── | 409 `IDEMPOTENT_IN_FLIGHT`, `retryable=true`, `Retry-After: 2` | 같은 키가 아직 실행 중. 결과 불명 | **같은 키로** 기다렸다 재전송. 새 키 금지 | | 422 `IDEMPOTENT_REQUEST_MISMATCH` | 같은 키에 다른 본문 | 클라이언트 버그. 재전송 안 함 | | 503 `IDEMPOTENCY_UNAVAILABLE` | 실행 전 거부 | 같은 키로 나중에 | +| 503 `IDEMPOTENCY_COMPLETION_UNKNOWN`, `retryable=true` | 실행 뒤 결과 기록 실패. 적용됐을 수 있음 | "적용 안 됨"이라 하지 않는다. **같은 키로** 나중에 재전송, 새 키 금지 | | 500 `IDEMPOTENCY_RECOVERY_REQUIRED` | 이전 시도 효과를 증명 못함 | 재전송·재실행 모두 위험. 업무 데이터로 확인 | | 500 `DB_COMPLETION_UNKNOWN`, `retryable=false` | DB 커밋 중 연결 끊김. 커밋됐을 수도 있음 | 키 없이 재시도 금지. KEYED면 같은 키로 재전송하면 서버가 판정 | diff --git a/docs/manual/06-errors.md b/docs/manual/06-errors.md index 4afebb58..d80efb4b 100644 --- a/docs/manual/06-errors.md +++ b/docs/manual/06-errors.md @@ -41,8 +41,9 @@ gRPC/GraphQL/WebSocket: 같은 ApiErrorCarrier를 자기 status 모양으로 | 서버 조립·설정 오류, 있을 수 없는 상태 | `IllegalStateException` | 500, 로그 남음 | | DB·외부 의존 실패 | adapter가 shared-contract carrier(`PersistenceFailureException`, `DependencyFailureException`)로 | 분류표대로(04·05장) | -- `IllegalArgumentException`을 "서버 조립이 틀렸다"에 쓰지 않는다. web은 그것을 로그 없이 400으로 - 바꿔서 서버 결함이 클라이언트 오류로 숨는다(리뷰 01-04). +- `IllegalArgumentException`을 "서버 조립이 틀렸다"에 쓰지 않는다. web은 그것을 400으로 바꾸고 WARN + 한 줄만 남긴다(`GlobalExceptionHandler`). 서버 결함이 클라이언트 오류 통계에 섞여 경보가 울리지 않는다 + (리뷰 01-04). 서버 쪽 잘못은 `IllegalStateException`(500, 로그)이다. - 메시지는 로그용이다. 클라이언트에는 코드와 category별 고정 문구(`ClientErrorMessages`)만 간다. 메시지에 SQLState·내부 경로·토큰을 넣어도 클라이언트에 새지 않지만, 로그 정책은 지킨다. diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index bbdfa5a9..4aef0641 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -62,13 +62,30 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re batch 메서드로 N+1 회피)를 구현한다. 존재를 숨길 필요가 없는 관리 화면은 403도 된다. - tenant: 인증 정보에서만 만든 `TenantId`를 command에 싣는다. 요청 본문의 tenant 값을 믿지 않는다. -## 지금 확인되지 않는 것 +## 시스템이 부르는 쓰기: `@SystemInvoked` -- web이 빠진 조립(gRPC 전용·배치 전용)에서는 advisor가 없어 선언이 검사되지 않는다. 이때 기동을 막는 - 장치는 아직 없다(리뷰 01-06). web 없이 조립하는 서비스는 그 전에 이 문제를 먼저 푼다. +스케줄러·relay처럼 사람이 아니라 시스템이 부르는 쓰기 유스케이스는 `@RequiresPermission` 대신 +`@SystemInvoked(reason = "...")`를 단다(`src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java`). +스케줄러 스레드에는 인증이 없어 권한 선언은 장식이 되기 때문이다. 이 표시가 붙은 유스케이스는 **권한 +검사가 없는 쓰기**이므로 전송 계층이 닿으면 안 된다. 그래서 두 가지가 막는다. + +| 막는 것 | 어디 | +| --- | --- | +| bean으로 등록하면 기동 실패. 조립 모듈이 `new`로 만들어 스케줄러에만 준다(예: `composition:outbox-relay`) | `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java` | +| inbound adapter가 그 클래스를 직접 쓰면 빌드 실패 | `INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | + +D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표시를 쓰지 않는다. 사용자가 부르는 +쓰기라면 권한을 선언하고 역할에 매핑한다. + +## web 없는 조립 + +web이 빠진 조립(gRPC 전용·배치 전용)에는 `@RequiresPermission`을 검사할 advisor가 없다. 그런 조립에 +권한을 선언한 bean이 있으면 `PermissionEnforcementGuard`가 기동을 실패시킨다(리뷰 01-06). web 없이 +조립하는 서비스는 자기 전송에 맞는 검사 advisor를 함께 넣어야 기동한다. ## 지금 이해하면 되는 것 - 쓰기 = `@RequiresPermission` + non-final + bean + 역할 매핑. +- 시스템만 부르는 쓰기 = `@SystemInvoked` + bean 아님 + 전송에서 안 닿음. - 객체 판정은 유스케이스 안, 남의 것은 404. - 역할은 자기 client 것만 읽는다. diff --git a/docs/manual/09-outbox-events.md b/docs/manual/09-outbox-events.md index 1c6f7999..753781b4 100644 --- a/docs/manual/09-outbox-events.md +++ b/docs/manual/09-outbox-events.md @@ -32,6 +32,10 @@ DB 저장과 broker 발행을 따로 하면(dual write) 둘 중 하나만 성공 등록을 빠뜨리면 append 때 실패한다. 예: `DurableOperationAutoConfiguration.durableOperationSubmittedContract()`. 5. 테스트: 계약 contribution 테스트(해시 고정), 유스케이스가 append했는지(`InMemoryOutboxStore`), 소비자 중복 제거 계약(sample `WorkLogReservedConsumerDedupeContractTest`). +6. schema를 출시한다: `src/test/resources/contracts/released-payload-schemas.sha256`에 새 version 파일의 + 해시를 한 줄 더한다. 출시한 version 파일은 고치지 않는다 — 바뀌면 `ReleasedPayloadSchemaContract` + 테스트가 실패한다. 필드를 바꾸는 변경은 새 version으로 낸다. 절차: `src/application-core/README.md` + "payload version 올리기"(리뷰 06-10). ## 판단 지점 @@ -49,22 +53,38 @@ DB 저장과 broker 발행을 따로 하면(dual write) 둘 중 하나만 성공 ### event id·correlation·순서 -- event id: UUIDv7, 소비자 중복 제거 키. 같은 작업의 재시도가 같은 event id를 내야 하면(durable - operation) 작업 id에서 파생한다. -- correlation: 요청의 correlation id가 문법에 맞으면 그것, 아니면 event id. 문법 밖 헤더가 업무 쓰기를 - 실패시키면 안 된다. +draft는 `IntegrationEventDrafts.draft(contract, eventId, aggregate, order, occurredAt, requestCorrelationId, payload)`로 +만든다(`src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDrafts.java`). +계약 id·payload 버전·목적지는 계약에서 오고, 기능이 정하는 것은 aggregate·순서·payload뿐이다. +`new IntegrationEventDraft<>(…)`를 직접 쓰면 빌드가 막는다(`INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`). +예: sample `PortfolioEventOutbox`, `SubmitDurableOperationUseCase`. + +- event id: 정규 소문자 UUIDv7, 소비자 중복 제거 키. draft(`IntegrationEventDraft`)가 다른 값(대문자, + v4, `event-1` 같은 문자열)을 거부하므로 업무 쓰기에서 바로 실패한다 — 커밋된 뒤 relay에서 DEAD가 되지 + 않는다(리뷰 06-06). 같은 작업의 재시도가 같은 event id를 내야 하면(durable operation) 작업 id를 쓰고, + 작업 id가 UUIDv7이 아니면 작업 id와 접수 시각에서 UUIDv7을 파생한다. +- correlation: 헬퍼가 정한다. 요청의 correlation id가 `IntegrationIdentity` 문법·길이에 맞으면 그것, + 아니면 event id. 문법 밖 헤더가 업무 쓰기를 실패시키지 않는다. 값을 미리 검사해야 하면 문법을 베끼지 + 말고 `IntegrationIdentity.isCanonical(value, IntegrationIdentity.CORRELATION_MAX_LENGTH)`를 부른다 + (aggregate id는 `AGGREGATE_ID_MAX_LENGTH`). +- tenant 범위: tenant가 없는 기능은 `IntegrationEventDrafts.SINGLE_TENANT_SCOPE`(`global`). - aggregate 순서: `OutboxAggregateSequencePort.nextSequence(aggregate)`로 같은 `tx.inWrite` 안에서 받는다(V21 카운터, 커밋 순서를 따른다). 이벤트가 하나뿐인 aggregate는 `AggregateOrder.first()`. 발생 - 시각(벽시계)은 쓰지 않는다 — 서버 시계가 어긋나면 순서가 뒤집힌다(리뷰 06-07). -- 이 규칙은 아직 기능마다 다시 쓴다(sample `PortfolioEventOutbox`). application-core 헬퍼로 올리는 일은 - 리뷰 01-09 후속이다. 그 전까지는 위 세 규칙을 지킨다. + 시각(벽시계)은 쓰지 않는다 — 서버 시계가 어긋나면 순서가 뒤집힌다(리뷰 06-07). 벽시계 번호를 쓰던 + 서비스가 포트로 옮기면 V21 floor 덕분에 새 번호는 옛 번호 뒤에서 시작한다. 그래서 첫 번호가 1이 + 아니라 약 1.7×10¹⁵일 수 있다. 소비자는 번호를 "마지막으로 본 값보다 큰가"로만 비교하고 연속성을 + 가정하지 않는다. ## relay와 실패 -- relay는 `composition:outbox-relay`가 조립한다. 유스케이스로 만든 relay를 bean으로 등록하지 않는다 - (스케줄러 스레드에는 인증이 없어 권한 프록시가 매번 거부한다). -- broker의 **재시도 가능한** 거부는 DEAD가 아니라 backoff 재시도다. broker가 멈춰도 대량 DEAD가 되지 - 않는다(1라운드 06-01·06-03). 진짜 인증 오류도 재시도로 남으니 경보로 잡는다. +- relay는 `composition:outbox-relay`가 `new`로 조립해 스케줄러에만 준다. relay는 `@SystemInvoked`라 권한 + 선언이 없어서, bean이 되면 전송 계층이 **권한 검사 없이** 닿는다. 그래서 bean으로 등록하면 + `PermissionEnforcementGuard`가 기동을 실패시킨다(07장 「시스템이 부르는 쓰기」). +- broker의 **재시도 가능한** 거부와 응답 없음은 DEAD가 아니라 backoff 재시도다. broker가 멈춰도 대량 + DEAD가 되지 않는다(1라운드 06-01·06-03). 대신 끝이 없다: 진짜 인증 오류, Kafka adapter가 이름을 모르는 + broker 거부도 영원히 재시도된다. 행의 `last_failure_code`와 로그의 `error.reason`이 원인 코드를 남기고, + `outbox.retry.long.size`가 오래 재시도 중인 행을 센다. 처분(보류·재개·skip)은 publish-failed runbook + §4.1이다(재리뷰 RR-05-03). - 발행 응답을 못 받으면 결과 불명(`OutboxPublishAmbiguousException`) — 05장 규칙과 같다. - 운영: `docs/runbooks/outbox-dead-letter.md`, `docs/runbooks/outbox-publish-failed.md`. diff --git a/docs/messaging/configuration-reference.md b/docs/messaging/configuration-reference.md index 3fc19e98..07130a20 100644 --- a/docs/messaging/configuration-reference.md +++ b/docs/messaging/configuration-reference.md @@ -26,7 +26,9 @@ producing-service identity다. ## Outbox -outbox는 canonical 하나다(2026-09-28). use case가 `IntegrationEventEncoderPort`로 만든 +application의 발행 경로는 하나다(2026-09-28): `outbox_event` 표와 `composition:outbox-relay`. vendored +platform의 `messaging_outbox`(`outbox-inbox.md`)는 이 경로에 쓰이지 않는다 — 두 모델의 상태 대응은 +`outbox-inbox.md` 머리의 표에 있다. use case가 `IntegrationEventEncoderPort`로 만든 `ValidatedIntegrationEvent`를 `OutboxAppendPort`로 append하고, relay는 claim한 row의 exact envelope bytes를 `IntegrationEventPublishPort`로 보낸다. 예전의 `app.outbox.canonical-transport-enabled` gate와 legacy `MessageBroker → KafkaSender` 경로는 삭제됐다. 발행할 contract의 logical destination마다 diff --git a/docs/messaging/outbox-inbox.md b/docs/messaging/outbox-inbox.md index 6ec2d046..08f18189 100644 --- a/docs/messaging/outbox-inbox.md +++ b/docs/messaging/outbox-inbox.md @@ -1,5 +1,25 @@ # Outbox · Inbox +> **이 문서의 Outbox는 vendored messaging platform의 outbox다**(`messaging_outbox` 표, +> `messaging-reliability`의 `OutboxRelay`). 이 템플릿 application이 쓰는 outbox는 그것이 아니다. +> application은 `outbox_event` 표(`adapter:outbound:persistence-jpa`)에 append하고, relay는 +> `composition:outbox-relay`가 돌린다. 그 동작과 운영은 `docs/manual/09-outbox-events.md`, +> `src/composition/outbox-relay/README.md`, `docs/runbooks/outbox-dead-letter.md`, +> `docs/runbooks/outbox-publish-failed.md`에 있다. platform outbox는 소유자 결정으로 제품 안에 남아 +> 있지만, platform outbox repository bean이 없으면 그 relay는 만들어지지 않는다(리뷰 2026-11-01 06-11). +> +> 두 모델은 같은 이름의 상태가 반대 뜻이다. 이름으로 옮기면 확정 거부는 영원히 재시도되고 응답 없는 +> 메시지는 버려진다. 대응은 아래 표 하나로만 읽는다(`OutboxPublishOutcome` Javadoc과 같은 내용). +> +> | 일어난 일 | application `outbox_event` | platform `messaging_outbox` | +> |---|---|---| +> | broker가 확인했다 | `PUBLISHED` | `PUBLISHED` | +> | 응답이 없었다(저장됐을 수 있음) | `FAILED`(재시도, 예산 안 씀, 끝 없음) | `AMBIGUOUS`(재시도, 예산을 다 쓰면 `EXHAUSTED`) | +> | 지금만 거부됐다(종료·포화·credential) | `FAILED`(재시도, 예산 안 씀, 끝 없음) | `FAILED`(종단) | +> | 확정 거부됐다(같은 payload는 또 거부) | `DEAD`(종단, 수동 처분) | `FAILED`(종단) | +> | publisher가 예외를 던졌고 시도 예산을 다 썼다 | `DEAD`(종단, 수동 처분) | `EXHAUSTED`(종단) | +> | 운영자가 재시도를 멈췄다 | `PARKED`(수동 재개·skip) | 없음 | +> > **이 템플릿 application의 소비 경로**: application의 `MessageHandler`와 inbox 부품(애플리케이션 > DataSource 위 `JdbcInboxRepository`, `PlatformTransactionManager` 위 `TransactionRunner`)은 > `adapter:inbound:messaging`(`src/adapter/inbound/messaging/README.md`)이 둔다. platform starter는 두 diff --git a/docs/notification/configuration-reference.md b/docs/notification/configuration-reference.md index f7a6fc7b..1e161d49 100644 --- a/docs/notification/configuration-reference.md +++ b/docs/notification/configuration-reference.md @@ -48,7 +48,7 @@ still waiting on gets claimed by a second worker, and the recipient receives the | `callbacks.replay-skew` | `APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW` | `1h` | positive; SNS messages whose `Timestamp` is further than this from receipt, either way, are rejected. The default is SNS's longest HTTP/S retry period (3,600 s), so a bounce or complaint SNS redelivers after an outage is still accepted; a replay inside the window is a duplicate in the provider event ledger, not a second event (review 05-20) | | `callbacks.trusted-proxies` | `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES` | *(empty)* | CSV of peer addresses | -콜백 응답: 기록(중복 포함) `204`, 거절 `400`(서명·topic·시각·형식), 본문 초과 `413`. SNS 서명 인증서를 가져오지 못하면 거절하지 않고 `503`+`Retry-After`로 답한다 — SNS는 4xx를 처리 완료로 보고 재전송을 멈추지만 5xx는 다시 보낸다(review 05-20). +콜백 응답: 기록(중복 포함) `204`, 거절 `400`(서명·topic·시각·형식), 본문 초과 `413`. SNS 서명 인증서를 가져오지 못하면(5xx·408·429·네트워크 실패) 거절하지 않고 `503`+`Retry-After`로 답한다 — SNS는 4xx를 처리 완료로 보고 재전송을 멈추지만 5xx는 다시 보낸다(review 05-20). 인증서 URL이 그 밖의 4xx(403·404 등)로 답하면 SNS가 발급하지 않은 인증서를 가리킨 위조 콜백이므로 서명 검증 실패로 `400` 거절하고 보안 감사(`callbackSignatureRejected`)에 남긴다(review 2026-11-03 RR-07-03). 호스트 검사를 통과한 URL이라 답하는 쪽은 SNS다. 여러 provider가 요청 URL에 서명하므로, 그 URL을 잘못 재구성하면 정상 webhook이 전부 서명 실패가 된다. `trusted-proxies`가 비어 있으면 forwarded 헤더를 **믿지 않고** 컨테이너가 관측한 값을 쓴다. 무조건 믿으면 diff --git a/docs/notification/evidence-manifest.json b/docs/notification/evidence-manifest.json index 752a4402..151f8860 100644 --- a/docs/notification/evidence-manifest.json +++ b/docs/notification/evidence-manifest.json @@ -54,7 +54,8 @@ "status": "satisfied", "lane": ":adapter:outbound:persistence-jpa:jpaPlatformContractTest", "evidence": [ - "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/WorkerCrashRecoveryContractTest.java" + "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/WorkerCrashRecoveryContractTest.java", + "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java" ] }, "provider-wire-qualified": { diff --git a/docs/notification/support-matrix.md b/docs/notification/support-matrix.md index 2c89927f..9850179e 100644 --- a/docs/notification/support-matrix.md +++ b/docs/notification/support-matrix.md @@ -49,10 +49,13 @@ assembler is absent because the relay was not configured. | Extension | nothing; the receiving contract owns its own guarantees | | Experimental | nothing; the grade is the warning | -`recoverable` was met on 2026-08-15 by `WorkerCrashRecoveryContractTest`, which walks the four -phases a dispatch passes through — claimed, attempt written, request started, body committed — and -asserts for each that the delivery becomes claimable again or becomes a question for the provider, -never both and never neither. +`recoverable` is backed by two tests. `WorkerCrashRecoveryContractTest` walks the four phases a +dispatch passes through — claimed, attempt written, request started, body committed — and pins the +rows a dead worker leaves at each: a passed lease, and from the attempt insert on an unfinished +attempt carrying that phase's evidence. It writes those rows itself, so it checks recovery's input, +not recovery. `PostgreSqlNotificationBackgroundPassIntegrationTest` runs lease recovery and +reconciliation over rows the dispatcher's own factory wrote and asserts the outcome: requeued before +any attempt, reconciled after one (review 05-01, RR-03-07). The remaining unmet claim, and what would meet it: diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index c59640f4..61e9ea02 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -1670,7 +1670,7 @@ env_keys: required: false reload_policy: restart-only owner_branch: redis-production-capability-completion - validation: positive_duration_le_1h + validation: duration_gt_in_flight_retry_after_2s_le_1h compatibility_impact: additive required_test: redis-idempotency-contract:processing-lease-bounded @@ -1806,6 +1806,24 @@ env_keys: compatibility_impact: additive required_test: redis-capability:cache-region-composition + - name: APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS + # The cache's own script-lane connections. Separate from APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS, + # which idempotency, rate limiting and leases share, so cache fills cannot starve them (review + # 2026-11-03 README section 4, RR-04-02). + property: app.capabilities.cache.maximum-script-connections + owner_module: adapter-outbound-cache-redis + type: integer + default: 4 + allowed_values: null + classification: public-config + required: false + required_when: app.capabilities.cache.bindings.default=redis + reload_policy: restart-only + owner_branch: refactor/maturity-review-2026-11 + validation: positive_integer + compatibility_impact: additive + required_test: redis-capability:cache-script-lane-separate-from-correctness + - name: APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT # The ceiling on one owner-safe transition. type: duration @@ -2000,7 +2018,7 @@ env_keys: # secret://@/ form as the application reference. Unset, scripts run # as the application account and startup logs a warning saying so. The Compose Redis lanes use # secret://ca-skeleton-application-advanced@environment/REDIS_LANE_ADVANCED_PASSWORD, a fixture - # account of infra/redis-sdk/acl/all-accounts.acl. + # account of infra/redis-sdk/acl/lane-fixture-accounts.acl. property: app.redis.authentication.advanced-credential-reference owner_module: adapter-outbound-cache-redis type: string @@ -2043,7 +2061,7 @@ env_keys: # . Without the account part the client authenticates as `default`, which a hardened # Redis turns off. The Compose Redis lanes use # secret://ca-skeleton-application@environment/REDIS_LANE_APPLICATION_PASSWORD, a fixture - # account of infra/redis-sdk/acl/all-accounts.acl. + # account of infra/redis-sdk/acl/lane-fixture-accounts.acl. property: app.redis.authentication.credential-reference owner_module: adapter-outbound-cache-redis type: string @@ -4043,6 +4061,39 @@ env_keys: compatibility_impact: behavior-change required_test: websocket-contract:canonical-property-namespace + - name: APP_OBJECTSTORAGE_ENABLED + # 2026-11-03 RR-06-07: the explicit off the Compose smoke wrapper sets for every lane that is + # not about object storage. It bound by relaxed binding and was in no registry, so the env + # contract could not tell it from an unread name. The module is on when present; absent from + # the build is the ordinary off state. + property: app.object-storage.enabled + owner_module: adapter-outbound-objectstorage + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: refactor/maturity-review-2026-11 + validation: boolean + compatibility_impact: none + required_test: off-state-zero-side-effects-and-env-round-trip + - name: APP_GRPC_SERVER_ENABLED + # 2026-11-03 RR-06-07: the explicit off for the gRPC server the Compose lanes set (it replaced + # CASKELETON_GRPC_ENABLED, which nothing read). The module is on when present; absent from the + # build is the ordinary off state. + property: app.grpc.server.enabled + owner_module: adapter-inbound-grpc + type: boolean + default: true + allowed_values: [true, false] + classification: public-config + required: false + reload_policy: restart-only + owner_branch: refactor/maturity-review-2026-11 + validation: boolean + compatibility_impact: none + required_test: off-state-zero-side-effects-and-env-round-trip - name: APP_GRAPHQL_ENABLED # 2026-09-25 capability packaging: the module is on when present (its own config yml maps # this key with default true); false is the explicit off. Absent from the build is the diff --git a/docs/registries/error-codes.yaml b/docs/registries/error-codes.yaml index 9c70a5a4..d569b16b 100644 --- a/docs/registries/error-codes.yaml +++ b/docs/registries/error-codes.yaml @@ -401,6 +401,9 @@ errors: # source: docs/web/http-contract.md §2 (2026-11-01 소유자 결정, 리뷰 02-01 대안 A) — 결과 불명. 같은 Idempotency-Key로 Retry-After 뒤 재전송. 새 키 금지. # 2초 = 기본 processing lease(30s)보다 짧은 고정값. 이전 "client는 polling"(retryable=false)은 조회 엔드포인트가 없어 폐기. + # 값 하나: IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER. processing-lease가 이 값 이하면 기동 실패(재리뷰 RR-02-05). + # behavior-change: retryable false→true는 web Envelope뿐 아니라 gRPC trailer error-retryable(status ABORTED)과 + # GraphQL extension retryable에도 나간다(재리뷰 RR-02-06, GrpcStatusMapperTest·GraphQlWireErrorMapperTest가 고정). - code: IDEMPOTENT_IN_FLIGHT category: CONFLICT http_status: 409 @@ -411,7 +414,7 @@ errors: client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." log_level: INFO runbook_link: null - compatibility_impact: none + compatibility_impact: behavior-change required_test: contract-verification:idempotency # source: feature-rate-limit-idempotency-contract L72 — "fingerprint mismatch (same key + different body) = 422 IDEMPOTENT_REQUEST_MISMATCH" @@ -442,6 +445,22 @@ errors: compatibility_impact: additive required_test: contract-verification:idempotency + # source: 재리뷰 2026-11-03 README 4절 결정, RR-02-03 — action이 돈 뒤 complete 단계에서 저장소가 응답하지 않음. + # 실행 전 거부(IDEMPOTENCY_UNAVAILABLE)와 code로 구분한다. 결과 불명: 같은 키로 재전송하면 서버가 replay·in-flight· + # recovery-required로 판정한다. 새 키 금지. docs/web/http-contract.md §2. + - code: IDEMPOTENCY_COMPLETION_UNKNOWN + category: TRANSIENT_DEPENDENCY + http_status: 503 + retryable: true + retry_after_seconds: null + owner_branch: feature-rate-limit-idempotency-contract + owner_layer: application + client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." + log_level: ERROR + runbook_link: "runbook://idempotency/unavailable" + compatibility_impact: additive + required_test: contract-verification:idempotency + # source: review-followup P15 (X2-P2-2a) — replay cannot decide whether an external effect happened - code: IDEMPOTENCY_RECOVERY_REQUIRED category: DATA_INTEGRITY diff --git a/docs/registries/metrics.yaml b/docs/registries/metrics.yaml index 0435f3a5..043fccf4 100644 --- a/docs/registries/metrics.yaml +++ b/docs/registries/metrics.yaml @@ -349,8 +349,10 @@ metrics: cardinality_limit: 50 - name: outcome cardinality_limit: 5 - # STALE: the relay's claim was taken over before its result could be written (V17 lease fence). - allowed_values: [PUBLISHED, FAILED, DEAD, IN_FLIGHT, STALE] + # The relay cycle outcomes (OutboxRelayResult.Outcome), not row statuses: IN_FLIGHT is a status + # and is never counted. STALE: the relay's claim was taken over before its result could be + # written (V17 lease fence). RELEASED: a stopping relay gave back a claim it had not used. + allowed_values: [PUBLISHED, FAILED, DEAD, STALE, RELEASED] percentiles: null histogram_buckets: null alert_severity_thresholds: @@ -378,13 +380,14 @@ metrics: required_test: contract-verification:metrics-cardinality # source: feature-domain-event-outbox-contract — row status enum + Outbox Defaults attemptCount + # PARKED: an operator held a row that was retried without end (re-review 2026-11-03 RR-05-03). - name: outbox.pending.size type: gauge unit: total tags: - name: status - cardinality_limit: 5 - allowed_values: [PENDING, IN_FLIGHT, PUBLISHED, FAILED, DEAD] + cardinality_limit: 6 + allowed_values: [PENDING, IN_FLIGHT, PUBLISHED, FAILED, DEAD, PARKED] percentiles: null histogram_buckets: null alert_severity_thresholds: @@ -394,6 +397,35 @@ metrics: compatibility_impact: additive required_test: contract-verification:metrics-cardinality + # source: re-review 2026-11-03 RR-05-03 — a refusal for now and an unanswered publish are retried + # without end; these count the FAILED rows deferred at least 10 times (OutboxMetrics + # LONG_RETRY_DEFERRED_CLAIMS, the publish-failed runbook's §4.1 query) and age the oldest of them. + - name: outbox.retry.long.size + type: gauge + unit: total + tags: [] + percentiles: null + histogram_buckets: null + alert_severity_thresholds: + p2: "> 0 for 10m (runbook://outbox/publish-failed §4.1)" + owner_branch: feature-domain-event-outbox-contract + log_field_mapping: [] + compatibility_impact: additive + required_test: contract-verification:metrics-cardinality + + - name: outbox.retry.long.age + type: gauge + unit: seconds + tags: [] + percentiles: null + histogram_buckets: null + alert_severity_thresholds: + p2: "> 3600 (runbook://outbox/publish-failed §4.1)" + owner_branch: feature-domain-event-outbox-contract + log_field_mapping: [] + compatibility_impact: additive + required_test: contract-verification:metrics-cardinality + # === Cache === # source: feature-cache-consistency-contract — Decisionized Work Items "cache pattern | cache-aside default" - name: cache.gets.total @@ -501,240 +533,122 @@ metrics: compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # source: redis-production-capability Task 16 — closed semantic operation outcomes - - name: redis.capability.operations.total - type: counter - unit: total - tags: - - name: capability - cardinality_limit: 6 - allowed_values: [cache, rate_limit, idempotency, efficiency_lease, session, runtime] - - name: role - cardinality_limit: 3 - allowed_values: [cache, coordination, session] - - name: operation - cardinality_limit: 24 - allowed_values: - - lookup - - record - - invalidate - - refresh_claim - - refresh_release - - rate_evaluate - - idempotency_claim - - idempotency_start - - idempotency_renew - - idempotency_complete - - idempotency_fail - - idempotency_release - - idempotency_inspect - - lease_acquire - - lease_inspect - - lease_renew - - lease_release - - session_create - - session_inspect - - session_save - - session_touch - - session_revoke - - session_rotate - - route_command - - name: redis_outcome - cardinality_limit: 15 - allowed_values: - - success - - hit - - miss - - denied - - contended - - conflict - - incompatible - - unavailable - - overloaded - - closed - - indeterminate - - stale - - skipped - - tombstoned - - absolute_expired - - name: certainty - cardinality_limit: 3 - allowed_values: [definite, not_applied, indeterminate] - percentiles: null - histogram_buckets: null - alert_severity_thresholds: - p1: "required coordination/session unavailable or indeterminate mutation sustained for 2m" - p2: "optional cache unavailable or overloaded above baseline for 5m" - owner_branch: redis-production-capability - log_field_mapping: [capability, role, operation, redis_outcome, certainty] - compatibility_impact: additive - required_test: contract-verification:metrics-cardinality - - # source: redis-production-capability Task 16 — monotonic semantic operation duration - - name: redis.capability.duration.seconds + # === Redis connection lanes === + # source: review 2026-11-03 RR-04-02 — the cache's conditional writes got their own lane + # (CACHE_SCRIPT) so that cache fills cannot take the SCRIPT lane's connections from idempotency, + # rate limiting and leases. These meters show, per lane, whether that holds. Emitted by + # redis-runtime RedisLaneMetrics for every lane RedisRuntimeOwner pools, only when the context has + # a MeterRegistry. Every counter series is registered at zero at startup. + - name: redis.lane.acquire.wait.seconds type: timer unit: seconds tags: - - name: capability - cardinality_limit: 6 - allowed_values: [cache, rate_limit, idempotency, efficiency_lease, session, runtime] - - name: role - cardinality_limit: 3 - allowed_values: [cache, coordination, session] - - name: operation - cardinality_limit: 24 - allowed_values: - - lookup - - record - - invalidate - - refresh_claim - - refresh_release - - rate_evaluate - - idempotency_claim - - idempotency_start - - idempotency_renew - - idempotency_complete - - idempotency_fail - - idempotency_release - - idempotency_inspect - - lease_acquire - - lease_inspect - - lease_renew - - lease_release - - session_create - - session_inspect - - session_save - - session_touch - - session_revoke - - session_rotate - - route_command - - name: redis_outcome - cardinality_limit: 15 - allowed_values: - - success - - hit - - miss - - denied - - contended - - conflict - - incompatible - - unavailable - - overloaded - - closed - - indeterminate - - stale - - skipped - - tombstoned - - absolute_expired + - name: lane + # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + cardinality_limit: 12 + - name: outcome + cardinality_limit: 2 + allowed_values: [admitted, refused] percentiles: [0.5, 0.9, 0.95, 0.99] histogram_buckets: slo_driven alert_severity_thresholds: - p2: "p99 approaches the configured command or caller deadline for 10m" + p2: "SCRIPT admitted p99 > 100ms for 10m (the correctness lane is queueing)" + p3: "CACHE_SCRIPT admitted p99 > 100ms for 30m" owner_branch: redis-production-capability - log_field_mapping: [capability, role, operation, redis_outcome] + log_field_mapping: [lane, outcome] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # source: redis-production-capability Task 16 — admission rejected before command ownership - - name: redis.capability.admission.rejected.total + - name: redis.lane.acquire.refused.total type: counter unit: total tags: - - name: role - cardinality_limit: 3 - allowed_values: [cache, coordination, session] - - name: admission - cardinality_limit: 2 - allowed_values: [rejected_saturated, rejected_closed] + - name: lane + # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + cardinality_limit: 12 + - name: reason + cardinality_limit: 4 + allowed_values: [saturated, closing, interrupted, connect_failed] percentiles: null histogram_buckets: null alert_severity_thresholds: - p1: "required role rejection sustained above zero for 2m" - p2: "optional cache saturation sustained for 5m" + p1: "SCRIPT or REGULAR saturated or connect_failed above zero for 2m while a correctness role is selected" + p2: "CACHE_SCRIPT saturated above baseline for 10m" owner_branch: redis-production-capability - log_field_mapping: [role, admission] + log_field_mapping: [lane, reason] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # source: redis-production-capability Task 16 — bounded admitted command count observation - - name: redis.capability.inflight.total + - name: redis.lane.connections.opened.total + type: counter + unit: total + tags: + - name: lane + # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + cardinality_limit: 12 + percentiles: null + histogram_buckets: null + alert_severity_thresholds: + p3: "opened rate after warm-up above baseline for 15m (reconnect churn against a slow Redis)" + owner_branch: redis-production-capability + log_field_mapping: [lane] + compatibility_impact: additive + required_test: contract-verification:metrics-cardinality + + - name: redis.lane.connections.discarded.total + type: counter + unit: total + tags: + - name: lane + # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + cardinality_limit: 12 + - name: reason + cardinality_limit: 2 + allowed_values: [invalidated, broken] + percentiles: null + histogram_buckets: null + alert_severity_thresholds: + p3: "invalidated rate above baseline for 15m (timed-out or failed calls discarding connections)" + owner_branch: redis-production-capability + log_field_mapping: [lane, reason] + compatibility_impact: additive + required_test: contract-verification:metrics-cardinality + + - name: redis.lane.connections.active type: gauge unit: total tags: - - name: role - cardinality_limit: 3 - allowed_values: [cache, coordination, session] - - name: state - cardinality_limit: 3 - allowed_values: [idle, active, saturated] + - name: lane + # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + cardinality_limit: 12 percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "saturated series remains nonzero for 5m" + p2: "SCRIPT active == configured maximum-script-connections for 5m" owner_branch: redis-production-capability - log_field_mapping: [role, state] + log_field_mapping: [lane] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - # source: redis-production-capability Task 16 — observations of exact sanitized RoleHealth - - name: redis.capability.readiness.total - type: counter + - name: redis.lane.connections.pending + type: gauge unit: total tags: - - name: capability - cardinality_limit: 5 - allowed_values: [cache, rate_limit, idempotency, efficiency_lease, session] - - name: role - cardinality_limit: 3 - allowed_values: [cache, coordination, session] - - name: state - cardinality_limit: 3 - allowed_values: [available, unavailable, overloaded] - - name: reason - cardinality_limit: 11 - allowed_values: - - 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 - - name: requirement - cardinality_limit: 2 - allowed_values: [optional, required] + - name: lane + # The lane's name: REGULAR, SCRIPT (redis-runtime), CACHE_SCRIPT (cache-redis), BLOCKING, + # TRANSACTION, ADMIN (redis-sdk), plus any lane a service composes as a RedisLaneContribution. + cardinality_limit: 12 percentiles: null histogram_buckets: null alert_severity_thresholds: - p1: "required coordination/session unavailable for 2m" - p2: "optional cache unavailable or overloaded for 5m" + p2: "SCRIPT pending > 0 for 5m" owner_branch: redis-production-capability - log_field_mapping: [capability, role, state, reason, requirement] - compatibility_impact: additive - required_test: contract-verification:metrics-cardinality - - # source: redis-production-capability Task 16 — bounded router shutdown drain result - - name: redis.capability.lifecycle.drain.total - type: counter - unit: total - tags: - - name: role - cardinality_limit: 3 - allowed_values: [cache, coordination, session] - - name: drain_outcome - cardinality_limit: 3 - allowed_values: [drained, forced_after_timeout, interrupted] - percentiles: null - histogram_buckets: null - alert_severity_thresholds: - p1: "required role forced_after_timeout or interrupted during shutdown" - p2: "optional cache forced close during shutdown" - owner_branch: redis-production-capability - log_field_mapping: [role, drain_outcome] + log_field_mapping: [lane] compatibility_impact: additive required_test: contract-verification:metrics-cardinality diff --git a/docs/registries/secrets-classification.yaml b/docs/registries/secrets-classification.yaml index cf814d6c..c10c2c2a 100644 --- a/docs/registries/secrets-classification.yaml +++ b/docs/registries/secrets-classification.yaml @@ -10,6 +10,9 @@ # (feature-secrets-config-source-contract 2026-05-22: "dev/local sentinel value prefix = __LOCAL_DEV_"). # - prod profile에서 `__LOCAL_DEV_` prefix 발견 시 startup fail # (feature-secrets-config-source-contract 2026-05-22). +# - prod profile에서 `fixture-` prefix 값(이 저장소에 적힌 lane fixture 비밀번호 — infra/redis-sdk/acl, +# compose lane의 REDIS_LANE_*)도 같은 이유로 startup fail. 어떤 변수 이름이든 검사한다 +# (review 2026-11-03 RR-07-04). # - Masking 기본 = `full_except_last_4` (feature-secrets-config-source-contract 2026-05-22: # "full mask except last 4 chars for non-secret tokens"). 진짜 secret(password/private key)은 `full`. # - Naming suffix는 보조 신호 (feature-secrets-config-source-contract: "_TOKEN, _KEY, _PASSWORD"). diff --git a/docs/reviews/2026-11-01-maturity-review/06-messaging.md b/docs/reviews/2026-11-01-maturity-review/06-messaging.md index e9557756..58f27bbf 100644 --- a/docs/reviews/2026-11-01-maturity-review/06-messaging.md +++ b/docs/reviews/2026-11-01-maturity-review/06-messaging.md @@ -39,8 +39,8 @@ | --- | --- | --- | --- | | techlead H10 | 자동조립 publisher가 관측을 기록하지 않음 | 해결 | `messaging-spring-boot-starter/.../MessagingPublishConfiguration.java:224-231` observation 주입 | | techlead H3 | consumer가 배선되지 않음 | 바뀜 | starter-kafka가 `MessageHandler` bean마다 consumer를 연다(`MessagingConsumeConfiguration.java:60-68`). 다만 application leaf 쪽 경로가 없다 → 06-08 | -| techlead M4 | 실행 경로에 스키마 호환성 검사 없음 | 바뀜 | 문서가 "선언만 하고 강제하지 않음"으로 표시(`docs/messaging/configuration-reference.md:123`). 앱 payload 버전에는 여전히 없음 → NN-10 | -| techlead M5 | outbox 두 개 공존 | 남음(소유자 결정으로 유지) | vendored `MessagingReliabilityAutoConfiguration`·`JdbcOutboxRepository`가 runtime classpath에 있음. 문서·종료 순서 비용 → 06-02, NN-11 | +| techlead M4 | 실행 경로에 스키마 호환성 검사 없음 | 바뀜 | 문서가 "선언만 하고 강제하지 않음"으로 표시(`docs/messaging/configuration-reference.md:123`). 앱 payload 버전에는 여전히 없음 → 06-10 | +| techlead M5 | outbox 두 개 공존 | 남음(소유자 결정으로 유지) | vendored `MessagingReliabilityAutoConfiguration`·`JdbcOutboxRepository`가 runtime classpath에 있음. 문서·종료 순서 비용 → 06-02, 06-11 | | techlead M7 / H-1b | producer-id 키 부재, 빈 값 통과 | 해결 | `messaging-kafka/src/main/resources/config/module-defaults/messaging.yml` `producer-id`, `MessagingBridgeRootAutoConfiguration.java:77-87` | | H-1a | bridge 조건이 platform보다 먼저 평가 | 해결 | `MessagingBridgeRootAutoConfiguration.java:32-33` `afterName` | | H-8 | bridge `prepare`가 모든 예외를 REJECTED로 | 해결 | `PlatformIntegrationEventPublishAdapter.java:59-67`, 테스트 `aFailureOtherThanAnIncompatibleValueIsNotTurnedIntoARefusal` | @@ -248,7 +248,7 @@ - 완료 기준: 앱 relay가 실제 Kafka로 발행한 레코드를 테스트가 읽어 envelope 바이트를 비교한다. 이 lane이 이름 있는 게이트에 들어 있다. - 검증 방법: 그 lane의 실행 로그. -### NN-10 — 이벤트 payload 버전을 올리는 방법과 호환성 검사가 없다 +### 06-10 — 이벤트 payload 버전을 올리는 방법과 호환성 검사가 없다 - 성격: 구조적 위험 - 관련 관점: 17, 11, 20 @@ -267,7 +267,7 @@ - 완료 기준: 필드 삭제 같은 깨지는 변경이 테스트에서 실패한다. - 검증 방법: 샘플 contract에 깨지는 v2를 넣는 변이 실험. -### NN-11 — outbox가 둘인데 문서와 주석은 하나처럼 말한다 +### 06-11 — outbox가 둘인데 문서와 주석은 하나처럼 말한다 - 성격: 개선 제안(이해 비용) - 관련 관점: 4, 5, 23, 24 @@ -285,7 +285,7 @@ - 완료 기준: `docs/messaging`에서 앱 outbox 문서로 가는 링크가 있고, 상태 대응표가 하나 있다. - 검증 방법: 문서 리뷰. -### NN-12 — 배치 크기와 lease 시간의 관계를 검사하지 않는다 +### 06-12 — 배치 크기와 lease 시간의 관계를 검사하지 않는다 - 성격: 구조적 위험 - 관련 관점: 12, 19, 21 @@ -300,7 +300,7 @@ - 완료 기준: lease를 넘을 수 있는 설정 조합이 기동에서 거부된다. - 검증 방법: `OutboxSettings` 바인딩 테스트에 경계 조합 추가. -### NN-13 — 이 영역 문서·주석의 낡은 설명 +### 06-13 — 이 영역 문서·주석의 낡은 설명 - 성격: 개선 제안 - 관련 관점: 24, 9, 26 @@ -317,7 +317,7 @@ - 완료 기준: 위 위치의 설명이 코드와 맞는다. - 검증 방법: 문서 리뷰. -### NN-14 — DLQ 격리 레코드가 모든 원인을 `POISON_MESSAGE`로 적는다 +### 06-14 — DLQ 격리 레코드가 모든 원인을 `POISON_MESSAGE`로 적는다 - 성격: 개선 제안 - 관련 관점: 8, 28 @@ -355,7 +355,7 @@ - claim은 `FOR UPDATE SKIP LOCKED`, 인스턴스마다 UUID owner, row마다 token 증가(`JpaOutboxStore.java:105-127`). - 완료는 owner·token이 맞을 때만 적용된다. 아니면 STALE(`:136-162`). `PostgreSqlOutboxConcurrentRelayIntegrationTest`가 있다. - 같은 aggregate의 두 row는 두 인스턴스가 동시에 가져갈 수 없다. 앞 row가 PUBLISHED가 아니면 뒤 row는 gate에 걸린다. -- 남은 위험: 배치 시간이 lease를 넘는 설정(NN-12). +- 남은 위험: 배치 시간이 lease를 넘는 설정(06-12). ### 4.4 외부 응답 지연·유실 (Kafka 느림·정지) @@ -373,7 +373,7 @@ - outbox row는 append 때의 바이트를 그대로 내보낸다. 배포가 바뀌어도 옛 row의 봉투는 변하지 않는다. - destination 선언이 새 배포에서 빠지면 옛 row는 `PUBLISH_PREPARATION_FAILED` REJECTED → DEAD가 된다. 이것은 설정 오류라 확정 거부로 보는 것이 맞다. -- payload 버전 호환성 검사와 절차가 없다(NN-10). +- payload 버전 호환성 검사와 절차가 없다(06-10). ### 4.7 선택 어댑터 제거 @@ -416,7 +416,7 @@ 1. 필요한 것: application은 검증된 봉투를 같은 트랜잭션에 기록하는 outbox가 필요하다. platform은 제품으로서 자기 outbox를 가진다. 2. 지킬 성질: 개발자가 어느 outbox가 동작 중인지 헷갈리지 않는다. platform의 종료·지표 설계가 앱 경로에도 맞는다. -3. 현재 보장: bean 조건으로 vendored relay가 앱에서 생기지 않는다. 문서·종료 순서는 vendored relay 기준이다(06-02, NN-11). +3. 현재 보장: bean 조건으로 vendored relay가 앱에서 생기지 않는다. 문서·종료 순서는 vendored relay 기준이다(06-02, 06-11). 4. 대안: (a) 결정 유지 + 경계 표시 보강, (b) vendored outbox를 starter `implementation`에서 빼서 opt-in 의존으로, (c) 하나로 합치기. 5. 비용: (a) 문서·주석 수정. (b) starter 의존 정리와 vendored 테스트 classpath 조정. (c) 결정 번복. 6. 선택: (a)를 먼저, (b)는 다음 단계 후보. 결정은 유지한다. @@ -445,7 +445,7 @@ - 이벤트 소비(handler 위치, inbox 조립) 예제와 leaf(06-08). - aggregate 순서 번호를 만드는 올바른 예(06-07). -- payload 버전 올리기 절차와 호환성 테스트(NN-10). +- payload 버전 올리기 절차와 호환성 테스트(06-10). - 앱 relay를 실제 Kafka로 돌리는 테스트 틀(06-09). - `MessagePublisher` fake와 본체의 공통 계약(TEST-FAKE-MessagePublisher). @@ -457,7 +457,7 @@ 4. payload를 바꾸는가? 바꾸면 새 `payloadVersion`을 추가하고 소비자가 먼저 두 버전을 읽게 한다. 5. 이 destination의 소비자는 부작용이 있는가? 있으면 INBOX_TRANSACTIONAL을 쓴다. 6. 한 aggregate가 초당 몇 건을 만드는가? 0.2건/초를 넘으면 현재 relay 기본값으로는 지연이 쌓인다(06-04). -7. relay를 몇 개 인스턴스에서 켤 것인가? batch-size를 올리면 lease 시간과 함께 계산한다(NN-12). +7. relay를 몇 개 인스턴스에서 켤 것인가? batch-size를 올리면 lease 시간과 함께 계산한다(06-12). ## 8. 28개 관점 판정표 @@ -467,27 +467,27 @@ | --- | --- | --- | --- | | 1 | 코드 성숙도 | P | 실패 경로를 의식한 코드가 많다. platform과 application 사이 실패 의미 번역에 결함(06-01, 06-06) | | 2 | 구조적 성숙도 | P | 발행 경로는 port → bridge → platform으로 깨끗하다. 소비 경로에 application leaf가 없다(06-08) | -| 3 | 변경 용이성 | P | 새 이벤트 추가 경로는 짧다. payload 버전 변경 경로가 없다(NN-10) | -| 4 | 인지 부하 | P | 두 outbox 모델과 반대 뜻의 상태 이름(NN-11) | +| 3 | 변경 용이성 | P | 새 이벤트 추가 경로는 짧다. payload 버전 변경 경로가 없다(06-10) | +| 4 | 인지 부하 | P | 두 outbox 모델과 반대 뜻의 상태 이름(06-11) | | 5 | 위험 가시성 | P | 중복 가능 구간은 README에 있다. "REJECTED = 영구"라는 가정이 코드에서 보이지 않는다(06-01) | | 6 | 실패 성숙도 | X | 일시 거부·종료·짧은 장애가 영구 DEAD로 이어진다(06-01, 06-02, 06-03) | | 7 | 운영 성숙도 | P | runbook·경보·구조화 ERROR가 있다. relay 꺼짐·실패 중 지표 정지(06-05), runbook 조회가 옛 키 | -| 8 | 디버깅 가능성 | P | failure report에 event·aggregate·correlation id가 있다. DLQ 사유가 한 값(NN-14) | -| 9 | 유지보수 성숙도 | P | 주석·README에 낡은 위치 설명(NN-13) | +| 8 | 디버깅 가능성 | P | failure report에 event·aggregate·correlation id가 있다. DLQ 사유가 한 값(06-14) | +| 9 | 유지보수 성숙도 | P | 주석·README에 낡은 위치 설명(06-13) | | 10 | 테스트 성숙도 | P | 단위 테스트 촘촘하고 빠름(합계 수 초). 앱 경로 실연 테스트 없음(06-09), 지표 변이 생존(06-05) | | 11 | 데이터 성숙도 | P | 봉투 바이트·hash 보존이 좋다. 순서 키 유일 제약 없음(06-07) | -| 12 | 동시성 성숙도 | P | SKIP LOCKED + fencing은 좋다. 배치·lease 관계 미검사(NN-12), 종료 순서(06-02) | +| 12 | 동시성 성숙도 | P | SKIP LOCKED + fencing은 좋다. 배치·lease 관계 미검사(06-12), 종료 순서(06-02) | | 13 | 확장성 | P | 인스턴스 수평 확장은 된다. aggregate당 처리량 상한(06-04) | | 14 | 성능 성숙도 | ? | 계산만 했다. 실측 없음. 회차당 약 43 DB 문장, 인스턴스당 최대 약 4건/초 | | 15 | 보안 성숙도 | O | Kafka TLS/SASL·ACL 적용 확인(M-2 해결). 실패 report에 payload를 싣지 못하게 타입으로 막음 | | 16 | 의존성 성숙도 | P | broker SDK는 선택 줄을 지우면 빠진다. starter가 쓰지 않는 vendored outbox 구현을 `implementation`으로 싣는다 | -| 17 | API / Contract 성숙도 | P | 봉투 v1 schema와 hash 검사가 있다. EventId/MessageId 불일치(06-06), payload 호환성 없음(NN-10) | +| 17 | API / Contract 성숙도 | P | 봉투 v1 schema와 hash 검사가 있다. EventId/MessageId 불일치(06-06), payload 호환성 없음(06-10) | | 18 | 배포 성숙도 | X | 배포 종료 중 row가 DEAD가 될 수 있다(06-02). broker 실연 lane이 기본 게이트 밖(06-09) | -| 19 | 설정 성숙도 | P | strict 바인딩, producer-id 필수. relay 기본 꺼짐의 결과가 안 보임(06-05), 값 사이 관계 미검사(NN-12) | -| 20 | 개발자 경험 | P | 발행 한 줄 켜기가 쉽다. 소비·버전·순서 번호 안내가 없다(06-07, 06-08, NN-10) | +| 19 | 설정 성숙도 | P | strict 바인딩, producer-id 필수. relay 기본 꺼짐의 결과가 안 보임(06-05), 값 사이 관계 미검사(06-12) | +| 20 | 개발자 경험 | P | 발행 한 줄 켜기가 쉽다. 소비·버전·순서 번호 안내가 없다(06-07, 06-08, 06-10) | | 21 | Guardrail 성숙도 | P | caller 트랜잭션 강제, 대역 publisher 금지, producer-id 필수가 좋다. 이벤트 id·순서 번호·설정 조합 가드 없음 | | 22 | 추상화 성숙도 | P | bridge는 필요한 만큼만 안다. outcome 어휘가 platform 의미 하나를 담지 못한다(06-01) | -| 23 | 일관성 | P | platform 종료 설계와 앱 relay 방식이 다르다(06-02, NN-11) | +| 23 | 일관성 | P | platform 종료 설계와 앱 relay 방식이 다르다(06-02, 06-11) | | 24 | 네이밍 / 의미 성숙도 | P | `OutboxLeaderElectionToken`이 하지 않는 일을 이름으로 말한다. 두 outbox의 FAILED 의미 반대 | | 25 | 조직 확장성 | P | 발행은 팀별로 독립 추가 가능. 소비는 registry 간선을 각자 만들게 된다(06-08) | | 26 | Ownership 성숙도 | P | leaf README가 근거를 잘 남긴다. composition·messaging-kafka에 `CLAUDE.md` 없음 | diff --git a/docs/reviews/2026-11-01-maturity-review/README.md b/docs/reviews/2026-11-01-maturity-review/README.md index a35d064a..958b7158 100644 --- a/docs/reviews/2026-11-01-maturity-review/README.md +++ b/docs/reviews/2026-11-01-maturity-review/README.md @@ -196,7 +196,9 @@ ## 12. 발견 색인 -영역 문서에 36.3 양식으로 적힌 발견 119건: High 21 · Medium 64 · Low 34, P1 25 · P2 59 · P3 35. Critical 0. 두 영역이 같은 결함을 적은 묶음(07-03+09-03, 02-03+07-05, 08-01+04-04+03-12, 05-09+08-04, 04-09+09-01)은 색인에 각각 남기고 2절에서 합쳤다. 06·08 영역 문서는 원래 `NN-` 접두사로 적혀 있어 `06-`·`08-`로 바꿨다. +영역 문서에 36.3 양식으로 적힌 발견 **124건**: High 21 · Medium 67 · Low 36, P1 25 · P2 60 · P3 39. + +> **정정 (2026-11-03 재리뷰)**: 처음 이 색인은 119건이었다. 06 영역 문서가 `NN-` 접두사로 쓰여 있었는데 오케스트레이터가 `NN-0x`만 `06-0x`로 바꿔 `NN-10`~`NN-14` 5건이 색인과 모든 수정 묶음에서 빠졌다. 13~16절의 "모든 발견 처리"는 이 5건에 대해 틀렸다. 5건은 `06-10`~`06-14`로 다시 매겨 아래 표에 넣었고, 재리뷰 수정(`../2026-11-03-rereview/README.md` 6절)에서 고쳤다. Critical 0. 두 영역이 같은 결함을 적은 묶음(07-03+09-03, 02-03+07-05, 08-01+04-04+03-12, 05-09+08-04, 04-09+09-01)은 색인에 각각 남기고 2절에서 합쳤다. 06·08 영역 문서는 원래 `NN-` 접두사로 적혀 있어 `06-`·`08-`로 바꿨다. | ID | 심각도 | 우선순위 | 내용 | |---|---|---|---| @@ -319,6 +321,11 @@ | [09-09](09-performance-measurement.md) | Low | P3 | persistence-jpa가 H2 드라이버를 운영 아티팩트에 실어 보냄 | | [09-10](09-performance-measurement.md) | Low | P3 | `local` 프로필이 `server.port`를 8080으로 고정 | | [09-11](09-performance-measurement.md) | Low | P3 | 기본 조합 jar에 Jackson 2·3과 kotlin-stdlib가 함께 실림 | +| [06-10](06-messaging.md) | Medium | P2 | 이벤트 payload 버전을 올리는 방법과 호환성 검사가 없다 (색인 누락 정정) | +| [06-11](06-messaging.md) | Medium | P3 | outbox가 둘인데 문서와 주석은 하나처럼 말한다 (색인 누락 정정) | +| [06-12](06-messaging.md) | Medium | P3 | 배치 크기와 lease 시간의 관계를 검사하지 않는다 (색인 누락 정정) | +| [06-13](06-messaging.md) | Low | P3 | 이 영역 문서·주석의 낡은 설명 (색인 누락 정정) | +| [06-14](06-messaging.md) | Low | P3 | DLQ 격리 레코드가 모든 원인을 `POISON_MESSAGE`로 적는다 (색인 누락 정정) | ## 13. 조치 현황 (개선 순서 1~3) diff --git a/docs/reviews/2026-11-03-rereview/README.md b/docs/reviews/2026-11-03-rereview/README.md index b6dee03d..484d3913 100644 --- a/docs/reviews/2026-11-03-rereview/README.md +++ b/docs/reviews/2026-11-03-rereview/README.md @@ -67,3 +67,46 @@ Minor 41건은 각 문서에 있다. ## 5. 다음 위 Important 전부, Minor 41건, 06-10~14를 영역별 수정 묶음으로 고친다. 각 묶음은 `5786126c`에서 만든 worktree에서 RED→GREEN, 오케스트레이터가 합쳐 전체 게이트 후 커밋·push한다. 결과는 이 문서 6절. + +## 6. 수정 결과 (2026-11-03) + +영역별 수정 묶음 7개가 `5786126c`(r4-G는 A·B·C·D·F를 합친 임시 기준)에서 `test-driven-development` 스킬 절차로 RED→GREEN 했고, 오케스트레이터가 합쳤다. 하위 에이전트 없음. + +| 묶음 | 상태 | 검증 (에이전트) | 처리 내용 | 결정·합칠 때 조치·남은 것 | +|---|---|---|---|---| +| r4-a | 완료 | leaf check 9, cache-redis test, architectureCheck, jpaPlatformContractTest fileserver 47, outbox sequence PG, verifyFeatureScaffold, 소유자 규칙 변이 잡힘 | RR-01-02=RR-07-01 @SystemInvoked bean 기동 실패+ArchUnit, RR-01-01·07·10 생성 명령, RR-01-03·09 매뉴얼·IntegrationEventDrafts ArchUnit, RR-01-04+RR-07-06 fileserver 계약 6개·fake 정합·소유자 정본 FileAccessSubject.owns(RED 17), RR-01-05=RR-04-04 move 쿼터(RED 2), RR-01-06 순서 계약 보강, RR-01-08 | 합칠 때 매뉴얼 09장·OutboxAggregateSequenceContract를 r4-c와 수동 병합(r4-a 새 케이스는 첫 번호 기준 상대값이라 floor와 충돌 없음). 결정: 만료·미해제 예약 확정은 받음, move는 복사 후 삭제 안 씀 | +| r4-b | 완료(sample 데모 체인 한 줄은 r4-f로) | leaf check 6, graphql·web systemTest, webJettyCompat, -p optional-platforms ci integrationCheck(ledger PG 41), architectureCheck, verifyEnvKeys, documentContractTest, verifyPublicPathSnapshot, 영향 모듈 test | RR-02-01 union 복잡도, RR-02-02 EnvelopeErrorController+ERROR 디스패치만 허용(JWT 체인 401→400), RR-02-03 IDEMPOTENCY_COMPLETION_UNKNOWN(503 재시도 가능), RR-02-04 GrpcClaimToken·claim_attempt·V003(옛 owner commit 거부·실패 무시, 조건부 commit), RR-02-05 Retry-After 상수·lease 이하면 기동 실패, RR-02-06~08 | 결정: 새 코드 503(code로 구분), 시도 번호는 카운터, ERROR 디스패치 허용(보안 정책 변경) | +| r4-c | 완료 | leaf check 5, notification test, sample·app-bootstrap architectureTest, architectureCheck, 실 PG jpaPlatformContract 334·Migration 45·Failure 6·V21·runbook·트랜잭션 lane 등 skip 0 | RR-03-01 counter ON CONFLICT(RED 실 PG), RR-03-02=RR-05-02 V21 floor 테이블+counter 미리 생성+행 최대값 하한(RED 3), RR-03-05 lock_timeout 5s·무효 인덱스 거부·CONCURRENTLY 절차 runbook, RR-03-03 마감 초과 분류(H2+실 PG), RR-03-04 양쪽 매핑 양방향 금지, RR-03-06~10 | 결정: V21 직접 수정(아직 어디에도 미적용 — 적용한 개발 DB는 재생성), H2 호환 위해 다문장 counter, 계약 '1부터'→'첫 번호부터 1씩'(JPA 첫 번호 ≈1.7e15) | +| r4-d | 완료(RR-04-02 지표·RR-07-04 운영 거부 남음) | leaf check 6, Redis container 52·topology standalone, Toxiproxy 4, spring70 compat, perf, notification 문서·환경 계약, PG 멱등성 계약 14, verifyEnvKeys, architectureCheck, verifyStrictLaneStages, compose 정적 18 | RR-04-01 호출자 deadline은 breaker 미집계(RED), RR-04-03 JDK 스트리밍 read-idle(RED), RR-04-02 CacheScriptLane(기본 4), RR-04-05 lane 연결, RR-04-06~08·10·11, RR-07-03 SNS 4xx 거절+감사(RED), RR-07-04 ACL 파일 이름 lane-fixture-accounts.acl, RR-07-07 SNS MessageId 기준 | 결정: total-call이 끊은 시도는 실패로 셈, 캐시 lane 4. 남음: lane별 지표(meter registry 없음), 운영 SecretSourceValidator가 fixture- 값 거부 | +| r4-e | 완료 | 건드린 leaf 13 check, Kafka relay·inbox, outbox PG 6·migration·jpaPlatformContract, architectureCheck, verifyDependencyLocks, verifyStrictLaneStages, documentContractTest | RR-05-01 재발행 SQL deferred 초기화+runbook SQL lane(RED 실 PG), RR-05-03 last_failure_code(V22)·오래 재시도 게이지·PARKED·runbook SQL(RED 4), RR-05-04 draft가 비UUIDv7 거부, RR-05-05~09, 06-10 schema 버전 해시 고정, 06-11~14 | 합칠 때 4곳 수동 병합: OrderKeyRunbook IT를 공용 OutboxRunbookSql로 + V22 추가로 latest가 22가 되어 'V21 적용' 단언을 applied 목록 기준으로, sha256에 V22, application-core README, 매뉴얼 09. 결정: PARKED는 DDL 없이, 발행 포트·저장소 포트 시그니처 변경(파생 서비스 깨짐), 오래 재시도 기준 10회, DB CHECK 제약 안 넣음. 남음: 2026-11-01 README 색인 정정(오케스트레이터), V21 주석의 없는 클래스명 | +| r4-f | 완료 | build-logic 107, ci, app-bootstrap documentContract·systemTest, sample check·webSystemTest·integrationTest·posterImageMigration, -p optional-platforms ci, 두 빌드 verifyStrictLaneStages, verifyEnvKeys, compose 정적 | RR-06-01=RR-04-09 규칙 생성 중 다른 singleton 생기면 기동 실패(RED), RR-06-02 lane 정책을 Test 입력으로(RED), RR-06-03·04 optional 빌드 단계 검사·-x/continue-on-error/if 해석(RED), RR-07-02 데모 계정 허용 목록 local·test·demo(RED 6), RR-06-05+07-05 CSRF 제외 축소·sample qualityCheck, RR-06-06~12, RR-02-02 샘플 체인 ERROR 디스패치 허용 | 남음: cache-redis 컨테이너 lane main 단계 중복 실행. 결정: release job --rerun-tasks 안 넣음 | +| r4-g | 완료 | redis-runtime 64·redis-sdk 310·cache-redis 192·app-bootstrap test 222·systemTest 11·documentContract 60, redisContainerContract 53, topology standalone, verifyEnvKeys, architectureCheck, verifyDependencyLocks, verifyStrictLaneStages | RR-04-02 redis.lane.* 지표 6개(RED 10), RR-07-04 prod에서 fixture- 값 거부(RED), cache-redis 컨테이너 lane main 중복 제거 | 합친 뒤 오케스트레이터: r4-g가 찾은 '레지스트리의 redis.capability.* 6개를 아무 코드도 내보내지 않음' → 레지스트리에서 빼고 incident runbook을 redis.lane.* 기준으로, cache-redis README에 미구현 지표로 기록. 남음(의도): httpclient failure injection lane main 2회(05-06/05-16 결정) | + +### 6.1 합칠 때 오케스트레이터가 고친 것 + +- 수동 병합: 매뉴얼 09장(r4-A·r4-C·r4-E), `OutboxAggregateSequenceContract`(r4-A·r4-C), `PostgreSqlOutboxOrderKeyRunbookIntegrationTest`(r4-C·r4-E — 공용 `OutboxRunbookSql`로, V22가 생겨 "V21 적용" 단언을 적용 목록 기준으로), `applied-migrations.sha256`(V22), application-core README. +- r4-G가 찾은 거짓 선언: `docs/registries/metrics.yaml`의 `redis.capability.*` 6개를 어떤 코드도 내보내지 않았고 incident runbook이 그것을 보라고 했다. 레지스트리에서 빼고 runbook을 실제로 나오는 `redis.lane.*` 기준으로 고쳤다. 원래 설계는 cache-redis README 「아직 내보내지 않는 지표」. +- 최종 게이트에서 드러난 2건: (1) sample `CreatePosterConcurrencyIntegrationTest`가 v4 event id를 써서 RR-05-04 이후 16건 모두 거부 → 운영과 같은 `UuidOutboxEventIdFactory`로. (2) `EnvelopeErrorController`의 `@RequestMapping`이 FindSecBugs `SPRING_CSRF_UNRESTRICTED_REQUEST_MAPPING` → 오류 디스패치 전용(보안 체인이 ERROR dispatch만 허용)이라 그 메서드에만 이유를 단 제외. +- 원래 리뷰 README 12절 색인에 06-10~06-14를 넣고 발견 수를 124건으로 정정했다. + +## 7. 게이트 (2026-11-03, 합친 메인 작업 트리, 공유 잠금) + +첫 실행(22:27)은 `ci`(FindSecBugs 1건)와 `integrationCheck`(sample 동시 생성 테스트)가 실패했고 6.1절대로 고쳤다. 재실행 결과: + +| 게이트 | 결과 | 시간 | 실행 직전 부하 | +|---|---|---|---| +| `ci` | rc=0 | 215초 | load 8.27 | +| `:integrationCheck` | rc=0 | 1,647초(부하 높음) | load 29.15 | +| `mainCheck` | rc=0 | 260초 | load 35.16 | +| `-p optional-platforms ci integrationCheck performanceCheck` | rc=0 | 62초 | load 16.51 (첫 실행, 두 수정과 무관) | +| `:performanceCheck` | rc=0 | 25초 | load 20.55 (첫 실행) | +| `:releaseCheck -PgitRevision=` | rc=0 | 4초 | 첫 실행 | +| `scripts/verify-compose-profile-contracts.sh` | rc=0, 18 lane | — | 첫 실행 | + +## 8. 남은 것 + +- **의도적으로 둔 것**: httpclient failure-injection lane이 main 단계에서 두 번 돈다(원래 리뷰 05-06·05-16 결정). capability 단위 Redis 지표(`redis.capability.*`)는 설계만 있고 구현하지 않았다(새 기능 범위, cache-redis README). +- **소유자 확인이 필요한 결정**: 4절 표, 그리고 묶음이 기본값으로 정한 것(6절 "결정" 칸) — 특히 서블릿 오류 디스패치 허용(보안 정책), 데모 계정 허용 목록, V21을 V22 없이 직접 수정(이 브랜치의 V21을 적용한 개발 DB는 재생성), 발행·저장소 포트 시그니처 변경, `IDEMPOTENCY_COMPLETION_UNKNOWN` 신설, prod에서 `fixture-` 값 거부. +- **짝 프론트**: `IDEMPOTENCY_COMPLETION_UNKNOWN`(503, 결과 불명)을 인계 문서에 더했다. +- **이 환경에서 확인할 수 없는 것**: 실제 CI runner 실행. + diff --git a/docs/runbooks/grpc-platform-operations.md b/docs/runbooks/grpc-platform-operations.md index 0b632126..aa896ec7 100644 --- a/docs/runbooks/grpc-platform-operations.md +++ b/docs/runbooks/grpc-platform-operations.md @@ -44,7 +44,9 @@ the time, and which half is not knowable from the status. and a later reconciler pass sees that attempt's `COMMITTED` or `FAILED_TERMINAL`. Until a retry arrives, the case stays pending. The re-run is safe only when the ledger commit is recorded in the mutation's own transaction; if this service commits them separately, check the business resource - before letting the retry through. + before letting the retry through. An owner that was only slow cannot spoil the takeover: its claim + attempt (`claim_attempt`) is behind, so its late commit is refused and its late failure ignored. + A log line saying an operation "is no longer held by attempt N" is that refusal, not an outage. **Escalate when** the reconciler's pending list grows across passes. That means the ledger is unreachable rather than slow. A case pending as `IN_PROGRESS` for longer than the claim TTL with no diff --git a/docs/runbooks/idempotency-unavailable.md b/docs/runbooks/idempotency-unavailable.md index f330c93f..423a05cc 100644 --- a/docs/runbooks/idempotency-unavailable.md +++ b/docs/runbooks/idempotency-unavailable.md @@ -1,10 +1,10 @@ --- title: Runbook — IDEMPOTENCY_UNAVAILABLE (멱등성 조정 저장소 사용 불가) category: TRANSIENT_DEPENDENCY -error_codes: [IDEMPOTENCY_UNAVAILABLE, IDEMPOTENCY_RECOVERY_REQUIRED] +error_codes: [IDEMPOTENCY_UNAVAILABLE, IDEMPOTENCY_COMPLETION_UNKNOWN, IDEMPOTENCY_RECOVERY_REQUIRED] severity: P2 owner: oncall -last_updated: 2026-09-28 +last_updated: 2026-11-03 status: active --- @@ -17,6 +17,10 @@ status: active - `IdempotencyExecutor` refused to run the action because the replay store (JPA or Redis, whichever `app.idempotency` selects) did not answer. Nothing was executed: the refusal happens before the action, so a client retry is safe. +- HTTP 503 `IDEMPOTENCY_COMPLETION_UNKNOWN` (`retryable=true`) is the same outage hitting after the + action ran: the store did not answer while the result was being recorded. Effects in the action's + own transaction rolled back; anything else it did (an outbound call, a message) may have happened. + This is not "nothing was executed". Clients resend with the same key. - HTTP 500 `IDEMPOTENCY_RECOVERY_REQUIRED` (`retryable=false`) means the opposite case: the store cannot tell whether an earlier attempt's external effect already happened. @@ -32,6 +36,10 @@ status: active ## Action - `IDEMPOTENCY_UNAVAILABLE`: restore the store; clients retry with the same key and backoff. +- `IDEMPOTENCY_COMPLETION_UNKNOWN`: restore the store, then check the effects outside the + transaction for the failed requests (the ERROR log line names the code). A same-key resend replays + a result that was in fact recorded, gets `IDEMPOTENT_IN_FLIGHT` while the attempt's lease lasts, + and `IDEMPOTENCY_RECOVERY_REQUIRED` after it — handle that one as below. - `IDEMPOTENCY_RECOVERY_REQUIRED`: do not ask the client to retry blindly. Confirm whether the downstream effect of the earlier attempt exists, then complete or release the record so the next request with that key replays or re-executes deterministically. diff --git a/docs/runbooks/job-timeout.md b/docs/runbooks/job-timeout.md index a474ab92..4c239492 100644 --- a/docs/runbooks/job-timeout.md +++ b/docs/runbooks/job-timeout.md @@ -4,7 +4,7 @@ category: TRANSIENT_DEPENDENCY error_codes: [JOB_TIMEOUT] severity: P2 owner: oncall -last_updated: 2026-06-13 +last_updated: 2026-11-03 status: stub --- @@ -48,7 +48,10 @@ status: stub ## 5. Escalation - 의존성 지연이 근본 원인이면 해당 의존성 오너에게 escalate -- shutdown 예산(20s) vs k8s `terminationGracePeriodSeconds`(30s) 정합 이슈면 플랫폼/런타임 오너에게 escalate +- 종료 예산은 차례로 더한 값이다: 웹 drain(`APP_SERVER_SHUTDOWN_TIMEOUT`, 기본 30s)이 끝난 뒤 async 대기 19s, + 합계 49s에 preStop(5s)과 여유를 더한다. k8s `terminationGracePeriodSeconds`가 이보다 작으면(예: 기본 30s) + async 대기 중 SIGKILL이다. compose는 60s(`docker-compose.yml` `stop_grace_period`, 합계는 + `DeveloperExperienceContractTest`가 검사). 정합 이슈면 플랫폼/런타임 오너에게 escalate ## 6. Recovery / Verification diff --git a/docs/runbooks/outbox-dead-letter.md b/docs/runbooks/outbox-dead-letter.md index e926abea..f0d212bd 100644 --- a/docs/runbooks/outbox-dead-letter.md +++ b/docs/runbooks/outbox-dead-letter.md @@ -4,7 +4,7 @@ category: INTERNAL error_codes: [OUTBOX_DEAD_LETTER] severity: P1 owner: oncall -last_updated: 2026-06-11 +last_updated: 2026-11-03 status: stub --- @@ -21,7 +21,12 @@ status: stub ## 2. First Response (5분 이내) ### Step 1 — 확인 -1. ERROR log에서 `OUTBOX_DEAD_LETTER` 라인 확인: `event_id`, `event_type`, `correlation_id`, 마지막 실패 원인 예외 추출 +1. ERROR log에서 `OUTBOX_DEAD_LETTER` 라인 확인: `event_id`, `event_type`, `correlation_id`, `error.reason`(원인 + 코드 — publisher가 붙인 코드, 없으면 거부 결과 이름, 분류되지 않은 예외면 그 타입 이름) 추출. 같은 값이 행의 + `last_failure_code`에 남는다. ERROR가 없고 WARN `outbox claim moved a row ... to DEAD`만 있으면 relay가 아니라 + claim이 행을 DEAD로 옮긴 것이다 — `error.reason`이 `ATTEMPT_COUNTERS_INCONSISTENT`면 `deferred_attempt_count`를 + 되돌리지 않은 수동 재발행이 원인이니 §4의 SQL로 다시 재발행한다. `UNREADABLE_ROW`면 행 자체가 event로 읽히지 + 않는다(canonical 봉투 없음, 저장된 해시와 바이트 불일치) 2. DB에서 DEAD row 확인: `SELECT * FROM outbox_event WHERE status = 'DEAD' ORDER BY occurred_at;` 3. **차단 영향 파악 (중요)**: strict per-aggregate FIFO 정책상 DEAD row는 같은 aggregate(`tenant_scope`, `aggregate_type`, `aggregate_id`)의 후행 이벤트를 계속 차단함. 순서는 `(aggregate_sequence, event_index)`로 비교한다(claim SQL `PostgreSqlOutboxClaimRepository`와 같은 키) — `SELECT count(*) FROM outbox_event b WHERE b.status <> 'PUBLISHED' AND EXISTS (SELECT 1 FROM outbox_event d WHERE d.status='DEAD' AND d.tenant_scope=b.tenant_scope AND d.aggregate_type=b.aggregate_type AND d.aggregate_id=b.aggregate_id AND (d.aggregate_sequence < b.aggregate_sequence OR (d.aggregate_sequence = b.aggregate_sequence AND d.event_index < b.event_index)));` @@ -42,14 +47,35 @@ status: stub ## 4. Mitigation (수동 처분 — 둘 중 하나) -- **재발행 (기본)**: 원인 해소 후 해당 row를 다시 claim 가능 상태로 되돌림 — - `UPDATE outbox_event SET status = 'PENDING', attempt_count = 0, next_attempt_at = now() WHERE event_id = '' AND status = 'DEAD';` - 장애 구간 전체를 한 번에 되돌리려면(원인이 해소된 것을 확인한 뒤): - `UPDATE outbox_event SET status = 'PENDING', attempt_count = 0, next_attempt_at = now() WHERE status = 'DEAD' AND occurred_at BETWEEN '<장애 시작>' AND '<장애 끝>';` (outbox_event에는 DEAD가 된 시각 컬럼이 없어 이벤트 발생 시각으로 고른다 — 먼저 같은 조건의 SELECT로 대상을 확인한다) - (consumer는 at-least-once + idempotencyKey dedupe 의무가 있으므로 중복 발행은 안전) -- **skip (영구 폐기)**: 이벤트가 더 이상 유효하지 않으면 PUBLISHED로 마킹해 FIFO 차단을 해제 — - `UPDATE outbox_event SET status = 'PUBLISHED' WHERE event_id = '' AND status = 'DEAD';` - ⚠️ skip은 다운스트림에 영구 이벤트 갭을 만든다 — 비즈니스 오너 승인 후에만 수행하고 incident 기록에 남김 +**재발행 (기본)**: 원인 해소 후 해당 row를 다시 claim 가능 상태로 되돌린다. 시도 횟수 두 개 +(`attempt_count`, `deferred_attempt_count`)를 함께 0으로 되돌린다. `attempt_count`만 되돌리면 다음 claim에서 +미룬 claim 수가 전체 claim 수보다 많아지고, claim은 그 행을 읽지 않고 다시 DEAD로 옮긴다(재리뷰 2026-11-03 +RR-05-01). + + +```sql +UPDATE outbox_event SET status = 'PENDING', attempt_count = 0, deferred_attempt_count = 0, next_attempt_at = now() WHERE event_id = '' AND status = 'DEAD'; +``` + +장애 구간 전체를 한 번에 되돌리려면(원인이 해소된 것을 확인한 뒤). outbox_event에는 DEAD가 된 시각 +컬럼이 없어 이벤트 발생 시각으로 고른다 — 먼저 같은 조건의 SELECT로 대상을 확인한다. + + +```sql +UPDATE outbox_event SET status = 'PENDING', attempt_count = 0, deferred_attempt_count = 0, next_attempt_at = now() WHERE status = 'DEAD' AND occurred_at BETWEEN '<장애 시작>' AND '<장애 끝>'; +``` + +consumer는 at-least-once + idempotencyKey dedupe 의무가 있으므로 중복 발행은 안전하다. + +**skip (영구 폐기)**: 이벤트가 더 이상 유효하지 않으면 PUBLISHED로 마킹해 FIFO 차단을 해제한다. +⚠️ skip은 다운스트림에 영구 이벤트 갭을 만든다 — 비즈니스 오너 승인 후에만 수행하고 incident 기록에 +남긴다. + + +```sql +UPDATE outbox_event SET status = 'PUBLISHED' WHERE event_id = '' AND status = 'DEAD'; +``` + - 장기: poison event 재발 방지(payload 계약 테스트 보강), DEAD 빈발 event_type의 producer 검증 강화 ## 5. Escalation @@ -67,7 +93,10 @@ status: stub - error-codes.yaml rows: `OUTBOX_DEAD_LETTER` (INTERNAL, retryable=false) - metrics.yaml: `outbox.publisher.published.total{outcome=DEAD}`, `outbox.pending.size{status=DEAD}`, `outbox.publisher.lag` -- 코드: `application-core` `PublishPendingOutboxEventsUseCase`(FAILED→DEAD 전이), `adapter-persistence` `outbox/OutboxEventJpaRepository`(FIFO 게이트 — DEAD가 후행 차단) +- 코드: `application-core` `PublishPendingOutboxEventsUseCase`(FAILED→DEAD 전이), `adapter:outbound:persistence-jpa` `outbox/postgresql/PostgreSqlOutboxClaimRepository`(FIFO 게이트 — DEAD가 후행 차단), `outbox/jpa/JpaOutboxStore#claimBatch`(읽을 수 없는 행을 claim 때 DEAD로) +- §4의 SQL 블록은 문서에서 그대로 읽어 실제 PostgreSQL에서 실행하는 테스트가 있다 + (`PostgreSqlOutboxDispositionRunbookIntegrationTest`, lane `postgresqlOutboxDispositionRunbookIntegrationTest`). + 블록을 고치면 그 lane을 다시 돌린다 - 관련 runbook: [[outbox-publish-failed]] - 관련 branch: [[feature-domain-event-outbox-contract]], [[feature-background-job-async-contract]] (max attempts/DLQ vocabulary SSOT) @@ -80,8 +109,58 @@ V21(`V21__outbox_aggregate_sequence.sql`)은 `outbox_event`의 순서 키 README 15절 결정). 같은 키의 행들은 claim gate가 순서를 정하지 못한 행이다. 그냥 넘기면 순서 위반이 숨는다. V21은 transaction 하나로 적용되므로, 실패하면 V21 전체가 롤백되고 V20 상태로 남는다. +V21이 하는 일은 세 가지 더 있다. + +- **floor 기록.** `outbox_aggregate_sequence_floor`에 V21 적용 시각(epoch 마이크로초)을 한 번 쓴다. 새로 + 생기는 aggregate counter는 이 값과 남은 행의 최대 번호 중 큰 값 다음에서 시작한다. 그래서 reaper가 + 행을 지운 aggregate, tenant scope가 바뀐 aggregate도 소비자가 이미 받은 벽시계 번호(약 1.7×10¹⁵)보다 + 작은 번호를 받지 않는다(리뷰 RR-03-02). 벽시계 번호를 쓴 적 없는 서비스도 첫 번호가 floor + 1이다. +- **counter 미리 만들기.** 남은 행이 있는 aggregate의 counter를 그 최대 번호로 만든다. +- **잠금 대기 5초.** 유일 인덱스는 만드는 동안 `outbox_event`에 SHARE 잠금을 건다. 그동안 outbox를 쓰는 + 업무 쓰기가 모두 멈춘다. V21은 `lock_timeout = 5s`로 잠금을 기다린다. 열린 outbox 쓰기 트랜잭션 때문에 + 5초 안에 못 잡으면 V21이 실패하고 V20에 남는다(`MIGRATION_FAILED`). 덜 바쁜 시각에 다시 배포하거나 + Step 0으로 인덱스를 먼저 만든다. + +rolling 배포 중 아직 옛 버전인 인스턴스가 벽시계 번호로 쓴 행은 floor보다 크다. 새 버전의 counter는 +그 aggregate의 가장 큰 행 번호보다 작아지지 않으므로 그 행 뒤에 번호를 준다. 서로 커밋되지 않은 채 +겹친 옛·새 쓰기 사이의 순서는 보장하지 않는다 — 옛 벽시계 방식도 보장하지 않던 것이다. + +tenant scope를 바꾼 서비스(샘플은 `portfolio` → 단일 scope)는 배포 전에 옛 scope의 미발행 행이 +없는지 확인한다. 옛 scope 행과 새 scope 행은 서로 다른 aggregate로 보여 claim gate가 서로를 막지 않고, +partition key도 달라 다른 partition으로 간다. + +```sql +SELECT tenant_scope, count(*) AS unpublished +FROM outbox_event +WHERE status <> 'PUBLISHED' +GROUP BY tenant_scope; +``` + V20 이하 DB를 V21 이상으로 올리는 배포 전에 아래 순서로 확인한다. +**Step 0 — (outbox가 큰 경우만) 순서 키 인덱스를 먼저 만든다** + +V21이 인덱스를 만드는 동안 outbox 쓰기가 멈춘다. reaper가 `outbox_event`를 보존 기간 안으로 줄이므로 +보통은 짧다. 그 시간도 멈출 수 없을 만큼 크면, Step 1~3으로 중복을 없앤 뒤 같은 이름·같은 열의 인덱스를 +`CONCURRENTLY`로 먼저 만든다. 쓰기를 막지 않는다. transaction 밖(autocommit)에서 실행한다. V21의 +`IF NOT EXISTS`가 이 인덱스를 그대로 쓴다. + + +```sql +CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS ux_outbox_event_aggregate_order + ON outbox_event (tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index); +``` + +`CONCURRENTLY` 빌드가 중복이나 중단으로 실패하면 INVALID 인덱스가 남는다. 이 인덱스는 유일성을 지키지 +않는다. V21은 이 이름의 인덱스가 유효한 유일 인덱스가 아니면 건너뛰지 않고 실패한다. 그때는 +`DROP INDEX CONCURRENTLY ux_outbox_event_aggregate_order;` 뒤 Step 1부터 다시 한다. 빌드가 아직 도는 +중에도 INVALID로 보이므로, 지우기 전에 `pg_stat_progress_create_index`에 진행 중인 빌드가 없는지 본다. + +V21 안에서 `CONCURRENTLY`를 쓰지 않은 이유: `CONCURRENTLY`는 transaction 안에서 돌 수 없다. V21을 +transaction 밖으로 빼면 중복을 만났을 때 "V21 전체 롤백, V20 그대로"가 깨지고, 반쯤 적용된 counter·floor와 +INVALID 인덱스가 남는다. 인덱스만 V22로 떼어 내도 실패 시 INVALID 인덱스와 Flyway 실패 이력이 남아 수동 +복구가 필요하다. 그래서 기본은 transaction 안 빌드 + 잠금 대기 5초, 큰 outbox는 이 Step 0이다. + **Step 1 — 중복 확인 (읽기 전용)** @@ -149,9 +228,10 @@ Step 1을 다시 돌려 0행이면 배포한다. 정리와 배포 사이에 옛 순서 번호를 만든 샘플 코드가 그 원인이었다). 그래도 V21은 실패하고 롤백될 뿐이니 Step 1부터 다시 한다. `outbox_event_v21_duplicates`는 확인이 끝나면 지운다. -확인 쿼리와 정리 SQL은 이 문서에서 그대로 읽어 실제 PostgreSQL에서 실행하는 테스트가 있다 -(`PostgreSqlOutboxOrderKeyRunbookIntegrationTest`, lane `postgresqlOutboxOrderKeyRunbookIntegrationTest`). -두 SQL 블록을 고치면 그 lane을 다시 돌린다. +확인 쿼리, 정리 SQL, Step 0의 인덱스 SQL은 이 문서에서 그대로 읽어 실제 PostgreSQL에서 실행하는 +테스트가 있다(`PostgreSqlOutboxOrderKeyRunbookIntegrationTest`, lane +`postgresqlOutboxOrderKeyRunbookIntegrationTest`). 같은 lane이 V21의 counter·floor, 잠금 대기 실패, +INVALID 인덱스 거부도 본다. 이 절의 `runbook-sql` 블록을 고치면 그 lane을 다시 돌린다. --- diff --git a/docs/runbooks/outbox-publish-failed.md b/docs/runbooks/outbox-publish-failed.md index 5d35c179..41e9dd6b 100644 --- a/docs/runbooks/outbox-publish-failed.md +++ b/docs/runbooks/outbox-publish-failed.md @@ -4,7 +4,7 @@ category: TRANSIENT_DEPENDENCY error_codes: [OUTBOX_PUBLISH_FAILED] severity: P2 owner: oncall -last_updated: 2026-06-11 +last_updated: 2026-11-03 status: stub --- @@ -14,17 +14,23 @@ status: stub 이 runbook은 다음 alert에서 발동됩니다. -- alert name: `outbox_publish_failed_rate` 또는 `outbox_publisher_lag` -- alert payload 필수 field: `error.code=OUTBOX_PUBLISH_FAILED`, `event_type`, `correlation_id`, `runbook_link` +- alert name: `outbox_publish_failed_rate`, `outbox_publisher_lag` 또는 `outbox_retry_long` +- alert payload 필수 field: `error.code=OUTBOX_PUBLISH_FAILED`, `error.reason`, `event_type`, `correlation_id`, `runbook_link` - 임계 (metrics.yaml verbatim): - P2: `outbox.publisher.published.total{outcome=FAILED}` rate > 1% for 10m - P2: `outbox.publisher.lag` > 60s for 10m / P1: > 300s for 5m - P2: `outbox.pending.size{status=PENDING}` growing for 10m + - P2: `outbox.retry.long.size` > 0 for 10m — §4.1 "끝나지 않는 재시도"로 간다 ## 2. First Response (5분 이내) ### Step 1 — 확인 -1. ERROR log에서 `OUTBOX_PUBLISH_FAILED` 라인 확인: `event_type`, `event_id`, `correlation_id`, `attempt_count` 추출 +1. ERROR log에서 `OUTBOX_PUBLISH_FAILED` 라인 확인: `event_type`, `event_id`, `correlation_id`, `attempt_count`, + `error.reason` 추출. `error.reason`이 원인 코드다 — publisher가 붙인 코드(예: `KAFKA_AUTHENTICATIONEXCEPTION`, + `KAFKA_TRANSPORT_CLOSED`, `PUBLISH_RUNTIME_UNAVAILABLE`, `PUBLISH_DEADLINE_EXCEEDED`), 코드가 없으면 결과 + 이름(`AMBIGUOUS`, `REJECTED_RETRYABLE`), 분류되지 않고 던져진 실패면 예외 타입 이름이다. 같은 값이 행의 + `last_failure_code`에도 남는다. `error.cause_type`은 어느 결과였는지만 말한다(`OutboxPublishRefusedException`이면 + 거부, `OutboxPublishAmbiguousException`이면 응답 없음) 2. broker 상태 확인: `APP_MESSAGING_BROKER` 값과 broker endpoint 가용성. 이 키는 활성화 스위치가 아니라 **선택자**다 — messaging을 끄는 것은 `APP_MESSAGING_ENABLED=false`이고, 이 값을 비운다고 messaging이 꺼지지는 않는다. @@ -40,8 +46,12 @@ status: stub 3. `outbox.pending.size` status 분포 확인 (FAILED 누적 vs PENDING 누적) ### Step 2 — 임시 격리 -- 일시 실패는 자동 backoff 재시도(30s × 2^(attempt-1) + jitter, 상한 5분)가 동작 — 즉시 수동 개입 불필요 +- 일시 실패는 자동 backoff 재시도(30s × 2^(attempt-1) + jitter, 상한 5분)가 동작 — broker 장애처럼 원인이 저절로 + 풀리는 경우는 수동 개입이 필요 없다 - broker 정지·종료 중 거부·Kafka 인증/인가 실패(`AMBIGUOUS`, `REJECTED_RETRYABLE`)는 시도 예산을 쓰지 않는다 — 장애가 길어도 DEAD가 되지 않고, broker가 돌아오면 늦어도 약 5분 30초 안에 자동 재발행된다 +- **그 대신 끝이 없다.** 원인이 저절로 풀리지 않으면(진짜로 틀린 credential·ACL, Kafka adapter가 이름을 모르는 + broker 거부 — topic timestamp 정책, 없는 topic의 metadata 대기 초과는 기본값으로 `AMBIGUOUS`가 된다) 그 행은 5분 + 간격으로 영원히 FAILED가 되고 그 aggregate의 뒤 이벤트를 막는다. `outbox.retry.long.size` > 0이면 §4.1로 간다 - max attempts 3은 adapter가 분류하지 못하고 던진 발행 예외에만 적용된다 (소진 시 `runbook://outbox/dead-letter`로 이관) - relay 자체를 멈춰야 하면 `app.outbox.relay-enabled=false`로 스케줄러 비활성 (이벤트는 outbox 테이블에 안전하게 보존됨 — 유실 없음) @@ -57,7 +67,10 @@ status: stub - broker outage/네트워크 → broker 측 회복 대기 - Kafka adapter 미구성(enabled인데 brokers 누락은 기동 시 차단됨) / disabled 상태에서 producer 활성화 - poison event (직렬화 불가/payload 계약 위반) → 확정 거부(`REJECTED_*`)면 바로, 분류되지 않은 예외면 attempts 소진 후 DEAD로 흘러감 (의도된 동작) - - 같은 행의 `OUTBOX_PUBLISH_FAILED`가 5분 간격으로 끝없이 반복되고 원인이 Kafka 인증/인가면 credential·ACL이 실제로 틀린 것이다 — 고치면 다음 재시도에서 저절로 빠진다 + - 같은 행의 `OUTBOX_PUBLISH_FAILED`가 5분 간격으로 끝없이 반복되면 §4.1의 조회로 그 행의 `last_failure_code`를 + 본다. `KAFKA_AUTHENTICATIONEXCEPTION`·`KAFKA_*AUTHORIZATIONEXCEPTION`이면 credential·ACL이 실제로 틀린 + 것이다 — 고치면 다음 재시도에서 저절로 빠진다. 그 밖의 코드가 같은 행에서만 반복되면 broker가 그 레코드를 + 받지 않는 것이다 — §4.1로 보류한다 - 동일 aggregate head 실패로 후행 이벤트가 FIFO 게이트에 차단되어 lag 증가 (strict per-aggregate FIFO — 설계 의도) ## 4. Mitigation @@ -66,6 +79,61 @@ status: stub - IN_FLIGHT orphan(claim 후 crash)은 in-flight-timeout(기본 PT5M) 경과 후 자동 재claim — at-least-once이므로 중복 발행 가능, consumer dedupe(idempotencyKey)가 흡수 - 장기: `app.outbox.poll-interval`/`batch-size` 조정, broker 가용성 SLA 점검, 빈발 event_type의 payload 계약 검토 +### 4.1 끝나지 않는 재시도 — 찾기, 보류(park), 재개(resume), 버리기(skip) + +시도 예산을 쓰지 않는 실패(§2 Step 2)는 끝 상태가 없다. 리뷰 2026-11-01 README 15절 결정(재시도 유지)은 그대로 두고, +운영자가 그런 행을 보고 멈출 수 있게 한다(재리뷰 2026-11-03 RR-05-03 결정). + +**Step 1 — 찾기 (읽기 전용).** 미룬 claim(`deferred_attempt_count`)이 10번 이상인 FAILED 행이다. backoff 상한이 +5분이라 10번은 적어도 약 35분 동안 계속 실패했다는 뜻이다. `outbox.retry.long.size`·`outbox.retry.long.age`가 +같은 기준(`OutboxMetrics.LONG_RETRY_DEFERRED_CLAIMS`)으로 센다. + + +```sql +SELECT event_id, event_type, aggregate_type, aggregate_id, attempt_count, deferred_attempt_count, + last_failure_code, occurred_at, next_attempt_at +FROM outbox_event +WHERE status = 'FAILED' + AND deferred_attempt_count >= 10 +ORDER BY occurred_at, event_id; +``` + +`last_failure_code`로 원인을 가른다(§3). 원인이 고쳐지는 것(credential·ACL·topic 설정)이면 고치고 기다린다 — +다음 재시도에서 저절로 빠진다. 고칠 때까지 재시도 소음과 실패 로그를 멈추고 싶거나, 그 레코드만 broker가 +받지 않는 것이면 Step 2로 보류한다. + +**Step 2 — 보류(park).** FAILED 행 하나를 `PARKED`로 둔다. relay는 PARKED 행을 claim하지 않는다. 그 행은 +여전히 미발행이라 같은 aggregate의 뒤 이벤트를 계속 막는다 — 순서는 지킨다. `outbox.publisher.lag`도 계속 +오른다. 보류는 원인을 찾는 동안 재시도만 멈추는 것이지 incident를 닫는 것이 아니다. + + +```sql +UPDATE outbox_event SET status = 'PARKED' WHERE event_id = '' AND status = 'FAILED'; +``` + +`UPDATE 0`이면 그 사이 relay가 행을 claim해 IN_FLIGHT다. `next_attempt_at`이 지난 뒤 다시 실행한다. +보류된 행 수는 `outbox.pending.size{status=PARKED}`로 보인다. + +**Step 3 — 재개(resume) 또는 버리기(skip).** 원인을 고쳤으면 재개한다. 행은 FAILED로 돌아가 바로 claim +대상이 된다. 시도 횟수는 그대로 둔다(미룬 claim은 예산을 쓰지 않으므로 DEAD로 바로 가지 않는다). + + +```sql +UPDATE outbox_event SET status = 'FAILED', next_attempt_at = now() WHERE event_id = '' AND status = 'PARKED'; +``` + +그 이벤트를 영원히 보내지 않기로 했으면 버린다. DEAD skip과 같은 승인 조건이다 — 다운스트림에 영구 이벤트 +갭이 생기므로 비즈니스 오너 승인 후에만 하고 incident 기록에 남긴다. + + +```sql +UPDATE outbox_event SET status = 'PUBLISHED' WHERE event_id = '' AND status = 'PARKED'; +``` + +이 절의 SQL 블록은 문서에서 그대로 읽어 실제 PostgreSQL에서 실행하는 테스트가 있다 +(`PostgreSqlOutboxDispositionRunbookIntegrationTest`, lane `postgresqlOutboxDispositionRunbookIntegrationTest`). +블록을 고치면 그 lane을 다시 돌린다. + ## 5. Escalation - P1 lag(>300s 5m) 지속 + broker 회복 불가면 broker/infra 팀에 page @@ -79,8 +147,8 @@ status: stub ## 7. Related - error-codes.yaml rows: `OUTBOX_PUBLISH_FAILED` (TRANSIENT_DEPENDENCY, retryable=true, retry_after 30s) -- metrics.yaml: `outbox.publisher.published.total`, `outbox.publisher.lag`, `outbox.pending.size` -- 코드: `application-core` `PublishPendingOutboxEventsUseCase`(상태머신), `adapter-persistence` `outbox/OutboxEventJpaRepository`(SKIP LOCKED claim + FIFO 게이트), `adapter-outbound` `messaging/outbox/KafkaOutboxMessagePublishAdapter`(fail-closed) +- metrics.yaml: `outbox.publisher.published.total`, `outbox.publisher.lag`, `outbox.pending.size`, `outbox.retry.long.size`, `outbox.retry.long.age` +- 코드: `application-core` `PublishPendingOutboxEventsUseCase`(상태머신), `adapter:outbound:persistence-jpa` `outbox/postgresql/PostgreSqlOutboxClaimRepository`(SKIP LOCKED claim + FIFO 게이트), `adapter:outbound:messaging` `outbox/OutboxMessagePublishAdapter`·`platformbridge/PlatformIntegrationEventPublishAdapter`(fail-closed, 원인 코드 번역) - 관련 runbook: [[outbox-dead-letter]] - 관련 branch: [[feature-domain-event-outbox-contract]], [[feature-background-job-async-contract]] (retry/DLQ vocabulary SSOT) diff --git a/docs/runbooks/redis-capability-incident.md b/docs/runbooks/redis-capability-incident.md index 4c17b104..a40d93b4 100644 --- a/docs/runbooks/redis-capability-incident.md +++ b/docs/runbooks/redis-capability-incident.md @@ -34,20 +34,19 @@ Redis liveness 실패만으로 pod를 재시작하지 않는다. 재시작 폭 - `evictionValidation=CONFIGURED_EXPECTATION_ONLY`와 `externalEvictionAttestation=INCOMPLETE`는 effective server policy가 증명되지 않았다는 뜻이다. 이를 정상 attestation으로 해석하지 않는다. -- `redis.capability.operations.total`과 `redis.capability.duration.seconds`에서 affected - capability/role/operation의 실제 반환 outcome을 확인한다. mutation의 - `certainty=indeterminate`는 timeout이나 연결 끊김을 미실행 증거로 바꾸지 않는다. -- `redis.capability.admission.rejected.total`에서 `rejected_saturated`와 - `rejected_closed`를 구분하고, `redis.capability.inflight.total`의 같은 role에 대해 현재 0이 - 아닌 state를 확인한다. in-flight gauge는 bounded command count이며 byte 수나 queue depth가 - 아니다. -- `redis.capability.readiness.total`은 현재 상태 gauge가 아니라 exact sanitized - `RoleHealth` 관측 횟수다. 최신 health detail의 state/reason/requirement와 함께 해석한다. - optional cache의 degraded serving과 required coordination/session의 fail-closed 결정을 - 같은 availability 의미로 합치지 않는다. -- 종료 시 `redis.capability.lifecycle.drain.total`에서 `drained`, - `forced_after_timeout`, `interrupted`를 구분한다. repeated close는 새 drain을 시작하거나 - 중복 관측을 만들지 않는다. +- **지금 내보내는 Redis 지표는 connection lane 단위 `redis.lane.*`다**(`docs/registries/metrics.yaml`, + `lane` 태그). capability·operation 단위 지표(`redis.capability.*`)는 설계만 있고 아직 어떤 코드도 + 내보내지 않는다 — 대시보드에서 찾지 않는다(재리뷰 2026-11-03, `src/adapter/outbound/cache-redis/README.md` + 「아직 내보내지 않는 지표」). +- lane 포화: `redis.lane.acquire.refused.total`(거절)과 `redis.lane.acquire.wait.seconds`(대기)를 lane별로 + 본다. `CACHE_SCRIPT`만 차 있으면 캐시 조건부 쓰기의 문제이고, 멱등성·lease가 쓰는 `SCRIPT` lane은 + 따로 본다(재리뷰 RR-04-02). +- 연결 불안정: `redis.lane.connections.opened.total`·`redis.lane.connections.discarded.total`의 급증, + `redis.lane.connections.active`·`pending`. +- operation 결과(hit/miss/denied/conflict, `certainty=indeterminate`)는 지표가 아니라 각 capability의 + 로그와 health detail에서 확인한다. timeout이나 연결 끊김은 미실행 증거가 아니다. +- readiness는 최신 health detail의 state/reason/requirement로 본다. optional cache의 degraded serving과 + required coordination/session의 fail-closed 결정을 같은 availability 의미로 합치지 않는다. - reconnect, cache source-load, session repository error 지표의 변화를 함께 본다. - Redis server 측에서는 memory/eviction, rejected clients, replication link/lag, persistence error, Cluster coverage를 operator dashboard에서 확인한다. @@ -56,9 +55,8 @@ Redis liveness 실패만으로 pod를 재시작하지 않는다. 재시작 폭 ### Observability and lifecycle boundaries -- 여섯 `redis.capability.*` meter의 tag는 닫힌 enum에서만 생성된다. key, subject, session id, - token, endpoint, exception text, script/SHA, value 같은 identity/wire material을 metric이나 - ticket에 복사하지 않는다. +- `redis.lane.*` meter의 tag는 닫힌 lane 이름뿐이다. key, subject, session id, token, endpoint, + exception text, script/SHA, value 같은 identity/wire material을 metric이나 ticket에 복사하지 않는다. - semantic operation 계측은 logical provider가 실제로 반환한 hit/miss/denied/conflict/ unavailable/indeterminate 결과를 기록한다. cache의 `stale`/`skipped`, session의 `tombstoned`/`absolute_expired`도 정상 hit/miss와 분리한다. meter registry, classifier, diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index 09723148..1afecf1f 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -189,8 +189,8 @@ adapter leaf의 실 DB·Redis lane에서 돈다. fake가 실제와 다르게 동 `public interface *Port`)와, `application-notification`이 소유하고 `persistence-notification`이 구현하는 저장소 포트 전부다(review 04-14, 표에 `(notification)`으로 표시). notification 포트의 계약은 `application-notification` testFixtures에 있고, 실제 구현 쪽은 persistence-jpa의 `postgresqlIntegrationTest` -source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌린다. fileserver 포트는 -`application-fileserver` testFixtures의 `*PortContract`가 맡고 `persistence-fileserver/CLAUDE.md`에 적혀 있다. +source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌린다. fileserver 저장 포트는 +9.3에 있다. ### 9.1 계약이 있는 포트 @@ -248,8 +248,15 @@ source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌 고쳤다. in-memory store는 `DirectTransactionPort`를 받으면 같은 규칙(트랜잭션 밖·읽기 전용 거부, 롤백 시 취소)으로 동작한다. 인자 없이 만들면 지금처럼 바로 쓴다(relay 테스트가 행을 미리 심는 용도). - `IdempotencyStoreContract`의 시간 케이스(renew가 lease를 실제로 늘린다, review 05-02)는 시계를 - 가진 store(실 Redis, PostgreSQL)에서만 의미가 있다. in-memory fake는 만료가 없어 `elapse`가 - no-op이다. PostgreSQL에서 renew가 lease를 늘리지 않게 바꾼 변이로 이 케이스가 실패함을 확인했다. + 가진 store(실 Redis, PostgreSQL)에서만 의미가 있다. 시계를 움직일 수 없는 store(in-memory fake, + command fake 위 Redis)는 `elapse`를 재정의하지 않고, 기본 `elapse`가 그 케이스를 abort해 보고서에 + skipped로 남는다. 예전에는 no-op이라 시간이 흐르지 않은 채 통과했다(review 2026-11-03 RR-01-06). + PostgreSQL에서 renew가 lease를 늘리지 않게 바꾼 변이로 이 케이스가 실패함을 확인했다. +- `OutboxAggregateSequenceContract`는 포트 Javadoc의 세 약속 중 둘을 보지 않았다(RR-01-06). "쓰기 + 트랜잭션 밖 거부"와 "롤백된 번호는 다시 준다"를 넣었다. fake는 `DirectTransactionPort`를 받으면 같은 + 규칙으로 동작한다(인자 없이 만들면 예전처럼 트랜잭션을 보지 않는다 — sample 테스트가 쓰는 방식). + `CacheRegionContract`에는 2^53 위 revision 한 자리 차이 경우를 넣었다. fake가 revision을 double로 + 비교하게 바꾼 변이가 이제 실패한다(전에는 통과). notification 계약 다섯 개(deduplication·request·reconciliation job·admin operation·template, 2026-11-03)는 PostgreSQL 쪽에만 있던 테스트를 계약으로 옮긴 것이다. `ReconciliationJobClaimContractTest`(8건)와 @@ -301,6 +308,36 @@ r3-J: queue가 fence를 보지 않음(같은 worker 이름 재claim 1건), queue `SuppressionSideEffect`가 complaint를 INVALID로 기록함(1건). relay use case가 결과 조회 대신 예외만 보는 `publish`를 부르게 바꾸면 relay 테스트 7건이 실패한다. +### 9.3 application-fileserver 저장 포트 (review 2026-11-03 RR-01-04·RR-07-06) + +`persistence-fileserver`가 구현하는 포트 9개와 소유자 규칙 포트. 계약은 `application-fileserver` +testFixtures(`dev.caskeleton.application.fileserver.testkit`)에 있고, 실제 구현 쪽은 persistence-jpa의 +`postgresqlIntegrationTest` source set(`readiness` 패키지, 공용 기동 `FileserverPostgreSqlStack`)에서 태그 +`jpa-contract`로 `jpaPlatformContractTest` lane이 돌린다. 시간이 걸린 경우는 stack이 움직이는 시계로 본다. + +| 포트 | 계약 | fake | 상속하는 실제 구현 테스트 | +| --- | --- | --- | --- | +| `FileMetadataPort` | `FileMetadataPortContract` | `InMemoryFileMetadataStore` | `PostgreSqlFileserverMetadataStoreIntegrationTest` (`postgresqlFileserverMetadataIntegrationTest`) | +| `CleanupQueuePort` | `CleanupQueuePortContract` | `InMemoryCleanupQueue` | `PostgreSqlFileserverReclamationIntegrationTest` (`postgresqlFileserverReclamationIntegrationTest`) | +| `FileQuotaPort`·`QuotaCommitPort`·`QuotaReclaimPort` | `FileQuotaLedgerContract` — 세 포트가 한 장부라 한 계약 | `FakeFileQuotaService`(장부) + `FakeQuotaCommitGateway`·`RecordingQuotaReclaimGateway`(같은 장부에 쓴다) | `PostgreSqlFileQuotaLedgerContractTest` | +| `UploadSessionPort` | `UploadSessionPortContract` | `InMemoryUploadSessionStore` | `PostgreSqlUploadSessionContractTest` | +| `StagingUploadLocatorPort` | `StagingUploadLocatorPortContract` | `InMemoryUploadSessionStore`(같은 세션) | `PostgreSqlStagingUploadLocatorContractTest` | +| `RecoveryQueuePort` | `RecoveryQueuePortContract` | `InMemoryRecoveryQueue` | `PostgreSqlRecoveryQueueContractTest` | +| `ContentReferenceLedgerPort` | `ContentReferenceLedgerPortContract` | `InMemoryFileMetadataStore`(같은 레코드) | `PostgreSqlContentReferenceLedgerContractTest` | +| `FileAccessPolicyPort` | `FileAccessPolicyPortContract` — 규칙 정본은 `FileAccessSubject.owns` | `FakeFileAccessPolicy` | `RoleBasedFileAccessPolicyContractTest` — fileserver adapter (`test`) | + +계약을 처음 적용할 때 fake가 실제와 다르게 답한 경우와 처리(모두 fake를 실제에 맞췄다): + +- 쿼터: fake에 시계가 없어 만료된 예약도 사용량에 셌고, 해제한 예약의 확정·연장을 조용히 받았다. 확정· + 회수 fake는 기록만 하고 장부를 바꾸지 않았다. 이제 한 장부에 시계가 있고 JPA와 같은 조건으로 거절한다. + 만료됐지만 해제되지 않은 예약의 확정은 JPA SQL이 받으므로(쓴 바이트는 사용량이다) 계약도 받는다 — + `JpaFileQuota` Javadoc의 "만료된 예약은 확정할 수 없다"는 SQL과 달라 고쳤다. +- 업로드 세션: fake가 기한이 지난 업로드에 lease를 줬고, lease가 만료된 writer의 offset 확정을 받았고, + `findExpired`를 기한 순이 아니라 넣은 순서로 줬다. +- 복구 큐: fake가 한도 0을 거절하지 않았다. +- 소유자 규칙: fake와 실제 정책이 같은 규칙을 따로 썼다(principal·tenant 비교 두 벌). 정본 + `FileAccessSubject.owns` 하나를 둘 다 부른다. fake 규칙에서 tenant 비교를 빼는 변이가 계약 2건으로 잡힌다. + ### 9.2 계약이 없는 포트 (의도) | 포트 | 실제 구현 | fake | 계약이 없는 이유 | 다음 단계 | diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index 7d98487b..3e8c1f9b 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -7,8 +7,11 @@ 코드가 이 문서를 지키는지는 다음 테스트가 확인한다. - 응답 원문의 키 집합: `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireShapeTest.java` +- 핸들러 밖 오류(`/error` 디스패치)의 실패 Envelope: 실제 컨테이너에서 `WebContractAssertions` + (`TomcatWebContractIT`·Jetty lane), 기본 JWT 체인에서 `JwtChainErrorDispatchIT` - 멱등성 응답의 status·code·retryable·`Retry-After`: `IdempotencyExceptionMappingTest`, - `RetryAfterAdvisorTest`, `OperationalErrorTest`, 키 형식은 `IdempotencyKeyHeaderTest` + `RetryAfterAdvisorTest`, `OperationalErrorTest`, 키 형식은 `IdempotencyKeyHeaderTest`, + 실행 전 거부와 결과 불명의 구분은 `IdempotencyExecutorTest`, lease 하한은 `IdempotencySettingsTest` - 헤더 규칙(3절): `WebMvcRequestIdFilterTest`, `CorsSecurityFilterIntegrationTest` - web 전용 코드(4절): `TransportErrorHandlingTest`, `IdempotencyKeyHeaderTest`, web-advanced `WebAdvancedErrorMappingTest` @@ -51,8 +54,14 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). ** | `correlationId` | 위와 같음. 값이 없으면 키가 없다 | | `page` | 페이지 목록 응답에만. `number`·`size`·`total`·`sort`(미정렬이면 `sort: null`) | -필터 앞에서 끊긴 응답(필터 체인 밖의 오류)은 id 키가 빠질 수 있다. 클라이언트는 `meta`의 모르는 -키를 무시한다. +컨트롤러에 닿기 전에 거부된 요청(보안 방화벽이 막은 경로, 필터의 `sendError`, 필터가 던진 예외)도 같은 +실패 Envelope다. 컨테이너가 `/error`로 넘긴 요청을 `EnvelopeErrorController`가 status에 맞는 코드로 답한다. +본문에 요청 경로나 시각을 싣지 않는다. 원래 status가 그대로 나가고, 기본 JWT 체인에서도 익명 400이 401로 +바뀌지 않는다(재리뷰 RR-02-02). 다만 요청 id 필터를 지나기 전에 끊긴 응답은 `meta`의 id 키가 빠질 수 있다. +클라이언트는 `meta`의 모르는 키를 무시한다. + +4xx·5xx status로 나가는 본문은 `success:true`로 감싸지 않는다. 실패 Envelope가 아닌 본문을 오류 status로 +돌려주는 핸들러는 그 본문이 그대로 나간다. ### 왜 이렇게 나가는가 @@ -79,21 +88,31 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). ** 첫 요청이 끝나면 같은 작업이 두 번 적용된다. - **`Retry-After: 2`의 근거.** 기본 processing lease(`app.capabilities.idempotency.processing-lease`, 30s)보다 짧아, 첫 시도가 아직 끝날 수 있는 동안 다시 묻는다. 너무 이르면 409를 한 번 더 받을 뿐이고 - 결과가 바뀌지는 않는다. lease를 2초보다 짧게 설정한 서비스는 이 값이 lease를 넘으므로 값을 다시 - 정한다(`RetryAfterAdvisor`, `docs/registries/error-codes.yaml`). + 결과가 바뀌지는 않는다. 값은 `IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER` 하나이고 `RetryAfterAdvisor`가 + 그 값을 쓴다. `processing-lease`를 이 값(2초) 이하로 설정하면 기동이 실패한다(`IdempotencySettings`, + 재리뷰 RR-02-05). - executor는 기다리지 않는다. 처리 중이면 바로 409를 돌려준다. 키로 결과를 조회하는 엔드포인트는 없다. - **키 문법**: 보이는 ASCII(`0x21`–`0x7E`) 1~256자. 서버는 trim하거나 고치지 않는다. 짝 프론트의 `isValidIdempotencyKey`와 같은 규칙이다. KEYED 엔드포인트는 모두 `IdempotencyKeyHeader.parse`로 헤더를 읽어 같은 코드로 거부한다(리뷰 02-12). 키 원문은 응답에 돌려 쓰지 않는다. 키를 요구하지 않는 엔드포인트는 키 없이 보호 없이 실행된다. -같은 executor가 내는 나머지 두 실패: +같은 executor가 내는 나머지 세 실패. 저장소가 응답하지 않은 경우는 **언제** 멈췄는지로 코드가 갈린다. | 경우 | status | `error.code` | `retryable` | `Retry-After` | 클라이언트 행동 | | --- | --- | --- | --- | --- | --- | -| 멱등성 저장소 응답 없음 | 503 | `IDEMPOTENCY_UNAVAILABLE` | `true` | 없음 | 작업 실행 전에 거부됐다. 같은 키로 나중에 다시 보낸다 | +| 작업 실행 전(claim·시작 단계) 멱등성 저장소 응답 없음 | 503 | `IDEMPOTENCY_UNAVAILABLE` | `true` | 없음 | 작업은 실행되지 않았다. 같은 키로 나중에 다시 보낸다 | +| 작업 실행 뒤 결과 기록(complete 단계) 중 저장소 응답 없음 — **결과 불명** | 503 | `IDEMPOTENCY_COMPLETION_UNKNOWN` | `true` | 없음 | "적용되지 않았다"고 알리지 않는다. **같은 키로** 나중에 다시 보낸다. 새 키 금지 | | 이전 시도의 효과를 증명할 수 없음 | 500 | `IDEMPOTENCY_RECOVERY_REQUIRED` | `false` | 없음 | 재전송도 재실행도 안전하지 않다. 업무 데이터로 결과를 확인한다 | +- **결과 불명이 무엇을 뜻하나.** 작업은 이미 돌았다. 그 작업의 트랜잭션 안 DB 변경은 예외와 함께 + 롤백되지만, 트랜잭션 밖 효과(다른 시스템 호출, 메시지)는 일어났을 수 있다. 그래서 실행 전 거부와 같은 + 503이어도 code가 다르다. 클라이언트는 status가 아니라 `error.code`로 가른다. +- **같은 키로 다시 보내면 서버가 판정한다.** 결과가 실제로는 기록됐으면 재생(첫 요청의 성공 응답), 첫 시도의 + processing lease가 아직 남았으면 409 `IDEMPOTENT_IN_FLIGHT`, lease가 지났으면 500 + `IDEMPOTENCY_RECOVERY_REQUIRED`다. 새 키로 보내면 서버는 다른 요청으로 보고 막지 못한다 + (재리뷰 2026-11-03 README 4절 결정, RR-02-03). + ## 3. 헤더 ### 요청 id·correlation id @@ -127,7 +146,7 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 | 코드 | status | category | `retryable` | `Retry-After` | 언제 | | --- | --- | --- | --- | --- | --- | -| `REQUEST_TIMEOUT` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 없음 | 비동기 요청(`Callable`·`DeferredResult`·스트리밍)이 시간 안에 끝나지 않았다 | +| `REQUEST_TIMEOUT` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 없음 | 비동기 요청(`Callable`·`DeferredResult`·스트리밍)이 시간 안에 끝나지 않았다. GraphQL도 같은 이름을 쓰지만 그쪽 `category`는 GraphQL 전용 어휘 `TIMEOUT`이다(`src/adapter/inbound/graphql/README.md`) | | `IDEMPOTENCY_KEY_INVALID` | 400 | `VALIDATION` | `false` | 없음 | 2절 | | `RATE_LIMIT_UNAVAILABLE` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 있음 | rate-limit 저장소 응답 없음(`docs/web/runbook.md`) | | `RATE_LIMIT_INCOMPATIBLE` | 503 | `INTERNAL` | `false` | 없음 | rate-limit 제공자가 계약과 맞지 않음 | @@ -143,6 +162,8 @@ CORS가 켜져 있으면(`app.cors.enabled=true`) cross-origin 실제 응답의 - 응답 키를 더하거나 빼면 `EnvelopeWireShapeTest`와 이 문서 1절을 같이 고친다. - 응답 헤더를 새로 쓰면 `CorsExposedHeaders`에 넣고 3절을 고친다. - 멱등성 코드의 status·retryable·`Retry-After`를 바꾸면 `OperationalError`, `RetryAfterAdvisor`, - `docs/registries/error-codes.yaml`, 이 문서 2절을 같은 변경에서 고친다. + `docs/registries/error-codes.yaml`, 이 문서 2절을 같은 변경에서 고친다. 공유 코드의 `retryable`은 + gRPC trailer(`error-retryable`)와 GraphQL extension(`retryable`)에도 그대로 나가므로 그 둘의 README와 + 매핑 테스트(`GrpcStatusMapperTest`, `GraphQlWireErrorMapperTest`)도 같이 본다. - 짝 프론트의 백엔드 계약 문서(`clean-architecture-frontend-template` `docs/architecture/backend-api-and-server-state-contract.md` §4.1·§6)는 이 문서를 가리켜야 한다. diff --git a/infra/redis-sdk/README.md b/infra/redis-sdk/README.md index d6d687c3..832c5860 100644 --- a/infra/redis-sdk/README.md +++ b/infra/redis-sdk/README.md @@ -38,7 +38,7 @@ qualifies nothing, so "no CA configured" is an error rather than a client with v ## The ACL fixture -`acl/all-accounts.acl` provisions the accounts every lane uses. Two things about it matter, and +`acl/lane-fixture-accounts.acl` provisions the accounts every lane uses. Two things about it matter, and neither can be written in the file itself — **Redis refuses to start if an `aclfile` contains a comment line**, so the whole file is directives and the explanation lives here. diff --git a/infra/redis-sdk/acl/README.md b/infra/redis-sdk/acl/README.md index d561a860..0117e9b1 100644 --- a/infra/redis-sdk/acl/README.md +++ b/infra/redis-sdk/acl/README.md @@ -1,4 +1,16 @@ -# ACL accounts +# ACL accounts — test fixtures, not a deployment file + +**Nothing in this directory is loaded by a deployment.** Every file here is a fixture for the local +and test lanes: its passwords are public (`fixture-*`, written in this repository), and +`lane-fixture-accounts.acl` also provisions three accounts that only a lane topology needs — among +them `ca-skeleton-cluster-bootstrap`, which has `~* &* +@all`, every command on every key. Loaded into +a real Redis, that line alone gives anyone who can reach the server and read this repository full +control of it (`CONFIG`, `MODULE`, every key). A deployment writes its own ACL file of the same +shape: the application accounts it actually uses, passwords from its secret store, and none of the +lane-only accounts (review 2026-11-03 RR-07-04). The application enforces its half of that: under +the `prod` runtime profile it refuses to start while any setting or environment variable holds a +value beginning with `fixture-` (`SecretSourceValidator`), so a deployment that copied a lane's +`REDIS_LANE_*` values stops before it connects. One file per `CommandAccess` level. Each account is deliberately narrower than the SDK's own rules: the account is the last enforcement boundary and a permit issued inside the process never widens it, @@ -7,23 +19,21 @@ so a mistake in the SDK is still refused by the server. A Redis ACL file accepts nothing but complete `user` lines — no comments and no line continuations — which is why the rationale lives here instead of inline. -Every account here carries a **fixture** password (`fixture-*`). None of them is a deployment -credential and none is read by anything but the local lanes; a deployment replaces the whole file -with one whose passwords come from its secret store. They are written down rather than left as -`nopass` because an account that accepts any password makes every assertion about authentication -pass for the same reason a typo would have — and because these files are what a fork copies. The -four per-role files carried `nopass` long after `all-accounts.acl`, the file a deployment actually -loads, had been fixed; a fork that copied one of them got an open account and a green lane. +Every account here carries a **fixture** password (`fixture-*`). They are written down rather than +left as `nopass` because an account that accepts any password makes every assertion about +authentication pass for the same reason a typo would have — and because these files are what a fork +copies. The four per-role files carried `nopass` long after the combined lane file had been fixed; +a fork that copied one of them got an open account and a green lane. | File | Account | Grants | | --- | --- | --- | | `application.acl` | `CommandAccess.APPLICATION` | the typed data-structure commands over `prod:*`, with the dangerous and deprecated names denied | | `application-advanced.acl` | `APPLICATION_ADVANCED` | the above plus pub/sub, transactions, and the registered-script path. `EVAL` is absent: only `EVALSHA` of an already loaded digest is reachable. `+time` is granted because the rate-limit and idempotency scripts read the server clock with `redis.call('TIME')`, and `TIME` is in no data category (`@read`/`@write`): without it every such script fails with an ACL error. The startup SCRIPT probe runs `TIME` so a template missing it fails at boot | | `raw-gateway.acl` | `RAW_GATEWAY` | exactly the commands the catalog classifies `RAW_ONLY`, and nothing else | -| `all-accounts.acl` | – | the four accounts concatenated; Redis takes one `aclfile`, so this is what a deployment loads | +| `lane-fixture-accounts.acl` | – | what the lanes load (Redis takes one `aclfile`): `user default off`, the four per-role accounts of this table, and three lane-only accounts — `ca-skeleton-replication` (replica sync) and `ca-skeleton-sentinel` for the replicated and sentinel topologies, `ca-skeleton-cluster-bootstrap` (`+@all`) to create the cluster lane's slots. Never a deployment file | | `admin-readonly.acl` | `ADMIN_READONLY` | read-only diagnostics. Every destructive counterpart is denied here and blocked in the command policy catalog — two independent controls for the same rule | -## Who loads `all-accounts.acl` +## Who loads `lane-fixture-accounts.acl` The Redis topology lanes (`../standalone`, `../sentinel`, `../cluster`, `../tls`) and the application's Compose lanes that switch Redis on (`local-redis`, `all-adapters` in diff --git a/infra/redis-sdk/acl/all-accounts.acl b/infra/redis-sdk/acl/lane-fixture-accounts.acl similarity index 100% rename from infra/redis-sdk/acl/all-accounts.acl rename to infra/redis-sdk/acl/lane-fixture-accounts.acl diff --git a/infra/redis-sdk/cluster/compose.yml b/infra/redis-sdk/cluster/compose.yml index 6ef79fd7..aefe63ff 100644 --- a/infra/redis-sdk/cluster/compose.yml +++ b/infra/redis-sdk/cluster/compose.yml @@ -42,7 +42,7 @@ x-node: &node --min-replicas-max-lag 1 \ --masteruser ca-skeleton-replication \ --masterauth fixture-replication \ - --aclfile /etc/redis/acl/all-accounts.acl + --aclfile /etc/redis/acl/lane-fixture-accounts.acl healthcheck: test: ["CMD-SHELL", "[ \"$$(redis-cli -p $$NODE_PORT --user ca-skeleton-application --pass fixture-application --no-auth-warning ping)\" = PONG ]"] interval: 2s diff --git a/infra/redis-sdk/sentinel/compose.yml b/infra/redis-sdk/sentinel/compose.yml index 49aea446..9aab8f37 100644 --- a/infra/redis-sdk/sentinel/compose.yml +++ b/infra/redis-sdk/sentinel/compose.yml @@ -51,7 +51,7 @@ x-data-node: &data-node --min-replicas-max-lag 1 \ --masteruser ca-skeleton-replication \ --masterauth fixture-replication \ - --aclfile /etc/redis/acl/all-accounts.acl + --aclfile /etc/redis/acl/lane-fixture-accounts.acl healthcheck: test: ["CMD-SHELL", "[ \"$$(redis-cli -p $$NODE_PORT --user ca-skeleton-application --pass fixture-application --no-auth-warning ping)\" = PONG ]"] interval: 2s diff --git a/infra/redis-sdk/standalone/compose.yml b/infra/redis-sdk/standalone/compose.yml index df271ab7..ea8f4be0 100644 --- a/infra/redis-sdk/standalone/compose.yml +++ b/infra/redis-sdk/standalone/compose.yml @@ -14,7 +14,7 @@ services: - --save - "" - --aclfile - - /etc/redis/acl/all-accounts.acl + - /etc/redis/acl/lane-fixture-accounts.acl volumes: - ../acl:/etc/redis/acl:ro ports: diff --git a/infra/redis-sdk/tls/compose.yml b/infra/redis-sdk/tls/compose.yml index 051b0221..218adb92 100644 --- a/infra/redis-sdk/tls/compose.yml +++ b/infra/redis-sdk/tls/compose.yml @@ -61,7 +61,7 @@ services: - --save - "" - --aclfile - - /etc/redis/acl/all-accounts.acl + - /etc/redis/acl/lane-fixture-accounts.acl ports: - "${REDIS_PORT:-6390}:6379" healthcheck: diff --git a/scripts/feature-scaffold/probes/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/testkit/CallerTransaction__Feature__RepositoryContractTest.java.tmpl b/scripts/feature-scaffold/probes/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/testkit/CallerTransaction__Feature__RepositoryContractTest.java.tmpl new file mode 100644 index 00000000..e1cc1e27 --- /dev/null +++ b/scripts/feature-scaffold/probes/src/domain-core/src/test/java/dev/caskeleton/domain/__feature__/testkit/CallerTransaction__Feature__RepositoryContractTest.java.tmpl @@ -0,0 +1,51 @@ +package dev.caskeleton.domain.__feature__.testkit; + +import dev.caskeleton.domain.__feature__.__Feature__; +import dev.caskeleton.domain.__feature__.__Feature__Id; +import dev.caskeleton.domain.__feature__.__Feature__Repository; +import java.util.Optional; +import java.util.function.Supplier; + +/** + * Round-trip probe, never generated into a feature: a repository that refuses work outside its + * caller's transaction, as docs/manual/04-persistence.md teaches a real adapter to, inherits the + * generated contract and passes it (review 2026-11-03 RR-01-01). + */ +class CallerTransaction__Feature__RepositoryContractTest extends __Feature__RepositoryContract { + + private final InMemory__Feature__Repository rows = new InMemory__Feature__Repository(); + private boolean transactionActive; + + @Override + protected __Feature__Repository repository() { + return new __Feature__Repository() { + @Override + public __Feature__ save(__Feature__ aggregate) { + requireTransaction(); + return rows.save(aggregate); + } + + @Override + public Optional<__Feature__> findById(__Feature__Id id) { + requireTransaction(); + return rows.findById(id); + } + }; + } + + @Override + protected T inTransaction(Supplier work) { + transactionActive = true; + try { + return work.get(); + } finally { + transactionActive = false; + } + } + + private void requireTransaction() { + if (!transactionActive) { + throw new IllegalStateException("requires an active caller transaction"); + } + } +} diff --git a/scripts/feature-scaffold/templates/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__Config.java.tmpl b/scripts/feature-scaffold/templates/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__Config.java.tmpl index 4cc9b7c7..7fe6caf5 100644 --- a/scripts/feature-scaffold/templates/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__Config.java.tmpl +++ b/scripts/feature-scaffold/templates/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/__feature__/__Feature__Config.java.tmpl @@ -19,15 +19,22 @@ import org.springframework.context.annotation.Import; * *

        Turns itself on from what is on the classpath: a {@link __Feature__Repository} adapter and a * {@link TransactionPort}. Until a repository adapter exists the feature is absent rather than half - * present (docs/manual/02-new-feature.md step 5). When the adapter comes from another - * auto-configuration, name it in {@code afterName} so this condition sees its bean. + * present (docs/manual/02-new-feature.md step 5). + * + *

        {@code @ConditionalOnBean} only sees beans of auto-configurations processed before this one, + * and nothing orders them by itself: without {@code afterName} the feature would be on or off + * depending on the class names' alphabetical order. {@code TransactionPort} comes from + * persistence-jpa's {@code PersistenceJpaAutoConfiguration}, named here. When the repository adapter + * comes from another auto-configuration, add its name to the list. * *

        The use cases are beans, not objects the controller builds, because the method security * advisor proxies beans: {@code @RequiresPermission} on create is enforced by that proxy. Grant * {@code __feature_kebab__:create} to a role under {@code app.authz.role-permissions}; until then * every create is refused (docs/manual/07-authorization.md). */ -@AutoConfiguration +@AutoConfiguration( + afterName = + "dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaAutoConfiguration") @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnBean({__Feature__Repository.class, TransactionPort.class}) @Import(__Feature__Controller.class) diff --git a/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/__Feature__RepositoryContract.java.tmpl b/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/__Feature__RepositoryContract.java.tmpl index cbab07f8..290a1492 100644 --- a/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/__Feature__RepositoryContract.java.tmpl +++ b/scripts/feature-scaffold/templates/src/domain-core/src/testFixtures/java/dev/caskeleton/domain/__feature__/testkit/__Feature__RepositoryContract.java.tmpl @@ -6,12 +6,17 @@ import dev.caskeleton.domain.__feature__.__Feature__; import dev.caskeleton.domain.__feature__.__Feature__Id; import dev.caskeleton.domain.__feature__.__Feature__Repository; import java.util.Optional; +import java.util.function.Supplier; import org.junit.jupiter.api.Test; /** * What every {@link __Feature__Repository} promises. {@link InMemory__Feature__Repository} extends * it in domain-core's tests; a real adapter extends it in a lane that runs against its real store * (docs/manual/04-persistence.md). Add a test here before adding a repository method. + * + *

        Every repository call goes through {@link #inTransaction(Supplier)}. A real adapter refuses + * work outside its caller's transaction ({@code CallerTransaction.require}), so its contract test + * opens one there; the fake needs none and keeps the default. */ public abstract class __Feature__RepositoryContract { @@ -25,13 +30,25 @@ public abstract class __Feature__RepositoryContract { */ protected abstract __Feature__Repository repository(); + /** + * Runs one repository call the way a use case does, inside its transaction. The default runs it + * directly; an adapter that requires a caller transaction opens and commits one here. + * + * @param work one call on the repository + * @param what the call returns + * @return what the call returned + */ + protected T inTransaction(Supplier work) { + return work.get(); + } + @Test void aSaved__Feature__IsFoundByItsId() { // given - repository().save(__Feature__.create(FIRST, "first")); + inTransaction(() -> repository().save(__Feature__.create(FIRST, "first"))); // when - Optional<__Feature__> found = repository().findById(FIRST); + Optional<__Feature__> found = inTransaction(() -> repository().findById(FIRST)); // then assertThat(found.map(__Feature__::name)).contains("first"); @@ -39,18 +56,19 @@ public abstract class __Feature__RepositoryContract { @Test void anIdNothingWasSavedUnderIsNotFound() { - assertThat(repository().findById(UNKNOWN)).isEmpty(); + assertThat(inTransaction(() -> repository().findById(UNKNOWN))).isEmpty(); } @Test void savingTheSameIdAgainReplacesTheStoredState() { // given - repository().save(__Feature__.create(FIRST, "first")); + inTransaction(() -> repository().save(__Feature__.create(FIRST, "first"))); // when - repository().save(__Feature__.restore(FIRST, "renamed")); + inTransaction(() -> repository().save(__Feature__.restore(FIRST, "renamed"))); // then - assertThat(repository().findById(FIRST).map(__Feature__::name)).contains("renamed"); + assertThat(inTransaction(() -> repository().findById(FIRST)).map(__Feature__::name)) + .contains("renamed"); } } diff --git a/scripts/verify-feature-scaffold.sh b/scripts/verify-feature-scaffold.sh index 4bcfa754..01573e99 100755 --- a/scripts/verify-feature-scaffold.sh +++ b/scripts/verify-feature-scaffold.sh @@ -12,6 +12,9 @@ # 그 전에 템플릿 패키지 이름(Operation, Notification, Common)을 넣어 거절되는지와 아무것도 쓰지 # 않는지 확인한다. # +# 생성물의 테스트가 모두 실제로 돌았는지 템플릿 목록으로 확인하고, 생성된 저장소 계약을 호출자 +# 트랜잭션을 요구하는 저장소로 한 번 더 돌린다(scripts/feature-scaffold/probes, 기능에는 생성되지 않는다). +# # 루트 Gradle 태스크 `verifyFeatureScaffold`가 이 스크립트를 부르고 mainCheck에 들어 있다. set -euo pipefail @@ -92,18 +95,68 @@ cd "$copy/src" :app-bootstrap:check \ architectureCheck -# 생성된 테스트가 실제로 실행되었는지: 각 leaf의 테스트 결과에 기능 테스트 클래스가 있어야 한다. +# 생성된 테스트가 실제로 실행되었는지: 템플릿의 테스트 클래스 하나하나가 자기 leaf의 결과 XML을 +# 남겨야 한다. 목록을 손으로 적지 않고 템플릿에서 만든다 — 손으로 적은 목록은 8개 중 4개만 보았고, +# 필터·태그가 바뀌어 나머지가 실행되지 않아도 녹색이었다(review 2026-11-03 RR-01-10). +scaffold_templates="$copy/scripts/feature-scaffold/templates/src" +mapfile -t test_templates < <(cd "$scaffold_templates" && find . -path '*/src/test/java/*' -name '*Test.java.tmpl' | sort) +[ "${#test_templates[@]}" -gt 0 ] || { echo "템플릿에 테스트가 없다: $scaffold_templates" >&2; exit 1; } + +# 결과 XML 하나를 확인한다: 있고, 한 건 이상 돌았고, 실패·오류가 없다. +require_test_result() { + local result="$1" what="$2" + [ -f "$result" ] || { echo "$what 실행되지 않았다: $result" >&2; exit 1; } + if grep -q 'tests="0"' "$result"; then + echo "$what 한 건도 돌지 않았다: $result" >&2 + exit 1 + fi + if grep -q '&2 + exit 1 + fi +} + +# 템플릿 경로(/src/test/java/<패키지 경로>/<클래스>.java.tmpl)를 그 leaf의 결과 XML 경로로. +result_of() { + local template="${1#./}" name="$2" package_name="$3" + local leaf="${template%%/src/test/java/*}" + local class_path="${template#*/src/test/java/}" + class_path="${class_path%.java.tmpl}" + local fqcn + fqcn="$(printf '%s' "$class_path" | sed -e "s/__Feature__/$name/g" -e "s/__feature__/$package_name/g" | tr '/' '.')" + printf '%s/build/test-results/test/TEST-%s.xml' "$leaf" "$fqcn" +} + for name in "${names[@]}"; do - for result in \ - "domain-core/build/test-results/test/TEST-dev.caskeleton.domain.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}Test.xml" \ - "application-core/build/test-results/test/TEST-dev.caskeleton.application.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').Create${name}UseCaseTest.xml" \ - "adapter/inbound/web/build/test-results/test/TEST-dev.caskeleton.adapter.inbound.web.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}ControllerTest.xml" \ - "app-bootstrap/build/test-results/test/TEST-dev.caskeleton.bootstrap.autoconfigure.$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]').${name}ConfigTest.xml"; do - [ -f "$result" ] || { echo "생성된 테스트가 실행되지 않았다: $result" >&2; exit 1; } - if grep -q '&2 - exit 1 - fi + package_name="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')" + for template in "${test_templates[@]}"; do + require_test_result "$(result_of "$template" "$name" "$package_name")" "생성된 테스트가" + done +done + +# 생성된 저장소 계약은 실제 adapter가 상속할 수 있어야 한다. 매뉴얼 04장의 adapter는 호출자 +# 트랜잭션 밖의 호출을 거부하므로, 그렇게 하는 저장소로 계약을 돌려 본다(review 2026-11-03 RR-01-01). +# 탐침은 기능에 생성되지 않는 테스트라 PR 게이트(check)와 따로 test 태스크만 돌린다. +probe_templates="$copy/scripts/feature-scaffold/probes/src" +mapfile -t probes < <(cd "$probe_templates" && find . -type f -name '*.java.tmpl' | sort) +probe_filters=() +for name in "${names[@]}"; do + package_name="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')" + for probe in "${probes[@]}"; do + target="$(printf '%s' "${probe#./}" | sed -e "s/__Feature__/$name/g" -e "s/__feature__/$package_name/g")" + target="${target%.tmpl}" + mkdir -p "$(dirname "$copy/src/$target")" + sed -e "s/__Feature__/$name/g" -e "s/__feature__/$package_name/g" \ + "$probe_templates/${probe#./}" > "$copy/src/$target" + class_path="${target#*/src/test/java/}" + probe_filters+=(--tests "$(printf '%s' "${class_path%.java}" | tr '/' '.')") + done +done +./gradlew --console=plain :domain-core:test "${probe_filters[@]}" +for name in "${names[@]}"; do + package_name="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')" + for probe in "${probes[@]}"; do + require_test_result "$(result_of "$probe" "$name" "$package_name")" "저장소 계약 탐침이" done done echo "feature scaffold 왕복 통과: ${names[*]}" diff --git a/src/.env.example b/src/.env.example index 895cc69d..200bb942 100644 --- a/src/.env.example +++ b/src/.env.example @@ -135,6 +135,7 @@ APP_CACHE_CANONICAL_DEFAULT_PROVIDER=disabled APP_REDIS_ENABLED=true APP_CACHE_REDIS_POSITIVE_HARD_TTL=5m APP_CACHE_REDIS_NEGATIVE_TTL=10s +APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS=4 APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT=200ms APP_LEASE_REDIS_COMMAND_TIMEOUT=200ms APP_LEASE_REDIS_CONTENTION_RETRY_AFTER=50ms @@ -151,7 +152,7 @@ APP_REDIS_TIMEOUT_SCRIPT=1s # reads the password from and authenticates as . With the application # reference empty and anonymous access not accepted, the application refuses to start while Redis # is on; with the advanced one empty, scripts run as the application account and startup warns. The -# Compose Redis lanes connect as the fixture accounts of infra/redis-sdk/acl/all-accounts.acl (the +# Compose Redis lanes connect as the fixture accounts of infra/redis-sdk/acl/lane-fixture-accounts.acl (the # Redis comment in src/config/runtime/compose-profile-contracts.json). APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE= APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=false @@ -293,6 +294,9 @@ APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD=10 # Optional build-composition: these bind only when :adapter:inbound:websocket is present. # The default bootJar does not contain that leaf. APP_WEBSOCKET_ENABLED=true +# Explicit offs for two more capabilities that are on when present (the Compose lanes set them). +APP_OBJECTSTORAGE_ENABLED=true +APP_GRPC_SERVER_ENABLED=true APP_WEBSOCKET_ENDPOINT=/ws APP_WEBSOCKET_ALLOWED_ORIGINS=http://localhost:3000 APP_WEBSOCKET_BROADCAST_DESTINATION=/topic/events diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index 69252f30..08d0f9d2 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -77,7 +77,12 @@ instrumentation, data fetcher resolver 세 곳이 같은 bean 을 받는다). - **client 문구**: shared-contract `ClientErrorMessages`(Category 별 한국어 문구 표 하나, 소유자 결정 11). 예외 메시지는 절대 나가지 않는다. - **retryable**: 코드의 `retryable()` 이다(category 에서 계산하지 않는다). 플랫폼 자체 코드만 wire - category 기본값을 쓴다. + category 기본값을 쓴다. 그래서 공유 코드의 값을 바꾸면 이 wire 도 바뀐다: 처리 중 중복 + `IDEMPOTENT_IN_FLIGHT` 는 2026-11-01 리뷰(02-01)부터 `retryable: true` 다 — 같은 키로 다시 보내면 서버가 + 판정한다(`docs/web/http-contract.md` §2). `GraphQlWireErrorMapperTest` 가 고정한다(재리뷰 RR-02-06). +- **`REQUEST_TIMEOUT` 은 web 과 이름만 같다.** 여기의 `category` 는 GraphQL wire 전용 6값 어휘(`TIMEOUT`)이고, + web 의 같은 이름 코드는 HTTP 503·operational category `TRANSIENT_DEPENDENCY` 다 + (`docs/web/http-contract.md` §4). 둘 다 `retryable: true` 다. - **body 크기 초과**: `PAYLOAD_TOO_LARGE`(web 과 같은 코드). 문서 모양 거부(`GRAPHQL_DOCUMENT_SHAPE_REJECTED`)는 별도 코드. diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlDeadline.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlDeadline.java index 3baa3a76..97d0aabf 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlDeadline.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/context/GraphQlDeadline.java @@ -14,6 +14,9 @@ import java.time.Instant; *

      8. {@code GraphQlPlatformWebInterceptor} ends the request with {@code REQUEST_TIMEOUT} when it * passes, and Spring cancels the execution so no further field is dispatched. A resolver * already running is not interrupted. + *
      9. {@code GraphQlDeadlineInstrumentation} refuses to start a non-trivial resolver once it has + * passed, failing that field with {@code REQUEST_TIMEOUT}; this is what still holds when the + * whole execution runs on the request thread and the interceptor's timer starts too late. *
      10. {@code GraphQlCostBudgetHandler} refuses to start an execution whose deadline has passed. *
      11. {@code GraphQlBatchExecutor} clamps each platform-registered DataLoader batch to what is * left, and stops between chunks once it is spent. diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlComplexityCalculator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlComplexityCalculator.java index 90aae3a8..943feffe 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlComplexityCalculator.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlComplexityCalculator.java @@ -121,11 +121,6 @@ public final class GraphQlComplexityCalculator { } } - /** The effective page size for a connection request. */ - public int effectivePageSize(Integer first, Integer last) { - return first != null ? first : last != null ? last : defaultPageSize; - } - private void requireAllowedPage(Integer requested) { if (requested == null) { return; diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorer.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorer.java index b67d7366..cd3b109b 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorer.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorer.java @@ -15,6 +15,7 @@ import graphql.language.Value; import graphql.language.VariableDefinition; import graphql.language.VariableReference; import graphql.schema.GraphQLArgument; +import graphql.schema.GraphQLCompositeType; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLFieldsContainer; import graphql.schema.GraphQLList; @@ -59,6 +60,13 @@ import java.util.Objects; *

        Pricing an omitted argument as one row was the bypass: {@code items(first: 20)} scored 410 * while {@code items} scored 40, and four nested lists added up instead of multiplying. * + *

        A selection set is walked whatever kind of composite type it selects from. A union has no + * fields of its own — only {@code __typename} — so its selections are inline fragments and fragment + * spreads, each priced against its type condition. Treating "not a fields container" as "nothing + * below" was the second bypass (re-review 2026-11-03, RR-02-01): {@code search { ... on Post { + * comments(first: 100000) } }} scored 20, and neither the budget nor the page maximum applied under + * any union-typed field. + * *

        Traversal is bounded, and fragment cycles are cut by tracking the expansion path. This runs on * documents that have passed validation, but the bound stays because the scorer is also used from * the pre-execution path where a hostile document is exactly what it is meant to price. @@ -143,7 +151,7 @@ public final class GraphQlDocumentComplexityScorer { private long selectionSetCost( GraphQLSchema schema, - GraphQLFieldsContainer parent, + GraphQLCompositeType parent, SelectionSet selectionSet, Map fragments, PageVariables variables, @@ -173,10 +181,10 @@ public final class GraphQlDocumentComplexityScorer { expansionPath, listsAreThePage)); } else if (selection instanceof InlineFragment inlineFragment) { - GraphQLFieldsContainer target = + GraphQLCompositeType target = inlineFragment.getTypeCondition() == null ? parent - : fieldsContainer(schema, inlineFragment.getTypeCondition().getName()); + : compositeType(schema, inlineFragment.getTypeCondition().getName()); total = GraphQlComplexityCalculator.saturatedAdd( total, @@ -196,10 +204,10 @@ public final class GraphQlDocumentComplexityScorer { if (fragment == null || expansionPath.contains(spread.getName())) { continue; } - GraphQLFieldsContainer target = + GraphQLCompositeType target = fragment.getTypeCondition() == null ? parent - : fieldsContainer(schema, fragment.getTypeCondition().getName()); + : compositeType(schema, fragment.getTypeCondition().getName()); expansionPath.push(spread.getName()); total = GraphQlComplexityCalculator.saturatedAdd( @@ -221,7 +229,7 @@ public final class GraphQlDocumentComplexityScorer { private long fieldCost( GraphQLSchema schema, - GraphQLFieldsContainer parent, + GraphQLCompositeType parent, Field field, Map fragments, PageVariables variables, @@ -235,8 +243,12 @@ public final class GraphQlDocumentComplexityScorer { return 0; } - GraphQLFieldDefinition definition = parent.getFieldDefinition(field.getName()); String coordinate = parent.getName() + "." + field.getName(); + // A union declares no fields; validation rejects anything but __typename directly under one. + GraphQLFieldDefinition definition = + parent instanceof GraphQLFieldsContainer container + ? container.getFieldDefinition(field.getName()) + : null; if (definition == null) { // Validation rejects an unknown field; price what is there rather than invent a type. return calculator.fieldCost(coordinate, 0).total(); @@ -250,7 +262,7 @@ public final class GraphQlDocumentComplexityScorer { long childCost = selectionSetCost( schema, - fieldsContainer(definition.getType()), + compositeType(definition.getType()), field.getSelectionSet(), fragments, variables, @@ -353,14 +365,14 @@ public final class GraphQlDocumentComplexityScorer { }; } - private static GraphQLFieldsContainer fieldsContainer(GraphQLSchema schema, String typeName) { - GraphQLType type = schema.getType(typeName); - return fieldsContainer(type); + private static GraphQLCompositeType compositeType(GraphQLSchema schema, String typeName) { + return compositeType(schema.getType(typeName)); } - private static GraphQLFieldsContainer fieldsContainer(GraphQLType type) { + /** The object, interface or union a selection set selects from; null for a leaf type. */ + private static GraphQLCompositeType compositeType(GraphQLType type) { GraphQLType unwrapped = unwrap(type); - return unwrapped instanceof GraphQLFieldsContainer container ? container : null; + return unwrapped instanceof GraphQLCompositeType composite ? composite : null; } private static GraphQLType unwrap(GraphQLType type) { diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorerTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorerTest.java index cc5d8dd7..2e06b0a5 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorerTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentComplexityScorerTest.java @@ -34,11 +34,19 @@ class GraphQlDocumentComplexityScorerTest { pagedWithDefault(first: Int = 50): [Item!]! itemConnection(first: Int): ItemConnection node: Item + allItems: [Item!]! + search: [SearchResult!]! + nodes: [Named!]! } - type Item { + union SearchResult = Item + interface Named { + name: String! + } + type Item implements Named { name: String! children: [Item!]! grid: [[Item!]!]! + paged(first: Int): [Item!]! } type ItemConnection { edges: [ItemEdge!]! @@ -48,10 +56,15 @@ class GraphQlDocumentComplexityScorerTest { } """; + // Pricing never resolves a runtime type; the resolvers only satisfy the schema generator. private static final GraphQLSchema SCHEMA = new SchemaGenerator() .makeExecutableSchema( - new SchemaParser().parse(SDL), RuntimeWiring.newRuntimeWiring().build()); + new SchemaParser().parse(SDL), + RuntimeWiring.newRuntimeWiring() + .type("SearchResult", type -> type.typeResolver(environment -> null)) + .type("Named", type -> type.typeResolver(environment -> null)) + .build()); private static final long BUDGET = 10_000; @@ -246,6 +259,87 @@ class GraphQlDocumentComplexityScorerTest { assertThat(score).isEqualTo(20L + 20L); } + @Test + @DisplayName("union 필드 아래 inline fragment 의 중첩 list 도 일반 list 와 같이 곱한다") + void nestedListsUnderAUnionFieldMultiplyLikeAPlainList() { + // given + String plain = "query Q { allItems { children { children { children { name } } } } }"; + + // when + long score = + score( + "query Q { search { ... on Item { children { children { children { name } } } } } }", + Map.of()); + + // then + assertThat(score).isEqualTo(score(plain, Map.of())); + assertThatThrownBy(() -> calculator.verify(new GraphQlComplexityResult(score), BUDGET)) + .isInstanceOf(GraphQlComplexityRejectedException.class); + } + + @Test + @DisplayName("union 필드 아래 fragment spread 도 그 타입으로 내려가 곱한다") + void aFragmentSpreadUnderAUnionFieldIsPricedAgainstItsTypeCondition() { + // given + String plain = "query Q { allItems { children { children { children { name } } } } }"; + + // when + long score = + score( + "query Q { search { ...F } } " + + "fragment F on Item { children { children { children { name } } } }", + Map.of()); + + // then + assertThat(score).isEqualTo(score(plain, Map.of())); + } + + @Test + @DisplayName("union 필드 아래 page 인자도 상한을 넘으면 page size exceeds maximum 으로 거부된다") + void aPageSizeUnderAUnionFieldIsCheckedAgainstTheMaximum() { + // given + String document = "query Q { search { ... on Item { paged(first: 100000) { name } } } }"; + + // when + Throwable thrown = catchThrowable(() -> score(document, Map.of())); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlComplexityRejectedException.class) + .hasMessageContaining("page size exceeds maximum"); + } + + @Test + @DisplayName("interface 필드 아래 inline fragment 의 중첩 list 도 일반 list 와 같이 곱한다") + void nestedListsUnderAnInterfaceFieldMultiplyLikeAPlainList() { + // given + String plain = "query Q { allItems { children { children { children { name } } } } }"; + + // when + long score = + score( + "query Q { nodes { ... on Item { children { children { children { name } } } } } }", + Map.of()); + + // then + assertThat(score).isEqualTo(score(plain, Map.of())); + } + + @Test + @DisplayName("interface 필드 아래 page 인자도 상한을 넘으면 page size exceeds maximum 으로 거부된다") + void aPageSizeUnderAnInterfaceFieldIsCheckedAgainstTheMaximum() { + // given + String document = "query Q { nodes { ... on Item { paged(first: 100000) { name } } } }"; + + // when + Throwable thrown = catchThrowable(() -> score(document, Map.of())); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlComplexityRejectedException.class) + .hasMessageContaining("page size exceeds maximum"); + } + private long score(String source, Map variables) { return score(calculator, source, variables); } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java index 3a39c97d..c27ccb56 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java @@ -55,6 +55,29 @@ class GraphQlWireErrorMapperTest { .containsExactly("DB_QUERY_CANCELED", false); } + /** + * The in-flight duplicate's {@code retryable} became {@code true} in the 2026-11-01 review + * (02-01): a resend with the same key is judged by the server, so it is safe. GraphQL carries the + * code's own value, so the change reached this wire too; this pins it (re-review RR-02-06). + */ + @org.junit.jupiter.api.Test + @DisplayName("처리 중 중복(IDEMPOTENT_IN_FLIGHT)은 GraphQL extension 에서도 retryable=true 로 나간다") + void anInFlightDuplicateIsRetryableOnTheGraphQlWire() { + // given + GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking(); + RuntimeException failure = + dev.caskeleton.application.idempotency.IdempotencyInFlightException.forScopeDigest( + "digest"); + + // when + GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test()); + + // then + assertThat(error.extensions()) + .extracting(extensions -> extensions.get("code"), extensions -> extensions.get("retryable")) + .containsExactly("IDEMPOTENT_IN_FLIGHT", true); + } + @org.junit.jupiter.api.Test void anIllegalArgumentIsABadParameterRequestError() { // given diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index 9c45f9fd..80201aa2 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -140,7 +140,8 @@ handler throw, listener callback throw, `responseObserver.onError(...)`, raw - **와이어 status(coarse)** 는 `GrpcStatusMapper.toStatus(Category)` 가 결정한다(HTTP status 가 coarse 인 것과 동형). 정확한 `code`/`category`/`retryable` 은 `Status` trailer `Metadata` (`error-code` / `error-category` / `error-retryable`)에 실어 클라이언트가 switch 하게 한다. - `retryable` 은 코드의 값이다. status description 은 shared-contract `ClientErrorMessages` 의 + `retryable` 은 코드의 값이다(처리 중 중복 `IDEMPOTENT_IN_FLIGHT` 는 2026-11-01 리뷰 02-01부터 `ABORTED` + + `error-retryable: true` — 같은 키로 다시 보내면 서버가 판정한다. `GrpcStatusMapperTest` 가 고정, 재리뷰 RR-02-06). status description 은 shared-contract `ClientErrorMessages` 의 Category 별 한국어 문구(web·GraphQL 과 같은 표)다. - **`IllegalArgumentException`** 은 `BAD_PARAMETER`(`INVALID_ARGUMENT`) — 모든 전송이 같다. - **`ApiErrorCode` 추출**: feature 예외는 `ApiErrorCarrier`(이 모듈이 제공하는 전송-중립 hook)를 diff --git a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapperTest.java b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapperTest.java index 57aa1bd4..c996114a 100644 --- a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapperTest.java +++ b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcStatusMapperTest.java @@ -7,6 +7,7 @@ import dev.caskeleton.shared.error.OperationalError; import io.grpc.Metadata; import io.grpc.Status; import java.util.EnumSet; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -64,4 +65,22 @@ class GrpcStatusMapperTest { // then assertThat(retryable).isEqualTo("false"); } + + /** + * The in-flight duplicate's {@code retryable} became {@code true} in the 2026-11-01 review + * (02-01). The trailer carries the code's own value, so the change reached the gRPC wire as well: + * status {@code ABORTED} (category {@code CONFLICT}) with {@code error-retryable: true} + * (re-review RR-02-06). + */ + @Test + @DisplayName("처리 중 중복(IDEMPOTENT_IN_FLIGHT)은 ABORTED 이고 trailer 의 retryable 은 true 다") + void anInFlightDuplicateIsAbortedAndRetryableOnTheGrpcWire() { + // when + Metadata trailers = mapper.trailersFor(OperationalError.IDEMPOTENT_IN_FLIGHT); + + // then + assertThat(mapper.statusFor(OperationalError.IDEMPOTENT_IN_FLIGHT).getCode()) + .isEqualTo(Status.Code.ABORTED); + assertThat(trailers.get(GrpcStatusMapper.RETRYABLE_KEY)).isEqualTo("true"); + } } diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index b71ce115..0754f787 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -241,6 +241,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML | `PreconditionFailedException` | `PRECONDITION_FAILED` | 412 | D15: `If-Match` 불일치 쓰기 = 낙관적 동시성 충돌 → 412 (raw 409/500 금지) | | `PageValidationException` | `VALIDATION_FAILED` | 400 | D18/D20/D21: 계약 범위 밖 페이지/정렬/필터 파라미터. field + reasonCode 를 details 로 | | `IdempotencyUnavailableException` | `IDEMPOTENCY_UNAVAILABLE` | 503 (retryable=true) | 조정 저장소가 응답하지 않아 action 전에 거부. carrier 분기 | +| `IdempotencyCompletionUnknownException` | `IDEMPOTENCY_COMPLETION_UNKNOWN` | 503 (retryable=true) | action 이 돈 뒤 결과 기록(complete) 중 저장소가 응답하지 않음. 결과 불명 — 같은 키로 재전송, 새 키 금지(`docs/web/http-contract.md` §2, 재리뷰 RR-02-03). carrier 분기 | | `IdempotencyRecoveryRequiredException` | `IDEMPOTENCY_RECOVERY_REQUIRED` | 500 (retryable=false) | 이전 시도의 외부 효과 여부를 판단할 수 없음. carrier 분기 | | `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=true, `Retry-After: 2`) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 클라이언트 행동: 결과 불명. 같은 `Idempotency-Key`로 `Retry-After` 뒤 재전송. 새 키 금지(`docs/web/http-contract.md` §2). 진단정보(scope digest)는 클라이언트 미도달 | | `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 (retryable=false) | D8: `Idempotency-Key` 를 다른 본문으로 재사용. 다시 보내지 않는다(`docs/web/http-contract.md` §2). fingerprint/scope 노출 금지 | @@ -284,9 +285,26 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML advice 가 같은 mapper 로 Envelope 를 문자열로 직렬화해 넘긴다. 텍스트를 요청한 클라이언트는 그대로 문자열을 받는다. ArchUnit 으로 `String` 반환을 금지하는 안은 버렸다: `text/plain` 엔드포인트의 정당한 용도를 막고, 규칙을 돌리지 않는 서비스에는 함정이 그대로 남는다. +- **4xx·5xx 본문은 감싸지 않는다.** `success` 는 클라이언트가 가르는 판별자라, 오류 status 본문을 + `success:true` 로 감싸면 성공으로 읽힌다. Boot `/error` 의 map 이 그렇게 나갔다(재리뷰 RR-02-02). - 위치: sample 모듈이 아니라 adapter-web. 실행 앱은 adapter-web 에 의존하지만 sample-portfolio 에는 의존하지 않으므로, 응답 래핑이 실제로 동작하려면 여기 있어야 한다. +### EnvelopeErrorController +- 컨트롤러에 닿기 전에 생긴 오류(보안 방화벽의 `RequestRejectedException`, 필터의 `sendError`, 필터가 + 던진 예외)는 `GlobalExceptionHandler` 를 지나지 않고 컨테이너의 `/error` 디스패치로 간다. Boot 기본 + `BasicErrorController` 는 거기서 `{timestamp, status, error, path}` 를 썼고, advice 가 그것을 + `success:true` 로 감쌌으며 `path` 는 요청 경로 원문이었다(재리뷰 RR-02-02). 이 컨트롤러가 그 자리를 + 대신해 status 를 `GlobalExceptionHandler` 와 같은 표(`HttpStatusErrorCodes`)로 코드에 매핑하고 실패 + Envelope 를 `EnvelopeResponseWriter` 로 쓴다. 요청에서 가져온 값은 싣지 않는다. +- `WebMvcPlatformAutoConfiguration` 이 `ErrorMvcAutoConfiguration` 보다 먼저 `ErrorController` 가 없을 때만 + 등록한다. 어댑터가 자기 `ErrorController` 를 두면 물러난다. +- `SecurityConfig` 는 오류 **디스패치**만 허용한다(`DispatcherType.ERROR`). 예전에는 `/error` 가 공개 경로가 + 아니라서 익명 요청의 400 이 401 로 바뀌었다. `/error` 를 직접 부른 요청은 여전히 인증이 필요하다. + 단언은 실제 Tomcat 의 `TomcatWebContractIT`(공유 `WebContractAssertions`)와 `JwtChainErrorDispatchIT`. +- 앱이 보안 체인을 직접 정의하면(예: sample 의 데모 체인) 같은 한 줄 + (`dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()`)을 그 체인에도 둬야 원래 status 가 나간다. + ### CacheControlFilter - 스켈레톤 기본 HTTP 캐시 정책. - `Cache-Control: no-store` 는 인증된 API 의 안전한 기본값. `Vary: Accept, Accept-Encoding, Authorization` 로 diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java index 0ca348d0..9c3a634d 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.web.auth; import dev.caskeleton.adapter.inbound.web.settings.CorsSettings; import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; +import jakarta.servlet.DispatcherType; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -83,6 +84,11 @@ public class SecurityConfig { .requestCache(cache -> cache.disable()) .authorizeHttpRequests( auth -> { + // The container's error dispatch for a request that already failed. Authorising it + // again turned an anonymous 400 into a 401 that blamed authentication. Only the + // dispatch type is opened: a request that names /error itself is still a request. + // The error controller writes nothing from the request (re-review RR-02-02). + auth.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll(); if (publicPaths.length > 0) { auth.requestMatchers(publicPaths).permitAll(); } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java index b5dbec59..76ac5ba9 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdvice.java @@ -12,6 +12,7 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; +import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import tools.jackson.databind.ObjectMapper; @@ -34,6 +35,13 @@ import tools.jackson.databind.json.JsonMapper; * still sees {@code 200 text/plain}. So when the String converter is about to write JSON, the * envelope is serialised here, with the same mapper and wire rules, and the converter writes that * text (review 2026-11-01 02-06). A text client still gets the plain string. + * + *

        A body sent with a 4xx or 5xx status is never wrapped. {@code success} is the discriminator a + * client branches on, so a {@code success:true} envelope around an error-status body tells it the + * request worked. Boot's {@code /error} map reached clients exactly that way until the error + * dispatch got its own envelope writer ({@code EnvelopeErrorController}, re-review 2026-11-03 + * RR-02-02). Failure envelopes come from the error handlers; a handler that returns some other body + * with an error status gets that body on the wire as it wrote it, not a false success. */ @RestControllerAdvice public final class EnvelopeBodyAdvice implements ResponseBodyAdvice { @@ -74,10 +82,18 @@ public final class EnvelopeBodyAdvice implements ResponseBodyAdvice { if (selectedContentType != null && !MediaType.APPLICATION_JSON.includes(selectedContentType)) { return body; } + if (isErrorStatus(response)) { + return body; + } Envelope envelope = Envelope.ok(body, ResponseMetaFactory.fromMdc()); if (StringHttpMessageConverter.class.isAssignableFrom(selectedConverterType)) { return objectMapper.writeValueAsString(envelope); } return envelope; } + + private static boolean isErrorStatus(ServerHttpResponse response) { + return response instanceof ServletServerHttpResponse servlet + && servlet.getServletResponse().getStatus() >= 400; + } } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java index 4ed63d8f..f75421a4 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeWireFormatConfig.java @@ -29,7 +29,7 @@ public class EnvelopeWireFormatConfig { } /** The module itself, for a writer that has no Boot mapper to take it from. */ - static SimpleModule module() { + public static SimpleModule module() { SimpleModule module = new SimpleModule("EnvelopeWireFormatModule"); module.setMixInAnnotation(Envelope.class, OmitNullFields.class); module.setMixInAnnotation(BulkEnvelope.class, OmitNullFields.class); diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorController.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorController.java new file mode 100644 index 00000000..2b60ccd8 --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorController.java @@ -0,0 +1,72 @@ +package dev.caskeleton.adapter.inbound.web.error; + +import dev.caskeleton.adapter.inbound.web.core.OwnsAbsoluteWebRoute; +import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; +import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.OperationalError; +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Objects; +import org.springframework.boot.webmvc.error.ErrorController; +import org.springframework.http.HttpStatusCode; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import tools.jackson.databind.ObjectMapper; + +/** + * Answers the container's error dispatch with the failure {@code Envelope}. + * + *

        A failure raised outside the MVC handler — the security firewall's {@code + * RequestRejectedException}, a filter's {@code sendError}, an exception thrown by a filter — never + * reaches {@link GlobalExceptionHandler}. The container forwards it to {@code /error} instead, + * where Boot's {@code BasicErrorController} wrote {@code {timestamp, status, error, path}}; the + * success advice then wrapped that map as {@code success:true}, and {@code path} echoed the raw + * request URI back (re-review 2026-11-03, RR-02-02). This replaces that controller: the error + * status is classified by the same table the exception handler uses, and the body is the failure + * envelope, with nothing from the request in it. + * + *

        Written straight to the response by {@link EnvelopeResponseWriter}, like the other refusals + * made outside a converter. An error dispatch has no handler of its own to negotiate for, and a + * browser's {@code Accept: text/html} would otherwise turn the error into a 406 about the error. + * + *

        A request that names {@code /error} itself carries no error status; it is answered as an + * unknown route. The security chain permits only the error dispatch, so such a request still needs + * a token under the JWT chain. + * + *

        An absolute route ({@link OwnsAbsoluteWebRoute}): the container forwards to {@code /error}, + * not to {@code /error} under the presentation prefix. + */ +@Controller +@OwnsAbsoluteWebRoute +@RequestMapping("${server.error.path:${error.path:/error}}") +public final class EnvelopeErrorController implements ErrorController { + + private final ObjectMapper objectMapper; + + /** + * Creates the controller. + * + * @param objectMapper Boot's mapper, which carries the envelope wire rules + */ + public EnvelopeErrorController(ObjectMapper objectMapper) { + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + } + + /** Writes the failure envelope for the status the error dispatch carries. */ + @RequestMapping + public void error(HttpServletRequest request, HttpServletResponse response) throws IOException { + if (response.isCommitted()) { + return; + } + ApiErrorCode code = + request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE) instanceof Integer status + ? HttpStatusErrorCodes.forStatus(HttpStatusCode.valueOf(status)) + : OperationalError.ROUTE_NOT_FOUND; + RetryAfterAdvisor.retryAfterSeconds(code) + .ifPresent(seconds -> response.setHeader(ApiHeaders.RETRY_AFTER, String.valueOf(seconds))); + EnvelopeResponseWriter.write(response, code, objectMapper); + } +} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java index 40a19f4e..f1e29196 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java @@ -407,7 +407,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { return null; } } - ApiErrorCode code = errorCodeFor(statusCode); + ApiErrorCode code = HttpStatusErrorCodes.forStatus(statusCode); if (code.httpStatus() >= 500) { log.error("spring mvc failure classified as {}", code.code(), ex); spanErrorRecorder.recordException(ex, code.code()); @@ -415,25 +415,4 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { return new ResponseEntity<>( ErrorResponseFactory.body(code, null), headers, HttpStatusCode.valueOf(code.httpStatus())); } - - private static ApiErrorCode errorCodeFor(HttpStatusCode status) { - return switch (status.value()) { - case 401 -> OperationalError.UNAUTHENTICATED; - case 403 -> OperationalError.FORBIDDEN; - case 404 -> OperationalError.ROUTE_NOT_FOUND; - case 405 -> OperationalError.METHOD_NOT_ALLOWED; - case 406 -> OperationalError.NOT_ACCEPTABLE; - case 412 -> OperationalError.PRECONDITION_FAILED; - case 413 -> OperationalError.PAYLOAD_TOO_LARGE; - case 414 -> OperationalError.URI_TOO_LONG; - case 415 -> OperationalError.UNSUPPORTED_MEDIA_TYPE; - case 429 -> OperationalError.RATE_LIMIT_EXCEEDED; - // Spring answers its async request timeout with 503: transient, not an internal fault. - case 503 -> WebTransportError.REQUEST_TIMEOUT; - default -> - status.is4xxClientError() - ? OperationalError.BAD_PARAMETER - : OperationalError.INTERNAL_ERROR; - }; - } } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java new file mode 100644 index 00000000..e37d6948 --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/HttpStatusErrorCodes.java @@ -0,0 +1,38 @@ +package dev.caskeleton.adapter.inbound.web.error; + +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.OperationalError; +import org.springframework.http.HttpStatusCode; + +/** + * The operational code a bare HTTP status stands for, when a status is all that is known. + * + *

        Two places only have a status to classify: a Spring MVC exception this adapter has no + * dedicated handler for, and the container's error dispatch for a failure raised outside the + * handler. They share this one table, so the same status never reaches a client as two codes. + */ +final class HttpStatusErrorCodes { + + private HttpStatusErrorCodes() {} + + static ApiErrorCode forStatus(HttpStatusCode status) { + return switch (status.value()) { + case 401 -> OperationalError.UNAUTHENTICATED; + case 403 -> OperationalError.FORBIDDEN; + case 404 -> OperationalError.ROUTE_NOT_FOUND; + case 405 -> OperationalError.METHOD_NOT_ALLOWED; + case 406 -> OperationalError.NOT_ACCEPTABLE; + case 412 -> OperationalError.PRECONDITION_FAILED; + case 413 -> OperationalError.PAYLOAD_TOO_LARGE; + case 414 -> OperationalError.URI_TOO_LONG; + case 415 -> OperationalError.UNSUPPORTED_MEDIA_TYPE; + case 429 -> OperationalError.RATE_LIMIT_EXCEEDED; + // Spring answers its async request timeout with 503: transient, not an internal fault. + case 503 -> WebTransportError.REQUEST_TIMEOUT; + default -> + status.is4xxClientError() + ? OperationalError.BAD_PARAMETER + : OperationalError.INTERNAL_ERROR; + }; + } +} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java index 5d8328ad..3f7989be 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure; +import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig; +import dev.caskeleton.adapter.inbound.web.error.EnvelopeErrorController; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.adapter.inbound.web.mvc.filter.JsonBodyLimitFilter; import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; @@ -12,8 +14,12 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer; +import org.springframework.boot.webmvc.autoconfigure.error.ErrorMvcAutoConfiguration; +import org.springframework.boot.webmvc.error.ErrorController; import org.springframework.context.annotation.Bean; import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; /** * Wires the web platform into a servlet application. @@ -30,8 +36,12 @@ import tools.jackson.core.StreamReadFeature; * *

        Every bean is {@link ConditionalOnMissingBean}: the platform supplies the one that would * otherwise be missing rather than the one that must be used. + * + *

        Before {@link ErrorMvcAutoConfiguration}, so the envelope error controller is the {@link + * ErrorController} that configuration finds and Boot's {@code BasicErrorController} backs off. Its + * error-page registration with the container stays: that is what forwards to {@code /error}. */ -@AutoConfiguration +@AutoConfiguration(before = ErrorMvcAutoConfiguration.class) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnProperty( prefix = "app.web.mvc", @@ -54,6 +64,22 @@ public class WebMvcPlatformAutoConfiguration { return new GlobalExceptionHandler(spanErrorRecorderProvider); } + /** + * Answers the container's error dispatch — failures raised outside the MVC handler — with the + * failure envelope instead of Boot's {@code {timestamp, status, error, path}} map. + * + *

        Boot's mapper when there is one, which already carries the envelope wire rules; otherwise a + * mapper with only those rules, as {@code EnvelopeBodyAdvice} does without Boot. + */ + @Bean + @ConditionalOnMissingBean(ErrorController.class) + public EnvelopeErrorController envelopeErrorController( + ObjectProvider objectMapper) { + return new EnvelopeErrorController( + objectMapper.getIfAvailable( + () -> JsonMapper.builder().addModule(EnvelopeWireFormatConfig.module()).build())); + } + /** * Assigns the correlation identifiers, validating anything a caller proposed. With a tracer in * the composition the trace id is the tracer's: the filter runs inside Boot's server observation diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java index e46ec3d6..8fcae639 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.inbound.web.observability; +import dev.caskeleton.application.idempotency.IdempotencyExecutor; import dev.caskeleton.shared.error.ApiErrorCode; import java.util.Map; import java.util.OptionalInt; @@ -13,17 +14,26 @@ public final class RetryAfterAdvisor { /** Per-code {@code Retry-After} values (seconds). */ private static final Map RETRY_AFTER_SECONDS = Map.of( - "RATE_LIMIT_EXCEEDED", 1, - // Below the default processing lease (30s): the resend arrives while the first attempt - // can still finish, and an early resend costs one more 409. docs/web/http-contract.md. - "IDEMPOTENT_IN_FLIGHT", 2, - "AUTH_KID_UNKNOWN", 5, - "AUTH_JWKS_UNAVAILABLE", 30, - "DEPENDENCY_TIMEOUT", 2, - "DEPENDENCY_CONNECT_FAILED", 2, - "DEPENDENCY_DNS_FAILED", 5, - "DEPENDENCY_5XX_SERVER", 2, - "DEPENDENCY_CIRCUIT_OPEN", 10); + "RATE_LIMIT_EXCEEDED", + 1, + // The application's value, which the processing-lease check also reads: the resend + // arrives while the first attempt can still finish. docs/web/http-contract.md §2. + "IDEMPOTENT_IN_FLIGHT", + Math.toIntExact(IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER.toSeconds()), + "AUTH_KID_UNKNOWN", + 5, + "AUTH_JWKS_UNAVAILABLE", + 30, + "DEPENDENCY_TIMEOUT", + 2, + "DEPENDENCY_CONNECT_FAILED", + 2, + "DEPENDENCY_DNS_FAILED", + 5, + "DEPENDENCY_5XX_SERVER", + 2, + "DEPENDENCY_CIRCUIT_OPEN", + 10); private RetryAfterAdvisor() {} diff --git a/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/mvc/JwtChainErrorDispatchIT.java b/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/mvc/JwtChainErrorDispatchIT.java new file mode 100644 index 00000000..3188c65b --- /dev/null +++ b/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/mvc/JwtChainErrorDispatchIT.java @@ -0,0 +1,91 @@ +package dev.caskeleton.adapter.inbound.web.testkit.mvc; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +/** + * The error dispatch under the production JWT security chain, over a real Tomcat. + * + *

        The chain authorises every dispatch, the container's error dispatch to {@code /error} + * included. {@code /error} is not a public path, so an anonymous request whose original failure was + * a 400 used to come back as 401 — the client was told to authenticate when its request was + * malformed (re-review 2026-11-03, RR-02-02). The error dispatch is now permitted; a request that + * names {@code /error} directly is still a request and still needs a token. + * + *

        The chain is {@code WebSecurityAutoConfiguration} itself. The JWT decoder is lazy, so the + * unreachable issuer below is never contacted: no request here carries a token. + */ +@SpringBootTest( + classes = JwtChainErrorDispatchIT.JwtChainApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = { + "spring.main.banner-mode=off", + "spring.mvc.problemdetails.enabled=false", + "app.web.mvc.enabled=true", + "app.security.auth-mode=jwt", + "app.security.issuer-uri=https://issuer.invalid/realms/ca", + "app.security.audience=ca-skeleton-api", + "app.security.public-paths=/api/v1/fixtures/**", + "app.cors.enabled=false" + }) +class JwtChainErrorDispatchIT { + + private final HttpClient client = + HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); + + @LocalServerPort private int port; + + @Test + @DisplayName("JWT 체인에서 익명 요청이 핸들러 밖에서 400 으로 거부되면 401 이 아니라 400 실패 Envelope 로 나간다") + void anAnonymousRequestRejectedOutsideTheHandlerKeepsItsOwnStatus() throws Exception { + // when + HttpResponse rejected = get(WebContractAssertions.FIREWALL_REJECTED_PATH); + + // then + assertThat(rejected.statusCode()).isEqualTo(400); + WebContractAssertions.assertFailureEnvelope(rejected, "BAD_PARAMETER"); + } + + @Test + @DisplayName("오류 디스패치만 허용한다 — /error 를 직접 부른 익명 요청은 여전히 401 이다") + void aDirectRequestForTheErrorPathStillNeedsAToken() throws Exception { + // when + HttpResponse direct = get("/error"); + + // then + assertThat(direct.statusCode()).isEqualTo(401); + } + + private HttpResponse get(String path) throws Exception { + return client.send( + HttpRequest.newBuilder(URI.create("http://localhost:" + port + path)) + .header("Accept", "application/json") + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()); + } + + /** + * The production web stack minus {@link WebAdapterAutoConfiguration}, whose request-logging + * filter needs the composition root's pseudonymizer, plus that root's envelope wire format; the + * security chain is the shipped one. + */ + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration(exclude = WebAdapterAutoConfiguration.class) + @Import({ContractFixtureController.class, EnvelopeWireFormatConfig.class}) + static class JwtChainApplication {} +} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java index 68a457f6..49028fc1 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/envelope/EnvelopeBodyAdviceTest.java @@ -23,6 +23,7 @@ import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.test.json.JsonCompareMode; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.bind.annotation.GetMapping; @@ -64,6 +65,12 @@ class EnvelopeBodyAdviceTest { return "{\"openapi\":\"3.1.0\"}".getBytes(StandardCharsets.UTF_8); } + /** A failure status with a body that is not an envelope. */ + @GetMapping("/probe/conflict") + public ResponseEntity> conflict() { + return ResponseEntity.status(409).body(Map.of("k", "v")); + } + @GetMapping("/probe/bulk") public BulkEnvelope> bulk() { return BulkEnvelope.allOk(List.of(Map.of("k", "v")), new ResponseMeta("r", "t", "c")); @@ -149,6 +156,25 @@ class EnvelopeBodyAdviceTest { .andExpect(content().json("{\"openapi\":\"3.1.0\"}", JsonCompareMode.STRICT)); } + /** + * A 4xx/5xx body is never a success envelope. {@code success} is the discriminator clients branch + * on (docs/web/http-contract.md §1), so wrapping an error-status body as {@code success:true} + * tells a contract-following client the request worked — Boot's {@code /error} map arrived that + * way (re-review 2026-11-03, RR-02-02). The body is left as the handler wrote it. + */ + @Test + @DisplayName("4xx·5xx 응답 본문은 success:true Envelope 로 감싸지 않는다") + void anErrorStatusBodyIsNotWrappedAsASuccess() throws Exception { + // when + var result = mvc.perform(get("/probe/conflict").accept(MediaType.APPLICATION_JSON)); + + // then + result + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.success").doesNotExist()) + .andExpect(content().json("{\"k\":\"v\"}", JsonCompareMode.STRICT)); + } + @SpringBootConfiguration @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) static class TestBootstrap {} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java index 2e1a8412..91ee5f16 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.web.error; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; +import dev.caskeleton.application.idempotency.IdempotencyCompletionUnknownException; import dev.caskeleton.application.idempotency.IdempotencyInFlightException; import dev.caskeleton.application.idempotency.IdempotencyRequestMismatchException; import dev.caskeleton.shared.error.Category; @@ -74,4 +75,24 @@ class IdempotencyExceptionMappingTest { false, ClientErrorMessages.of(Category.VALIDATION)); } + + @Test + @DisplayName("complete 단계 결과 불명은 실행 전 거부(IDEMPOTENCY_UNAVAILABLE)와 다른 code 의 retryable 503 이다") + void completionUnknownMapsToItsOwnRetryable503SoTheClientDoesNotReadItAsNotApplied() { + // given + IdempotencyCompletionUnknownException unknown = new IdempotencyCompletionUnknownException(); + + // when + ResponseEntity> response = handler.handleCarrier(unknown); + + // then + assertThat(response) + .extracting( + r -> r.getStatusCode().value(), + r -> r.getHeaders().getFirst(ApiHeaders.RETRY_AFTER), + r -> r.getBody().error().code(), + r -> r.getBody().error().category(), + r -> r.getBody().error().retryable()) + .containsExactly(503, null, "IDEMPOTENCY_COMPLETION_UNKNOWN", "TRANSIENT_DEPENDENCY", true); + } } diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/mvc/WebContractAssertions.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/mvc/WebContractAssertions.java index 84f47ef5..13cdb94e 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/mvc/WebContractAssertions.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/mvc/WebContractAssertions.java @@ -8,6 +8,8 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; /** * The status contract as socket-level assertions, written once and run against every container. @@ -22,6 +24,11 @@ import java.time.Duration; */ public final class WebContractAssertions { + /** A path the servlet firewall refuses before any handler runs ({@code ;} in the URI). */ + public static final String FIREWALL_REJECTED_PATH = "/api/v1/fixtures/f1;x=1"; + + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); @@ -122,6 +129,46 @@ public final class WebContractAssertions { assertThat(post("/api/v1/fixtures", "{\"name\":").statusCode()).isEqualTo(400); } + /** + * An error raised outside the MVC handler is still a failure envelope. + * + *

        The firewall rejects the request before any controller runs, and the container answers it + * with an error dispatch to {@code /error}. Boot's default error controller wrote a map there, + * which the success advice then wrapped as {@code success:true} with the raw request path inside + * (re-review 2026-11-03, RR-02-02). MockMvc performs no error dispatch, so only a container can + * show this. + */ + public void aRequestRejectedOutsideTheHandlerIsAFailureEnvelope() + throws IOException, InterruptedException { + HttpResponse rejected = get(FIREWALL_REJECTED_PATH); + + assertThat(rejected.statusCode()).isEqualTo(400); + assertFailureEnvelope(rejected, "BAD_PARAMETER"); + } + + /** + * Asserts the failure envelope of {@code docs/web/http-contract.md} §1 on an error response. + * + * @param response a response the container wrote through its error dispatch + * @param expectedCode the {@code error.code} the status maps to + */ + public static void assertFailureEnvelope(HttpResponse response, String expectedCode) { + JsonNode body = JSON.readTree(response.body()); + assertThat(body.path("success").isBoolean() && !body.path("success").booleanValue()) + .as( + "a 4xx/5xx body that says success:true is read as a success by a client that follows" + + " the contract: %s", + response.body()) + .isTrue(); + assertThat(body.path("error").path("code").asString()).isEqualTo(expectedCode); + assertThat(body.has("data")).as("a failure envelope has no data key").isFalse(); + assertThat(response.body()) + .as("the error body must not echo the request path back") + .doesNotContain(";x=1") + .doesNotContain("\"path\"") + .doesNotContain("timestamp"); + } + /** Runs every assertion, so a lane cannot silently cover a subset. */ public void assertWholeContract() throws IOException, InterruptedException { createdCarriesALocationHeader(); @@ -131,6 +178,7 @@ public final class WebContractAssertions { anUnknownMethodOnAKnownRouteIsRefused(); anUnsupportedMediaTypeIsRefused(); malformedJsonIsRefused(); + aRequestRejectedOutsideTheHandlerIsAFailureEnvelope(); } private HttpResponse post(String path, String body) @@ -143,6 +191,12 @@ public final class WebContractAssertions { HttpResponse.BodyHandlers.ofString()); } + private HttpResponse get(String path) throws IOException, InterruptedException { + return client.send( + HttpRequest.newBuilder(uri(path)).header("Accept", "application/json").GET().build(), + HttpResponse.BodyHandlers.ofString()); + } + private URI uri(String path) { return URI.create("http://localhost:" + port + path); } 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 3a650c0b..089d298d 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,5 +1,6 @@ package dev.caskeleton.webtestkit; +import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeWireFormatConfig; 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; @@ -31,6 +32,10 @@ import org.springframework.security.web.SecurityFilterChain; * are the "sum of the leaf" the paragraph above keeps out. Excluded by class, so a rename breaks * compilation rather than the gate. The third root, {@code WebMethodSecurityAutoConfiguration}, is * left in: no fixture route runs a permissioned use case, so it decides nothing here. + * + *

        {@link EnvelopeWireFormatConfig} is imported by name from the excluded web root: it is the + * wire shape of every envelope this gate reads (a failure body has no {@code data} key), not a + * capability, and without it the gate would certify {@code "data": null} that no deployment sends. */ // 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 @@ -40,7 +45,11 @@ import org.springframework.security.web.SecurityFilterChain; @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration( exclude = {WebAdapterAutoConfiguration.class, WebSecurityAutoConfiguration.class}) -@Import({ContractFixtureController.class, FaultFixtureController.class}) +@Import({ + ContractFixtureController.class, + FaultFixtureController.class, + EnvelopeWireFormatConfig.class +}) public class ContractFixtureApplication { /** diff --git a/src/adapter/outbound/cache-redis/CLAUDE.md b/src/adapter/outbound/cache-redis/CLAUDE.md index 9060c016..d3927556 100644 --- a/src/adapter/outbound/cache-redis/CLAUDE.md +++ b/src/adapter/outbound/cache-redis/CLAUDE.md @@ -128,12 +128,15 @@ Focused tests drive the semantic adapters against `InMemorySemanticRedisCommands served through `StubRedisRuntimeClient`. R1/R2 promotion requires a separate real Redis service lane; it may never be silently skipped when selected. -Two real-server lanes. `redisContainerContractTest` (integration category, in `integrationCheck` and -this leaf's `mainCheck`) starts its own Redis with Testcontainers — the `redis` image of -`config/testing/container-images.properties`, loading `infra/redis-sdk/acl/all-accounts.acl` — and -runs `LiveRedisCacheRegionContractTest` and `LiveRedisDistributedLeaseContractTest` (the -`application-core` port contracts the in-memory fakes also pass), `LiveRedisSemanticPortsTest` and -`LiveRedisSemanticScriptAclProbeTest`; a skip fails it (review 2026-11-01 05-16). `RedisTestContainer` +Two real-server lanes. `redisContainerContractTest` (integration category, in `integrationCheck` only — +not in this leaf's `mainCheck` too, which ran it twice per push to main) starts its own Redis with Testcontainers — the `redis` image of +`config/testing/container-images.properties`, loading `infra/redis-sdk/acl/lane-fixture-accounts.acl` — and +runs `LiveRedisCacheRegionContractTest`, `LiveRedisDistributedLeaseContractTest` and +`LiveRedisIdempotencyStoreContractTest` (the `application-core` port contracts the in-memory fakes +also pass), `LiveRedisSemanticPortsTest` and `LiveRedisSemanticScriptAclProbeTest`; a skip fails it +(review 2026-11-01 05-16). The idempotency contract was on the explicit-only topology lane alone +until review 2026-11-03 RR-04-05, so the Lua state machine's stale-handle, renew-refusal and +retry cases reached a real server in no gate. `RedisTestContainer` starts the server only when that lane names the ACL file. `redisTopologyTest` is the external-topology lane, declared through `ca.redis-topology-lane`. This @@ -177,6 +180,15 @@ deployment still gets exactly one client and one event loop. The `SCRIPT` lane i the reason it exists: `SCRIPT LOAD` and `EVALSHA` belong to the advanced account, so the account that reads a cache entry cannot execute a script. +The cache's conditional writes run on the same account but on a lane of their own, +`CacheScriptLane.CACHE_SCRIPT` (`app.capabilities.cache.maximum-script-connections`, contributed by +`RedisCacheConfig` as a `RedisLaneContribution`). Do not move them back to `SCRIPT`: that lane is the +idempotency, rate-limit and lease budget, and a cache under load must not take it (review 2026-11-03 +README §4, RR-04-02). Each lane's wait, refusals and reconnects are meters of `redis-runtime` +(`RedisLaneMetrics`, `redis.lane.*`, tag `lane`), so whether the cache stays off `SCRIPT` is a query, +not an assumption. The `DEGRADED` health order ships with `redis-runtime`, which reports the +status (`config/module-defaults/redis-runtime.yml`, RR-04-10). + A Cluster transaction runs on one node, so the SDK's `RedisTransactionRunner` derives a routing key from the watched keys (or an explicit `RedisSlotTag`) and borrows `RedisSdkLane.TRANSACTION`, which is pinned to its key's owner, on the node that owns that slot. Routed leases are never pooled: a pooled connection is pinned to the previous caller's diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 0be4ad8e..99026fa9 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -97,7 +97,10 @@ Connection lane limits and command queue limits are different contracts. In part - `app.redis.capacity.maximum-in-flight-commands` bounds the per-connection command queue. - `app.redis.capacity.maximum-script-connections` bounds physical SCRIPT lane connections - (default 8). + (default 8). Idempotency, rate limiting and leases share them. +- `app.capabilities.cache.maximum-script-connections` (`APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS`) + bounds the cache's own script lane (`CacheScriptLane`, default 4), contributed only when the cache + binding is `redis`. See "Why the cache has its own script lane" below. - `app.redis.lifecycle.acquire-timeout` (default 2s) is how long a borrow waits for a returned connection when its lane is full. @@ -153,7 +156,7 @@ Important contracts: Every lookup returns a `CacheWriteCondition` naming the state it saw — `absent`, `vacant:` (an invalidation marker, an entry of an older region generation, an expired entry) or `present:`. A record that carries the condition applies only while the key is still in that -state (registered program, SCRIPT lane). This is what rejects a source load that began before an +state (registered program, cache script lane). This is what rejects a source load that began before an invalidation and finished after it. A hit also returns an opaque SHA-1 observation token over the stored bytes. SHA-1 here is **not a @@ -181,10 +184,43 @@ example one written by `UPSERT` as `rev-1`), another schema version, a generatio writer knows — is `NOT_RECORDED_CONDITION`. Both conditional intents, and any record carrying a write condition, run registered scripts, so -they borrow the SCRIPT lane (the advanced account when one is configured, the application account -otherwise). The application account is not granted `EVALSHA`; on the REGULAR lane every conditional -write came back `INDETERMINATE`. Unconditioned `UPSERT` and `ONLY_IF_ABSENT` stay on the REGULAR -lane. +they run on the scripting account (the advanced account when one is configured, the application +account otherwise), on the cache's own script lane. The application account is not granted +`EVALSHA`; on the REGULAR lane every conditional write came back `INDETERMINATE`. Unconditioned +`UPSERT` and `ONLY_IF_ABSENT` stay on the REGULAR lane. + +### Why the cache has its own script lane + +Recording with the condition a lookup returned is the normal way to use this port, so nearly every +cache fill is a script. On the runtime's SCRIPT lane those fills shared eight connections per pod +with idempotency claims, rate-limit evaluations and lease calls, and a timed-out lease is discarded +rather than pooled, so each timeout also cost a reconnect. A slow Redis or a burst of misses after a +region invalidation filled the lane with cache work; an idempotency claim then waited out its +timeout and answered `UNAVAILABLE`, and a rate-limit call fell to its failure policy. The cache is a +speed feature that may degrade; idempotency, rate limiting and leases are correctness features that +must not (review 2026-11-03 README §4, RR-04-02). + +So `CacheScriptLane.CACHE_SCRIPT` is a lane of its own — the same scripting account, its own +connections, its own ceiling (`app.capabilities.cache.maximum-script-connections`, default 4). A cache +that runs out of them degrades (`DEGRADED_UNAVAILABLE`, nothing sent) without touching the SCRIPT +lane. Alternatives not taken: a per-capability permit cap inside the shared SCRIPT lane (still one +pool of connections and one reconnect cost), and running the cache programs on the REGULAR lane +(grants the application account `EVALSHA`, which the account split exists to withhold). + +Whether the split holds under load is visible per lane. With a `MeterRegistry` in the context, +`redis-runtime` registers these for every lane it pools — `REGULAR`, `SCRIPT`, `CACHE_SCRIPT` and the +typed SDK's — tagged `lane=` (`RedisLaneMetrics`; rows in `docs/registries/metrics.yaml`): + +| Meter | Type | Read it as | +| --- | --- | --- | +| `redis.lane.acquire.wait.seconds` (`outcome` = `admitted`/`refused`) | timer, histogram | how long a borrow queued for a connection; a growing admitted p99 comes before refusals | +| `redis.lane.acquire.refused.total` (`reason` = `saturated`/`closing`/`interrupted`/`connect_failed`) | counter | a borrow that got no connection, nothing sent; `saturated` on `SCRIPT` is the starvation this lane exists to prevent | +| `redis.lane.connections.opened.total` | counter | new connections; after warm-up every one is a reconnect | +| `redis.lane.connections.discarded.total` (`reason` = `invalidated`/`broken`) | counter | connections closed instead of pooled — `invalidated` is a timed-out or failed call (the lease is not reused), and is what the reconnects replace | +| `redis.lane.connections.active`, `redis.lane.connections.pending` | gauge | connections lent out now; borrows waiting now | + +Every counter series exists from startup at zero, so an alert on "refusals above zero" sees the first +one. A lane refusal is also logged, per call, by `RedisSemanticFailureLogger`. ### Key invalidation @@ -300,10 +336,21 @@ Useful focused checks: `redisContainerContractTest` runs the cache-region and lease port contracts (the ones the in-memory fakes pass) and the live semantic-port tests against a Redis it starts itself, under the standalone -topology's ACL file. It is in `integrationCheck` and `mainCheck`; the image is +topology's ACL file. It is in `integrationCheck` (integration-main.yml's `integration-check` job), and +only there: listing it in `mainCheck` as well ran it twice on every push to main. The image is `config/testing/container-images.properties` `redis`. Live Redis/topology qualification remains separate from fast unit tests. A release claim for a specific Redis topology or ACL layout requires the corresponding live qualification lane; the in-memory gateway is for deterministic contract tests, not evidence that an external Redis deployment accepts the same network/TLS/ACL configuration. + +## 아직 내보내지 않는 지표 + +`redis.capability.*` 여섯 개(operations.total, duration.seconds, admission.rejected.total, +inflight.total, readiness.total, lifecycle.drain.total)는 redis-production-capability 설계(Task 16)에 +있었지만 어떤 코드도 내보내지 않았다. 레지스트리(`docs/registries/metrics.yaml`)와 incident runbook이 있는 +것처럼 적고 있어서, 2026-11-03 재리뷰 수정에서 레지스트리에서 빼고 runbook을 지금 내보내는 +`redis.lane.*`(redis-runtime, lane별 대기·거절·연결) 기준으로 고쳤다. capability 단위 지표가 필요해지면 +operation 결과를 아는 semantic adapter(이 leaf)에서 내보내고, 그때 레지스트리에 다시 넣는다. + diff --git a/src/adapter/outbound/cache-redis/build.gradle b/src/adapter/outbound/cache-redis/build.gradle index fd9ac4d6..1719cf67 100644 --- a/src/adapter/outbound/cache-redis/build.gradle +++ b/src/adapter/outbound/cache-redis/build.gradle @@ -48,7 +48,8 @@ dependencies { // command surface the catalog exists to prevent. Zero imports. // io.micrometer:micrometer-core — observation leaves this leaf as RedisObservation through a // Consumer sink; binding it to a meter registry belongs to the composition root, not here. - // Zero imports. + // Zero imports. The connection lanes' meters, CACHE_SCRIPT's included, are redis-runtime's + // (RedisLaneMetrics): the lanes are pooled there, so that is where they are counted. } // Redis topology qualification is opt-in and owned by `ca.redis-topology-lane`: mode/property @@ -69,8 +70,12 @@ redisTopologyLane { // adapters' port contracts reached a real server in no stage, and the fake and the adapter could hide // the same defect (05-02, 05-03). The image is config/testing/container-images.properties' `redis`, // and the ACL file is infra/redis-sdk's own, so the accounts and their rights are the standalone -// topology's. Integration category: integrationCheck runs it, and so does this leaf's mainCheck, like -// the HTTP client's Toxiproxy lane. Sentinel, cluster and TLS remain the topology lane's. +// topology's. Integration category, so integrationCheck runs it — integration-main.yml's +// `integration-check` job, on every push to main and nightly. It is deliberately not in this leaf's +// mainCheck as well: `main-check` and `integration-check` are two jobs of the same workflow run, so a +// lane in both started a second Redis container and ran every live contract twice per push without +// covering anything the first run did not (found while fixing review 2026-11-03). Sentinel, cluster +// and TLS remain the topology lane's. def redisAclDirectory = rootProject.projectDir.parentFile.toPath().resolve('infra/redis-sdk/acl').toFile() strictTestLanes { lane('redisContainerContractTest') { @@ -78,15 +83,16 @@ strictTestLanes { description = 'Runs the Redis semantic adapters\' live contracts against a Testcontainers Redis on the pinned image.' requires 'dev.caskeleton.adapter.outbound.cache.redis.cache.LiveRedisCacheRegionContractTest', 'dev.caskeleton.adapter.outbound.cache.redis.lease.LiveRedisDistributedLeaseContractTest', + // The fake carries a Java copy of the idempotency Lua state machine; only a real + // server proves the two agree (05-02 was the fake copying the Lua's bug). It ran on + // the explicit-only topology lane alone, so no gate ever ran it (RR-04-05). + 'dev.caskeleton.adapter.outbound.cache.redis.idempotency.LiveRedisIdempotencyStoreContractTest', 'dev.caskeleton.adapter.outbound.cache.redis.LiveRedisSemanticPortsTest', 'dev.caskeleton.adapter.outbound.cache.redis.capability.LiveRedisSemanticScriptAclProbeTest' rejectSkipped = true - systemProperty 'redis.container.acl-file', new File(redisAclDirectory, 'all-accounts.acl').absolutePath + systemProperty 'redis.container.acl-file', new File(redisAclDirectory, 'lane-fixture-accounts.acl').absolutePath inputDirectory redisAclDirectory shouldRunAfter 'test' } } -tasks.named('mainCheck') { - dependsOn 'redisContainerContractTest' -} diff --git a/src/adapter/outbound/cache-redis/gradle.lockfile b/src/adapter/outbound/cache-redis/gradle.lockfile index 05009344..2c16a9d3 100644 --- a/src/adapter/outbound/cache-redis/gradle.lockfile +++ b/src/adapter/outbound/cache-redis/gradle.lockfile @@ -50,7 +50,7 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnota io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor io.lettuce:lettuce-core:6.8.2.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.7=testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-jakarta9:1.16.7=testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.netty:netty-buffer:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -103,7 +103,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.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath -org.hdrhistogram:HdrHistogram:2.2.2=testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle org.jetbrains:annotations:17.0.0=testCompileClasspath,testRuntimeClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath @@ -116,7 +116,7 @@ org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs -org.latencyutils:LatencyUtils:2.0.3=testRuntimeClasspath +org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath org.objenesis:objenesis:3.3=testRuntimeClasspath diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScriptLane.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScriptLane.java new file mode 100644 index 00000000..152d45ee --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScriptLane.java @@ -0,0 +1,34 @@ +package dev.caskeleton.adapter.outbound.cache.redis.cache; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccount; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; + +/** + * The cache's own script lane, so a cache's load cannot starve a correctness capability (review + * 2026-11-03 README §4, RR-04-02). + * + *

        Every conditional cache write is a registered program, and a registered program needs the + * scripting account. On the runtime's SCRIPT lane those writes shared eight connections with + * idempotency claims, rate-limit evaluations and lease calls — and the normal way to use the cache + * (record with the condition the lookup returned) makes every cache fill a script. A slow Redis or + * a burst of misses after a region invalidation then held those connections with cache work while + * an idempotency claim waited out its timeout and failed. The cache is a speed feature and may + * degrade; idempotency and leases are correctness features and must not. They get separate + * connection budgets. + * + *

        Same account as the SCRIPT lane: the grant is the same, only the connections and their ceiling + * ({@code app.capabilities.cache.maximum-script-connections}) are the cache's. Alternatives that + * were not taken: a per-capability permit cap inside the shared SCRIPT lane would still share the + * connections and their reconnect cost after a discarded lease; running cache programs on the + * REGULAR lane would grant the application account {@code EVALSHA}, which the account split exists + * to withhold. + */ +public enum CacheScriptLane implements RedisLane { + /** The cache region's conditional and revision-ordered writes. */ + CACHE_SCRIPT; + + @Override + public RedisAccount account() { + return RedisAccount.ADVANCED; + } +} diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java index 95b3a6e3..7cd93fbf 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapter.java @@ -68,8 +68,10 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort implements CacheRegionPortThe runtime pools a contributed lane like its own SCRIPT lane, on the same scripting + * account, but with connections and a ceiling of its own: the cache's conditional writes no + * longer compete with idempotency claims, rate-limit evaluations and lease calls for the SCRIPT + * lane (review 2026-11-03 README §4, RR-04-02). + * + * @param capabilities the capability settings + * @return the lane contribution + */ + @Bean + @ConditionalOnProperty(name = CapabilitySelectors.CACHE_DEFAULT_BINDING, havingValue = "redis") + RedisLaneContribution redisCacheScriptLane(RedisCapabilitySettings capabilities) { + RedisCapabilitySettings.Cache cache = capabilities.getCache(); + cache.validate(); + return new RedisLaneContribution( + CacheScriptLane.CACHE_SCRIPT, cache.getMaximumScriptConnections()); + } } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilitySettings.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilitySettings.java index c10d57be..5303e105 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilitySettings.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilitySettings.java @@ -86,6 +86,7 @@ public class RedisCapabilitySettings { private Duration positiveHardTtl = Duration.ofMinutes(5); private Duration negativeTtl = Duration.ofSeconds(10); private Duration minimumHardTtl = Duration.ofSeconds(1); + private int maximumScriptConnections = 4; /** * Reports whether the default binding selected Redis. @@ -119,6 +120,10 @@ public class RedisCapabilitySettings { if (keyVersion < 1) { throw new CapabilityStartupValidationException("the cache key version must be positive"); } + if (maximumScriptConnections < 1) { + throw new CapabilityStartupValidationException( + "the cache script lane needs at least one connection"); + } } public Map getBindings() { @@ -192,6 +197,23 @@ public class RedisCapabilitySettings { public void setMinimumHardTtl(Duration minimumHardTtl) { this.minimumHardTtl = minimumHardTtl; } + + /** + * The ceiling on the cache's own script-lane connections. + * + *

        Separate from {@code app.redis.capacity.maximum-script-connections}, which idempotency, + * rate limiting and leases share: a cache is a speed feature and may run out of connections and + * degrade; it must not take them from the correctness features (review 2026-11-03 README §4). + * + * @return the ceiling, at least 1 + */ + public int getMaximumScriptConnections() { + return maximumScriptConnections; + } + + public void setMaximumScriptConnections(int maximumScriptConnections) { + this.maximumScriptConnections = maximumScriptConnections; + } } /** Edge rate-limit provider composition. */ diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbe.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbe.java index dd88d831..431246aa 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbe.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbe.java @@ -28,11 +28,12 @@ import org.springframework.beans.factory.SmartInitializingSingleton; * {@code {1}} only when the value it wrote reads back. * *

        A cache-only deployment is probed too: its conditional writes and revision-ordered writes are - * registered programs on the same lane, and without the permission every one of them would come + * registered programs on the same account, and without the permission every one of them would come * back degraded while plain reads looked healthy. Its probe runs only what the cache programs call - * ({@code GET}, {@code SET}), and a Redis it cannot reach at startup is logged, not fatal — a cache - * outage degrades, it never stops a pod from starting. A server that answers and refuses the - * scripts is a configuration error and fails startup as it does for the correctness roles. + * ({@code GET}, {@code SET}). Only a server that answers and refuses the scripts — an ACL refusal, + * {@code NOSCRIPT}, or a reply other than the value the probe wrote — is a configuration error and + * fails startup as it does for the correctness roles. Every other failure is a cache outage and is + * logged, not fatal: a cache outage degrades, it never stops a pod from starting. */ final class RedisSemanticScriptAclProbe implements SmartInitializingSingleton { @@ -89,7 +90,7 @@ final class RedisSemanticScriptAclProbe implements SmartInitializingSingleton { try { probe(CACHE_PROBE_SCRIPT); } catch (CapabilityStartupValidationException failure) { - if (!unreachable(failure.getCause())) { + if (refusedByTheServer(failure.getCause())) { throw new CapabilityStartupValidationException( "Redis cache is selected but its account cannot run the cache's conditional-write" + " scripts (SCRIPT LOAD/EVALSHA, GET, SET); every conditional record would" @@ -98,15 +99,49 @@ final class RedisSemanticScriptAclProbe implements SmartInitializingSingleton { failure.getCause()); } LOG.warn( - "Redis cache is selected but Redis was unreachable at startup; the cache script" - + " permission is unverified and the cache runs degraded until Redis answers", + "Redis cache is selected but the startup script probe could not complete; the cache" + + " script permission is unverified and the cache runs degraded until Redis answers", failure.getCause()); } } } - private static boolean unreachable(Throwable cause) { - return cause instanceof RedisLaneUnavailableException || cause instanceof TimeoutException; + /** + * Whether the cache probe failed because the server refused the cache's scripts. + * + *

        "Refused" is a statement about the account, and only three answers make it: an ACL refusal + * ({@code NOPERM}, or a script's inner command denied), {@code NOSCRIPT} for the program the same + * connection had just loaded, and a reply other than the value the probe wrote. The check used to + * run the other way — only a lane refusal or a timeout counted as "unreachable" and everything + * else was a configuration error — so a connection that dropped mid-probe, a restarting Redis + * answering {@code LOADING}, or a busy one answering {@code BUSY} stopped a cache-only pod from + * starting, against this leaf's promise that a cache outage never does (review 2026-11-03 + * RR-04-07). + * + * @param cause the probe's failure + * @return {@code true} when the account, not the server's availability, is at fault + */ + private static boolean refusedByTheServer(Throwable cause) { + for (Throwable current = cause; + current != null; + current = current.getCause() == current ? null : current.getCause()) { + if (current instanceof CapabilityStartupValidationException) { + // The probe ran and read back something other than what it wrote. + return true; + } + if (current instanceof RedisLaneUnavailableException || current instanceof TimeoutException) { + return false; + } + String message = current.getMessage(); + if (message != null + && (message.startsWith("NOPERM") + || message.startsWith("NOSCRIPT") + || message.contains("no permissions") + || message.contains("ACL failure"))) { + return true; + } + } + return false; } private void probe(byte[] script) { diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java index b0ddddda..47e32400 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java @@ -141,6 +141,12 @@ public final class IdempotencyScripts { * it started from and the lease it asked for. A retry from that revision with the same lease is * the same renewal; with a different lease it is a different request, because confirming it would * leave the caller believing it holds the record for a lease the record does not carry. + * + *

        The key's own TTL is stretched to cover the new lease. Claim sets it to the replay TTL, + * which may be shorter than a lease renewed past it; the key then expired while the holder was + * still executing, and the next request got a fresh claim and ran the side effect again (review + * 2026-11-03 RR-04-08). The TTL is only ever lengthened here — completion sets the replay TTL + * again. */ private static final String RENEW = """ @@ -177,6 +183,10 @@ public final class IdempotencyScripts { redis.call('HSET', KEYS[1], 'leaseUntil', nowMillis + tonumber(ARGV[4]), 'rev', rev + 1, 'renewedFromRev', ARGV[2], 'renewedLease', ARGV[4]) + local ttl = redis.call('PTTL', KEYS[1]) + if ttl >= 0 and ttl < tonumber(ARGV[4]) then + redis.call('PEXPIRE', KEYS[1], ARGV[4]) + end return {'APPLIED', attempt, rev + 1, owner, '', ''} """; diff --git a/src/adapter/outbound/cache-redis/src/main/resources/config/module-defaults/cache-redis.yml b/src/adapter/outbound/cache-redis/src/main/resources/config/module-defaults/cache-redis.yml index eab2668f..8dc4b8f2 100644 --- a/src/adapter/outbound/cache-redis/src/main/resources/config/module-defaults/cache-redis.yml +++ b/src/adapter/outbound/cache-redis/src/main/resources/config/module-defaults/cache-redis.yml @@ -39,6 +39,10 @@ app: # Floor on the hard TTL. Below it, entries expire faster than the round trip that wrote them: # every read misses and every miss writes. minimum-hard-ttl: ${APP_CACHE_REDIS_MINIMUM_HARD_TTL:1s} + # The cache's own script-lane connections, apart from the SCRIPT lane that idempotency, rate + # limiting and leases share (app.redis.capacity.maximum-script-connections). A cache under + # load runs out of these and degrades; it cannot take the correctness features' connections. + maximum-script-connections: ${APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS:4} idempotency: # Redis store tuning only; the provider selector and lifecycle policy stay with the # application's idempotency executor. @@ -75,15 +79,8 @@ app: maximum-cost: ${APP_RATE_LIMIT_MAXIMUM_COST:10} cleanup-grace: ${APP_RATE_LIMIT_CLEANUP_GRACE:5s} -# redis-runtime 의 redisOptional 은 Redis 에 닿지 못하면 DEGRADED 를 보고한다. Boot 기본 순서 -# (DOWN, OUT_OF_SERVICE, UP, UNKNOWN)에 없는 상태는 DOWN 보다 앞에 정렬돼, 다른 contributor 가 DOWN -# 이어도 전체 health 가 HTTP 200 DEGRADED 로 보였다(리뷰 05-23e). DEGRADED 를 DOWN 뒤, UP 앞에 둔다. -# 이 키를 정하는 module-defaults 는 이 파일 하나뿐이다. 서비스가 순서를 바꾸면 DEGRADED 를 넣어야 한다. -management: - endpoint: - health: - status: - order: DOWN,OUT_OF_SERVICE,DEGRADED,UP,UNKNOWN +# DEGRADED 상태 순서(management.endpoint.health.status.order)는 그 상태를 내는 redis-runtime 이 +# 싣는다(config/module-defaults/redis-runtime.yml, 리뷰 2026-11-03 RR-04-10). # /actuator/info 에 싣는 이 모듈의 상태(management.info.env). compose smoke 가 lane 이 실제로 켠 # capability 를 이 값으로 확인한다. 위 스위치를 해석한 값이고, 기본값은 RedisCapabilityConfig 의 diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java index 654c0bc0..6ec0796c 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis; +import dev.caskeleton.adapter.outbound.cache.redis.cache.CacheScriptLane; import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisCredentialResolver.RedisCredentials; import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; @@ -71,6 +72,9 @@ public final class LiveRedisRuntime { for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, 4); } + // The cache region's own script lane, which the composition root contributes when the cache + // binding is redis (RedisCacheConfig). + limits.put(CacheScriptLane.CACHE_SCRIPT, 4); return new RedisRuntimeOwner( new RedisTopologyClientFactory( settings, diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java index a23f444b..65ef2da7 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java @@ -28,7 +28,7 @@ final class RedisTestContainer { static final String ACL_FILE_PROPERTY = "redis.container.acl-file"; private static final String IMAGE_PROPERTY = "ca.test.image.redis"; - private static final String ACL_IN_CONTAINER = "/etc/redis/acl/all-accounts.acl"; + private static final String ACL_IN_CONTAINER = "/etc/redis/acl/lane-fixture-accounts.acl"; private static final int PORT = 6379; private static GenericContainer server; diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java index e83d72d9..25fc90db 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java @@ -60,8 +60,17 @@ class RedisCacheRegionAdapterTest { for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, 4); } - return new RedisCacheRegionAdapter<>( + limits.put(CacheScriptLane.CACHE_SCRIPT, 4); + return cache( + now, new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1), Duration.ofSeconds(1)), + cacheKeys); + } + + private RedisCacheRegionAdapter cache( + Instant now, RedisRuntimeOwner owner, RedisCacheRegionAdapter.CacheKeys cacheKeys) { + return new RedisCacheRegionAdapter<>( + owner, cacheKeys, key -> "digest-" + key, value -> value.getBytes(StandardCharsets.UTF_8), @@ -428,6 +437,31 @@ class RedisCacheRegionAdapterTest { .hasMessageContaining("ONLY_IF_SOURCE_REVISION_NEWER"); } + @Test + @DisplayName("멱등성·lease가 SCRIPT lane을 모두 잡고 있어도 캐시 조건부 기록은 캐시 전용 lane에서 기록된다") + void aConditionalCacheWriteDoesNotWaitForTheCorrectnessScriptLane() { + // given + Map limits = new java.util.LinkedHashMap<>(); + limits.put(RedisConnectionKind.REGULAR, 4); + limits.put(RedisConnectionKind.SCRIPT, 1); + limits.put(CacheScriptLane.CACHE_SCRIPT, 1); + try (RedisRuntimeOwner owner = + new RedisRuntimeOwner( + StubRedisRuntimeClient.serving(gateway), + limits, + Duration.ofMillis(100), + Duration.ofSeconds(1)); + var heldByAnIdempotencyClaim = owner.borrow(RedisConnectionKind.SCRIPT)) { + RedisCacheRegionAdapter cache = cache(T0, owner, keys); + + // when + CacheRecordOutcome outcome = cache.record("order-1", "payload", newerThan("2")); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED); + } + } + @Test @DisplayName("an unreachable Redis degrades: the cache is bypassed, nothing fails") void anUnreachableRedisDegrades() { diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionContractTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionContractTest.java index d3a996dc..8044176a 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionContractTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionContractTest.java @@ -23,6 +23,7 @@ class RedisCacheRegionContractTest extends CacheRegionContract { for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, 4); } + limits.put(CacheScriptLane.CACHE_SCRIPT, 4); return new RedisCacheRegionAdapter<>( new RedisRuntimeOwner( StubRedisRuntimeClient.serving(new InMemorySemanticRedisCommands()), 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 16e01054..d81e6d13 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 @@ -3,6 +3,9 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; +import dev.caskeleton.adapter.outbound.cache.redis.cache.CacheScriptLane; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisLaneContribution; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisLaneMetrics; import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeAutoConfiguration; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; @@ -11,6 +14,8 @@ import dev.caskeleton.application.idempotency.IdempotencyStorePort; import dev.caskeleton.application.lease.DistributedLeasePort; import dev.caskeleton.application.secret.SecretSourcePort; import dev.caskeleton.shared.ratelimit.EdgeRateLimitPort; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Clock; import java.time.Duration; import java.util.Arrays; @@ -94,6 +99,66 @@ class RedisCapabilityCompositionTest { }); } + @Test + @DisplayName("Redis 캐시 binding은 설정한 상한으로 캐시 전용 script lane을 SCRIPT lane과 따로 기여한다") + void theCacheBindingContributesItsOwnScriptLane() { + runner + .withPropertyValues( + "app.capabilities.cache.bindings.default=redis", + "app.capabilities.cache.maximum-script-connections=3") + .run( + context -> { + // when + List contributions = + List.copyOf(context.getBeansOfType(RedisLaneContribution.class).values()); + + // then + assertThat(context).hasNotFailed(); + assertThat(contributions) + .containsExactly(new RedisLaneContribution(CacheScriptLane.CACHE_SCRIPT, 3)); + }); + } + + @Test + @DisplayName("Redis 캐시 binding의 캐시 전용 lane은 SCRIPT lane과 따로 대기·거절·재연결 지표를 낸다") + void theCacheScriptLaneHasMetersOfItsOwn() { + runner + .withPropertyValues("app.capabilities.cache.bindings.default=redis") + .withBean(MeterRegistry.class, SimpleMeterRegistry::new) + .run( + context -> { + // when + MeterRegistry registry = context.getBean(MeterRegistry.class); + + // then + assertThat(context).hasNotFailed(); + for (String lane : List.of(CacheScriptLane.CACHE_SCRIPT.name(), "SCRIPT")) { + assertThat( + registry + .find(RedisLaneMetrics.CONNECTIONS_PENDING) + .tag("lane", lane) + .gauge()) + .as("waiting borrows of lane %s", lane) + .isNotNull(); + assertThat( + registry + .find(RedisLaneMetrics.ACQUIRE_REFUSED) + .tag("lane", lane) + .tag("reason", "saturated") + .counter()) + .as("refusals of lane %s", lane) + .isNotNull(); + assertThat( + registry + .find(RedisLaneMetrics.CONNECTIONS_OPENED) + .tag("lane", lane) + .counter()) + .as("connections opened on lane %s", lane) + .isNotNull(); + } + }); + } + @Test @DisplayName("a rate limiter with no configured policy is refused at startup") void aRateLimiterWithoutPoliciesIsRefused() { diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java index c1909150..71a846dc 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java @@ -191,6 +191,85 @@ class RedisSemanticScriptAclProbeTest { assertThat(failure).isNull(); } + @ParameterizedTest + @ValueSource( + strings = { + "LOADING Redis is loading the dataset in memory", + "Connection closed", + "BUSY Redis is busy running a script" + }) + @DisplayName("cache만 고른 배포는 probe 도중 연결이 끊기거나 Redis가 아직 준비 중이어도 권한 오류로 보지 않고 기동한다") + void aCacheOnlyDeploymentStartsWhenTheProbeIsInterruptedByATransientFailure(String reply) { + // given + RedisCapabilitySettings capabilities = new RedisCapabilitySettings(); + capabilities.getCache().getBindings().put("default", "redis"); + RedisSemanticScriptAclProbe probe = + new RedisSemanticScriptAclProbe( + owner(gatewayFailingLoadWith(reply), new AtomicInteger()), + capabilities, + "prod:svc:shared:probe".getBytes(StandardCharsets.UTF_8), + Duration.ofSeconds(1)); + + // when + Throwable failure = catchThrowable(probe::afterSingletonsInstantiated); + + // then + assertThat(failure).isNull(); + } + + @Test + @DisplayName("cache만 고른 배포도 probe가 기대와 다른 답을 받으면 기동에서 실패한다") + void aCacheOnlyDeploymentWhoseProbeReadsBackTheWrongValueFailsStartup() { + // given + RedisCapabilitySettings capabilities = new RedisCapabilitySettings(); + capabilities.getCache().getBindings().put("default", "redis"); + RedisSemanticScriptAclProbe probe = + new RedisSemanticScriptAclProbe( + owner(gatewayAnswering(List.of(0L)), new AtomicInteger()), + capabilities, + "prod:svc:shared:probe".getBytes(StandardCharsets.UTF_8), + Duration.ofSeconds(1)); + + // when + Throwable failure = catchThrowable(probe::afterSingletonsInstantiated); + + // then + assertThat(failure) + .isInstanceOf(CapabilityStartupValidationException.class) + .hasMessageContaining("cache"); + } + + private static SemanticRedisCommands gatewayFailingLoadWith(String reply) { + return (SemanticRedisCommands) + Proxy.newProxyInstance( + SemanticRedisCommands.class.getClassLoader(), + new Class[] {SemanticRedisCommands.class}, + (proxy, method, arguments) -> + switch (method.getName()) { + case "loadScript" -> CompletableFuture.failedFuture(new RuntimeException(reply)); + case "toString" -> "RedisSemanticScriptAclProbeTestGateway"; + default -> + throw new UnsupportedOperationException( + "unexpected gateway method: " + method.getName()); + }); + } + + private static SemanticRedisCommands gatewayAnswering(List reply) { + return (SemanticRedisCommands) + Proxy.newProxyInstance( + SemanticRedisCommands.class.getClassLoader(), + new Class[] {SemanticRedisCommands.class}, + (proxy, method, arguments) -> + switch (method.getName()) { + case "loadScript" -> CompletableFuture.completedFuture("probe-digest"); + case "evaluateRegisteredForList" -> CompletableFuture.completedFuture(reply); + case "toString" -> "RedisSemanticScriptAclProbeTestGateway"; + default -> + throw new UnsupportedOperationException( + "unexpected gateway method: " + method.getName()); + }); + } + private static RedisRuntimeOwner owner(SemanticRedisCommands gateway, AtomicInteger opened) { RedisRuntimeClient client = new RedisRuntimeClient() { diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/security/RoleBasedFileAccessPolicy.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/security/RoleBasedFileAccessPolicy.java index 3405c544..fbab6023 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/security/RoleBasedFileAccessPolicy.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/security/RoleBasedFileAccessPolicy.java @@ -71,26 +71,15 @@ public final class RoleBasedFileAccessPolicy implements FileAccessPolicyPort { if (permitted.stream().noneMatch(subject.roles()::contains)) { throw denied(FileserverErrorCode.ACCESS_DENIED, "subject does not hold a permitted role"); } - if (descriptor.isPresent() && !isOwnedBy(descriptor.get(), subject)) { + // Ownership is FileAccessSubject.owns, the rule the port owns (owner decision 14): a file with + // no recorded owner predates ownership and belongs to nobody on the data plane. An admin role + // does not bypass it — acting on somebody else's file is what the audited management plane is + // for, and its operations carry no descriptor. + if (descriptor.isPresent() && !subject.owns(descriptor.get())) { throw denied(FileserverErrorCode.ACCESS_DENIED, "subject does not own the file"); } } - /** - * Whether the file was created by this caller, in this caller's tenant. - * - *

        A file without a recorded owner predates ownership and belongs to nobody on the data plane. - * An admin role does not bypass this: acting on somebody else's file is what the audited - * management plane is for, and its operations carry no descriptor. - */ - private static boolean isOwnedBy(FileDescriptor descriptor, FileAccessSubject subject) { - return descriptor - .owner() - .filter(owner -> owner.principalId().equals(subject.principalId())) - .filter(owner -> owner.tenantId().equals(subject.tenant())) - .isPresent(); - } - private static boolean isAnonymous(FileAccessSubject subject) { return subject.principalId().equals(FileAccessSubject.anonymous().principalId()); } diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/security/RoleBasedFileAccessPolicyContractTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/security/RoleBasedFileAccessPolicyContractTest.java new file mode 100644 index 00000000..f192d9ac --- /dev/null +++ b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/security/RoleBasedFileAccessPolicyContractTest.java @@ -0,0 +1,31 @@ +package dev.caskeleton.adapter.outbound.fileserver.platform.security; + +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileAccessSubject; +import dev.caskeleton.application.fileserver.testkit.FileAccessPolicyPortContract; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** The production policy held to the ownership contract its fake is held to (RR-07-06). */ +class RoleBasedFileAccessPolicyContractTest extends FileAccessPolicyPortContract { + + private static final String READ = "ROLE_FILE_READ"; + private static final String WRITE = "ROLE_FILE_WRITE"; + + private final RoleBasedFileAccessPolicy policy = + new RoleBasedFileAccessPolicy(Set.of(READ), Set.of(WRITE), Set.of("ROLE_FILE_ADMIN"), false); + + @Override + protected FileAccessPolicyPort policy() { + return policy; + } + + @Override + protected FileAccessSubject permittedSubject(String principalId, Optional tenant) { + return new FileAccessSubject( + principalId, + Set.of(READ, WRITE), + tenant.map(value -> Map.of(FileAccessSubject.TENANT_ATTRIBUTE, value)).orElse(Map.of())); + } +} diff --git a/src/adapter/outbound/httpclient/README.md b/src/adapter/outbound/httpclient/README.md index faa4f02a..b80f46d8 100644 --- a/src/adapter/outbound/httpclient/README.md +++ b/src/adapter/outbound/httpclient/README.md @@ -41,7 +41,11 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d cancels the request at the deadline, the JDK transport bounds its exchange timeout by the time left, the experimental Jetty HTTP/3 transport aborts the request, and the caller gets `HttpDeadlineExceededException`. A streaming download's setup (up to the response headers) runs - inside the same deadline; after hand-over each body gap is bounded by `read-idle`. + inside the same deadline; after hand-over each body gap is bounded by `read-idle` and nothing else, + on both transports — the JDK transport arms its own per-read timer for this, because the JDK client + has no socket read timeout. A body that fails after hand-over throws the same stable exceptions as + a buffered call (`HttpResponseTimeoutException` for a stalled body, `HttpResponseTruncatedException` + for a cut one). - **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or `PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it. - **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline, @@ -53,7 +57,9 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d whether the call throws them or returns them as a result (`RETURN_RESULT`). Any other 4xx (404, 409, 422 …) is a healthy answer, even when it reaches the caller as `HttpRemoteErrorException`. Window, threshold and open-state wait are per profile under `clients[N].circuit-breaker.*` - (defaults are Resilience4j's; see `docs/httpclient/configuration-reference.md`). + (defaults are Resilience4j's; see `docs/httpclient/configuration-reference.md`). An attempt that + the caller's own deadline (`HttpOperation.deadline()`) ended is not counted at all: the caller ran + out of time, the upstream did not fail. An attempt the profile's `total-call` ended still counts. - **Resources.** Connections and buffers are reclaimed after success, error, decode failure, size rejection, and cancellation alike. - **Secrets.** No URL, query value, path variable, token, cookie, or idempotency key reaches a log, diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java index ce9ed51a..6b28ad8f 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java @@ -21,22 +21,35 @@ import org.springframework.http.client.JdkClientHttpRequestFactory; * timeout is fixed per factory, so a factory is made per request with {@code min(response-header * timeout, remaining deadline)} from {@link AttemptDeadline}. The factory only holds references; * the client and the write executor are shared. + * + *

        A streaming download cannot use that request. Its body is handed to the caller and may run for + * minutes, but Spring's timer only stops when the body stream is closed, so every JDK download + * longer than the response-header timeout was cut mid-body (review 2026-11-03 RR-04-03). Inside a + * streaming setup scope the factory makes a {@link JdkStreamingClientHttpRequest} instead: the + * JDK's own request timeout bounds the wait for headers, the attempt deadline cancels the exchange + * up to hand-over, and the body is bounded per gap by {@code read-idle}. */ final class DeadlineAwareJdkRequestFactory implements ClientHttpRequestFactory { private final HttpClient client; private final Executor writeExecutor; private final Duration exchangeTimeout; + private final Duration readIdle; - DeadlineAwareJdkRequestFactory(HttpClient client, Duration exchangeTimeout) { + DeadlineAwareJdkRequestFactory(HttpClient client, Duration exchangeTimeout, Duration readIdle) { this.client = Objects.requireNonNull(client, "jdk http client"); this.exchangeTimeout = Objects.requireNonNull(exchangeTimeout, "exchange timeout"); + this.readIdle = Objects.requireNonNull(readIdle, "read idle timeout"); // The executor Spring would pick itself, chosen once instead of once per request. this.writeExecutor = client.executor().orElseGet(SimpleAsyncTaskExecutor::new); } @Override public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { + if (AttemptDeadline.boundsSetupOnly()) { + return new JdkStreamingClientHttpRequest( + client, uri, httpMethod, AttemptDeadline.bound(exchangeTimeout), readIdle); + } JdkClientHttpRequestFactory delegate = new JdkClientHttpRequestFactory(client, writeExecutor); delegate.setReadTimeout(AttemptDeadline.bound(exchangeTimeout)); return delegate.createRequest(uri, httpMethod); diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkBlockingTransportProvider.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkBlockingTransportProvider.java index 64fab27f..4453f4b4 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkBlockingTransportProvider.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkBlockingTransportProvider.java @@ -62,7 +62,8 @@ public final class JdkBlockingTransportProvider implements BlockingTransportProv HttpClient client = clientFactory.create(profile, tlsMaterialResolver.apply(profile)); clients.put(new TransportResourceKey(profile.name(), generation), client); ClientHttpRequestFactory factory = - new DeadlineAwareJdkRequestFactory(client, profile.timeout().responseHeader()); + new DeadlineAwareJdkRequestFactory( + client, profile.timeout().responseHeader(), profile.timeout().readIdle()); listener.onRuntimeCreated(profile.name(), ID); return factory; } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpRequest.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpRequest.java new file mode 100644 index 00000000..f38f1459 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpRequest.java @@ -0,0 +1,128 @@ +package dev.caskeleton.adapter.outbound.httpclient.jdk; + +import dev.caskeleton.adapter.outbound.httpclient.transport.AttemptDeadline; +import java.io.IOException; +import java.io.InputStream; +import java.io.InterruptedIOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.AbstractBufferingClientHttpRequest; +import org.springframework.http.client.ClientHttpResponse; + +/** + * A JDK request for a streaming download, whose timeouts end at the response headers (review + * 2026-11-03 RR-04-03). + * + *

        Three limits, each where the JDK can enforce it: + * + *

          + *
        • the JDK's own request timeout bounds the wait for the response headers and stops when they + * arrive; + *
        • the attempt deadline cancels the pending exchange, so connect, send and the header wait + * stay inside the call's total budget; + *
        • after hand-over, {@link ReadIdleInputStream} bounds each gap of the body by {@code + * read-idle} — the JDK client has no socket read timeout of its own. + *
        + * + *

        The request body is buffered: a streaming download sends none or a small one, and the JDK + * needs a body publisher before the exchange starts. + */ +final class JdkStreamingClientHttpRequest extends AbstractBufferingClientHttpRequest { + + /** Headers the JDK client refuses to set, as Spring's own JDK request lists them. */ + private static final Set RESTRICTED_HEADERS = restrictedHeaders(); + + private final HttpClient client; + private final URI uri; + private final HttpMethod method; + private final Duration responseHeaderTimeout; + private final Duration readIdle; + + JdkStreamingClientHttpRequest( + HttpClient client, + URI uri, + HttpMethod method, + Duration responseHeaderTimeout, + Duration readIdle) { + this.client = Objects.requireNonNull(client, "jdk http client"); + this.uri = Objects.requireNonNull(uri, "uri"); + this.method = Objects.requireNonNull(method, "method"); + this.responseHeaderTimeout = + Objects.requireNonNull(responseHeaderTimeout, "response header timeout"); + this.readIdle = Objects.requireNonNull(readIdle, "read idle timeout"); + } + + @Override + public HttpMethod getMethod() { + return method; + } + + @Override + public URI getURI() { + return uri; + } + + @Override + protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] body) + throws IOException { + HttpRequest.Builder request = + HttpRequest.newBuilder(uri) + .timeout(responseHeaderTimeout) + .method( + method.name(), + body.length == 0 + ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofByteArray(body)); + headers.forEach( + (name, values) -> { + if (!RESTRICTED_HEADERS.contains(name)) { + values.forEach(value -> request.header(name, value)); + } + }); + CompletableFuture> pending = + client.sendAsync(request.build(), HttpResponse.BodyHandlers.ofInputStream()); + AttemptDeadline.abortOnExpiry(() -> pending.cancel(true)); + HttpResponse response = await(pending); + return new JdkStreamingClientHttpResponse( + response, new ReadIdleInputStream(response.body(), readIdle)); + } + + private static HttpResponse await( + CompletableFuture> pending) throws IOException { + try { + return pending.get(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + pending.cancel(true); + InterruptedIOException failure = new InterruptedIOException("streaming setup interrupted"); + failure.initCause(interrupted); + throw failure; + } catch (CancellationException cancelled) { + // Only the attempt deadline cancels this future; the gateway names the deadline. + throw new IOException("streaming setup cancelled at the attempt deadline", cancelled); + } catch (ExecutionException failed) { + Throwable cause = failed.getCause(); + if (cause instanceof IOException io) { + throw io; + } + throw new IOException("streaming setup failed", cause); + } + } + + private static Set restrictedHeaders() { + Set restricted = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); + restricted.addAll(Set.of("connection", "content-length", "expect", "host", "upgrade")); + return restricted; + } +} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpResponse.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpResponse.java new file mode 100644 index 00000000..7a6f8ffa --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpResponse.java @@ -0,0 +1,63 @@ +package dev.caskeleton.adapter.outbound.httpclient.jdk; + +import java.io.IOException; +import java.io.InputStream; +import java.net.http.HttpResponse; +import java.util.Objects; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.client.ClientHttpResponse; + +/** The response of a {@link JdkStreamingClientHttpRequest}, body bounded per gap. */ +final class JdkStreamingClientHttpResponse implements ClientHttpResponse { + + private final HttpResponse response; + private final InputStream body; + private final HttpHeaders headers = new HttpHeaders(); + + JdkStreamingClientHttpResponse(HttpResponse response, InputStream body) { + this.response = Objects.requireNonNull(response, "jdk response"); + this.body = Objects.requireNonNull(body, "body stream"); + // HTTP/2 pseudo-headers (":status") are protocol framing, not response headers. + response + .headers() + .map() + .forEach( + (name, values) -> { + if (!name.startsWith(":")) { + headers.addAll(name, values); + } + }); + } + + @Override + public HttpStatusCode getStatusCode() { + return HttpStatusCode.valueOf(response.statusCode()); + } + + @Override + public String getStatusText() { + HttpStatus known = HttpStatus.resolve(response.statusCode()); + return known == null ? "" : known.getReasonPhrase(); + } + + @Override + public HttpHeaders getHeaders() { + return headers; + } + + @Override + public InputStream getBody() { + return body; + } + + @Override + public void close() { + try { + body.close(); + } catch (IOException ignored) { + // Closing releases the exchange; a failure to close has nothing left to release. + } + } +} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java new file mode 100644 index 00000000..02643336 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java @@ -0,0 +1,90 @@ +package dev.caskeleton.adapter.outbound.httpclient.jdk; + +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.SocketTimeoutException; +import java.time.Duration; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * A JDK response body whose every read is bounded by {@code read-idle} (review 2026-11-03 + * RR-04-03). + * + *

        The JDK client has no socket read timeout, so a streamed body that stopped arriving held the + * caller's thread and the connection forever. Each read arms a timer on the JDK's shared delay + * scheduler; when it fires the stream is closed, which wakes the blocked read, and the read reports + * a {@link SocketTimeoutException} — the same exception Apache's socket timeout raises, so one + * classifier reading names both. A read that returns first disarms its timer. + */ +final class ReadIdleInputStream extends FilterInputStream { + + @FunctionalInterface + private interface Read { + long run() throws IOException; + } + + private final Duration readIdle; + private final AtomicBoolean idled = new AtomicBoolean(); + + ReadIdleInputStream(InputStream delegate, Duration readIdle) { + super(Objects.requireNonNull(delegate, "body stream")); + this.readIdle = Objects.requireNonNull(readIdle, "read idle timeout"); + } + + @Override + public int read() throws IOException { + return (int) guarded(super::read); + } + + @Override + public int read(byte[] buffer, int offset, int length) throws IOException { + return (int) guarded(() -> super.read(buffer, offset, length)); + } + + @Override + public long skip(long count) throws IOException { + return guarded(() -> super.skip(count)); + } + + private long guarded(Read read) throws IOException { + requireNotIdled(); + CompletableFuture timer = new CompletableFuture<>(); + CompletableFuture expiry = + timer.completeOnTimeout(null, readIdle.toNanos(), TimeUnit.NANOSECONDS).thenRun(this::idle); + try { + long result = read.run(); + requireNotIdled(); + return result; + } catch (IOException failure) { + requireNotIdled(); + throw failure; + } finally { + // Completing first skips the idle action and lets the scheduler drop the pending task. + timer.cancel(false); + expiry.cancel(false); + } + } + + private void idle() { + idled.set(true); + try { + in.close(); + } catch (IOException ignored) { + // The read this wakes reports the timeout; a failed close has nothing more to say. + } + } + + /** + * After the timer fired, whatever the read returned — data, end of stream or "closed" — is not + * the rest of the body. + */ + private void requireNotIdled() throws SocketTimeoutException { + if (idled.get()) { + throw new SocketTimeoutException("no response body bytes within the read-idle timeout"); + } + } +} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptCircuitBreaker.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptCircuitBreaker.java index 26b571da..88f89eef 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptCircuitBreaker.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptCircuitBreaker.java @@ -17,6 +17,13 @@ public interface AttemptCircuitBreaker { void onError(long durationNanos, Throwable failure); + /** + * Gives back a permission without recording an outcome, for an attempt that says nothing about + * the upstream (an attempt its caller's own deadline ended). Half-open trial slots are returned; + * the window is left as it was. + */ + void releasePermission(); + String state(); static AttemptCircuitBreaker alwaysClosed() { @@ -36,6 +43,11 @@ public interface AttemptCircuitBreaker { // Nothing to record. } + @Override + public void releasePermission() { + // Nothing was taken. + } + @Override public String state() { return "CLOSED"; @@ -60,6 +72,11 @@ public interface AttemptCircuitBreaker { delegate.onError(durationNanos, TimeUnit.NANOSECONDS, failure); } + @Override + public void releasePermission() { + delegate.releasePermission(); + } + @Override public String state() { return delegate.getState().name(); diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptResiliencePipeline.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptResiliencePipeline.java index d306c441..df8c946e 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptResiliencePipeline.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptResiliencePipeline.java @@ -7,6 +7,7 @@ import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpFailureMetadata; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRateLimitRejectedException; import java.util.Objects; import java.util.Optional; +import java.util.function.BooleanSupplier; import java.util.function.Function; import java.util.function.Supplier; @@ -21,6 +22,11 @@ import java.util.function.Supplier; *

        A local rejection (rate limiter or bulkhead) is deliberately not recorded as a * circuit error: the upstream never saw the request, and counting our own back-pressure as upstream * failure would open the breaker on a healthy dependency. + * + *

        An attempt its caller abandoned is not recorded either, for the same reason: an attempt that a + * caller's own deadline ended while the upstream was still answering within the profile's limits is + * the caller running out of time, not the upstream failing (review 2026-11-03 RR-04-01). Its + * permission is given back instead. */ public final class AttemptResiliencePipeline { @@ -79,7 +85,24 @@ public final class AttemptResiliencePipeline { * @return the attempt's value, whether or not it represents a remote failure */ public T execute(AttemptCall call, Function> remoteFailure) { + return execute(call, remoteFailure, () -> false); + } + + /** + * Runs one attempt, recording nothing against the upstream when its caller abandoned it. + * + * @param call the attempt, including any redirect hops it follows + * @param remoteFailure returns the failure to record when the value represents an upstream error + * @param abandonedByCaller read after the attempt failed: whether the caller's own deadline ended + * it, in which case the failure is not the upstream's and the breaker records nothing + * @return the attempt's value, whether or not it represents a remote failure + */ + public T execute( + AttemptCall call, + Function> remoteFailure, + BooleanSupplier abandonedByCaller) { Objects.requireNonNull(remoteFailure, "remote failure classifier"); + Objects.requireNonNull(abandonedByCaller, "abandoned-by-caller signal"); if (!circuitBreaker.tryAcquirePermission()) { rejections.circuitOpen(); throw new HttpCircuitOpenException( @@ -110,7 +133,11 @@ public final class AttemptResiliencePipeline { return result; } catch (Throwable failure) { releaseAttemptPermits(); - circuitBreaker.onError(System.nanoTime() - started, failure); + if (abandonedByCaller.getAsBoolean()) { + circuitBreaker.releasePermission(); + } else { + circuitBreaker.onError(System.nanoTime() - started, failure); + } throw translate(failure); } } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/Deadline.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/Deadline.java index 3ee96a73..f29f6c9a 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/Deadline.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/Deadline.java @@ -10,11 +10,31 @@ import java.util.Objects; * *

        Everything — pool acquire, DNS, connect, TLS, request write, response read, and every retry * backoff — is spent inside this single budget. + * + * @param at the instant the call ends + * @param source who set that instant, which decides what an attempt it ends says about the upstream */ -public record Deadline(Instant at) { +public record Deadline(Instant at, Source source) { + + /** + * Who set the instant a call ends at. + * + *

        The two say different things when they end an attempt. The profile's total-call timeout is + * the operator's statement of how long a healthy upstream may take, so an attempt it ends is the + * upstream's failure. A caller's own deadline is a statement about the caller — it had only that + * much time left — so an attempt it ends says nothing about the upstream (review 2026-11-03 + * RR-04-01). + */ + public enum Source { + /** The profile's {@code timeout.total-call}. */ + PROFILE_TOTAL_CALL, + /** The caller's {@code HttpOperation.deadline()}, when it is earlier than the profile's. */ + CALLER + } public Deadline { Objects.requireNonNull(at, "deadline instant"); + Objects.requireNonNull(source, "deadline source"); } public Duration remaining(Clock clock) { @@ -26,6 +46,11 @@ public record Deadline(Instant at) { return !clock.instant().isBefore(at); } + /** Whether the instant is the caller's own budget rather than the profile's total-call. */ + public boolean setByCaller() { + return source == Source.CALLER; + } + /** The earlier of two deadlines; a parent budget can only ever shrink a child's. */ public Deadline earliest(Deadline other) { return at.isBefore(other.at) ? this : other; diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DeadlineCalculator.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DeadlineCalculator.java index 04e7d007..a356fb25 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DeadlineCalculator.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DeadlineCalculator.java @@ -9,6 +9,9 @@ import java.util.Optional; /** * Derives the effective deadline from the caller's parent budget and the profile total-call timeout * (design §15.2): {@code effectiveDeadline = min(parentDeadline, now + totalCallTimeout)}. + * + *

        The result also records which of the two won. A tie goes to the profile: the profile's limit + * would have ended the call at that instant anyway. */ public final class DeadlineCalculator { @@ -17,6 +20,9 @@ public final class DeadlineCalculator { Objects.requireNonNull(totalCall, "total call timeout"); Objects.requireNonNull(clock, "clock"); Instant local = clock.instant().plus(totalCall); - return new Deadline(parent.map(value -> value.isBefore(local) ? value : local).orElse(local)); + return parent + .filter(value -> value.isBefore(local)) + .map(value -> new Deadline(value, Deadline.Source.CALLER)) + .orElseGet(() -> new Deadline(local, Deadline.Source.PROFILE_TOTAL_CALL)); } } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java index 3b6df73f..70c80312 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingAttemptExecutor.java @@ -63,6 +63,7 @@ public final class BlockingAttemptExecutor { try (AttemptDeadline.Scope scope = AttemptDeadline.open(deadline.remaining(support.clock()))) { return executeWithin( scope, + deadline, runtime, prepared, responseType, @@ -76,6 +77,7 @@ public final class BlockingAttemptExecutor { private AttemptOutcome executeWithin( AttemptDeadline.Scope scope, + Deadline deadline, BlockingClientRuntime runtime, PreparedOperation prepared, ResponseType responseType, @@ -146,7 +148,12 @@ public final class BlockingAttemptExecutor { tracker.firstByteDelivered()); } }, - outcome -> upstreamFailure(outcome, baseMetadata)); + outcome -> upstreamFailure(outcome, baseMetadata), + // The caller's own deadline ending the attempt is not the upstream failing. The + // profile's total-call ending it is: that limit is the operator's statement of + // how long a healthy upstream may take, and a slow-drip upstream that never trips + // a per-gap timeout is seen by the breaker only through it (RR-04-01). + () -> deadline.setByCaller() && scope.expired()); return finish(observation, scope, attemptOutcome); } catch (HttpClientException stable) { return finish( diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingGateway.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingGateway.java index 9fabdca1..4f21342e 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingGateway.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BlockingStreamingGateway.java @@ -5,6 +5,7 @@ import dev.caskeleton.adapter.outbound.httpclient.api.HttpStatus; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpFailureMetadata; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; import dev.caskeleton.adapter.outbound.httpclient.api.result.BlockingStreamingResponse; @@ -78,9 +79,11 @@ public final class BlockingStreamingGateway { // which deregisters the transport's abort, so the body is then bounded by read-idle per gap // and a long download is not cut at an arbitrary total. Without the scope a setup was bounded // only by per-gap stage timeouts, and an upstream that held or dripped its headers kept the - // caller past its deadline (finding 05-06). + // caller past its deadline (finding 05-06). It is a setup scope, not an attempt scope: the + // JDK transport arms an exchange-wide timeout for an attempt, which cut every download + // longer than the response-header timeout (RR-04-03). AttemptDeadline.Scope setupDeadline = - AttemptDeadline.open(setup.deadline().remaining(runtime.support().clock())); + AttemptDeadline.openStreamSetup(setup.deadline().remaining(runtime.support().clock())); try (setupDeadline) { response = spec.exchange( @@ -102,9 +105,24 @@ public final class BlockingStreamingGateway { .withStatus(new HttpStatus(status)) .withEvidence(ExecutionEvidence.RESPONSE_RECEIVED)); } + // A body that fails after hand-over reaches the caller as the same stable + // exceptions a buffered call throws, classified by the transport's own + // classifier at the body stage — not as the engine's bare IOException, which + // carried no category, no evidence and nothing to log (RR-04-03). InputStream bounded = - new CountingBoundedInputStream( - rawResponse.getBody(), limiter::recordWireBytes); + new ClassifiedBodyInputStream( + new CountingBoundedInputStream( + rawResponse.getBody(), limiter::recordWireBytes), + bodyFailure -> + runtime + .support() + .exceptionMapper() + .map( + runtime + .failureClassifier() + .classify(bodyFailure, AttemptStage.RESPONSE_BODY), + metadata, + bodyFailure)); return new DefaultBlockingStreamingResponse( new HttpStatus(status), responseHeaders, bounded, rawResponse::close); }, diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ClassifiedBodyInputStream.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ClassifiedBodyInputStream.java new file mode 100644 index 00000000..f2597bda --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ClassifiedBodyInputStream.java @@ -0,0 +1,64 @@ +package dev.caskeleton.adapter.outbound.httpclient.restclient; + +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpClientException; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; +import java.util.function.Function; + +/** + * A handed-over response body whose read failures reach the caller as stable exceptions (review + * 2026-11-03 RR-04-03). + * + *

        A streamed body is read after the gateway has returned, so the gateway's own failure mapping + * never sees it. Without this a read-idle timeout or a cut connection reached the caller as the + * engine's bare {@code IOException} — no category, no evidence, nothing a retry policy or a log + * could branch on. Closing is the caller's own act and is passed through unclassified. + */ +final class ClassifiedBodyInputStream extends FilterInputStream { + + private final Function classifier; + + ClassifiedBodyInputStream( + InputStream delegate, Function classifier) { + super(Objects.requireNonNull(delegate, "body stream")); + this.classifier = Objects.requireNonNull(classifier, "body failure classifier"); + } + + @Override + public int read() throws IOException { + try { + return super.read(); + } catch (IOException failure) { + throw classifier.apply(failure); + } + } + + @Override + public int read(byte[] buffer, int offset, int length) throws IOException { + try { + return super.read(buffer, offset, length); + } catch (IOException failure) { + throw classifier.apply(failure); + } + } + + @Override + public long skip(long count) throws IOException { + try { + return super.skip(count); + } catch (IOException failure) { + throw classifier.apply(failure); + } + } + + @Override + public int available() throws IOException { + try { + return super.available(); + } catch (IOException failure) { + throw classifier.apply(failure); + } + } +} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java index bde2d067..36d072bb 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java @@ -28,6 +28,11 @@ import java.util.concurrent.TimeUnit; *

        The scope is thread-confined because a blocking attempt runs on the caller's thread from * request creation to the last body byte. When no scope is open — a transport used outside the * gateway — both methods leave the transport's own behaviour unchanged. + * + *

        A streaming download opens a different scope ({@link #openStreamSetup(Duration)}): it bounds + * the exchange only up to the response headers and is closed when the body is handed over. A + * transport whose engine timeout would otherwise keep running over the body reads {@link + * #boundsSetupOnly()} and keeps that timeout off it (review 2026-11-03 RR-04-03). */ public final class AttemptDeadline { @@ -41,8 +46,34 @@ public final class AttemptDeadline { * @param remaining the time left before the logical call's effective deadline */ public static Scope open(Duration remaining) { + return open(remaining, false); + } + + /** + * Opens the deadline scope for a streaming download's setup on the current thread. + * + *

        The caller closes it when the response is handed over, so the deadline never reaches the + * body: a download may legitimately outlast any fixed total (design §15.3). + * + * @param remaining the time left before the logical call's effective deadline + */ + public static Scope openStreamSetup(Duration remaining) { + return open(remaining, true); + } + + /** + * Whether the current scope bounds only a streaming setup, so a timeout the transport arms must + * not outlive the response headers. + */ + public static boolean boundsSetupOnly() { + Scope scope = CURRENT.get(); + return scope != null && scope.setupOnly; + } + + private static Scope open(Duration remaining, boolean setupOnly) { Objects.requireNonNull(remaining, "remaining deadline"); - Scope scope = new Scope(remaining.isNegative() ? Duration.ZERO : remaining, CURRENT.get()); + Scope scope = + new Scope(remaining.isNegative() ? Duration.ZERO : remaining, setupOnly, CURRENT.get()); CURRENT.set(scope); return scope; } @@ -78,6 +109,7 @@ public final class AttemptDeadline { public static final class Scope implements AutoCloseable { private final long endNanos; + private final boolean setupOnly; private final Scope outer; private final CompletableFuture timer = new CompletableFuture<>(); private final CompletableFuture expiry; @@ -85,8 +117,9 @@ public final class AttemptDeadline { private boolean fired; private boolean closed; - private Scope(Duration remaining, Scope outer) { + private Scope(Duration remaining, boolean setupOnly, Scope outer) { this.endNanos = System.nanoTime() + remaining.toNanos(); + this.setupOnly = setupOnly; this.outer = outer; // The JDK's shared delay scheduler, the same one Spring's JDK request uses for its timeout. // Completing the future on close() also cancels the scheduled task, so a finished attempt diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DeadlineCalculatorTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DeadlineCalculatorTest.java index 143e9f13..6d54534f 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DeadlineCalculatorTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/DeadlineCalculatorTest.java @@ -34,7 +34,8 @@ class DeadlineCalculatorTest { @Test void refusesAttemptWhenBackoffConsumesRemainingBudget() { - Deadline deadline = new Deadline(Instant.parse("2026-08-08T00:00:01Z")); + Deadline deadline = + new Deadline(Instant.parse("2026-08-08T00:00:01Z"), Deadline.Source.PROFILE_TOTAL_CALL); Optional result = new AttemptBudgetCalculator(clock) .nextAttempt( @@ -44,7 +45,8 @@ class DeadlineCalculatorTest { @Test void grantsAttemptWhenBudgetCoversBackoffMinimumAndCleanup() { - Deadline deadline = new Deadline(Instant.parse("2026-08-08T00:00:02Z")); + Deadline deadline = + new Deadline(Instant.parse("2026-08-08T00:00:02Z"), Deadline.Source.PROFILE_TOTAL_CALL); Optional result = new AttemptBudgetCalculator(clock) .nextAttempt( @@ -60,7 +62,8 @@ class DeadlineCalculatorTest { assertThatThrownBy( () -> guard.requireTimeRemaining( - new Deadline(Instant.parse("2026-08-07T23:59:59Z")), + new Deadline( + Instant.parse("2026-08-07T23:59:59Z"), Deadline.Source.PROFILE_TOTAL_CALL), CoreFixtures.notSentMetadata())) .isInstanceOf(HttpDeadlineExceededException.class); assertThatThrownBy( diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/RetryCoordinatorTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/RetryCoordinatorTest.java index 82b1e4b4..d36ab666 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/RetryCoordinatorTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/resilience/RetryCoordinatorTest.java @@ -147,7 +147,7 @@ class RetryCoordinatorTest { @Override public Deadline deadline() { - return new Deadline(clock.instant().plusSeconds(5)); + return new Deadline(clock.instant().plusSeconds(5), Deadline.Source.PROFILE_TOTAL_CALL); } @Override @@ -202,7 +202,7 @@ class RetryCoordinatorTest { @Override public Deadline deadline() { - return new Deadline(clock.instant().plusSeconds(5)); + return new Deadline(clock.instant().plusSeconds(5), Deadline.Source.PROFILE_TOTAL_CALL); } @Override diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java index adb33f86..95ca1839 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/CircuitBreakerStatusAccountingTest.java @@ -5,20 +5,28 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpCircuitOpenException; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpDeadlineExceededException; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpRemoteErrorException; import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; import dev.caskeleton.adapter.outbound.httpclient.api.result.HttpCallResult; import dev.caskeleton.adapter.outbound.httpclient.api.result.ResponseType; import dev.caskeleton.adapter.outbound.httpclient.profile.CircuitBreakerSettings; +import dev.caskeleton.adapter.outbound.httpclient.profile.TimeoutSettings; +import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType; import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; +import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; /** * What the per-profile circuit breaker counts as an upstream failure, end to end (finding 05-05). @@ -31,6 +39,10 @@ class CircuitBreakerStatusAccountingTest { private static final int CALLS = 200; private static final int LIBRARY_DEFAULT_WINDOW = 100; private static final int SMALL_WINDOW = 5; + private static final int TINY_WINDOW = 2; + private static final Duration HEALTHY_ANSWER_TIME = Duration.ofMillis(600); + private static final Duration CALLER_BUDGET = Duration.ofMillis(200); + private static final Duration PROFILE_TOTAL_CALL = Duration.ofSeconds(1); @Test @DisplayName("정상 응답인 404가 200번 이어져도 circuit이 열리지 않고 모든 호출이 상대 서버에 닿는다") @@ -158,6 +170,113 @@ class CircuitBreakerStatusAccountingTest { } } + @ParameterizedTest(name = "{0}") + @EnumSource( + value = TransportType.class, + names = {"APACHE", "JDK"}) + @DisplayName("호출자 deadline으로 끊은 시도는 상대 장애로 세지 않아 창을 채워도 다음 호출이 상대 서버에 닿는다") + void attemptsCutShortByTheCallersOwnDeadlineDoNotOpenTheCircuit(TransportType transport) + throws Exception { + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = + TestGateways.forProfile( + ClientProfiles.builder("caller-deadline") + .baseUrl(server.uri("/")) + .transport(transport) + .circuitBreaker( + new CircuitBreakerSettings( + 50, SMALL_WINDOW, SMALL_WINDOW, Duration.ofMinutes(1), 1)) + .build())) { + // given + for (int i = 0; i <= SMALL_WINDOW; i++) { + server.enqueueDelayedHeaders( + 200, + "application/json", + "\"ok\"".getBytes(StandardCharsets.UTF_8), + HEALTHY_ANSWER_TIME); + } + List windowFailures = new ArrayList<>(); + for (int i = 0; i < SMALL_WINDOW; i++) { + windowFailures.add( + catchThrowable( + () -> getUserWithin(harness, Optional.of(Instant.now().plus(CALLER_BUDGET))))); + } + assertThat(windowFailures) + .allSatisfy(f -> assertThat(f).isInstanceOf(HttpDeadlineExceededException.class)); + + // when + Throwable next = catchThrowable(() -> getUserWithin(harness, Optional.empty())); + + // then + assertThat(next).isNull(); + assertThat(server.requestCount()).isEqualTo(SMALL_WINDOW + 1); + } + } + + @ParameterizedTest(name = "{0}") + @EnumSource( + value = TransportType.class, + names = {"APACHE", "JDK"}) + @DisplayName("프로필 total-call 시간으로 끊긴 시도는 상대 장애로 세어 창을 채우면 circuit이 열린다") + void attemptsCutShortByTheProfileTotalCallStillOpenTheCircuit(TransportType transport) + throws Exception { + TimeoutSettings base = ClientProfiles.timeouts(); + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = + TestGateways.forProfile( + ClientProfiles.builder("profile-deadline") + .baseUrl(server.uri("/")) + .transport(transport) + .timeout( + new TimeoutSettings( + base.dns(), + base.connect(), + base.tlsHandshake(), + base.responseHeader(), + base.readIdle(), + PROFILE_TOTAL_CALL)) + .circuitBreaker( + new CircuitBreakerSettings( + 50, TINY_WINDOW, TINY_WINDOW, Duration.ofMinutes(1), 1)) + .build())) { + // given + List windowFailures = new ArrayList<>(); + for (int i = 0; i < TINY_WINDOW; i++) { + server.enqueueSlowDripBody(200, 100, Duration.ofMillis(50)); + windowFailures.add(catchThrowable(() -> getUserWithin(harness, Optional.empty()))); + } + assertThat(windowFailures) + .allSatisfy(f -> assertThat(f).isInstanceOf(HttpDeadlineExceededException.class)); + + // when + Throwable next = catchThrowable(() -> getUserWithin(harness, Optional.empty())); + + // then + assertThat(next).isInstanceOf(HttpCircuitOpenException.class); + assertThat(server.requestCount()).isEqualTo(TINY_WINDOW); + } + } + + private static HttpCallResult getUserWithin( + TestGateways.Harness harness, Optional deadline) { + HttpOperation get = HttpOperation.get(new OperationName("get-user"), "/users/1", Map.of()); + return harness + .gateway() + .exchange( + harness.profile().name(), + new HttpOperation( + get.operationName(), + get.method(), + get.uriTemplate(), + get.uriVariables(), + get.headers(), + get.body(), + get.idempotency(), + get.idempotencyKey(), + deadline), + ResponseType.of(String.class)); + } + private static HttpCallResult getUserAsResult(TestGateways.Harness harness) { return harness .gateway() diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingBodyLifetimeTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingBodyLifetimeTest.java new file mode 100644 index 00000000..a19d3c6f --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingBodyLifetimeTest.java @@ -0,0 +1,124 @@ +package dev.caskeleton.adapter.outbound.httpclient.restclient; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpResponseTimeoutException; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.HttpOperation; +import dev.caskeleton.adapter.outbound.httpclient.api.result.BlockingStreamingResponse; +import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; +import dev.caskeleton.adapter.outbound.httpclient.profile.ResponseLimits; +import dev.caskeleton.adapter.outbound.httpclient.profile.TimeoutSettings; +import dev.caskeleton.adapter.outbound.httpclient.profile.TransportType; +import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; +import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; +import dev.caskeleton.adapter.outbound.httpclient.testkit.TestGateways; +import java.time.Duration; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +/** + * What bounds a streaming download's body once it has been handed over (review 2026-11-03 RR-04-03, + * design §15.3). + * + *

        The documented contract is transport-independent: the total budget and the response-header + * timeout bound the setup, and after hand-over each gap of the body is bounded by {@code read-idle} + * alone, so a long download is not cut at an arbitrary total. The JDK transport used to break it: + * Spring's JDK request enforces its read timeout over the whole exchange and closes the body stream + * when it fires, so every JDK download longer than the response-header timeout was cut, and the + * caller got an unclassified {@code IOException: closed}. + * + *

        The profile's response-header timeout (500 ms) and total budget (1 s) are both shorter than + * the body (about 2 s), and the read-idle timeout (1 s) is longer than every gap of it. + */ +class StreamingBodyLifetimeTest { + + private static final int BODY_BYTES = 20; + private static final Duration DRIP_GAP = Duration.ofMillis(100); + private static final Duration STALL_GAP = Duration.ofMillis(2500); + + @ParameterizedTest(name = "{0}") + @EnumSource( + value = TransportType.class, + names = {"APACHE", "JDK"}) + @DisplayName("넘겨받은 스트리밍 본문은 응답 헤더 시간과 전체 예산을 넘겨도 끝까지 읽힌다") + void aStreamedBodyOutlivesTheResponseHeaderTimeoutAndTheTotalBudget(TransportType transport) + throws Exception { + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = TestGateways.forProfile(profile(server, transport))) { + // given + server.enqueueSlowDripBody(200, BODY_BYTES, DRIP_GAP); + BlockingStreamingGateway gateway = new BlockingStreamingGateway(harness.registry()); + + // when + byte[] body; + try (BlockingStreamingResponse response = gateway.download(harness.profile().name(), get())) { + body = response.body().readAllBytes(); + } + + // then + assertThat(body).hasSize(BODY_BYTES); + } + } + + @ParameterizedTest(name = "{0}") + @EnumSource( + value = TransportType.class, + names = {"APACHE", "JDK"}) + @DisplayName("본문 사이 공백이 read-idle을 넘으면 분류된 응답 시간 초과로 끝난다") + void aBodyGapLongerThanReadIdleEndsWithAClassifiedTimeout(TransportType transport) + throws Exception { + try (MockHttpServer server = MockHttpServer.start(); + TestGateways.Harness harness = TestGateways.forProfile(profile(server, transport))) { + // given + server.enqueueSlowDripBody(200, BODY_BYTES, STALL_GAP); + BlockingStreamingGateway gateway = new BlockingStreamingGateway(harness.registry()); + long started = System.nanoTime(); + + // when + Throwable failure = + catchThrowable( + () -> { + try (BlockingStreamingResponse response = + gateway.download(harness.profile().name(), get())) { + response.body().readAllBytes(); + } + }); + + // then + Duration elapsed = Duration.ofNanos(System.nanoTime() - started); + assertThat(failure).isInstanceOf(HttpResponseTimeoutException.class); + assertThat(elapsed).isLessThan(STALL_GAP); + HttpResponseTimeoutException timeout = (HttpResponseTimeoutException) failure; + assertThat(timeout.metadata().stage()).isEqualTo(AttemptStage.RESPONSE_BODY); + assertThat(timeout.metadata().evidence()).isEqualTo(ExecutionEvidence.PARTIAL_RESPONSE); + } + } + + private static HttpOperation get() { + return HttpOperation.get(new OperationName("download"), "/download", Map.of()); + } + + private static ClientProfile profile(MockHttpServer server, TransportType transport) { + TimeoutSettings base = ClientProfiles.timeouts(); + return ClientProfiles.builder("streaming-body") + .baseUrl(server.uri("/")) + .transport(transport) + .timeout( + new TimeoutSettings( + base.dns(), + base.connect(), + base.tlsHandshake(), + Duration.ofMillis(500), + Duration.ofSeconds(1), + Duration.ofSeconds(1))) + .response(new ResponseLimits(1024, 1024, Set.of("text/plain"))) + .build(); + } +} diff --git a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/RecordingResilienceComponents.java b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/RecordingResilienceComponents.java index d013194b..0c8f600d 100644 --- a/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/RecordingResilienceComponents.java +++ b/src/adapter/outbound/httpclient/src/testFixtures/java/dev/caskeleton/adapter/outbound/httpclient/testkit/RecordingResilienceComponents.java @@ -68,6 +68,11 @@ public final class RecordingResilienceComponents { events.add("circuit-error"); } + @Override + public void releasePermission() { + events.add("circuit-release"); + } + @Override public String state() { return circuitOpen ? "OPEN" : "CLOSED"; diff --git a/src/adapter/outbound/identifier/CLAUDE.md b/src/adapter/outbound/identifier/CLAUDE.md index 0c1a7c11..85a1c08c 100644 --- a/src/adapter/outbound/identifier/CLAUDE.md +++ b/src/adapter/outbound/identifier/CLAUDE.md @@ -20,16 +20,22 @@ build choices) live in [README.md](README.md). - `UuidV7DurableOperationIdFactory` — `DurableOperationIdFactory` implementation (UUIDv7 via `uuid-creator`). The operation id is also the submission event's id, and the messaging platform's message id accepts only UUIDv7 (review 2026-11-01 06-06). Wired by `composition:durable-operation`. -- The leaf name says "identifier"; general identifier generation, clock and random sources are not here. +- The leaf name says "identifier"; general-purpose clock and random sources are not here. The name is kept because Gradle paths and consumers use it (README, review 05-21). - Wiring is `composition/service-runtime` (`PseudonymizationConfig`), not this leaf. ## Allowed -- `:application-core` (declared in [build.gradle](build.gradle)); the registry entry is the SSOT. +Declared in [build.gradle](build.gradle); the registry entry is the SSOT. + +- `:application-core` — the ports both classes implement. - `:shared-contract`, for `HmacSha256` only (review 2026-11-01 01-11). The pseudonym is the hex HMAC of the principal; `HmacUserPrincipalPseudonymizerVectorTest` pins it to a vector computed outside the JVM, because logs written before and after a release are joined on it. +- `:domain-core` — a feature's server-assigned id adapter implements its domain `*IdFactory` port + here (registry edge `adapter:outbound:identifier -> domain-core`; `docs/manual/02-new-feature.md`). +- `com.github.f4b6a3:uuid-creator` (`libs.uuid.creator`) — UUIDv7 for + `UuidV7DurableOperationIdFactory`, the generator the sample's id adapters use. ## Forbidden @@ -42,8 +48,9 @@ build choices) live in [README.md](README.md). ## Test -Pure unit tests, no Spring context (`HmacUserPrincipalPseudonymizerTest`, including the RFC 4231 -known-answer vector). +Pure unit tests, no Spring context: `HmacUserPrincipalPseudonymizerTest` (including the RFC 4231 +known-answer vector), `HmacUserPrincipalPseudonymizerVectorTest` and +`UuidV7DurableOperationIdFactoryTest`. ```bash cd src diff --git a/src/adapter/outbound/identifier/README.md b/src/adapter/outbound/identifier/README.md index f63eca2f..f740eb57 100644 --- a/src/adapter/outbound/identifier/README.md +++ b/src/adapter/outbound/identifier/README.md @@ -9,7 +9,8 @@ ## 이름과 내용이 다른 이유 (review 05-21) leaf 이름은 `identifier`지만 범용 식별자 생성기·clock·random 소스는 여기 없다. 식별자 생성은 -durable operation id(UUIDv7) 하나뿐이다(아래). 예전 문서가 범용 생성기 계획을 현재 내용처럼 적었다. 이름은 바꾸지 않았다: Gradle 경로·registry id·소비자 +durable operation id(UUIDv7) 하나뿐이고(아래), 기능이 서버에서 id를 정하면 그 기능의 domain +`*IdFactory` 구현도 여기 둔다(`:domain-core` 의존이 그 때문이다). 예전 문서가 범용 생성기 계획을 현재 내용처럼 적었다. 이름은 바꾸지 않았다: Gradle 경로·registry id·소비자 (`composition:service-runtime`, `app-bootstrap`, `sample-portfolio`)의 의존 선언이 모두 이 이름을 쓰고, 바꿔서 얻는 것은 이름 하나뿐이다. 외부 연동이 없는 crypto 능력을 새로 둘 곳이 필요하면 이 leaf에 둔다. 그때 이 절을 고친다. @@ -25,10 +26,10 @@ leaf에 둔다. 그때 이 절을 고친다. 대소문자를 바꾸면 테스트가 실패한다. - Salt: `APP_PRIVACY_PSEUDONYMIZATION_SALT`(secret, 90일 회전)에서 온다. 이 클래스는 salt를 스스로 읽지 않고 생성자로 받는다. 받은 배열은 복사해 둔다. -- Thread safety: `Mac`은 thread-safe하지 않아서 호출마다 새로 만든다. 그래서 싱글톤 bean으로 - 공유해도 된다. `HmacSHA256`은 JDK 필수 알고리즘이라 `NoSuchAlgorithmException`· - `InvalidKeyException`은 사실상 나지 않는다. checked exception을 호출부에 남기지 않으려고 - `IllegalStateException`으로 감싼다. +- 서명: 이 클래스는 `Mac`을 직접 다루지 않는다. shared-contract의 `HmacSha256.sign`에 맡긴다(리뷰 + 2026-11-01 01-11). `HmacSha256`이 호출마다 새 `Mac`을 만들고(`Mac`은 thread-safe하지 않다), + JDK 필수 알고리즘이라 사실상 나지 않는 checked exception을 `IllegalStateException`으로 감싼다. + 그래서 이 클래스는 싱글톤 bean으로 공유해도 된다. ## UuidV7DurableOperationIdFactory @@ -46,6 +47,10 @@ Spring 어노테이션이 없다. bean은 ## 빌드 결정 +의존은 넷이다: `:application-core`(두 클래스가 구현하는 port), `:shared-contract`(`HmacSha256`), +`:domain-core`(기능의 `*IdFactory` 구현 자리), `uuid-creator`(UUIDv7). 목록과 이유는 +[CLAUDE.md](CLAUDE.md) Allowed 절이 기준이다. + `:application-core`를 `implementation`으로 받는다. 이 leaf의 public 타입 시그니처에 application-core 타입이 드러나지만, 조립하는 쪽이 application-core를 이미 classpath에 갖고 있다. 허용 edge는 `src/config/architecture/modules.json`이 기준이다. diff --git a/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/package-info.java b/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/package-info.java index 5f6c7d82..481742d4 100644 --- a/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/package-info.java +++ b/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/package-info.java @@ -1,5 +1,7 @@ /** - * The HMAC-SHA-256 user-principal pseudonymizer. Despite the leaf name, no identifier generation, - * clock or random source lives here; see README for why the name was kept. + * Two identifier adapters with no external IO: the HMAC-SHA-256 user-principal pseudonymizer and + * the UUIDv7 durable operation id factory. A feature's server-assigned id adapter for a domain + * {@code *IdFactory} port belongs here too. General clock and random sources do not live here; see + * README for why the leaf name was kept. */ package dev.caskeleton.adapter.outbound.identifier; diff --git a/src/adapter/outbound/messaging-kafka/CLAUDE.md b/src/adapter/outbound/messaging-kafka/CLAUDE.md new file mode 100644 index 00000000..293b83c7 --- /dev/null +++ b/src/adapter/outbound/messaging-kafka/CLAUDE.md @@ -0,0 +1,14 @@ +# adapter:outbound:messaging-kafka + +- Module ID `adapter-outbound-messaging-kafka`, Gradle path `:adapter:outbound:messaging-kafka`. + Registry SSOT: `src/config/architecture/modules.json`. +- Responsibility: the Kafka publishing capability as one `runtimeOnly` line. It has no production + code: it bundles `adapter:outbound:messaging` (the application's bridge) with + `messaging:messaging-spring-boot-starter-kafka` (the vendored platform and its Kafka transport) and + ships the module defaults in `config/module-defaults/messaging.yml`. +- Boundaries: add no code here. A publish rule belongs to the bridge (`adapter:outbound:messaging`), + a Kafka rule to the vendored product (`src/messaging/CLAUDE.md`); a class here would be a third + place. Allowed edges come only from the registry entry. +- Tests: activation tests (`./gradlew :adapter:outbound:messaging-kafka:test`) and the real-Kafka + lane `messagingKafkaRelayIntegrationTest` (relay → bridge → broker record bytes; `:integrationCheck`). +- Design: `README.md`. diff --git a/src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java b/src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java index bd113251..2957e18d 100644 --- a/src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java +++ b/src/adapter/outbound/messaging-kafka/src/integrationTest/java/dev/caskeleton/adapter/outbound/messaging/kafka/relay/ApplicationRelayKafkaIntegrationTest.java @@ -8,6 +8,7 @@ import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxCompletion; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; +import dev.caskeleton.application.outbox.OutboxLongRetries; import dev.caskeleton.application.outbox.OutboxStorePort; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.application.outbox.testkit.OutboxEvents; @@ -282,13 +283,15 @@ class ApplicationRelayKafkaIntegrationTest { } @Override - public synchronized OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { - return delegate.markFailed(lease, nextAttemptAt); + public synchronized OutboxCompletion markFailed( + OutboxLease lease, Instant nextAttemptAt, String failureCode) { + return delegate.markFailed(lease, nextAttemptAt, failureCode); } @Override - public synchronized OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt) { - return delegate.markDeferred(lease, nextAttemptAt); + public synchronized OutboxCompletion markDeferred( + OutboxLease lease, Instant nextAttemptAt, String failureCode) { + return delegate.markDeferred(lease, nextAttemptAt, failureCode); } @Override @@ -297,8 +300,13 @@ class ApplicationRelayKafkaIntegrationTest { } @Override - public synchronized OutboxCompletion markDead(OutboxLease lease) { - return delegate.markDead(lease); + public synchronized OutboxCompletion markDead(OutboxLease lease, String failureCode) { + return delegate.markDead(lease, failureCode); + } + + @Override + public synchronized OutboxLongRetries longRetries(int minDeferredClaims, Instant now) { + return delegate.longRetries(minDeferredClaims, now); } @Override diff --git a/src/adapter/outbound/messaging/CLAUDE.md b/src/adapter/outbound/messaging/CLAUDE.md index 025499f2..6cdb166a 100644 --- a/src/adapter/outbound/messaging/CLAUDE.md +++ b/src/adapter/outbound/messaging/CLAUDE.md @@ -5,7 +5,7 @@ - Module ID: `adapter-outbound-messaging` - Gradle path: `:adapter:outbound:messaging` - Focused test (derived from Gradle path): `./gradlew :adapter:outbound:messaging:test --console=plain` -- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. +- Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.8. - Registry SSOT: `src/config/architecture/modules.json`. Package root: `dev.caskeleton.adapter.outbound.messaging`. diff --git a/src/adapter/outbound/messaging/README.md b/src/adapter/outbound/messaging/README.md index 63e6ff03..10323d26 100644 --- a/src/adapter/outbound/messaging/README.md +++ b/src/adapter/outbound/messaging/README.md @@ -42,13 +42,33 @@ platform `REJECTED` 중 `FailureDescriptor.retryable()`이 true인 것(종료 멈춘다(2026-11-01 리뷰 06-01). `AMBIGUOUS`로 번역하지 않은 이유: 동작은 같지만 "전송됐을 수 있음"이라는 거짓 정보가 남아 중복 경고를 오염시킨다. +### 실패 원인 코드 + +결과(outcome)는 relay가 무엇을 할지만 정한다. 종료 중 거부, 닫힌 transport, 거부된 credential은 모두 +`REJECTED_RETRYABLE` 하나다. 그런데 이 셋은 끝이 없는 재시도다(시도 예산을 쓰지 않는다). 그래서 bridge는 +platform `FailureDescriptor.code()`를 버리지 않고 `OutboxPublishAttempt.failureCode()`로 함께 넘긴다 +(재리뷰 2026-11-03 RR-05-03). relay는 그 코드를 행의 `last_failure_code`(V22)와 실패 로그의 +`error.reason`에 남긴다. 운영자는 이 값으로 "credential이 진짜 틀렸다"와 "broker가 이 레코드만 받지 +않는다"를 가른다(`docs/runbooks/outbox-publish-failed.md` §4.1). + +- platform code는 이미 정제된 이름이다(`KAFKA_AUTHENTICATIONEXCEPTION`, `PUBLISH_DEADLINE_EXCEEDED` 등). + driver 메시지가 아니므로 그대로 옮긴다. application 코드 문법(`[A-Za-z0-9][A-Za-z0-9._:-]*`, 120자)에 + 맞지 않는 code는 그 실패의 `FailureCategory` 이름으로 옮긴다. +- platform으로 옮길 수 없는 event(아래 id 규칙)는 bridge가 `EVENT_NOT_REPRESENTABLE`로 거부한다. +- 버린 대안: relay가 platform 타입을 직접 보는 것(경계가 깨진다), outcome 값을 원인별로 늘리는 것(relay가 + 할 일은 같은데 분기만 는다). + ### event id → message id application `EventId`는 문자열이고 platform `MessageId`는 **UUIDv7**만 받는다. bridge는 event id가 정규 소문자 UUIDv7 문자열일 때만 같은 값으로 옮기고, 그 밖(대문자·축약 표기·v4 등 다른 버전)은 다른 문자열의 message id로 바꿔 보내지 않고 `REJECTED_BEFORE_SEND`로 거부한다(relay는 DEAD). 소비자 중복 -제거 키가 event id라서 값을 바꿔 보내면 중복 제거가 깨지기 때문이다(리뷰 2026-11-01 06-06). 이 거부는 -append 시점(`EventId` 문법)에서 먼저 일어나야 한다 — application 쪽 문법 일원화는 별도 작업이다. +제거 키가 event id라서 값을 바꿔 보내면 중복 제거가 깨지기 때문이다(리뷰 2026-11-01 06-06). + +같은 규칙이 append 쪽에 먼저 있다. `IntegrationEventDraft`가 정규 소문자 UUIDv7이 아닌 event id와 +causation id를 거부하므로(`IntegrationIdentity.isCanonicalUuidV7`), 그런 id는 업무 트랜잭션 안에서 실패한다 +(재리뷰 2026-11-03 RR-05-04). bridge의 거부는 이 규칙 전에 쓰인 행(저장 문법 `EventId`는 그대로 넓다)을 위한 +마지막 방어선이다. ## outbox 발행 포트에는 대역이 없다 @@ -70,9 +90,10 @@ event가 다시 publish될 수 있다. 같은 event id로 다시 나가므로 co 있으면 `messaging-platform`이다. 이 adapter는 confirmed FAILED/DEAD report 하나를 SLF4J 2 fluent ERROR 하나로 렌더링한다. -공통 field는 `error.code`, `error.category`, `dependency_name`, +공통 field는 `error.code`, `error.category`, `error.cause_type`, `error.reason`, `dependency_name`, `dependency_type=messaging`, `outcome`, `event_id`, `event_type`, `aggregate_id`, `correlation_id`, `attempt_count`, `runbook_link`다. retry report만 `next_attempt_at`을 추가한다. +`error.reason`은 위 실패 원인 코드다. payload/envelope/exception-derived field는 받거나 렌더링하지 않는다. logging 내부 `RuntimeException`은 adapter와 use case 양쪽에서 방어하므로 persisted FAILED/DEAD outcome을 바꾸지 않는다. @@ -85,10 +106,8 @@ payload/envelope/exception-derived field는 받거나 렌더링하지 않는다. `envelope`·`realtime`)은 2026-09-25에 삭제됐고 복구 경로는 `docs/capability-status.md` 제거 표에 있다. -공통 build evidence manifest 검증은 build-tools로 옮겼다. 루트 `verifyMessagingContracts` -(`VerifyMessagingEvidenceTask`)가 application-core·shared-contract 두 qualification 레인 결과로 -`build/messaging-evidence/contracts-schema/manifest.json`을 쓰고, 쓴 바이트를 바로 common schema로 -검증한다. 이 leaf는 그 검증에 관여하지 않는다. +integration event 계약 검증은 루트 `verifyMessagingContracts`(`src/build.gradle`)가 한다. application-core· +shared-contract·sample-portfolio의 qualification lane 셋을 묶은 task다. 이 leaf는 그 검증에 관여하지 않는다. canonical path는 platform `PublishResult`의 confirmation/transmission evidence를 application -`OutboxPublishOutcome`으로 명시적으로 변환한다. +`OutboxPublishOutcome`으로 명시적으로 변환하고, 실패 code를 `OutboxPublishAttempt`에 함께 싣는다. diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java index 91528ef2..3a7d209c 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java @@ -4,17 +4,21 @@ import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.application.outbox.ClaimedOutboxEvent; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.application.outbox.OutboxPublishAmbiguousException; +import dev.caskeleton.application.outbox.OutboxPublishAttempt; import dev.caskeleton.application.outbox.OutboxPublishOutcome; import dev.caskeleton.application.outbox.OutboxPublishRefusedException; +import java.time.Duration; import java.util.Objects; +import java.util.Optional; /** * The relay's publish port: a claimed row's validated event, delegated unchanged to the canonical * {@link IntegrationEventPublishPort}. * *

        The event is the one the append validated, restored from its exact envelope bytes; nothing - * here re-renders it. The platform's four-valued outcome is passed through, so the relay can tell a - * possibly-stored message (ambiguous) from a refused one. + * here re-renders it. The canonical publisher's attempt — its outcome and its failure code — is + * passed through unchanged, so the relay can tell a possibly-stored message (ambiguous) from a + * refused one, and a refused credential from a closed transport. */ public final class OutboxMessagePublishAdapter implements OutboxMessagePublishPort { @@ -27,7 +31,7 @@ public final class OutboxMessagePublishAdapter implements OutboxMessagePublishPo @Override public void publish(ClaimedOutboxEvent event) { - OutboxPublishOutcome outcome = publishForOutcome(event); + OutboxPublishOutcome outcome = publishForOutcome(event).outcome(); if (outcome == OutboxPublishOutcome.CONFIRMED) { return; } @@ -37,8 +41,14 @@ public final class OutboxMessagePublishAdapter implements OutboxMessagePublishPo throw new OutboxPublishRefusedException(outcome); } + /** The canonical publisher's, unchanged: this adapter adds no wait of its own. */ @Override - public OutboxPublishOutcome publishForOutcome(ClaimedOutboxEvent event) { + public Optional longestAttempt() { + return canonicalPublisher.longestAttempt(); + } + + @Override + public OutboxPublishAttempt publishForOutcome(ClaimedOutboxEvent event) { Objects.requireNonNull(event, "event must not be null"); return canonicalPublisher.publish(event.event()).toCompletableFuture().join(); } diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapter.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapter.java index 9c6d897a..588a82bb 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapter.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapter.java @@ -48,6 +48,10 @@ public final class Slf4jOutboxRelayFailureReportAdapter implements OutboxRelayFa // occasionally credentials. The class name is a type; the code is bounded. .addKeyValue("error.code", report.code().code()) .addKeyValue("error.cause_type", report.causeType()) + // Why, in the publisher's words: the cause type of a returned outcome names only + // which + // outcome it was, and a refused credential and a closed transport are one outcome. + .addKeyValue("error.reason", report.failureCode()) .addKeyValue("error.category", report.code().category().name()) .addKeyValue("dependency_name", dependencyName) .addKeyValue("dependency_type", DEPENDENCY_TYPE) diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java index 49e84155..8b81e8ae 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapter.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.messaging.platformbridge; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.OutboxPublishAttempt; import dev.caskeleton.application.outbox.OutboxPublishOutcome; import dev.caskeleton.messaging.api.CausationId; import dev.caskeleton.messaging.api.ContentType; @@ -26,6 +27,7 @@ import dev.caskeleton.messaging.api.publish.TransmissionEvidence; import dev.caskeleton.messaging.schema.EncodedMessage; import dev.caskeleton.messaging.schema.EncodedMessagePublisher; import dev.caskeleton.messaging.schema.SchemaReference; +import java.time.Duration; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; @@ -45,6 +47,12 @@ import java.util.concurrent.CompletionStage; */ public final class PlatformIntegrationEventPublishAdapter implements IntegrationEventPublishPort { + /** + * The failure code of an event this bridge refuses before the platform sees it: a value — an id + * above all — the platform's types cannot carry. + */ + public static final String NOT_REPRESENTABLE = "EVENT_NOT_REPRESENTABLE"; + private final EncodedMessagePublisher publisher; private final ProducerId producer; @@ -55,7 +63,7 @@ public final class PlatformIntegrationEventPublishAdapter implements Integration } @Override - public CompletionStage publish(ValidatedIntegrationEvent event) { + public CompletionStage publish(ValidatedIntegrationEvent event) { Objects.requireNonNull(event, "event must not be null"); final PreparedPublish prepared; try { @@ -64,12 +72,27 @@ public final class PlatformIntegrationEventPublishAdapter implements Integration // Only a value the platform cannot represent is a definite refusal: the same payload is // refused again, so the relay dead-letters it at once. Any other failure is not evidence of // that and propagates, so the relay treats it as a retryable failure with its real cause. - return CompletableFuture.completedFuture(OutboxPublishOutcome.REJECTED_BEFORE_SEND); + return CompletableFuture.completedFuture( + OutboxPublishAttempt.failed( + OutboxPublishOutcome.REJECTED_BEFORE_SEND, NOT_REPRESENTABLE)); } return publisher .publishEncoded(prepared.destination(), prepared.envelope(), PublishOptions.defaults()) - .thenApply(PlatformIntegrationEventPublishAdapter::mapOutcome); + .thenApply(PlatformIntegrationEventPublishAdapter::translate); + } + + /** + * Twice the publish deadline this bridge asks for ({@link PublishOptions#defaults()}). + * + *

        The platform measures the deadline from the call, but a transport may block inside its send + * before the deadline is applied to the stage it returns — Kafka's {@code max.block.ms} is set to + * the same default for exactly that wait — so an attempt can take the deadline twice over. The + * relay sizes its batch against this (review 2026-11-01 06-12). + */ + @Override + public Optional longestAttempt() { + return Optional.of(PublishOptions.defaults().timeout().multipliedBy(2)); } private PreparedPublish prepare(ValidatedIntegrationEvent event) { @@ -146,8 +169,10 @@ public final class PlatformIntegrationEventPublishAdapter implements Integration * * *

        Either refusal is {@code REJECTED_BEFORE_SEND}: the same id is refused again, so the relay - * dead-letters it. The append side's {@code EventId} grammar is where such an id should fail - * first, in the writer's transaction; until it does, this is where the mismatch is caught. + * dead-letters it. A new event fails earlier, in the writer's transaction: {@code + * IntegrationEventDraft} refuses an id that is not a canonical lower-case UUIDv7 (re-review + * 2026-11-03 RR-05-04). This check stays for rows appended before that rule — the stored {@code + * EventId} grammar is wider, so they can still be read back. * * @throws IllegalArgumentException when the value is not a canonical lower-case UUIDv7 */ @@ -177,8 +202,37 @@ public final class PlatformIntegrationEventPublishAdapter implements Integration * committed event, and its aggregate behind it, for a cause that clears on its own. It gets its * own value instead. */ - private static OutboxPublishOutcome mapOutcome(PublishResult result) { + private static OutboxPublishAttempt translate(PublishResult result) { Objects.requireNonNull(result, "publish result must not be null"); + OutboxPublishOutcome outcome = mapOutcome(result); + if (outcome == OutboxPublishOutcome.CONFIRMED) { + return OutboxPublishAttempt.confirmed(); + } + return result + .failure() + .map(PlatformIntegrationEventPublishAdapter::failureCode) + .map(code -> OutboxPublishAttempt.failed(outcome, code)) + .orElseGet(() -> OutboxPublishAttempt.of(outcome)); + } + + /** + * The platform's failure code, carried as the application's failure code (re-review 2026-11-03 + * RR-05-03). + * + *

        The outcome is all the relay acts on, and it loses the reason on purpose: a shutdown, a + * closed transport and a refused credential are one {@code REJECTED_RETRYABLE}. The code keeps it + * for the operator, on the row and in the failure log. The platform's code is already sanitized — + * a stable name, never a driver message — and passes as it is; one outside the application's code + * grammar (the platform only bounds its length) is carried as the failure's category instead, a + * name the platform owns too. + */ + private static String failureCode(FailureDescriptor failure) { + return OutboxPublishAttempt.isFailureCode(failure.code()) + ? failure.code() + : failure.category().name(); + } + + private static OutboxPublishOutcome mapOutcome(PublishResult result) { if (result.completion() == PublishCompletion.CONFIRMED) { return OutboxPublishOutcome.CONFIRMED; } diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java index 54ea4f2d..9923ddab 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java @@ -5,7 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.messaging.outbox.OutboxMessagePublishAdapter; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; -import dev.caskeleton.application.outbox.OutboxPublishOutcome; +import dev.caskeleton.application.outbox.OutboxPublishAttempt; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -32,7 +32,7 @@ class MessagingConfigTest { runner .withBean( IntegrationEventPublishPort.class, - () -> event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED)) + () -> event -> CompletableFuture.completedFuture(OutboxPublishAttempt.confirmed())) .run( context -> assertThat(context.getBean(OutboxMessagePublishPort.class)) diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapterTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapterTest.java index 85322ffb..5c7e7cd8 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapterTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapterTest.java @@ -51,7 +51,14 @@ class Slf4jOutboxRelayFailureReportAdapterTest { adapter.report( OutboxRelayFailureReport.retryableFailure( - "evt-1", "WorkLogReserved", "agg-1", "corr-1", 2, nextAttemptAt, cause)); + "evt-1", + "WorkLogReserved", + "agg-1", + "corr-1", + 2, + nextAttemptAt, + cause, + "KAFKA_AUTHENTICATIONEXCEPTION")); assertThat(appender.list).hasSize(1); ILoggingEvent event = appender.list.getFirst(); @@ -71,6 +78,7 @@ class Slf4jOutboxRelayFailureReportAdapterTest { Map.entry("correlation_id", "corr-1"), Map.entry("attempt_count", 2), Map.entry("error.cause_type", "java.lang.RuntimeException"), + Map.entry("error.reason", "KAFKA_AUTHENTICATIONEXCEPTION"), Map.entry("runbook_link", "runbook://outbox/publish-failed"), Map.entry("next_attempt_at", "2026-07-25T01:02:03Z"))); assertThat(event.getThrowableProxy()) @@ -89,7 +97,7 @@ class Slf4jOutboxRelayFailureReportAdapterTest { adapter.report( OutboxRelayFailureReport.deadLetter( - "evt-2", "WorkLogReserved", "agg-2", "corr-2", 3, cause)); + "evt-2", "WorkLogReserved", "agg-2", "corr-2", 3, cause, "REJECTED_BEFORE_SEND")); assertThat(appender.list).hasSize(1); ILoggingEvent event = appender.list.getFirst(); @@ -142,7 +150,8 @@ class Slf4jOutboxRelayFailureReportAdapterTest { "agg-3", "corr-3", 3, - new RuntimeException("broker down")))) + new RuntimeException("broker down"), + "RuntimeException"))) .doesNotThrowAnyException(); } diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java index 41564585..d1564cd4 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/platformbridge/PlatformIntegrationEventPublishAdapterTest.java @@ -12,6 +12,7 @@ import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; import dev.caskeleton.application.messaging.event.testkit.BrokerAnswer; import dev.caskeleton.application.messaging.event.testkit.IntegrationEventPublishContract; +import dev.caskeleton.application.outbox.OutboxPublishAttempt; import dev.caskeleton.application.outbox.OutboxPublishOutcome; import dev.caskeleton.messaging.api.ContentType; import dev.caskeleton.messaging.api.MessageEnvelope; @@ -59,7 +60,7 @@ class PlatformIntegrationEventPublishAdapterTest extends IntegrationEventPublish new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service"); ValidatedIntegrationEvent event = event(EVENT_ID, Optional.of(CAUSATION_ID)); - assertThat(bridge.publish(event).toCompletableFuture().join()) + assertThat(bridge.publish(event).toCompletableFuture().join().outcome()) .isEqualTo(OutboxPublishOutcome.CONFIRMED); MessageDestination destination = publisher.destination; @@ -99,19 +100,19 @@ class PlatformIntegrationEventPublishAdapterTest extends IntegrationEventPublish new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service"); ValidatedIntegrationEvent event = event(EVENT_ID, Optional.empty()); - assertThat(bridge.publish(event).toCompletableFuture().join()) + assertThat(bridge.publish(event).toCompletableFuture().join().outcome()) .isEqualTo(OutboxPublishOutcome.CONFIRMED); publisher.result = ambiguous(); - assertThat(bridge.publish(event).toCompletableFuture().join()) + assertThat(bridge.publish(event).toCompletableFuture().join().outcome()) .isEqualTo(OutboxPublishOutcome.AMBIGUOUS); publisher.result = rejected(PublishEvidence.notTransmitted()); - assertThat(bridge.publish(event).toCompletableFuture().join()) + assertThat(bridge.publish(event).toCompletableFuture().join().outcome()) .isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND); publisher.result = rejected( new PublishEvidence( true, TransmissionEvidence.TRANSMITTED, false, ConfirmationLevel.NONE)); - assertThat(bridge.publish(event).toCompletableFuture().join()) + assertThat(bridge.publish(event).toCompletableFuture().join().outcome()) .isEqualTo(OutboxPublishOutcome.REJECTED_AFTER_BROKER); } @@ -132,12 +133,101 @@ class PlatformIntegrationEventPublishAdapterTest extends IntegrationEventPublish // when OutboxPublishOutcome outcome = - bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join(); + bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join().outcome(); // then assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_RETRYABLE); } + @Test + @DisplayName("platform이 붙인 실패 코드는 원인 코드로 그대로 옮긴다") + void thePlatformsFailureCodeIsCarriedAsTheFailureCode() { + // given: the broker refused this producer's credentials + RecordingPublisher publisher = + new RecordingPublisher( + PublishResult.rejected( + Duration.ZERO, + new FailureDescriptor( + FailureCategory.AUTHENTICATION, + "KAFKA_AUTHENTICATIONEXCEPTION", + true, + "kafka publish failed with AuthenticationException", + Optional.of("AuthenticationException")))); + PlatformIntegrationEventPublishAdapter bridge = + new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service"); + + // when + OutboxPublishAttempt attempt = + bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join(); + + // then + assertThat(attempt) + .isEqualTo( + OutboxPublishAttempt.failed( + OutboxPublishOutcome.REJECTED_RETRYABLE, "KAFKA_AUTHENTICATIONEXCEPTION")); + } + + @Test + @DisplayName("코드 문법에 맞지 않는 platform 실패 코드는 그 실패의 분류 이름으로 옮긴다") + void aPlatformCodeOutsideTheCodeGrammarIsCarriedAsItsCategory() { + // given + RecordingPublisher publisher = + new RecordingPublisher( + PublishResult.ambiguous( + Duration.ZERO, + FailureDescriptor.of( + FailureCategory.AMBIGUOUS, "timed out after 5000 ms", "no answer"))); + PlatformIntegrationEventPublishAdapter bridge = + new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service"); + + // when + OutboxPublishAttempt attempt = + bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join(); + + // then + assertThat(attempt.failureCode()).contains("AMBIGUOUS"); + } + + @Test + @DisplayName("platform으로 옮길 수 없는 event는 그 이유를 원인 코드로 알린다") + void anEventThePlatformCannotRepresentIsRefusedWithItsOwnFailureCode() { + // given + RecordingPublisher publisher = new RecordingPublisher(confirmed()); + PlatformIntegrationEventPublishAdapter bridge = + new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service"); + + // when + OutboxPublishAttempt attempt = + bridge.publish(event("event-1", Optional.empty())).toCompletableFuture().join(); + + // then + assertThat(attempt) + .isEqualTo( + OutboxPublishAttempt.failed( + OutboxPublishOutcome.REJECTED_BEFORE_SEND, + PlatformIntegrationEventPublishAdapter.NOT_REPRESENTABLE)); + } + + /** + * The relay sizes its batch against this (review 2026-11-01 06-12). The platform's deadline is + * measured from the call, but a transport may block in its send before the deadline is applied — + * Kafka's {@code max.block.ms} is set to the same default — so an attempt can take twice it. + */ + @Test + @DisplayName("발행 하나의 최악 시간은 platform 기본 발행 기한의 두 배다") + void theLongestAttemptIsTwiceThePlatformsDefaultPublishDeadline() { + // given + PlatformIntegrationEventPublishAdapter bridge = + new PlatformIntegrationEventPublishAdapter( + new RecordingPublisher(confirmed()), "portfolio-service"); + + // when + Optional longest = bridge.longestAttempt(); + + // then + assertThat(longest).contains(PublishOptions.defaults().timeout().multipliedBy(2)); + } + @Test @DisplayName("다시 시도해도 같은 결과인 거부는 지금처럼 확정 거부로 번역한다") void aRefusalThePlatformMarksFinalStaysADefiniteRejection() { @@ -153,7 +243,7 @@ class PlatformIntegrationEventPublishAdapterTest extends IntegrationEventPublish // when OutboxPublishOutcome outcome = - bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join(); + bridge.publish(event(EVENT_ID, Optional.empty())).toCompletableFuture().join().outcome(); // then assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND); @@ -165,7 +255,12 @@ class PlatformIntegrationEventPublishAdapterTest extends IntegrationEventPublish PlatformIntegrationEventPublishAdapter bridge = new PlatformIntegrationEventPublishAdapter(publisher, "portfolio-service"); - assertThat(bridge.publish(event("event-1", Optional.empty())).toCompletableFuture().join()) + assertThat( + bridge + .publish(event("event-1", Optional.empty())) + .toCompletableFuture() + .join() + .outcome()) .isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND); assertThat(publisher.calls).isZero(); } @@ -192,7 +287,7 @@ class PlatformIntegrationEventPublishAdapterTest extends IntegrationEventPublish // when OutboxPublishOutcome outcome = - bridge.publish(event(eventId, Optional.empty())).toCompletableFuture().join(); + bridge.publish(event(eventId, Optional.empty())).toCompletableFuture().join().outcome(); // then assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND); diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java index 97cb53a8..95e2ef4f 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java @@ -64,17 +64,39 @@ class NotificationCallbackProviderConfig { return cachingCertificates(uri -> fetchCertificate(client, uri)); } - private static byte[] fetchCertificate(HttpClient client, URI uri) { + /** + * Fetches the certificate document at a host-checked SNS URL. + * + *

        The status decides what a failed fetch says. The URL already passed the SNS host check, so + * the host answering is SNS. A 4xx is SNS saying it has no such certificate: a real SNS message + * names one that exists, so the envelope is forged — {@link IllegalArgumentException}, which the + * verifier turns into an invalid signature that is refused and audited. It used to be "cannot + * verify now" like every other non-2xx, so a forged envelope pointing at a certificate SNS never + * issued got a 503, was never audited, and was logged as a provider hiccup (review 2026-11-03 + * RR-07-03). A 5xx, a 408 or 429 (slow or throttling host), or a network failure says nothing + * about the certificate and stays "cannot verify now". + * + * @param client the no-redirect client + * @param uri the host-checked certificate URL + * @return the certificate document, at most {@link #MAX_SNS_CERTIFICATE_BYTES} + * @throws IllegalArgumentException when SNS answers that the certificate does not exist + * @throws CallbackVerificationUnavailableException when the certificate could not be fetched now + */ + static byte[] fetchCertificate(HttpClient client, URI uri) { HttpRequest request = HttpRequest.newBuilder(uri).timeout(SNS_CERTIFICATE_TIMEOUT).GET().build(); try { HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); try (InputStream body = response.body()) { - if (response.statusCode() / 100 != 2) { + int status = response.statusCode(); + if (status / 100 == 4 && status != 408 && status != 429) { + throw new IllegalArgumentException( + "SNS has no signing certificate at the URL the message names (HTTP " + status + ")"); + } + if (status / 100 != 2) { throw certificateUnavailable( - new IOException( - "SNS signing certificate fetch failed with HTTP " + response.statusCode())); + new IOException("SNS signing certificate fetch failed with HTTP " + status)); } return body.readNBytes(MAX_SNS_CERTIFICATE_BYTES); } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java index 78e583ae..3aa9373a 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java @@ -16,6 +16,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import tools.jackson.databind.JsonNode; @@ -36,8 +37,12 @@ import tools.jackson.databind.JsonNode; * signed string), for up to {@link #SNS_HTTP_RETRY_HORIZON}. A window of five minutes threw away * every bounce and complaint that arrived after an outage longer than that, and with them the * suppressions they should have created (review 05-20). Accepting a replay inside the window costs - * nothing: the provider event ledger is unique on {@code (provider_profile_id, provider_event_id)}, - * so a second delivery of the same event is a duplicate, not a second event. + * nothing: the provider event ledger is unique on {@code (provider_profile_id, provider_event_id)} + * whenever an event id is present, and this adapter gives every SES event the signed SNS {@code + * MessageId} as that id, so a second delivery of the same message is a duplicate, not a second + * event. It used to give none, and the only identity left was the {@code (provider_profile_id, + * event_fingerprint)} index — a fingerprint keyed by the active HMAC key, so a redelivery after a + * key rotation inside the window was recorded twice (review 2026-11-03 RR-07-07). */ public final class SesCallbackAdapter implements ProviderCallbackAdapter { @@ -118,7 +123,10 @@ public final class SesCallbackAdapter implements ProviderCallbackAdapter { return List.of(); } String message = envelope.getOrDefault("Message", "{}"); - return normalizer.normalize(message); + // The SNS MessageId is in the signed string and survives every redelivery, so it — not a + // fingerprint under the current HMAC key — is what the ledger recognises a replay by. + return normalizer.normalize( + message, Optional.ofNullable(envelope.get("MessageId")).filter(id -> !id.isBlank())); } private boolean withinReplayWindow(String timestamp, Instant receivedAt) { diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesEventNormalizer.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesEventNormalizer.java index 24d5d5ff..f35bd5b5 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesEventNormalizer.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesEventNormalizer.java @@ -7,6 +7,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import tools.jackson.databind.JsonNode; @@ -19,8 +20,16 @@ import tools.jackson.databind.JsonNode; */ public final class SesEventNormalizer { - /** Normalize one SES notification payload. */ - public List normalize(String payload) { + /** + * Normalize one SES notification payload. + * + * @param payload the SES event JSON (the SNS envelope's {@code Message}) + * @param providerEventId the identity of the delivery that carried it — the signed SNS {@code + * MessageId}, which SNS keeps across redeliveries — or empty when the envelope had none + * @return the provider events, each carrying {@code providerEventId} + */ + public List normalize(String payload, Optional providerEventId) { + Objects.requireNonNull(providerEventId, "providerEventId"); JsonNode root = NotificationJsonMapper.mapper().readTree(payload); String type = text(root, "eventType").orElse(text(root, "notificationType").orElse("Unknown")); Optional messageId = @@ -30,24 +39,26 @@ public final class SesEventNormalizer { List events = new ArrayList<>(1); events.add( switch (type) { - case "Send" -> - event(NormalizedEventType.PROVIDER_ACCEPTED, type, messageId, occurredAt, Map.of()); + case "Send" -> event(NormalizedEventType.PROVIDER_ACCEPTED, type, messageId, occurredAt); case "Delivery" -> - event(NormalizedEventType.DELIVERY_CONFIRMED, type, messageId, occurredAt, Map.of()); + event(NormalizedEventType.DELIVERY_CONFIRMED, type, messageId, occurredAt); case "DeliveryDelay" -> - event(NormalizedEventType.DELIVERY_DELAYED, type, messageId, occurredAt, Map.of()); + event(NormalizedEventType.DELIVERY_DELAYED, type, messageId, occurredAt); case "Bounce" -> bounce(root, type, messageId, occurredAt); - case "Complaint" -> - event(NormalizedEventType.COMPLAINT, type, messageId, occurredAt, Map.of()); + case "Complaint" -> event(NormalizedEventType.COMPLAINT, type, messageId, occurredAt); case "Reject" -> - event(NormalizedEventType.PROVIDER_REJECTED, type, messageId, occurredAt, Map.of()); + event(NormalizedEventType.PROVIDER_REJECTED, type, messageId, occurredAt); case "RenderingFailure" -> - event(NormalizedEventType.TEMPLATE_FAILURE, type, messageId, occurredAt, Map.of()); - case "Open" -> event(NormalizedEventType.OPENED, type, messageId, occurredAt, Map.of()); - case "Click" -> event(NormalizedEventType.CLICKED, type, messageId, occurredAt, Map.of()); - default -> event(NormalizedEventType.UNKNOWN, type, messageId, occurredAt, Map.of()); + event(NormalizedEventType.TEMPLATE_FAILURE, type, messageId, occurredAt); + case "Open" -> event(NormalizedEventType.OPENED, type, messageId, occurredAt); + case "Click" -> event(NormalizedEventType.CLICKED, type, messageId, occurredAt); + default -> event(NormalizedEventType.UNKNOWN, type, messageId, occurredAt); }); - return List.copyOf(events); + // One SNS delivery carries one SES event, so the delivery's id is the event's. It is what makes + // a redelivery a duplicate in the ledger: the other identity, the event fingerprint, is keyed + // by + // the active HMAC key and changes when the key rotates (review 2026-11-03 RR-07-07). + return events.stream().map(event -> withEventId(event, providerEventId)).toList(); } private static NormalizedProviderEvent bounce( @@ -68,6 +79,14 @@ public final class SesEventNormalizer { Map.of("bounceType", bounceType)); } + private static NormalizedProviderEvent event( + NormalizedEventType type, + String nativeType, + Optional messageId, + Optional occurredAt) { + return event(type, nativeType, messageId, occurredAt, Map.of()); + } + private static NormalizedProviderEvent event( NormalizedEventType type, String nativeType, @@ -78,6 +97,17 @@ public final class SesEventNormalizer { type, nativeType, Optional.empty(), messageId, occurredAt, attributes); } + private static NormalizedProviderEvent withEventId( + NormalizedProviderEvent event, Optional providerEventId) { + return new NormalizedProviderEvent( + event.type(), + event.providerNativeType(), + providerEventId, + event.providerRequestId(), + event.providerOccurredAt(), + event.attributes()); + } + private static Optional text(JsonNode node, String field) { JsonNode value = node.get(field); return value == null || value.isNull() ? Optional.empty() : Optional.of(value.asString()); diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatch.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatch.java index b19ef84a..ca659a9f 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatch.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatch.java @@ -112,7 +112,12 @@ public final class JavaMailSenderSmtpDispatch implements SmtpDispatch { } else if (cause instanceof SMTPSendFailedException send) { code = send.getReturnCode(); } - return code >= 200 && code < 600 ? Optional.of(code) : Optional.empty(); + // Only a refusal is a reply code here: 4xx (transient) and 5xx (permanent). Angus's sendpartial + // path throws SMTPSendFailedException carrying the last reply, which can be a success (250); + // read as a reply code it reached the classifier as a permanent refusal of a message the relay + // had partly accepted. Anything else takes the conservative "may have been delivered" path + // below (review 2026-11-03 RR-04-11). + return code >= 400 && code < 600 ? Optional.of(code) : Optional.empty(); } /** diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateFetchTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateFetchTest.java new file mode 100644 index 00000000..50ace0f3 --- /dev/null +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateFetchTest.java @@ -0,0 +1,104 @@ +package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.sun.net.httpserver.HttpServer; +import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationUnavailableException; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.URI; +import java.net.http.HttpClient; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * What a failed SNS signing-certificate fetch says about the callback (review 2026-11-03 RR-07-03). + * + *

        The URL has passed the SNS host check before it is fetched, so the host is SNS's. A real SNS + * message names a certificate that exists; when SNS itself answers 4xx for it, the envelope named a + * certificate SNS never issued — a forged callback, to be rejected and audited. Only a failure that + * says nothing about the certificate — a 5xx, a 408 or 429 (the host is slow or throttling), or a + * network failure — is "cannot verify now" (503, the provider retries). + */ +class SnsCertificateFetchTest { + + private final HttpClient client = HttpClient.newHttpClient(); + + @ParameterizedTest + @ValueSource(ints = {403, 404, 410}) + @DisplayName("인증서 URL이 4xx로 답하면 없는 인증서를 가리킨 위조 콜백이므로 검증 실패로 거절된다") + void aCertificateTheHostDoesNotHaveFailsVerification(int status) throws IOException { + // given + HttpServer server = answering(status); + try { + URI url = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/cert.pem"); + + // when + Throwable failure = + catchThrowable(() -> NotificationCallbackProviderConfig.fetchCertificate(client, url)); + + // then + assertThat(failure) + .isInstanceOf(IllegalArgumentException.class) + .isNotInstanceOf(CallbackVerificationUnavailableException.class); + } finally { + server.stop(0); + } + } + + @ParameterizedTest + @ValueSource(ints = {408, 429, 500, 503}) + @DisplayName("인증서 URL이 5xx나 시간 초과·요청 제한(408·429)으로 답하면 아무것도 모르므로 지금 검증할 수 없다고 답한다") + void aFailingCertificateHostLeavesTheCallbackUnverified(int status) throws IOException { + // given + HttpServer server = answering(status); + try { + URI url = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/cert.pem"); + + // when + Throwable failure = + catchThrowable(() -> NotificationCallbackProviderConfig.fetchCertificate(client, url)); + + // then + assertThat(failure).isInstanceOf(CallbackVerificationUnavailableException.class); + } finally { + server.stop(0); + } + } + + @Test + @DisplayName("인증서 호스트에 닿지 못하면 지금 검증할 수 없다고 답한다") + void anUnreachableCertificateHostLeavesTheCallbackUnverified() throws IOException { + // given + int closedPort; + try (ServerSocket probe = new ServerSocket(0)) { + closedPort = probe.getLocalPort(); + } + URI url = URI.create("http://127.0.0.1:" + closedPort + "/cert.pem"); + + // when + Throwable failure = + catchThrowable(() -> NotificationCallbackProviderConfig.fetchCertificate(client, url)); + + // then + assertThat(failure).isInstanceOf(CallbackVerificationUnavailableException.class); + } + + private static HttpServer answering(int status) throws IOException { + HttpServer server = + HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.createContext( + "/", + exchange -> { + exchange.sendResponseHeaders(status, -1); + exchange.close(); + }); + server.start(); + return server; + } +} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapterTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapterTest.java index d425bf65..292f2b58 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapterTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapterTest.java @@ -8,6 +8,7 @@ import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVe import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationUnavailableException; import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackVerificationRequest; import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationJsonMapper; +import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; import dev.caskeleton.application.notification.platform.api.ProviderId; import dev.caskeleton.application.notification.platform.api.ProviderProfileId; import java.nio.charset.StandardCharsets; @@ -19,6 +20,7 @@ import java.time.Duration; import java.time.Instant; import java.util.Base64; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -135,6 +137,28 @@ class SesCallbackAdapterTest { assertThat(unavailable.reasonCode()).isEqualTo("SNS_CERTIFICATE_UNAVAILABLE")); } + @Test + @DisplayName( + "SES 이벤트의 provider event id는 서명된 SNS MessageId라 fingerprint 키를 회전해도 같은 콜백이 같은 이벤트로 남는다") + void theSignedSnsMessageIdIsTheProviderEventId() { + // given + CallbackVerificationResult verified = + adapter.verify(request(signed(ALLOWED_TOPIC, RECEIVED_AT))); + + // when + List events = + adapter.normalize(verified.verifiedCallback().orElseThrow()); + + // then + // The ledger is unique on (profile, provider_event_id) whenever an id is present. Without one + // the only identity was a fingerprint keyed by the active HMAC key, so a redelivery after a + // key rotation inside the one-hour replay window became a second row (RR-07-07). + assertThat(events) + .singleElement() + .extracting(NormalizedProviderEvent::providerEventId) + .isEqualTo(Optional.of("sns-message-1")); + } + /** The adapter with the window a deployment gets when it sets nothing. */ private static SesCallbackAdapter withDefaultWindow() { return new SesCallbackAdapter( diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatchTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatchTest.java index 4fd987ad..28009d6b 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatchTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/smtp/JavaMailSenderSmtpDispatchTest.java @@ -16,9 +16,11 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Optional; import java.util.Properties; +import org.eclipse.angus.mail.smtp.SMTPSendFailedException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.mail.MailAuthenticationException; +import org.springframework.mail.MailSendException; import org.springframework.mail.javamail.JavaMailSenderImpl; /** @@ -136,6 +138,38 @@ class JavaMailSenderSmtpDispatchTest { .containsExactly(Optional.empty(), false); } + @Test + @DisplayName("성공 코드(250)를 실은 부분 전송 실패는 거절 reply code가 아니라 전달됐을 수 있는 실패로 보고된다") + void aPartialSendCarryingASuccessCodeIsNotReportedAsARefusal() { + // given + // Angus's sendpartial path reports a partly delivered message as SMTPSendFailedException + // carrying the last reply, which is a success (250), not a refusal. + JavaMailSenderImpl partlyDelivered = + new JavaMailSenderImpl() { + @Override + public void send(MimeMessage... messages) { + throw new MailSendException( + "partly sent", + new SMTPSendFailedException( + "DATA", + 250, + "250 2.0.0 queued", + null, + new jakarta.mail.Address[0], + new jakarta.mail.Address[0], + new jakarta.mail.Address[0])); + } + }; + JavaMailSenderSmtpDispatch dispatch = new JavaMailSenderSmtpDispatch(partlyDelivered); + + // when + SmtpDispatchException failure = sendExpectingFailure(dispatch); + + // then + assertThat(List.of(failure.replyCode(), failure.dataCommitted())) + .containsExactly(Optional.empty(), true); + } + private static SmtpDispatchException sendExpectingFailure(JavaMailSenderSmtpDispatch dispatch) { return catchThrowableOfType(SmtpDispatchException.class, () -> dispatch.send(message())); } diff --git a/src/adapter/outbound/objectstorage/build.gradle b/src/adapter/outbound/objectstorage/build.gradle index ff65bbb7..ee772b62 100644 --- a/src/adapter/outbound/objectstorage/build.gradle +++ b/src/adapter/outbound/objectstorage/build.gradle @@ -155,9 +155,9 @@ strictTestLanes { } } -// The MinIO lanes start a container, so they are the main-branch stage of this leaf, not its -// pull-request `check` (review BUILD-계획-B3); object-storage-qualification.yml runs them on pull -// requests that touch object storage, and integrationCheck runs them with every integration lane. -tasks.named('mainCheck') { - dependsOn 'objectStorageMinioContractTest', 'objectStorageMinioFaultTest' -} +// The MinIO lanes start a container, so they are not this leaf's pull-request `check` (review +// BUILD-계획-B3). They are integration lanes, and the root integrationCheck owns every container lane +// on main and nightly; object-storage-qualification.yml runs them on pull requests that touch object +// storage. This leaf's `mainCheck` used to run them too, so each main push ran them twice in two +// parallel jobs (review 2026-11-03 RR-06-09, original 08-04 (d)). + diff --git a/src/adapter/outbound/persistence-fileserver/CLAUDE.md b/src/adapter/outbound/persistence-fileserver/CLAUDE.md index d4ae3bf1..21a15ad1 100644 --- a/src/adapter/outbound/persistence-fileserver/CLAUDE.md +++ b/src/adapter/outbound/persistence-fileserver/CLAUDE.md @@ -46,12 +46,18 @@ in `platform`), so the two capability leaves read the same way (review 04-16). write; Spring Data repositories are mocks). - `FileserverPersistenceActivationTest` — the scan covers this package only, behind `app.fileserver-platform.enabled`, and runs before the JPA root auto-configuration. - - `repository.CleanupClaimSqlTest` — the claim keeps its one-statement shape (the Claims rule). + - `repository.CleanupClaimSqlTest` — the claim's text keeps its one-statement shape (the Claims + rule); the locking itself is checked on PostgreSQL by + `PostgreSqlFileserverReclamationIntegrationTest`. - `entity.AssignedIdEntityTest` — newness from `Persistable`, on Hibernate over H2. A new store write adds its case to the guard test; a new auto-configuration adds its line to the activation test. -- Port contracts live in `application-fileserver` testFixtures (`*PortContract`). The in-memory - fakes and the PostgreSQL tests both extend them. +- Port contracts live in `application-fileserver` testFixtures (`*PortContract`, and + `FileQuotaLedgerContract` for the three quota ports, which share one table). The in-memory fakes + and the PostgreSQL tests both extend them; every port this leaf implements has one + (`docs/testing/TESTING_STRATEGY.md` 9.3). The PostgreSQL side of the seven added in review + 2026-11-03 RR-01-04 is tagged `jpa-contract` and runs in persistence-jpa's + `jpaPlatformContractTest` lane on `FileserverPostgreSqlStack`, whose clock a case moves. - The real-PostgreSQL tests are still in `persistence-jpa`'s `postgresqlIntegrationTest` source set, which owns the container and Flyway wiring, and the JPA readiness card (`config/jpa/readiness-cards.yaml`, checked by `JpaReadinessRegistryTest`) names them as that diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuota.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuota.java index 939f972b..4c935dc0 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuota.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuota.java @@ -18,8 +18,11 @@ import java.util.UUID; /** * JPA-backed {@link FileQuotaPort}. * - *

        Reservation, extension, commit, and release are conditional statements, so a reservation that - * already expired or was released can never be extended or committed. + *

        Reservation, extension, commit, and release are conditional statements: a reservation that + * expired or was released can never be extended, and a released or already committed one can never + * be committed. An expired reservation that was not released still commits — bytes that were + * written are durable usage whether or not the reservation outlived its TTL. {@code + * FileQuotaLedgerContract} holds this adapter and the in-memory ledger to the same cases. */ public class JpaFileQuota implements FileQuotaPort { diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSql.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSql.java index 40cddd7d..e9e198bf 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSql.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/CleanupClaimSql.java @@ -15,8 +15,8 @@ package dev.caskeleton.adapter.outbound.persistence.fileserver.repository; * every claimed item is fenced on its own. * *

        Package-private: the repository is its one reader, and the leaf's public surface is a ceiling. - * {@link #positional(String)} rewrites the named parameters to JDBC placeholders for a test in this - * package that runs the identical text on a bare {@code Connection}. + * The PostgreSQL lane runs it through the repository ({@code + * PostgreSqlFileserverReclamationIntegrationTest}); nothing runs the text on its own. */ final class CleanupClaimSql { @@ -43,14 +43,4 @@ final class CleanupClaimSql { + " c.file_id, c.upload_id, c.content_key"; private CleanupClaimSql() {} - - /** - * Rewrites the named parameters to JDBC placeholders, left to right. - * - * @param namedSql the statement above - * @return the same statement with {@code ?} in place of every {@code :name} - */ - static String positional(String namedSql) { - return namedSql.replaceAll("(? :expected::jsonb"); - - // then - assertThat(positional).isEqualTo("payload::jsonb @> ?::jsonb"); - } } diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index 5b563043..a8c65e89 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -235,7 +235,11 @@ made Spring call `getTransactionIsolation()` at every begin, which pgjdbc answer Every mode is time-bounded (review 04-10). Spring hands the remaining time to each statement, so a slow query or lock wait is cancelled by the server (`57014` → `DB_QUERY_CANCELED`), and a deadline -that passed before the next statement (`TransactionTimedOutException`) gets the same code. +that passed before the next statement gets the same code: Spring's `TransactionTimedOutException` +on the JDBC path, and on the JPA path (`JpaTransactionManager`, production) Hibernate's own +`TransactionException`, which has no SQLState and is classified because `SpringTransaction` knows +its deadline passed (`translateAfterDeadline`, review RR-03-03). A business exception thrown after +the deadline is passed on unchanged. Pre-built templates are immutable after construction so concurrent callers cannot observe each other's reconfiguration. `inRootWrite` reuses the pre-built write template, @@ -302,7 +306,9 @@ the two paths disagree on any state. **No SQLState, classified by type:** a lost `@Version` race (`OptimisticLockingFailureException`, JPA `OptimisticLockException`) → `DB_OPTIMISTIC_CONFLICT` (409, review 04-05); an expired Spring -transaction deadline (`TransactionTimedOutException`) → `DB_QUERY_CANCELED`. +transaction deadline (`TransactionTimedOutException`) → `DB_QUERY_CANCELED`; any other persistence +failure (JPA, Spring data-access or Spring transaction exception) of a transaction +`SpringTransaction` began, once its deadline has passed → `DB_QUERY_CANCELED`. **Commit phase (`translateCommitFailure`, ADR-JPA-003):** once the action has returned and `SpringTransaction` is committing a write transaction it began, a failure with `08*`, `40003`, a diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index 5c31cfbd..a2fc8b65 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -296,14 +296,26 @@ A가 FAILED로 바꾸면 다시 발행되고(중복 전달), A의 늦은 PUBLISH `WHERE event_id = ? AND status = 'IN_FLIGHT' AND lease_owner = ? AND lease_token = ?`. owner는 비우고 token은 그대로 둔다(token은 증가만 한다). 1 row면 `APPLIED`, 0 row면 `STALE`. `findById` + setter 경로와 `@Version`은 쓰지 않는다. +- **실패 원인 코드(`V22`)**: `markFailed`·`markDeferred`·`markDead`는 같은 조건부 UPDATE에서 + `last_failure_code`를 쓴다(publisher가 붙인 코드, 없으면 결과·예외 타입 이름). entity 필드는 읽기 + 전용이라 append INSERT와 claim flush는 이 열을 건드리지 않는다. `longRetries(n, now)`는 미룬 claim이 + n번 이상인 FAILED 행 수와 가장 오래된 행의 나이를 센다(`outbox.retry.long.*` 게이지). 상태 `PARKED`는 + DDL이 없다 — claim이 PENDING·FAILED·IN_FLIGHT만 고르고, FIFO 게이트는 PUBLISHED 아닌 모든 행을 막는 앞 + 행으로 본다. claim이 시도 횟수가 어긋난 행(`deferred_attempt_count > attempt_count`)을 만나면 DEAD로 + 옮기고 WARN `error.reason=ATTEMPT_COUNTERS_INCONSISTENT`로 원인을 말한다(재리뷰 2026-11-03 RR-05-01·03). - **미룬 실패와 claim 해제(`V20`)**: `markDeferred(lease, next)`는 `markFailed`와 같은 전이에 `deferred_attempt_count + 1`을 더한다(일시적 실패는 시도 예산 밖). `releaseLease(lease, at)`는 손대지 않은 claim을 `PENDING`, `next_attempt_at = at`, `attempt_count - 1`로 되돌린다(종료 중인 relay가 쓴다). 둘 다 같은 lease 조건부 UPDATE다. - **aggregate 순서 번호(`V21`)**: `JpaOutboxStore`는 `OutboxAggregateSequencePort`도 구현한다. - `outbox_aggregate_sequence` counter를 `UPDATE ... + 1`(row lock)로 올리고, 없으면 그 aggregate의 기존 - outbox 최대 `aggregate_sequence` + 1로 만든다. V21은 `outbox_event`의 순서 키 유일 인덱스도 만든다 — - 기존 중복 row가 있으면 migration이 실패하므로 먼저 정리해야 한다. + `outbox_aggregate_sequence` counter를 `UPDATE`(row lock)로 올린다. 올린 값은 그 aggregate의 가장 큰 + outbox 번호보다 작아지지 않는다(rolling 배포 중 옛 인스턴스가 쓴 벽시계 번호가 먼저 온다). counter가 + 없으면 `INSERT ... ON CONFLICT DO NOTHING`으로 만든다. 시작값은 남은 outbox 최대 번호와 V21이 + 기록한 floor(`outbox_aggregate_sequence_floor`, V21 적용 시각의 epoch 마이크로초) 중 큰 값 + 1이다. + 첫 쓰기 두 개가 겹치면 두 번째는 첫 번째 커밋을 기다렸다가 아무것도 넣지 않고 증가만 한다(리뷰 + RR-03-01). V21은 남은 row가 있는 aggregate의 counter를 그 최대 번호로 미리 만들고, `outbox_event`의 + 순서 키 유일 인덱스도 만든다 — 기존 중복 row가 있으면 migration이 실패하므로 먼저 정리해야 한다 + (`docs/runbooks/outbox-dead-letter.md` §8). - **STALE은 예외가 아니다**: row의 결과는 지금 lease를 가진 relay가 쓴다. use case는 결과를 `OutboxRelayResult.Outcome.STALE`로 남기고 `OutboxRelayFailureReportPort.reportStaleCompletion` 으로 알린 뒤 다음 이벤트로 넘어간다. FAILED/DEAD report는 보내지 않는다(아무것도 저장되지 diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index be148436..9a7e7a7c 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -187,6 +187,7 @@ def readinessLanes = [ postgresqlOutboxRowLifecycleIntegrationTest : ['PostgreSqlOutboxRowLifecycleIntegrationTest'], postgresqlOutboxAggregateSequenceIntegrationTest : ['PostgreSqlOutboxAggregateSequenceIntegrationTest'], postgresqlOutboxOrderKeyRunbookIntegrationTest : ['PostgreSqlOutboxOrderKeyRunbookIntegrationTest'], + postgresqlOutboxDispositionRunbookIntegrationTest : ['PostgreSqlOutboxDispositionRunbookIntegrationTest'], postgresqlFileserverMigrationIntegrationTest : ['PostgreSqlFileserverMigrationIntegrationTest'], postgresqlFileserverMetadataIntegrationTest : ['PostgreSqlFileserverMetadataStoreIntegrationTest'], postgresqlFileserverReclamationIntegrationTest : ['PostgreSqlFileserverReclamationIntegrationTest'], @@ -243,13 +244,20 @@ strictTestLanes { } } -// The V21 pre-deploy check and cleanup are SQL an operator runs from the outbox runbook (review -// 2026-11-01, README 15 decision). The lane reads them out of the runbook, so the document is one of -// its inputs: editing either block reruns the lane against real PostgreSQL. -tasks.named('postgresqlOutboxOrderKeyRunbookIntegrationTest', Test) { - def outboxRunbook = new File(rootProject.projectDir.parentFile, 'docs/runbooks/outbox-dead-letter.md') - inputs.file(outboxRunbook).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('outboxRunbook') - systemProperty 'outbox.runbook', outboxRunbook.absolutePath +// The outbox runbooks give an operator SQL to run: the V21 pre-deploy check and cleanup (review +// 2026-11-01, README 15 decision), the manual dispositions of a DEAD row (re-review 2026-11-03 +// RR-05-01), and finding, parking, resuming and skipping a row that is retried without end +// (RR-05-03). Each lane reads its blocks out of the runbooks, so the documents are its inputs: +// editing a block reruns the lane against real PostgreSQL. +['postgresqlOutboxOrderKeyRunbookIntegrationTest', 'postgresqlOutboxDispositionRunbookIntegrationTest'].each { laneName -> + tasks.named(laneName, Test) { + def outboxRunbook = new File(rootProject.projectDir.parentFile, 'docs/runbooks/outbox-dead-letter.md') + inputs.file(outboxRunbook).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('outboxRunbook') + systemProperty 'outbox.runbook', outboxRunbook.absolutePath + def publishFailedRunbook = new File(rootProject.projectDir.parentFile, 'docs/runbooks/outbox-publish-failed.md') + inputs.file(publishFailedRunbook).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('publishFailedRunbook') + systemProperty 'outbox.publish-failed.runbook', publishFailedRunbook.absolutePath + } } tasks.named('postgresqlSecurityBaselineIntegrationTest') { diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/FailureCategory.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/FailureCategory.java index 5e7c55de..5df08727 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/FailureCategory.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/FailureCategory.java @@ -46,8 +46,15 @@ public enum FailureCategory { QUERY_TIMEOUT, /** - * {@code 25P03} — the server ended a session that sat idle inside an open transaction. Nothing - * was committed, which is why its code is retryable where {@link #QUERY_TIMEOUT}'s is not. + * Not a transaction timeout: {@code 25P03}, the server ended a session that sat idle inside an + * open transaction ({@code idle_in_transaction_session_timeout}). Nothing was committed, which is + * why its code ({@code DB_IDLE_IN_TX_TIMEOUT}) is retryable. + * + *

        A transaction that ran past its own deadline ({@code SpringTransaction.Timeouts}) is {@link + * #QUERY_TIMEOUT} ({@code DB_QUERY_CANCELED}), not this. The name says otherwise and is kept only + * because the enum is public API ({@code docs/architecture/jpa-api-surface.txt}); it becomes + * {@code IDLE_IN_TRANSACTION_TIMEOUT}, with {@link TransactionTimeoutException}, at the next + * release that breaks this API anyway (review RR-03-10). */ TRANSACTION_TIMEOUT, diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/TransactionTimeoutException.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/TransactionTimeoutException.java index 6af43fff..fd1b971d 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/TransactionTimeoutException.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/TransactionTimeoutException.java @@ -1,10 +1,13 @@ package dev.caskeleton.adapter.outbound.persistence.api.error; /** - * A transaction exceeded its configured transaction timeout (design §15.4). + * The server ended a session that sat idle inside an open transaction ({@code 25P03}, {@link + * FailureCategory#TRANSACTION_TIMEOUT}). Not a transaction that ran past its own deadline: that is + * a cancelled statement ({@link FailureCategory#QUERY_TIMEOUT}). * - *

        The transaction is rolled back; whether the use case may be re-run is a business decision, so - * the platform does not retry it automatically. + *

        The transaction is rolled back and nothing was committed, so its code is retryable; whether + * the use case is re-run is still the caller's decision, and the platform does not retry it + * automatically. The name is kept until the next API-breaking release (review RR-03-10). */ public final class TransactionTimeoutException extends JpaPersistenceException { diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java index ceeabdc9..71820781 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java @@ -8,6 +8,7 @@ import dev.caskeleton.shared.error.ApiErrorCode; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; import jakarta.persistence.OptimisticLockException; +import jakarta.persistence.PersistenceException; import java.io.IOException; import java.sql.SQLException; import java.sql.SQLNonTransientConnectionException; @@ -23,6 +24,7 @@ import java.util.Optional; import java.util.Set; import org.springframework.dao.DataAccessException; import org.springframework.dao.OptimisticLockingFailureException; +import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionTimedOutException; /** @@ -140,6 +142,42 @@ public final class PersistenceExceptionTranslator { return Optional.empty(); } + /** + * Classify a failure raised once the transaction's deadline had passed, when neither a SQLState + * nor a type above identifies it. + * + *

        Past the deadline Hibernate refuses the next statement itself, before the driver is asked: + * an {@code org.hibernate.TransactionException} with no SQLState that is not Spring's {@link + * TransactionTimedOutException} — in the action as it is, at commit wrapped in a {@code + * JpaSystemException} (review RR-03-03). That is the production path ({@code + * JpaTransactionManager}); the JDBC path gets {@code 57014} from the server instead. Both are + * {@code DB_QUERY_CANCELED}. The caller decides that the deadline has passed; this method only + * makes sure the failure came from the persistence stack — a JPA, Spring data-access or Spring + * transaction exception anywhere in the cause chain — so a business exception thrown late is + * passed on as it is, and one already classified is not classified again. + */ + public Optional translateAfterDeadline(Throwable ex) { + Objects.requireNonNull(ex, "ex"); + if (ex instanceof PersistenceFailureException) { + return Optional.empty(); + } + for (Throwable t = ex; t != null; t = t.getCause()) { + if (t instanceof PersistenceException + || t instanceof DataAccessException + || t instanceof TransactionException) { + return Optional.of( + new PersistenceFailureException( + OperationalError.DB_QUERY_CANCELED, + "persistence failure after the transaction deadline passed", + ex)); + } + if (t.getCause() == t) { + break; + } + } + return Optional.empty(); + } + /** * Classify a failure raised while committing a write transaction this call began. * diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java index 40b83209..fba06bfb 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java @@ -14,6 +14,7 @@ import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxCompletion; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; +import dev.caskeleton.application.outbox.OutboxLongRetries; import dev.caskeleton.application.outbox.OutboxStorePort; import dev.caskeleton.shared.digest.Sha256; import java.nio.charset.StandardCharsets; @@ -29,6 +30,7 @@ import java.util.Objects; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.spi.LoggingEventBuilder; /** * JPA-backed {@link OutboxAppendPort} + {@link OutboxStorePort}. {@link #append} and the claim/mark @@ -103,12 +105,21 @@ public class JpaOutboxStore * *

        The increment is an {@code UPDATE}, which holds the counter row's lock until the caller * commits: a second writer of the same aggregate waits, then increments the committed value, so - * the numbers follow commit order. An aggregate's first number is inserted instead, seeded after - * the highest {@code aggregate_sequence} its outbox rows already carry — rows numbered before the - * counter existed (the sample used epoch microseconds) must still come first. Two writers - * creating the same counter at once collide on its primary key and one transaction fails: a - * rollback the caller retries, never two events with one number. The counter outlives the - * reaper's deletes, so a number is never handed out twice. + * the numbers follow commit order. It never goes below the aggregate's highest outbox row, so a + * row an instance still on the wall-clock scheme writes during a rolling deploy comes first. The + * counter outlives the reaper's deletes, so a number is never handed out twice. + * + *

        An aggregate's first number is inserted instead, after the larger of its highest remaining + * row and the floor V21 recorded — the moment it ran, above every clock number already sent for + * rows the reaper has deleted or that were written under an identity that has since changed + * (review RR-03-02). Two writers creating the same counter at once both succeed: the insert is + * {@code ON CONFLICT DO NOTHING}, so the second waits for the first to commit, writes nothing, + * and increments the committed counter instead (review RR-03-01). + * + *

        Statements rather than one {@code INSERT … ON CONFLICT DO UPDATE … RETURNING} like {@code + * JpaLiveEventReplay}'s position allocator: the sample appends events on the H2 developer run + * ({@code bootRunH2}), and H2 accepts {@code ON CONFLICT DO NOTHING} but not {@code DO UPDATE}. + * The common case — the counter exists — is still one {@code UPDATE} and one read. */ @Override public long nextSequence(AggregateIdentity aggregate) { @@ -118,8 +129,11 @@ public class JpaOutboxStore String tenant = aggregate.tenantScope(); String type = aggregate.aggregateType(); String id = aggregate.aggregateId(); - if (repository.incrementAggregateSequence(tenant, type, id) == 0) { - repository.createAggregateSequence(tenant, type, id); + if (repository.incrementAggregateSequence(tenant, type, id) == 0 + && repository.createAggregateSequence(tenant, type, id) == 0) { + // Another writer created the counter after our UPDATE found none; its commit ended our wait + // in the insert, so the counter is there to increment now. + repository.incrementAggregateSequence(tenant, type, id); } return repository.aggregateSequence(tenant, type, id); } @@ -132,6 +146,11 @@ public class JpaOutboxStore * instead rolled the whole claim back, and the next claim selected the same row first again, so * one bad row stopped the relay for good. DEAD is fail-closed: the row is never published, and it * waits for the DEAD-row runbook like any other. + * + *

        The WARN names the cause. A row whose deferred claims outnumber its claims is not damaged: + * it is what a manual re-drive that reset {@code attempt_count} and left {@code + * deferred_attempt_count} produces (re-review 2026-11-03 RR-05-01), and "cannot read" sent the + * operator looking for corruption instead of re-running the corrected runbook SQL. */ @Override public List claimBatch( @@ -145,13 +164,26 @@ public class JpaOutboxStore entity.setNextAttemptAt(now.plus(inFlightTimeout)); entity.setLeaseOwner(owner); entity.setLeaseToken(entity.getLeaseToken() + 1); + if (entity.getDeferredAttemptCount() > entity.getAttemptCount()) { + deadLetterOnClaim(entity) + .addKeyValue("error.reason", "ATTEMPT_COUNTERS_INCONSISTENT") + .log( + "outbox claim moved a row to DEAD: deferred_attempt_count ({}) exceeds" + + " attempt_count ({}); a manual re-drive that did not reset" + + " deferred_attempt_count leaves this behind — re-drive it with the runbook" + + " SQL", + entity.getDeferredAttemptCount(), + entity.getAttemptCount()); + continue; + } ClaimedOutboxEvent event; try { event = toClaimedOutboxEvent(entity); } catch (RuntimeException unreadable) { - entity.setStatus(OutboxEventStatus.DEAD.name()); - entity.setLeaseOwner(null); - log.warn("outbox claim moved a row it cannot read to DEAD", unreadable); + deadLetterOnClaim(entity) + .addKeyValue("error.reason", "UNREADABLE_ROW") + .setCause(unreadable) + .log("outbox claim moved a row it cannot read as an event to DEAD"); continue; } leases.add(new OutboxLease(event, owner, entity.getLeaseToken())); @@ -159,6 +191,15 @@ public class JpaOutboxStore return List.copyOf(leases); } + /** Moves a claimed row it will not hand out to DEAD and starts the WARN that says why. */ + private static LoggingEventBuilder deadLetterOnClaim(OutboxEventEntity entity) { + entity.setStatus(OutboxEventStatus.DEAD.name()); + entity.setLeaseOwner(null); + return log.atWarn() + .addKeyValue("event_id", entity.getEventId()) + .addKeyValue("runbook_link", "runbook://outbox/dead-letter"); + } + /** * One conditional UPDATE, no load-and-set: it applies only while the lease still holds the row * (see README "outbox"). Zero rows is {@link OutboxCompletion#STALE}, not an error — the relay @@ -174,18 +215,21 @@ public class JpaOutboxStore /** Marks the leased row FAILED with its next attempt time; see {@link #markPublished}. */ @Override - public OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { + public OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt, String failureCode) { requireTransaction("markFailed"); return completion( - repository.failLease(lease.eventId(), lease.owner(), lease.token(), nextAttemptAt)); + repository.failLease( + lease.eventId(), lease.owner(), lease.token(), nextAttemptAt, failureCode)); } /** Marks the leased row FAILED as a deferred claim; see {@link #markPublished}. */ @Override - public OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt) { + public OutboxCompletion markDeferred( + OutboxLease lease, Instant nextAttemptAt, String failureCode) { requireTransaction("markDeferred"); return completion( - repository.deferLease(lease.eventId(), lease.owner(), lease.token(), nextAttemptAt)); + repository.deferLease( + lease.eventId(), lease.owner(), lease.token(), nextAttemptAt, failureCode)); } /** Returns the leased row to PENDING without spending an attempt; see {@link #markPublished}. */ @@ -198,11 +242,10 @@ public class JpaOutboxStore /** Marks the leased row DEAD; see {@link #markPublished}. */ @Override - public OutboxCompletion markDead(OutboxLease lease) { + public OutboxCompletion markDead(OutboxLease lease, String failureCode) { requireTransaction("markDead"); return completion( - repository.completeLease( - lease.eventId(), lease.owner(), lease.token(), OutboxEventStatus.DEAD.name())); + repository.deadLease(lease.eventId(), lease.owner(), lease.token(), failureCode)); } private static OutboxCompletion completion(int updatedRows) { @@ -237,6 +280,21 @@ public class JpaOutboxStore return result; } + @Override + public OutboxLongRetries longRetries(int minDeferredClaims, Instant now) { + if (minDeferredClaims < 1) { + throw new IllegalArgumentException( + "minDeferredClaims must be >= 1, was " + minDeferredClaims); + } + Object[] row = repository.countLongRetries(minDeferredClaims).getFirst(); + long count = (Long) row[0]; + if (count == 0) { + return OutboxLongRetries.NONE; + } + Instant oldest = (Instant) row[1]; + return new OutboxLongRetries(count, Math.max(0, Duration.between(oldest, now).toSeconds())); + } + /** * Restores the appended event. A row without its envelope — written by the pre-canonical * generation, or damaged — is unreadable, and so is one whose stored hash is not the hash of its diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java index 87b0c782..9f4d6d0c 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxEventJpaRepository.java @@ -62,18 +62,22 @@ public interface OutboxEventJpaRepository extends Repository 'PUBLISHED' group by e.eventType") List findOldestUnpublishedOccurredAtByEventType(); + + /** + * {@code [count (Long), oldestOccurredAt (Instant)]} of the FAILED rows with at least {@code + * minDeferredClaims} deferred claims, for the long-retry gauges. One row, whose instant is null + * when the count is 0. + */ + @Query( + "select count(e), min(e.occurredAt) from OutboxEventEntity e " + + "where e.status = 'FAILED' and e.deferredAttemptCount >= :minDeferredClaims") + List countLongRetries(@Param("minDeferredClaims") int minDeferredClaims); } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxAggregateSequenceFloorEntity.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxAggregateSequenceFloorEntity.java new file mode 100644 index 00000000..fb79e5d7 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxAggregateSequenceFloorEntity.java @@ -0,0 +1,32 @@ +package dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +/** + * The one-row floor a new aggregate counter starts after ({@code outbox_aggregate_sequence_floor}, + * V21): the moment V21 ran, in epoch microseconds, above every number the replaced wall-clock + * scheme wrote. Read by {@code JpaOutboxStore#nextSequence} with a native statement; mapped, like + * {@link OutboxAggregateSequenceEntity}, so the table exists where Hibernate builds the schema (H2, + * where no migration writes the row and the floor is 0) and is validated where Flyway does. + * Package-private: no code reads it as an entity. + */ +@Entity +@Table(name = "outbox_aggregate_sequence_floor") +class OutboxAggregateSequenceFloorEntity { + + @Id + @Column(name = "singleton", nullable = false) + private boolean singleton; + + @Column(name = "floor_sequence", nullable = false) + private long floorSequence; + + protected OutboxAggregateSequenceFloorEntity() {} + + long floorSequence() { + return floorSequence; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java index 72a6a537..4ed084a8 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java @@ -58,6 +58,18 @@ public class OutboxEventEntity implements Persistable { private int deferredAttemptCount; /** Dual-purpose per status (PENDING / IN_FLIGHT / FAILED) — see README "outbox". */ + /** + * The code of the row's last failed completion (V22): the publisher's own name for the failure, + * or the outcome or exception type when it gave none. + * + *

        Read-only to the entity: only the relay's failed completions write it, each in its one + * fenced UPDATE ({@code OutboxEventJpaRepository#failLease} and its siblings). The append's + * INSERT and the claim's flush leave it out, so they neither clear a code nor need the column on + * a database that has not run V22 yet. + */ + @Column(name = "last_failure_code", length = 120, insertable = false, updatable = false) + private String lastFailureCode; + @Column(name = "next_attempt_at", nullable = false) private Instant nextAttemptAt; @@ -379,4 +391,8 @@ public class OutboxEventEntity implements Persistable { public void setCausationId(String causationId) { this.causationId = causationId; } + + public String getLastFailureCode() { + return lastFailureCode; + } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java index 911ff56c..aad85fd9 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java @@ -123,7 +123,9 @@ public final class SpringTransaction implements TransactionPort { * dry and every other request fails at {@code connection-timeout}. With one, Spring hands the * remaining time to every statement (Hibernate and {@code JdbcTemplate} both set the JDBC query * timeout), so the server cancels the statement ({@code 57014}, {@code DB_QUERY_CANCELED}) and - * the connection comes back. + * the connection comes back. A statement Hibernate is asked to run after the deadline has passed + * is refused by Hibernate itself, with no SQLState; this class reports that as {@code + * DB_QUERY_CANCELED} too (review RR-03-03). * *

        The default is 30 seconds for both: the budget {@code inNew} already has, and the Hikari * {@code leak-detection-threshold} at which the pool already reports a held connection as a leak. @@ -194,6 +196,9 @@ public final class SpringTransaction implements TransactionPort { private T execute(ModeTemplate mode, Supplier action) { long startedAt = System.nanoTime(); + // Whether this call began the transaction, and so owns its deadline. A call that joined an + // outer one leaves the deadline to the call that began it. + AtomicBoolean beganTransaction = new AtomicBoolean(); // Set only once the action has returned in a write transaction this call began: from then on // the only thing TransactionTemplate.execute still does is commit it. AtomicBoolean committingOwnWrite = new AtomicBoolean(); @@ -201,20 +206,32 @@ public final class SpringTransaction implements TransactionPort { return mode.template() .execute( status -> { + beganTransaction.set(status.isNewTransaction()); T result = action.get(); committingOwnWrite.set(status.isNewTransaction() && !mode.template().isReadOnly()); return result; }); } catch (RuntimeException failure) { + Duration elapsed = Duration.ofNanos(System.nanoTime() - startedAt); Optional translated = committingOwnWrite.get() - ? exceptionTranslator.translateCommitFailure( - failure, mode.commitOperation(), Duration.ofNanos(System.nanoTime() - startedAt)) + ? exceptionTranslator.translateCommitFailure(failure, mode.commitOperation(), elapsed) : exceptionTranslator.translate(failure); + if (translated.isEmpty() && beganTransaction.get() && pastDeadline(mode, elapsed)) { + // Hibernate's own deadline refusal carries no SQLState (review RR-03-03). + translated = exceptionTranslator.translateAfterDeadline(failure); + } throw translated.map(RuntimeException.class::cast).orElse(failure); } } + /** Whether {@code elapsed} reached the timeout the mode's transactions run under. */ + private static boolean pastDeadline(ModeTemplate mode, Duration elapsed) { + int timeoutSeconds = mode.template().getTimeout(); + return timeoutSeconds != TransactionDefinition.TIMEOUT_DEFAULT + && elapsed.compareTo(Duration.ofSeconds(timeoutSeconds)) >= 0; + } + /** * The vendor-neutral default translator. * diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V21__outbox_aggregate_sequence.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V21__outbox_aggregate_sequence.sql index f22aa20f..c19a2ce2 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V21__outbox_aggregate_sequence.sql +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V21__outbox_aggregate_sequence.sql @@ -7,8 +7,32 @@ -- -- outbox_aggregate_sequence holds one counter per aggregate. Incrementing it locks the row until -- the writer commits, so the numbers follow commit order; it outlives the reaper's deletes, so a --- number is never reused. JpaOutboxAggregateSequences seeds a new counter from the aggregate's --- highest existing aggregate_sequence, so rows numbered by the old clock scheme still come first. +-- number is never reused. JpaOutboxStore#nextSequence reads and writes it. +-- +-- Consumers have already seen clock numbers (about 1.7e15) for aggregates whose rows this +-- database no longer holds: the reaper deleted them, or they were written under an identity that +-- has since changed (the sample's tenant scope). A counter that started after the rows still +-- present would start at 1 for those aggregates, behind numbers already sent (review RR-03-02, +-- RR-05-02). So this migration records one floor, the moment it runs in epoch microseconds, which +-- is above every clock number written before it; a counter created later starts after the floor +-- or after the aggregate's highest remaining row, whichever is larger. The aggregates that still +-- have rows get their counter here, at their highest number. A clock number an instance still on +-- the old version writes during the rollout is above the floor; nextSequence also never goes below +-- the highest row it can see, so such a row still comes first. +-- +-- This file was edited after it was first written, before any deployment applied it (the branch +-- that added it was not merged): splitting the floor into a V22 would have left V21 alone handing +-- out numbers from 1 for one release, and its comment pointed at a class that does not exist. +-- applied-migrations.sha256 carries the new checksum. A development database that applied the +-- earlier text fails Flyway validation; recreate it. + +-- Bound the wait for the table lock the unique index below takes (SHARE on outbox_event, held until +-- this migration commits). Without a bound, the migration queues behind any open outbox write and +-- every outbox write after it queues behind the migration. Five seconds, then this migration fails, +-- rolls back whole and the database stays at V20: deploy again, or build the index first +-- (runbook §8, CONCURRENTLY). +SET LOCAL lock_timeout = '5s'; + CREATE TABLE IF NOT EXISTS outbox_aggregate_sequence ( tenant_scope VARCHAR(96) NOT NULL, aggregate_type VARCHAR(64) NOT NULL, @@ -18,10 +42,55 @@ CREATE TABLE IF NOT EXISTS outbox_aggregate_sequence ( CONSTRAINT ck_outbox_aggregate_sequence_positive CHECK (last_sequence >= 1) ); +-- One row, written once: the lowest number a counter created from now on may start after. +CREATE TABLE IF NOT EXISTS outbox_aggregate_sequence_floor ( + singleton BOOLEAN NOT NULL DEFAULT TRUE, + floor_sequence BIGINT NOT NULL, + CONSTRAINT pk_outbox_aggregate_sequence_floor PRIMARY KEY (singleton), + CONSTRAINT ck_outbox_aggregate_sequence_floor_singleton CHECK (singleton), + CONSTRAINT ck_outbox_aggregate_sequence_floor_non_negative CHECK (floor_sequence >= 0) +); + +INSERT INTO outbox_aggregate_sequence_floor (singleton, floor_sequence) +VALUES (TRUE, (extract(epoch FROM clock_timestamp()) * 1000000)::BIGINT) +ON CONFLICT (singleton) DO NOTHING; + +INSERT INTO outbox_aggregate_sequence (tenant_scope, aggregate_type, aggregate_id, last_sequence) +SELECT tenant_scope, aggregate_type, aggregate_id, MAX(aggregate_sequence) + FROM outbox_event + WHERE tenant_scope IS NOT NULL + AND aggregate_type IS NOT NULL + AND aggregate_sequence IS NOT NULL + GROUP BY tenant_scope, aggregate_type, aggregate_id +ON CONFLICT (tenant_scope, aggregate_type, aggregate_id) DO NOTHING; + -- One number, one event: a second event appended under an order its aggregate already used is -- refused at append time, in the writer's transaction, rather than released by the gate in no -- defined order. Rows without canonical order columns (pre-canonical, all NULL) are not compared. -- This fails if duplicates already exist; resolve them (they are exactly the rows the gate could --- not order) before migrating. +-- not order) before migrating (runbook §8). +-- +-- Built here, inside this migration's transaction, not CONCURRENTLY: a duplicate then rolls the +-- whole of V21 back and leaves the database at V20 with nothing to clean up, which is what the +-- runbook's retry relies on. A failed CONCURRENTLY build leaves an INVALID index that IF NOT EXISTS +-- would then skip, so the uniqueness would silently not hold; and CONCURRENTLY cannot run in the +-- transaction that writes the counters and the floor. The reaper bounds outbox_event to the +-- retention window, so the build is normally short. An outbox too large to lock for that long is +-- indexed first with the runbook's CONCURRENTLY statement (same name, same columns); the check +-- below refuses an index such a build left invalid, and IF NOT EXISTS keeps the valid one. +DO $$ +BEGIN + IF EXISTS (SELECT 1 + FROM pg_index + WHERE indexrelid = to_regclass('ux_outbox_event_aggregate_order') + AND NOT (indisvalid AND indisunique)) THEN + RAISE EXCEPTION 'ux_outbox_event_aggregate_order exists but is not a valid unique index' + USING HINT = 'A CREATE INDEX CONCURRENTLY failed or is still running. ' + || 'DROP INDEX CONCURRENTLY ux_outbox_event_aggregate_order, then rebuild it ' + || 'or let V21 build it (runbook outbox-dead-letter §8).'; + END IF; +END +$$; + CREATE UNIQUE INDEX IF NOT EXISTS ux_outbox_event_aggregate_order ON outbox_event (tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index); diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V22__outbox_event_last_failure_code.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V22__outbox_event_last_failure_code.sql new file mode 100644 index 00000000..dbe4ed59 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V22__outbox_event_last_failure_code.sql @@ -0,0 +1,21 @@ +-- Why a row keeps failing, kept on the row. +-- +-- A publish refused for now (a closed transport, a credential refused) or left unanswered is +-- retried without spending the attempt budget (V20), so it has no end: the relay retries it five +-- minutes apart for as long as nobody looks. The outcome the relay records cannot say why — a +-- shutdown, a closed transport and a refused credential are one outcome — and the relay's log line +-- said it in one sentence for all four. The publisher's failure code can (a messaging platform code +-- such as KAFKA_AUTHENTICATIONEXCEPTION); every failed completion writes it here, so the runbook's +-- query for rows that have been retrying long shows what each one is waiting on (re-review +-- 2026-11-03 RR-05-03). +-- +-- A code, never a message: a driver message can carry an endpoint, a statement or a credential. +-- Nullable with no default, so adding it rewrites no row; rows written before it stay NULL until +-- their next failure. +-- +-- The new status PARKED needs no DDL: status has no CHECK, the claim selects PENDING, FAILED and +-- IN_FLIGHT only (so the partial index ix_outbox_event_eligible leaves PARKED out), and the order +-- gate and its index ix_outbox_event_unpublished_aggregate_order treat every status but PUBLISHED as +-- blocking — which is what holding a row in its aggregate's place means. +ALTER TABLE outbox_event + ADD COLUMN last_failure_code VARCHAR(120); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/WorkerCrashRecoveryContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/WorkerCrashRecoveryContractTest.java index 0cddeb3c..a3af1b93 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/WorkerCrashRecoveryContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/notification/WorkerCrashRecoveryContractTest.java @@ -23,7 +23,8 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** - * What a worker's death leaves behind, at each phase of a dispatch. + * What a worker's death leaves behind, at each phase of a dispatch — the rows, not what recovery + * does with them. * *

        This is the {@code recoverable} claim in {@code docs/notification/evidence-manifest.json}, and * until now nothing backed it. Lease recovery and event replay had unit coverage against fakes; the @@ -36,9 +37,13 @@ import org.junit.jupiter.api.Test; * worker is from the database's point of view — a lease nobody will renew and a phase nobody will * advance. * - *

        The matrix walks the phases a dispatch passes through. For each, the question is the same and - * has only two acceptable answers: the delivery becomes claimable again, or it becomes a question - * for the provider. Never both, and never neither. + *

        The matrix walks the phases a dispatch passes through and pins, for each, the state recovery + * starts from: a lease that has passed (the claim takes the row again) and, from the attempt insert + * on, an unfinished attempt row carrying the evidence of that phase (what reconciliation asks the + * provider about). These rows are written by this test, so the tests check the shape of the input + * and the predicates recovery reads, not recovery itself. {@code + * PostgreSqlNotificationBackgroundPassIntegrationTest} runs recovery and reconciliation over rows + * the dispatcher's own factory wrote (review 05-01, RR-03-07). */ @Tag("jpa-contract") class WorkerCrashRecoveryContractTest { @@ -73,8 +78,8 @@ class WorkerCrashRecoveryContractTest { } @Test - @DisplayName("a crash after claiming and before any attempt leaves the delivery claimable") - void aCrashBeforeAnyAttemptLeavesItClaimable() throws SQLException { + @DisplayName("claim 뒤 attempt 전에 죽은 delivery는 attempt 행이 없고 lease가 지나 있다") + void aDeliveryDeadBeforeAnyAttemptHasNoAttemptRowAndAPassedLease() throws SQLException { UUID delivery = deliveryHeldByADeadWorker(); assertThat(isClaimableAgain(delivery)) @@ -88,12 +93,12 @@ class WorkerCrashRecoveryContractTest { /** * The attempt row is written before the call and keeps the factory's "unknown" evidence for the * whole call (review 05-01), so a crash anywhere between the insert and the provider's answer - * leaves the same row. Recovery cannot tell "never called" from "called and died", so the row - * goes to reconciliation rather than back to the queue. + * leaves the same row. This test writes that row itself; that recovery hands it to reconciliation + * is {@code PostgreSqlNotificationBackgroundPassIntegrationTest}'s. */ @Test - @DisplayName("attempt 행을 쓴 뒤 호출이 끝나기 전 죽으면 시작 여부 불명인 미완료 attempt 가 남아 reconcile 대상이 된다") - void aCrashAfterTheAttemptRowIsWrittenLeavesAnUnfinishedAttemptOfUnknownStart() + @DisplayName("attempt 행을 쓰고 호출 전에 죽은 delivery는 시작 여부 불명인 미완료 attempt와 지난 lease를 남긴다") + void aDeliveryDeadAfterTheAttemptInsertLeavesAnUnfinishedAttemptOfUnknownStart() throws SQLException { // given UUID delivery = deliveryHeldByADeadWorker(); @@ -103,17 +108,18 @@ class WorkerCrashRecoveryContractTest { // then assertThat(evidenceOf(attempt)) - .as("the row the factory writes records that whether the call started is not known") + .as("the row stands for the factory's: whether the call started is not known") .containsExactly("false", "UNKNOWN", "false", "UNKNOWN"); assertThat(isUnfinished(attempt)) - .as("an unfinished attempt is what recovery hands to reconciliation") + .as("completed_at is empty, the predicate recovery selects unfinished attempts by") .isTrue(); assertThat(isClaimableAgain(delivery)).isTrue(); } @Test - @DisplayName("a crash after the request started is a question for the provider, not a requeue") - void aCrashAfterTheRequestStartedIsAQuestion() throws SQLException { + @DisplayName("요청 시작 뒤 죽은 delivery는 시작 증거가 있는 미완료 attempt와 지난 lease를 남긴다") + void aDeliveryDeadAfterTheRequestStartedLeavesAnUnfinishedAttemptWithStartEvidence() + throws SQLException { UUID delivery = deliveryHeldByADeadWorker(); UUID attempt = attemptOn(delivery, true, "PROVEN", false, "UNKNOWN"); @@ -125,13 +131,14 @@ class WorkerCrashRecoveryContractTest { "the lease still expires — the row must not be stranded — but the attempt is unfinished") .isTrue(); assertThat(isUnfinished(attempt)) - .as("an unfinished attempt is what recovery hands to reconciliation") + .as("completed_at is empty, the predicate recovery selects unfinished attempts by") .isTrue(); } @Test - @DisplayName("a crash after the body was committed is never silently retried") - void aCrashAfterTheBodyWasCommittedIsNeverSilentlyRetried() throws SQLException { + @DisplayName("본문 전송 뒤 죽은 delivery는 전송 증거가 있는 미완료 attempt를 남긴다") + void aDeliveryDeadAfterTheBodyWasSentLeavesAnUnfinishedAttemptWithSendEvidence() + throws SQLException { UUID delivery = deliveryHeldByADeadWorker(); UUID attempt = attemptOn(delivery, true, "PROVEN", true, "PROVEN"); @@ -142,8 +149,8 @@ class WorkerCrashRecoveryContractTest { } @Test - @DisplayName("a completed attempt is not recovered at all") - void aCompletedAttemptIsNotRecovered() throws SQLException { + @DisplayName("완료 시각이 적힌 attempt는 미완료로 보이지 않는다") + void aCompletedAttemptIsNotUnfinished() throws SQLException { UUID delivery = deliveryHeldByADeadWorker(); UUID attempt = attemptOn(delivery, true, "PROVEN", true, "PROVEN"); complete(attempt); @@ -154,8 +161,9 @@ class WorkerCrashRecoveryContractTest { } @Test - @DisplayName("across every phase, exactly one delivery row survives with one attempt each") - void acrossEveryPhaseNothingIsLostOrDuplicated() throws SQLException { + @DisplayName("네 단계에서 죽은 워커들은 delivery 4개와 attempt 3개를 남기고 모든 lease가 지나 있다") + void deadWorkersAcrossEveryPhaseLeaveFourDeliveriesThreeAttemptsAndPassedLeases() + throws SQLException { List deliveries = new ArrayList<>(); // The four crash phases, run together, so the recovery sweep sees a mixed table rather than one // hand-picked row. 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 fa0a4210..55db6eb9 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 @@ -59,7 +59,14 @@ import org.springframework.transaction.PlatformTransactionManager; class DurableOperationSubmissionOutboxIntegrationTest { private static final Instant NOW = Instant.parse("2026-08-25T09:00:00Z"); - private static final DurableOperationId ID = new DurableOperationId("op-1"); + + /** + * A canonical lower-case UUIDv7, as the HTTP adapter mints: the operation id is then the event id + * and the aggregate id itself (an id of any other spelling becomes a UUIDv7 derived from it). + */ + private static final String OPERATION_UUID = "01994e11-4d88-7000-8000-0000000000a1"; + + private static final DurableOperationId ID = new DurableOperationId(OPERATION_UUID); private static JpaPlatformContractSupport support; private static AnnotationConfigApplicationContext context; @@ -103,7 +110,7 @@ class DurableOperationSubmissionOutboxIntegrationTest { // then assertThat(queryStrings("SELECT contract_id || '|' || aggregate_id FROM outbox_event")) - .containsExactly("durable-operation.submitted|op-1"); + .containsExactly("durable-operation.submitted|" + OPERATION_UUID); } @Test diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java new file mode 100644 index 00000000..a6e77b62 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java @@ -0,0 +1,159 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileMetadata; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.metadata.FileOwner; +import dev.caskeleton.application.fileserver.api.metadata.FileRecordDraft; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.Optional; +import java.util.OptionalLong; +import java.util.UUID; +import java.util.function.Supplier; +import org.flywaydb.core.Flyway; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * One real PostgreSQL with the Fileserver schema and stores, for the port contract tests that hold + * the JPA stores to the cases their in-memory fakes pass (review 2026-11-03 RR-01-04). + * + *

        The stores read a clock this stack owns and moves, so a contract case about expiry passes time + * the way it does against a fake instead of sleeping. One server per test class; {@link #empty()} + * makes each case independent of the one before it. + */ +final class FileserverPostgreSqlStack implements AutoCloseable { + + private final PostgreSqlReadinessSupport postgres; + private final MovableClock clock; + private final FileserverJpaTestContext context; + private final TransactionTemplate transactions; + private final JdbcTemplate jdbc; + + private FileserverPostgreSqlStack(PostgreSqlReadinessSupport postgres) { + this.postgres = postgres; + migrate("classpath:db/migration/postgresql", "flyway_schema_history", false, null); + migrate( + "classpath:db/migration/jpa/core", + "flyway_jpa_core_history", + true, + "explicit-jpa-core-adoption"); + migrate( + "classpath:db/migration/jpa/fileserver", + "flyway_jpa_fileserver_history", + true, + "explicit-jpa-fileserver-adoption"); + this.clock = new MovableClock(Instant.now().truncatedTo(ChronoUnit.MICROS)); + this.context = new FileserverJpaTestContext(postgres.dataSource(), clock); + this.transactions = context.transactions(); + this.jdbc = new JdbcTemplate(postgres.dataSource()); + } + + /** Starts a server, applies the three schema streams and builds the Fileserver stores. */ + static FileserverPostgreSqlStack start() { + PostgreSqlReadinessSupport.assertDockerAvailable(); + return new FileserverPostgreSqlStack(PostgreSqlReadinessSupport.start(8, 2_000)); + } + + T bean(Class type) { + return context.bean(type); + } + + /** Runs {@code work} in one committed transaction, as the application's transaction port does. */ + T inTransaction(Supplier work) { + return transactions.execute(status -> work.get()); + } + + /** The instant the stores read as now. */ + Instant now() { + return clock.instant(); + } + + /** Moves the stores' clock forward. */ + void elapse(Duration duration) { + clock.advance(duration); + } + + /** Records a file in {@code namespace}, so rows that reference a file may name it. */ + FileId recordFileIn(StorageNamespace namespace) { + FileId fileId = FileId.of(UUID.randomUUID()); + inTransaction( + () -> + bean(JpaFileMetadata.class) + .insert( + new FileRecordDraft( + fileId, + namespace, + "report.bin", + Optional.of("application/octet-stream"), + OptionalLong.of(1_000), + new FileOwner("user-1", Optional.empty())))); + return fileId; + } + + /** Deletes every Fileserver row, children first. */ + void empty() { + jdbc.execute( + "TRUNCATE fs_recovery_item, fs_cleanup_item, fs_quota_reservation," + + " fs_verification_result, fs_upload_session, fs_file CASCADE"); + } + + @Override + public void close() { + context.close(); + postgres.close(); + } + + private void migrate( + String location, String historyTable, boolean independent, String baselineDescription) { + var configuration = + Flyway.configure() + .dataSource(postgres.dataSource()) + .locations(location) + .table(historyTable) + .baselineOnMigrate(false) + .outOfOrder(false); + if (independent) { + configuration.baselineVersion("0").baselineDescription(baselineDescription); + } + Flyway flyway = configuration.load(); + if (independent) { + flyway.baseline(); + } + flyway.migrate(); + } + + /** A clock a test moves forward; microsecond precision, as PostgreSQL stores timestamps. */ + private static final class MovableClock extends Clock { + + private Instant now; + + private MovableClock(Instant start) { + this.now = start; + } + + private synchronized void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public synchronized Instant instant() { + return now; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + throw new UnsupportedOperationException("the stack's clock is UTC"); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java new file mode 100644 index 00000000..395ffcc9 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java @@ -0,0 +1,80 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +/** + * The SQL an outbox runbook gives an operator, read out of the runbook itself. + * + *

        A runbook block is marked {@code } and followed by a {@code sql} + * fence. The lanes that run these blocks against real PostgreSQL read them from the document rather + * than keep a copy, so editing a block in the runbook is what the lane tests: a copy would pass + * while the document an operator follows is wrong. + */ +final class OutboxRunbookSql { + + private final String runbook; + + private OutboxRunbookSql(String runbook) { + this.runbook = runbook; + } + + /** + * Reads the runbook the lane was given in the system property {@code property}. + * + * @param property the system property holding the runbook's absolute path + * @return the runbook's SQL blocks + * @throws IOException when the file cannot be read + */ + static OutboxRunbookSql fromSystemProperty(String property) throws IOException { + String path = System.getProperty(property); + if (path == null || path.isBlank()) { + throw new IllegalStateException( + "system property " + property + " must name the runbook this lane runs"); + } + return new OutboxRunbookSql(Files.readString(Path.of(path), StandardCharsets.UTF_8)); + } + + /** + * The SQL block that follows {@code }. + * + * @param id the block's marker id + * @return the SQL text between the fences + */ + String block(String id) { + String marker = ""; + int at = runbook.indexOf(marker); + if (at < 0) { + throw new IllegalStateException("the outbox runbook has no SQL block marked " + id); + } + int open = runbook.indexOf("```sql\n", at); + int close = runbook.indexOf("\n```", open + 1); + if (open < 0 || close < 0) { + throw new IllegalStateException("the block marked " + id + " is not a closed sql fence"); + } + return runbook.substring(open + "```sql\n".length(), close); + } + + /** + * The block with its {@code }s filled in, as an operator would before running it. + * + * @param id the block's marker id + * @param values each placeholder as written in the runbook, without the angle brackets, and its + * value + * @return the runnable SQL + */ + String block(String id, Map values) { + String sql = block(id); + for (Map.Entry value : values.entrySet()) { + String placeholder = "<" + value.getKey() + ">"; + if (!sql.contains(placeholder)) { + throw new IllegalStateException("the block marked " + id + " has no " + placeholder); + } + sql = sql.replace(placeholder, value.getValue()); + } + return sql; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlContentReferenceLedgerContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlContentReferenceLedgerContractTest.java new file mode 100644 index 00000000..8e6d3e14 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlContentReferenceLedgerContractTest.java @@ -0,0 +1,54 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaContentReferenceLedger; +import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileMetadata; +import dev.caskeleton.application.fileserver.admin.ContentReferenceLedgerPort; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.testkit.ContentReferenceLedgerPortContract; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaContentReferenceLedger} held to the contract the in-memory metadata store passes, on + * real PostgreSQL (review 2026-11-03 RR-01-04). + */ +@Tag("jpa-contract") +class PostgreSqlContentReferenceLedgerContractTest extends ContentReferenceLedgerPortContract { + + private static FileserverPostgreSqlStack stack; + + @BeforeAll + static void start() { + stack = FileserverPostgreSqlStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.empty(); + } + + @Override + protected ContentReferenceLedgerPort ledger() { + return stack.bean(JpaContentReferenceLedger.class); + } + + @Override + protected FileMetadataPort metadata() { + return stack.bean(JpaFileMetadata.class); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileQuotaLedgerContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileQuotaLedgerContractTest.java new file mode 100644 index 00000000..e66aebd2 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileQuotaLedgerContractTest.java @@ -0,0 +1,92 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileQuota; +import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaCommit; +import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaReclaim; +import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaUploadSession; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; +import dev.caskeleton.application.fileserver.api.metadata.UploadSession; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft; +import dev.caskeleton.application.fileserver.api.transfer.UploadMode; +import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort; +import dev.caskeleton.application.fileserver.testkit.FileQuotaLedgerContract; +import dev.caskeleton.application.fileserver.upload.QuotaCommitPort; +import java.time.Duration; +import java.util.OptionalLong; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaFileQuota}, {@link JpaQuotaCommit} and {@link JpaQuotaReclaim} held to the ledger + * contract the in-memory ledger passes, on real PostgreSQL (review 2026-11-03 RR-01-04). + */ +@Tag("jpa-contract") +class PostgreSqlFileQuotaLedgerContractTest extends FileQuotaLedgerContract { + + private static FileserverPostgreSqlStack stack; + + @BeforeAll + static void start() { + stack = FileserverPostgreSqlStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.empty(); + } + + @Override + protected FileQuotaPort quota() { + return stack.bean(JpaFileQuota.class); + } + + @Override + protected QuotaCommitPort commits() { + return stack.bean(JpaQuotaCommit.class); + } + + @Override + protected QuotaReclaimPort reclaims() { + return stack.bean(JpaQuotaReclaim.class); + } + + @Override + protected UploadSession uploadIn(StorageNamespace namespace) { + FileId fileId = stack.recordFileIn(namespace); + return stack.inTransaction( + () -> + stack + .bean(JpaUploadSession.class) + .create( + new UploadSessionDraft( + UploadId.of(UUID.randomUUID()), + fileId, + UploadMode.SINGLE_SHOT, + OptionalLong.of(1_000), + stack.now().plus(Duration.ofHours(1))))); + } + + @Override + protected void elapse(Duration duration) { + stack.elapse(duration); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java index 58809891..bf5117a8 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java @@ -50,7 +50,7 @@ class PostgreSqlMigrationIntegrationTest { assertThat(appliedVersions(postgres, "flyway_schema_history")) .containsExactly( "1", "3", "4", "5", "6", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", - "19", "20", "21"); + "19", "20", "21", "22"); assertThat( singleValue( postgres, diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAggregateSequenceIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAggregateSequenceIntegrationTest.java index e40cca12..f598452f 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAggregateSequenceIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxAggregateSequenceIntegrationTest.java @@ -19,11 +19,18 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; /** * The aggregate order counter and the order uniqueness rule against real PostgreSQL (V21, review - * 06-07): the shared {@link OutboxAggregateSequenceContract}, the seed from rows numbered before - * the counter existed, and a second append under a used order refused at append time. + * 06-07): the shared {@link OutboxAggregateSequenceContract}, where a counter starts when the + * aggregate already has history, and a second append under a used order refused at append time. + * + *

        "History" is what the old wall-clock scheme left (epoch microseconds, about 1.7e15): rows that + * are still in the outbox, rows the reaper deleted, rows under an identity that has since changed, + * and rows an instance still on the old version writes during a rolling deploy. A consumer that + * reads the number as "which change came last" must never see a later change with a smaller number + * (review RR-03-02, RR-05-02). */ class PostgreSqlOutboxAggregateSequenceIntegrationTest extends OutboxAggregateSequenceContract { @@ -32,6 +39,7 @@ class PostgreSqlOutboxAggregateSequenceIntegrationTest extends OutboxAggregateSe private static PostgreSqlReadinessSupport postgres; private static AnnotationConfigApplicationContext context; private static OutboxAggregateSequencePort sequences; + private static JdbcTemplate jdbc; @BeforeAll static void setup() { @@ -40,6 +48,7 @@ class PostgreSqlOutboxAggregateSequenceIntegrationTest extends OutboxAggregateSe OutboxIntegrationSupport.migrate(dataSource); context = OutboxIntegrationSupport.buildContext(dataSource, e -> {}, Clock.systemUTC()); sequences = context.getBean(JpaOutboxStore.class); + jdbc = new JdbcTemplate(dataSource); } @AfterAll @@ -63,25 +72,71 @@ class PostgreSqlOutboxAggregateSequenceIntegrationTest extends OutboxAggregateSe } @Test - @DisplayName("카운터가 없던 aggregate의 첫 번호는 이미 있는 outbox 행의 가장 큰 번호 다음이다") + @DisplayName("카운터가 없던 aggregate의 첫 번호는 floor보다 큰 남은 행의 가장 큰 번호 다음이다") void aNewCounterStartsAfterTheHighestOrderTheAggregatesRowsAlreadyCarry() { - // given: a row numbered by the old wall-clock scheme + // given: a row an instance still on the clock scheme wrote five seconds after V21 ran String aggregateId = "clock-numbered-" + UUID.randomUUID(); - long clockNumber = 1_761_955_200_000_000L; + long clockNumber = floor() + 5_000_000L; append(aggregateId, clockNumber); // when - long next = - transactions() - .inWrite( - () -> - sequences.nextSequence( - new AggregateIdentity("default", "testkit", aggregateId))); + long next = next(aggregateId); // then assertThat(next).isEqualTo(clockNumber + 1); } + @Test + @DisplayName("옛 행이 reaper로 지워진 aggregate의 첫 번호는 지워진 번호가 아니라 floor 다음이다") + void anAggregateWhoseRowsWereReapedStartsAboveTheFloor() { + // given: a week-old clock-numbered row, published and deleted by the reaper since + String aggregateId = "reaped-" + UUID.randomUUID(); + long clockNumber = 1_761_955_200_000_000L; + append(aggregateId, clockNumber); + jdbc.update("DELETE FROM outbox_event WHERE aggregate_id = ?", aggregateId); + + // when + long next = next(aggregateId); + + // then + assertThat(next).as("a number the consumer has already seen").isGreaterThan(clockNumber); + assertThat(next).isEqualTo(floor() + 1); + } + + @Test + @DisplayName("tenant scope가 바뀐 aggregate의 첫 번호는 옛 scope 행의 번호보다 큰 floor 다음이다") + void anAggregateWhoseIdentityChangedStartsAboveTheFloor() { + // given: the sample's rows were written under scope "portfolio" before it moved to one scope + String aggregateId = "rescoped-" + UUID.randomUUID(); + long clockNumber = 1_761_955_200_000_000L; + append(aggregateId, clockNumber); + jdbc.update( + "UPDATE outbox_event SET tenant_scope = 'portfolio' WHERE aggregate_id = ?", aggregateId); + + // when + long next = next(aggregateId); + + // then + assertThat(next).as("a number the consumer has already seen").isGreaterThan(clockNumber); + assertThat(next).isEqualTo(floor() + 1); + } + + @Test + @DisplayName("카운터가 생긴 뒤 옛 버전 인스턴스가 더 큰 번호로 쓴 행이 있으면 다음 번호는 그 행 다음이다") + void aRowAnOldInstanceWroteAfterTheCounterExistedStillComesFirst() { + // given: a new instance numbered the aggregate, then an old one wrote its clock number + String aggregateId = "rolling-" + UUID.randomUUID(); + long counted = next(aggregateId); + long oldInstancesNumber = counted + 10_000_000L; + append(aggregateId, oldInstancesNumber); + + // when + long next = next(aggregateId); + + // then + assertThat(next).isEqualTo(oldInstancesNumber + 1); + } + @Test @DisplayName("같은 aggregate에 같은 순서 번호로 두 번 append하면 두 번째는 실패한다") void aSecondEventUnderAnOrderItsAggregateAlreadyUsedIsRefused() { @@ -96,6 +151,19 @@ class PostgreSqlOutboxAggregateSequenceIntegrationTest extends OutboxAggregateSe assertThat(thrown).isNotNull(); } + private static long next(String aggregateId) { + return context + .getBean(SpringTransaction.class) + .inWrite( + () -> sequences.nextSequence(new AggregateIdentity("default", "testkit", aggregateId))); + } + + /** The number V21 recorded once: the moment it ran, in epoch microseconds. */ + private static long floor() { + return jdbc.queryForObject( + "SELECT floor_sequence FROM outbox_aggregate_sequence_floor", Long.class); + } + private static void append(String aggregateId, long sequence) { JpaOutboxStore store = context.getBean(JpaOutboxStore.class); context diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java index ae3b56f2..54f253ca 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java @@ -179,6 +179,13 @@ class PostgreSqlOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFencingC "select status from outbox_event where event_id = ?", String.class, eventId)); } + @Override + protected String lastFailureCodeOf(String eventId) { + return new JdbcTemplate(sharedDataSource) + .queryForObject( + "select last_failure_code from outbox_event where event_id = ?", String.class, eventId); + } + /** Runs the relay in a loop until claimedCount == 0 (store drained). */ private int drainRelay(PublishPendingOutboxEventsUseCase relay) { int total = 0; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java new file mode 100644 index 00000000..027408b4 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java @@ -0,0 +1,279 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; + +import com.zaxxer.hikari.HikariDataSource; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore; +import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; +import dev.caskeleton.application.outbox.OutboxLease; +import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import java.io.IOException; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * The outbox runbooks' manual dispositions, run as written against real PostgreSQL. + * + *

        An operator resolves a DEAD row by re-driving or skipping it ({@code + * docs/runbooks/outbox-dead-letter.md} §4), and a row that keeps failing for ever by finding it, + * parking it, and resuming or skipping it ({@code docs/runbooks/outbox-publish-failed.md}, "끝나지 않는 + * 재시도"). The SQL for each is read out of the runbook, not copied, and its result is checked the + * only way that matters: whether the relay's next claim takes the row. A re-drive that leaves a + * counter behind is accepted by the database and then refused by the claim, which moves the row + * back to DEAD — the failure the first re-drive test pins (re-review 2026-11-03 RR-05-01). + */ +class PostgreSqlOutboxDispositionRunbookIntegrationTest { + + private static final Instant OCCURRED = Instant.parse("2026-11-01T00:00:00Z"); + private static final Duration IN_FLIGHT_TIMEOUT = Duration.ofMinutes(5); + + private static PostgreSqlReadinessSupport postgres; + private static OutboxRunbookSql deadLetterRunbook; + private static OutboxRunbookSql publishFailedRunbook; + + @BeforeAll + static void setup() throws IOException { + deadLetterRunbook = OutboxRunbookSql.fromSystemProperty("outbox.runbook"); + publishFailedRunbook = OutboxRunbookSql.fromSystemProperty("outbox.publish-failed.runbook"); + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void cleanup() { + if (postgres != null) { + postgres.close(); + } + } + + @Test + @DisplayName("미뤄진 시도가 쌓인 DEAD 행을 runbook 재발행 SQL로 되돌리면 다음 claim이 그 행을 가져간다") + void theRedriveMakesADeadRowWithDeferredClaimsClaimableAgain() throws SQLException { + try (Outbox outbox = Outbox.create()) { + // given: dead-lettered after two claims an outage deferred and three that spent the budget + String dead = outbox.append("order-" + UUID.randomUUID(), 1, OCCURRED); + outbox.setCounters(dead, "DEAD", 5, 2); + String redrive = deadLetterRunbook.block("dead-redrive-one", Map.of("id", dead)); + + // when + outbox.jdbc().execute(redrive); + + // then + assertThat(outbox.claimedEventIds()).containsExactly(dead); + } + } + + @Test + @DisplayName("runbook 구간 재발행 SQL은 그 구간의 DEAD 행만 claim 가능하게 되돌린다") + void theWindowRedriveReturnsOnlyTheDeadRowsOfTheWindow() throws SQLException { + try (Outbox outbox = Outbox.create()) { + // given + String early = outbox.append("order-" + UUID.randomUUID(), 1, OCCURRED); + String late = outbox.append("order-" + UUID.randomUUID(), 1, OCCURRED.plusSeconds(60)); + String outside = outbox.append("order-" + UUID.randomUUID(), 1, OCCURRED.plusSeconds(3600)); + for (String eventId : List.of(early, late, outside)) { + outbox.setCounters(eventId, "DEAD", 3, 2); + } + String redrive = + deadLetterRunbook.block( + "dead-redrive-window", + Map.of( + "장애 시작", OCCURRED.minusSeconds(1).toString(), + "장애 끝", OCCURRED.plusSeconds(61).toString())); + + // when + outbox.jdbc().execute(redrive); + + // then + assertThat(outbox.claimedEventIds()).containsExactlyInAnyOrder(early, late); + } + } + + @Test + @DisplayName("runbook skip SQL은 DEAD 행을 발행된 것으로 두어 그 aggregate의 다음 행을 풀어 준다") + void theSkipReleasesTheNextRowOfTheDeadRowsAggregate() throws SQLException { + try (Outbox outbox = Outbox.create()) { + // given + String aggregate = "order-" + UUID.randomUUID(); + String dead = outbox.append(aggregate, 1, OCCURRED); + String next = outbox.append(aggregate, 2, OCCURRED.plusSeconds(1)); + outbox.setCounters(dead, "DEAD", 1, 0); + String skip = deadLetterRunbook.block("dead-skip-one", Map.of("id", dead)); + + // when + outbox.jdbc().execute(skip); + + // then + assertThat(List.of(outbox.claimedEventIds(), outbox.status(dead))) + .containsExactly(List.of(next), "PUBLISHED"); + } + } + + @Test + @DisplayName("오래 재시도 중인 행 조회는 미룬 claim이 기준 수 이상인 FAILED 행과 그 원인 코드를 보여 준다") + void theLongRetryQueryListsFailedRowsDeferredLongEnoughWithTheirFailureCode() + throws SQLException { + try (Outbox outbox = Outbox.create()) { + // given: one row deferred long enough, one that has only just started failing + String stuck = outbox.append("order-" + UUID.randomUUID(), 1, OCCURRED); + String fresh = outbox.append("order-" + UUID.randomUUID(), 1, OCCURRED); + outbox.setCounters(stuck, "FAILED", 12, 12); + outbox.setCounters(fresh, "FAILED", 1, 1); + outbox.setFailureCode(stuck, "KAFKA_INVALIDTIMESTAMPEXCEPTION"); + + // when + List> found = + outbox.jdbc().queryForList(publishFailedRunbook.block("long-retries")); + + // then + assertThat(found) + .extracting(row -> row.get("event_id"), row -> row.get("last_failure_code")) + .containsExactly(tuple(stuck, "KAFKA_INVALIDTIMESTAMPEXCEPTION")); + } + } + + @Test + @DisplayName("runbook park SQL로 보류한 행은 claim되지 않고 그 aggregate의 다음 행도 막는다") + void aParkedRowIsNotClaimedAndStillHoldsItsAggregatesNextRow() throws SQLException { + try (Outbox outbox = Outbox.create()) { + // given + String aggregate = "order-" + UUID.randomUUID(); + String failing = outbox.append(aggregate, 1, OCCURRED); + outbox.append(aggregate, 2, OCCURRED.plusSeconds(1)); + outbox.setCounters(failing, "FAILED", 12, 12); + String park = publishFailedRunbook.block("park-one", Map.of("id", failing)); + + // when + outbox.jdbc().execute(park); + + // then + assertThat(List.of(outbox.claimedEventIds(), outbox.status(failing))) + .containsExactly(List.of(), "PARKED"); + } + } + + @Test + @DisplayName("runbook resume SQL로 되돌린 보류 행은 다음 claim이 가져간다") + void aResumedRowIsClaimedAgain() throws SQLException { + try (Outbox outbox = Outbox.create()) { + // given + String parked = outbox.append("order-" + UUID.randomUUID(), 1, OCCURRED); + outbox.setCounters(parked, "FAILED", 12, 12); + outbox.jdbc().execute(publishFailedRunbook.block("park-one", Map.of("id", parked))); + String resume = publishFailedRunbook.block("resume-one", Map.of("id", parked)); + + // when + outbox.jdbc().execute(resume); + + // then + assertThat(outbox.claimedEventIds()).containsExactly(parked); + } + } + + @Test + @DisplayName("runbook skip SQL로 버린 보류 행은 발행된 것으로 남고 그 aggregate의 다음 행을 풀어 준다") + void aSkippedParkedRowReleasesItsAggregatesNextRow() throws SQLException { + try (Outbox outbox = Outbox.create()) { + // given + String aggregate = "order-" + UUID.randomUUID(); + String parked = outbox.append(aggregate, 1, OCCURRED); + String next = outbox.append(aggregate, 2, OCCURRED.plusSeconds(1)); + outbox.setCounters(parked, "FAILED", 12, 12); + outbox.jdbc().execute(publishFailedRunbook.block("park-one", Map.of("id", parked))); + String skip = publishFailedRunbook.block("parked-skip-one", Map.of("id", parked)); + + // when + outbox.jdbc().execute(skip); + + // then + assertThat(List.of(outbox.claimedEventIds(), outbox.status(parked))) + .containsExactly(List.of(next), "PUBLISHED"); + } + } + + /** A fresh database at the latest migration with the JPA outbox store over it. */ + private static final class Outbox implements AutoCloseable { + + private final HikariDataSource dataSource; + private final AnnotationConfigApplicationContext context; + private final JdbcTemplate jdbc; + + private Outbox(HikariDataSource dataSource) { + this.dataSource = dataSource; + OutboxIntegrationSupport.migrate(dataSource); + this.context = OutboxIntegrationSupport.buildContext(dataSource, e -> {}, Clock.systemUTC()); + this.jdbc = new JdbcTemplate(dataSource); + } + + static Outbox create() throws SQLException { + String name = + "runbook_" + UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ROOT); + return new Outbox(postgres.createDatabase(name)); + } + + JdbcTemplate jdbc() { + return jdbc; + } + + String append(String aggregateId, long sequence, Instant occurredAt) { + String eventId = UUID.randomUUID().toString(); + JpaOutboxStore store = context.getBean(JpaOutboxStore.class); + context + .getBean(SpringTransaction.class) + .inWrite( + () -> store.append(OutboxEvents.event(eventId, aggregateId, sequence, occurredAt))); + return eventId; + } + + /** The counters a relay leaves on a row; written directly because only their values matter. */ + void setCounters(String eventId, String status, int attempts, int deferred) { + jdbc.update( + "UPDATE outbox_event SET status = ?, attempt_count = ?, deferred_attempt_count = ?" + + " WHERE event_id = ?", + status, + attempts, + deferred, + eventId); + } + + void setFailureCode(String eventId, String failureCode) { + jdbc.update( + "UPDATE outbox_event SET last_failure_code = ? WHERE event_id = ?", failureCode, eventId); + } + + String status(String eventId) { + return jdbc.queryForObject( + "SELECT status FROM outbox_event WHERE event_id = ?", String.class, eventId); + } + + /** What the relay's next claim takes, a minute from now so every re-driven row is due. */ + List claimedEventIds() { + JpaOutboxStore store = context.getBean(JpaOutboxStore.class); + Instant now = Instant.now().plusSeconds(60); + return context + .getBean(SpringTransaction.class) + .inWrite(() -> store.claimBatch("runbook-relay", 50, now, IN_FLIGHT_TIMEOUT)) + .stream() + .map(OutboxLease::eventId) + .toList(); + } + + @Override + public void close() { + context.close(); + dataSource.close(); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java index 98ab6ecf..09a8381c 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java @@ -9,16 +9,20 @@ import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.application.outbox.testkit.OutboxEvents; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; +import java.sql.Connection; import java.sql.SQLException; +import java.sql.Statement; import java.time.Clock; import java.time.Instant; +import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; import org.junit.jupiter.api.AfterAll; @@ -43,15 +47,15 @@ class PostgreSqlOutboxOrderKeyRunbookIntegrationTest { private static final Instant OCCURRED = Instant.parse("2026-11-01T00:00:00Z"); private static PostgreSqlReadinessSupport postgres; + private static OutboxRunbookSql runbook; private static String duplicateCheck; private static String removePublishedDuplicates; @BeforeAll static void setup() throws IOException { - String runbook = - Files.readString(Path.of(System.getProperty("outbox.runbook")), StandardCharsets.UTF_8); - duplicateCheck = runbookSql(runbook, "v21-duplicate-order-keys"); - removePublishedDuplicates = runbookSql(runbook, "v21-remove-published-duplicates"); + runbook = OutboxRunbookSql.fromSystemProperty("outbox.runbook"); + duplicateCheck = runbook.block("v21-duplicate-order-keys"); + removePublishedDuplicates = runbook.block("v21-remove-published-duplicates"); postgres = PostgreSqlReadinessSupport.start(); } @@ -176,19 +180,143 @@ class PostgreSqlOutboxOrderKeyRunbookIntegrationTest { } } - /** The SQL block that follows {@code } in the runbook. */ - private static String runbookSql(String runbook, String id) { - String marker = ""; - int at = runbook.indexOf(marker); - if (at < 0) { - throw new IllegalStateException("the outbox runbook has no SQL block marked " + id); + @Test + @DisplayName("V21은 남은 행이 있는 aggregate의 카운터를 그 aggregate의 가장 큰 번호로 미리 만든다") + void v21SeedsTheCounterOfEveryAggregateWithRowsAtItsHighestNumber() throws SQLException { + try (BeforeV21 database = BeforeV21.create()) { + // given + String twice = "twice-" + UUID.randomUUID(); + database.append(twice, 1_761_955_200_000_003L); + database.append(twice, 1_761_955_200_000_009L); + String once = "once-" + UUID.randomUUID(); + database.append(once, 1_761_955_200_000_004L); + + // when + database.migrateToLatest(); + + // then + assertThat(List.of(database.counterOf(twice), database.counterOf(once))) + .containsExactly(1_761_955_200_000_009L, 1_761_955_200_000_004L); } - int open = runbook.indexOf("```sql\n", at); - int close = runbook.indexOf("\n```", open + 1); - if (open < 0 || close < 0) { - throw new IllegalStateException("the block marked " + id + " is not a closed sql fence"); + } + + @Test + @DisplayName("V21은 적용한 시각을 마이크로초 floor로 한 번 기록한다") + void v21RecordsTheMomentItRanAsTheFloorInMicroseconds() throws SQLException { + try (BeforeV21 database = BeforeV21.create()) { + // given + long before = microsecondsNow() - 1_000_000L; + + // when + database.migrateToLatest(); + + // then + long after = microsecondsNow() + 1_000_000L; + assertThat( + database + .jdbc() + .queryForList( + "SELECT floor_sequence FROM outbox_aggregate_sequence_floor", Long.class)) + .singleElement() + .satisfies(floor -> assertThat(floor).isBetween(before, after)); } - return runbook.substring(open + "```sql\n".length(), close); + } + + @Test + @DisplayName("outbox 쓰기 트랜잭션이 잠금을 잡고 있으면 V21은 기다리다 실패하고 DB는 V20 그대로 남는다") + void v21GivesUpOnALockAWriterHoldsAndLeavesTheDatabaseAtV20() throws Exception { + try (BeforeV21 database = BeforeV21.create(); + Connection writer = database.connection()) { + // given: a writer transaction holding the lock every outbox insert takes, released after 15 s + writer.setAutoCommit(false); + try (Statement statement = writer.createStatement()) { + statement.execute("LOCK TABLE outbox_event IN ROW EXCLUSIVE MODE"); + } + ScheduledExecutorService release = Executors.newSingleThreadScheduledExecutor(); + ScheduledFuture released = + release.schedule( + () -> { + writer.rollback(); + return null; + }, + 15, + TimeUnit.SECONDS); + try { + // when + Throwable thrown = catchThrowable(database::migrateToLatest); + + // then + assertThat( + List.of( + thrown instanceof FlywayException, + database.flyway(null).info().current().getVersion().getVersion())) + .containsExactly(true, "20"); + } finally { + released.cancel(true); + release.shutdownNow(); + } + } + } + + @Test + @DisplayName("실패한 CONCURRENTLY 빌드가 남긴 무효 인덱스가 있으면 V21은 그것을 건너뛰지 않고 실패한다") + void anInvalidIndexLeftByAFailedConcurrentBuildFailsV21() throws SQLException { + try (BeforeV21 database = BeforeV21.create()) { + // given: a concurrent build that met a duplicate leaves an invalid index behind + String shared = "shared-" + UUID.randomUUID(); + String kept = database.append(shared, 1); + database.append(shared, 1); + Throwable failedBuild = + catchThrowable( + () -> + database + .jdbc() + .execute( + "CREATE UNIQUE INDEX CONCURRENTLY ux_outbox_event_aggregate_order ON" + + " outbox_event (tenant_scope, aggregate_type, aggregate_id," + + " aggregate_sequence, event_index)")); + assertThat(failedBuild).as("the concurrent build met the duplicate").isNotNull(); + database + .jdbc() + .update( + "DELETE FROM outbox_event WHERE aggregate_id = ? AND event_id <> ?", shared, kept); + + // when + Throwable thrown = catchThrowable(database::migrateToLatest); + + // then + assertThat( + List.of( + thrown instanceof FlywayException, + database.flyway(null).info().current().getVersion().getVersion())) + .containsExactly(true, "20"); + } + } + + @Test + @DisplayName("runbook대로 순서 키 인덱스를 CONCURRENTLY로 먼저 만들면 V21은 그 인덱스를 쓰고 적용된다") + void v21AppliesOverTheIndexTheRunbookBuiltConcurrently() throws SQLException { + try (BeforeV21 database = BeforeV21.create()) { + // given + database.append("ordered-" + UUID.randomUUID(), 1); + database.jdbc().execute(runbook.block("v21-prebuild-order-index")); + + // when + database.migrateToLatest(); + + // then + assertThat( + List.of( + Arrays.stream(database.flyway(null).info().applied()) + .anyMatch(migration -> "21".equals(migration.getVersion().getVersion())), + database.validIndexExists("ux_outbox_event_aggregate_order"))) + .containsExactly(true, true); + } + } + + private static long microsecondsNow() { + Instant now = Instant.now(); + return now.getEpochSecond() * 1_000_000L + now.getNano() / 1_000L; } /** @@ -259,6 +387,26 @@ class PostgreSqlOutboxOrderKeyRunbookIntegrationTest { jdbc.queryForObject("SELECT to_regclass(?) IS NOT NULL", Boolean.class, table)); } + Connection connection() throws SQLException { + return dataSource.getConnection(); + } + + long counterOf(String aggregateId) { + return jdbc.queryForObject( + "SELECT last_sequence FROM outbox_aggregate_sequence WHERE aggregate_id = ?", + Long.class, + aggregateId); + } + + boolean validIndexExists(String index) { + return Boolean.TRUE.equals( + jdbc.queryForObject( + "SELECT EXISTS (SELECT 1 FROM pg_index WHERE indexrelid = to_regclass(?)" + + " AND indisvalid)", + Boolean.class, + index)); + } + boolean indexExists(String index) { return Boolean.TRUE.equals( jdbc.queryForObject( diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecoveryQueueContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecoveryQueueContractTest.java new file mode 100644 index 00000000..9ba78957 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecoveryQueueContractTest.java @@ -0,0 +1,60 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaRecoveryQueue; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.recovery.RecoveryQueuePort; +import dev.caskeleton.application.fileserver.testkit.RecoveryQueuePortContract; +import java.time.Duration; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaRecoveryQueue} held to the contract the in-memory queue passes, on real PostgreSQL + * (review 2026-11-03 RR-01-04). + */ +@Tag("jpa-contract") +class PostgreSqlRecoveryQueueContractTest extends RecoveryQueuePortContract { + + private static FileserverPostgreSqlStack stack; + + @BeforeAll + static void start() { + stack = FileserverPostgreSqlStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.empty(); + } + + @Override + protected RecoveryQueuePort queue() { + return stack.bean(JpaRecoveryQueue.class); + } + + @Override + protected FileId recordedFile() { + return stack.recordFileIn(StorageNamespace.of("tenant-a")); + } + + @Override + protected void elapse(Duration duration) { + stack.elapse(duration); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlStagingUploadLocatorContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlStagingUploadLocatorContractTest.java new file mode 100644 index 00000000..105eb397 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlStagingUploadLocatorContractTest.java @@ -0,0 +1,73 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaStagingUploadLocator; +import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaUploadSession; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort; +import dev.caskeleton.application.fileserver.testkit.StagingUploadLocatorPortContract; +import java.time.Duration; +import java.time.Instant; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaStagingUploadLocator} held to the contract the in-memory session store passes, on real + * PostgreSQL (review 2026-11-03 RR-01-04). + */ +@Tag("jpa-contract") +class PostgreSqlStagingUploadLocatorContractTest extends StagingUploadLocatorPortContract { + + private static FileserverPostgreSqlStack stack; + + @BeforeAll + static void start() { + stack = FileserverPostgreSqlStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.empty(); + } + + @Override + protected StagingUploadLocatorPort locator() { + return stack.bean(JpaStagingUploadLocator.class); + } + + @Override + protected UploadSessionPort sessions() { + return stack.bean(JpaUploadSession.class); + } + + @Override + protected FileId recordedFile() { + return stack.recordFileIn(StorageNamespace.of("tenant-a")); + } + + @Override + protected Instant now() { + return stack.now(); + } + + @Override + protected void elapse(Duration duration) { + stack.elapse(duration); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java index 2ee91d75..96d928a8 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java @@ -293,6 +293,49 @@ class PostgreSqlTransactionIntegrationTest { assertThat(elapsed).isLessThan(Duration.ofSeconds(5)); } + /** + * The production transaction manager is {@code JpaTransactionManager}, and past the deadline + * Hibernate refuses the next statement itself, before the driver is asked: no {@code 57014}, no + * SQLState at all (review RR-03-03). The test above covers the JDBC path only. + */ + @Test + @Tag("jpa-failure") + @Timeout(20) + @DisplayName("JPA 트랜잭션이 제한 시간을 넘긴 뒤 다음 문장을 Hibernate가 거부해도 DB_QUERY_CANCELED로 끝난다") + void aJpaWriteTransactionPastItsBoundIsAQueryCancellation() { + // given + Configuration configuration = new Configuration(); + configuration.getProperties().put("hibernate.connection.datasource", postgres.dataSource()); + configuration.setProperty("hibernate.hbm2ddl.auto", "create"); + configuration.addAnnotatedClass(VersionedRow.class); + try (SessionFactory sessionFactory = configuration.buildSessionFactory()) { + EntityManager entityManager = + SharedEntityManagerCreator.createSharedEntityManager(sessionFactory); + SpringTransaction port = + new SpringTransaction( + new JpaTransactionManager(sessionFactory), + translator(), + new SpringTransaction.Timeouts(Duration.ofSeconds(1), Duration.ofSeconds(1))); + + // when + Throwable thrown = + catchThrowable( + () -> + port.inWrite( + () -> { + sleepPastOneSecond(); + entityManager.persist(new VersionedRow(7L, "late")); + entityManager.flush(); + return null; + })); + + // then + assertThat(thrown).isInstanceOf(PersistenceFailureException.class); + assertThat(((PersistenceFailureException) thrown).errorCode()) + .isEqualTo(OperationalError.DB_QUERY_CANCELED); + } + } + // ---- review 09-05: READ COMMITTED comes from the pool, with no per-transaction round trip ---- @Test @@ -323,6 +366,15 @@ class PostgreSqlTransactionIntegrationTest { } } + private static void sleepPastOneSecond() { + try { + Thread.sleep(1_200); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + /** A data source whose connections count {@code getTransactionIsolation()} calls. */ private static DataSource countingIsolationQueries(DataSource target, AtomicInteger calls) { return (DataSource) diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlUploadSessionContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlUploadSessionContractTest.java new file mode 100644 index 00000000..0bf47b5d --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlUploadSessionContractTest.java @@ -0,0 +1,66 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaUploadSession; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.testkit.UploadSessionPortContract; +import java.time.Duration; +import java.time.Instant; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +/** + * {@link JpaUploadSession} held to the writer-lease contract the in-memory store passes, on real + * PostgreSQL (review 2026-11-03 RR-01-04). + */ +@Tag("jpa-contract") +class PostgreSqlUploadSessionContractTest extends UploadSessionPortContract { + + private static FileserverPostgreSqlStack stack; + + @BeforeAll + static void start() { + stack = FileserverPostgreSqlStack.start(); + } + + @AfterAll + static void stop() { + if (stack != null) { + stack.close(); + } + } + + @BeforeEach + void empty() { + stack.empty(); + } + + @Override + protected UploadSessionPort sessions() { + return stack.bean(JpaUploadSession.class); + } + + @Override + protected FileId recordedFile() { + return stack.recordFileIn(StorageNamespace.of("tenant-a")); + } + + @Override + protected Instant now() { + return stack.now(); + } + + @Override + protected void elapse(Duration duration) { + stack.elapse(duration); + } + + @Override + protected T inTransaction(Supplier work) { + return stack.inTransaction(work); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStoreTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStoreTest.java index 3905930f..6b359c1e 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStoreTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStoreTest.java @@ -13,6 +13,9 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; @@ -29,13 +32,16 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.util.HexFormat; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.slf4j.LoggerFactory; import org.springframework.transaction.support.TransactionSynchronizationManager; /** @@ -181,10 +187,10 @@ class JpaOutboxStoreTest { assertThatThrownBy(() -> adapter.markPublished(lease("evt-guard"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("markPublished"); - assertThatThrownBy(() -> adapter.markFailed(lease("evt-guard"), NOW.plusSeconds(1))) + assertThatThrownBy(() -> adapter.markFailed(lease("evt-guard"), NOW.plusSeconds(1), "CODE")) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("markFailed"); - assertThatThrownBy(() -> adapter.markDead(lease("evt-guard"))) + assertThatThrownBy(() -> adapter.markDead(lease("evt-guard"), "CODE")) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("markDead"); } @@ -281,6 +287,56 @@ class JpaOutboxStoreTest { assertThat(List.of(claimed, entity.getStatus())).containsExactly(List.of(), "DEAD"); } + /** + * A row whose deferred claims outnumber its claims was not damaged: a manual re-drive reset + * {@code attempt_count} and left {@code deferred_attempt_count} (re-review 2026-11-03 RR-05-01). + * The WARN says that, so the operator re-runs the corrected runbook SQL instead of hunting for + * corruption. + */ + @Test + @DisplayName("claim이 시도 횟수가 어긋난 행을 DEAD로 옮기면 WARN이 어긋난 두 값과 runbook을 말한다") + void claimBatchNamesInconsistentAttemptCountersWhenItMovesSuchARowToDead() { + // given + OutboxEventEntity redriven = pendingEntity("evt-redriven", "worklog-42"); + redriven.setDeferredAttemptCount(2); + when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(redriven)); + Logger storeLog = (Logger) LoggerFactory.getLogger(JpaOutboxStore.class); + ListAppender captured = new ListAppender<>(); + captured.start(); + storeLog.addAppender(captured); + + // when + try { + adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT); + } finally { + storeLog.detachAppender(captured); + } + + // then + assertThat(captured.list) + .singleElement() + .satisfies( + warn -> + assertThat(List.of(warn.getFormattedMessage(), keyValues(warn))) + .containsExactly( + "outbox claim moved a row to DEAD: deferred_attempt_count (2) exceeds" + + " attempt_count (1); a manual re-drive that did not reset" + + " deferred_attempt_count leaves this behind — re-drive it with the" + + " runbook SQL", + Map.of( + "event_id", "evt-redriven", + "error.reason", "ATTEMPT_COUNTERS_INCONSISTENT", + "runbook_link", "runbook://outbox/dead-letter"))); + } + + private static Map keyValues(ILoggingEvent event) { + Map values = new LinkedHashMap<>(); + if (event.getKeyValuePairs() != null) { + event.getKeyValuePairs().forEach(pair -> values.put(pair.key, pair.value)); + } + return values; + } + @Test void claimBatchReturnsEmptyWhenRepoReturnsNothing() { when(claimRepo.claimEligible(any(), anyInt())).thenReturn(List.of()); @@ -319,16 +375,18 @@ class JpaOutboxStoreTest { @Test void markFailedCompletesOnlyUnderTheLeaseAndSchedulesTheRetry() { Instant retryAt = NOW.plus(Duration.ofSeconds(30)); - when(repo.failLease("evt-004", OWNER, 1, retryAt)).thenReturn(1); + when(repo.failLease("evt-004", OWNER, 1, retryAt, "IllegalStateException")).thenReturn(1); - assertThat(adapter.markFailed(lease("evt-004"), retryAt)).isEqualTo(OutboxCompletion.APPLIED); + assertThat(adapter.markFailed(lease("evt-004"), retryAt, "IllegalStateException")) + .isEqualTo(OutboxCompletion.APPLIED); } @Test void markDeadCompletesOnlyUnderTheLease() { - when(repo.completeLease("evt-005", OWNER, 1, "DEAD")).thenReturn(1); + when(repo.deadLease("evt-005", OWNER, 1, "REJECTED_BEFORE_SEND")).thenReturn(1); - assertThat(adapter.markDead(lease("evt-005"))).isEqualTo(OutboxCompletion.APPLIED); + assertThat(adapter.markDead(lease("evt-005"), "REJECTED_BEFORE_SEND")) + .isEqualTo(OutboxCompletion.APPLIED); } /** 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 39ead9d6..38cd71e2 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 @@ -111,7 +111,7 @@ class FlywayProdSafetyValidatorTest { @Configuration static class ValidatorConfig { @Bean - FlywayProdSafetyValidator flywayProdSafetyValidator(Environment environment) { + static FlywayProdSafetyValidator flywayProdSafetyValidator(Environment environment) { return new FlywayProdSafetyValidator(); } } 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 906cc346..1864e69c 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 @@ -300,7 +300,7 @@ class HikariPoolConstraintValidatorTest { @Configuration static class ValidatorConfig { @Bean - HikariPoolConstraintValidator hikariPoolConstraintValidator(Environment environment) { + static HikariPoolConstraintValidator hikariPoolConstraintValidator(Environment environment) { return new HikariPoolConstraintValidator(); } } 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 fcf871f6..45c48aa4 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 @@ -72,7 +72,7 @@ class OpenInViewSafetyValidatorTest { @Configuration static class ValidatorConfig { @Bean - OpenInViewSafetyValidator openInViewSafetyValidator(Environment environment) { + static OpenInViewSafetyValidator openInViewSafetyValidator(Environment environment) { return new OpenInViewSafetyValidator(); } } 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 46b078b5..14a60e32 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 @@ -101,7 +101,7 @@ class PersistenceVendorProdSafetyValidatorTest { static class ValidatorConfig { @Bean - PersistenceVendorProdSafetyValidator validator(Environment environment) { + static PersistenceVendorProdSafetyValidator validator(Environment environment) { return new PersistenceVendorProdSafetyValidator(); } } 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 e012f579..876fe01e 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 @@ -102,7 +102,7 @@ class PostgreSqlTransportSecurityValidatorTest { static class ValidatorConfig { @Bean - PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator( + static PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator( Environment environment) { return new PostgreSqlTransportSecurityValidator(); } 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 2552d2c2..8c6842e4 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 @@ -81,7 +81,7 @@ class RequiredEnvironmentValidatorTest { @Configuration static class ValidatorConfig { @Bean - RequiredEnvironmentValidator requiredEnvironmentValidator(Environment environment) { + static RequiredEnvironmentValidator requiredEnvironmentValidator(Environment environment) { return new RequiredEnvironmentValidator(); } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java index 89a771c0..d9405ea5 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java @@ -10,6 +10,8 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.FinalEnti import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseCollectionParentEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseManyToManyEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseOneToOneEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnChildEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnParentEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.NoDefaultConstructorEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OrderEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningChildEntity; @@ -19,6 +21,7 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.Unidirect import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.BadOrderController; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.GoodOrderController; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.ListReturningController; +import dev.caskeleton.adapter.outbound.persistence.testkit.outsider.OrderEntityReader; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -181,6 +184,27 @@ class JpaArchitectureRulesTest { .hasMessageNotContaining("OwningChildEntity.parent"); } + @Test + @DisplayName("mappedBy 없이 두 엔티티가 서로를 연관으로 가리키면 양쪽 모두 거부된다") + void aPairThatPointsBothWaysWithoutMappedByIsRefusedOnBothSides() { + // given + var classes = + new ClassFileImporter() + .importClasses(JoinColumnParentEntity.class, JoinColumnChildEntity.class); + + // when + Throwable failure = + catchThrowable( + () -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)); + + // then + assertThat(failure) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("JoinColumnParentEntity.children") + .hasMessageContaining("JoinColumnChildEntity.parent") + .hasMessageContaining("one side only"); + } + @Test @DisplayName("단방향 연관관계는 통과한다") void unidirectionalAssociationsPass() { @@ -195,4 +219,44 @@ class JpaArchitectureRulesTest { assertThatCode(() -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)) .doesNotThrowAnyException(); } + + @Test + @DisplayName("leaf 밖의 클래스가 그 leaf의 엔티티를 쓰면 거부된다") + void aClassOutsideTheLeafThatUsesItsEntityIsRefused() { + // given + var classes = new ClassFileImporter().importClasses(OrderEntity.class, OrderEntityReader.class); + + // when + Throwable failure = + catchThrowable( + () -> + JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf( + "dev.caskeleton.adapter.outbound.persistence.testkit.arch") + .check(classes)); + + // then + assertThat(failure) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("OrderEntityReader") + .hasMessageContaining("OrderEntity"); + } + + @Test + @DisplayName("같은 leaf 안의 클래스가 그 leaf의 엔티티를 쓰는 것은 통과한다") + void aClassInsideTheLeafMayUseItsEntity() { + // given + var classes = + new ClassFileImporter().importClasses(OrderEntity.class, BadOrderController.class); + + // when + Throwable failure = + catchThrowable( + () -> + JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf( + "dev.caskeleton.adapter.outbound.persistence.testkit.arch") + .check(classes)); + + // then + assertThat(failure).isNull(); + } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinColumnChildEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinColumnChildEntity.java new file mode 100644 index 00000000..f8700aa8 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinColumnChildEntity.java @@ -0,0 +1,36 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; + +/** + * Refused by the association rule: the read-only half of {@link JoinColumnParentEntity}'s pair. + * + *

        {@code insertable = false, updatable = false} makes this field a second, read-only copy of the + * link the parent's collection writes. Within one persistence context it does not follow a change + * made through the collection. + */ +@Entity +public class JoinColumnChildEntity { + + @Id private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "parent_id", insertable = false, updatable = false) + private JoinColumnParentEntity parent; + + protected JoinColumnChildEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The read-only reference back to the parent. */ + public JoinColumnParentEntity parent() { + return parent; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinColumnParentEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinColumnParentEntity.java new file mode 100644 index 00000000..87cbb31a --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinColumnParentEntity.java @@ -0,0 +1,38 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToMany; +import java.util.ArrayList; +import java.util.List; + +/** + * Refused by the association rule: one half of a bidirectional pair that has no {@code mappedBy}. + * + *

        This collection and {@link JoinColumnChildEntity#parent} map the same {@code parent_id} + * column, the {@code @JoinColumn} form of a bidirectional association. Neither side says it is the + * inverse, so an attribute check finds nothing, yet the pair has the same two copies of one link + * that the rule exists to refuse (review RR-03-04). + */ +@Entity +public class JoinColumnParentEntity { + + @Id private Long id; + + @OneToMany + @JoinColumn(name = "parent_id") + private List children = new ArrayList<>(); + + protected JoinColumnParentEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The collection that writes the foreign key. */ + public List children() { + return List.copyOf(children); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/outsider/OrderEntityReader.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/outsider/OrderEntityReader.java new file mode 100644 index 00000000..36ed6a22 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/outsider/OrderEntityReader.java @@ -0,0 +1,18 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.outsider; + +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OrderEntity; + +/** + * Refused by the entity-confinement rule when {@code testkit.arch} plays the leaf: a class outside + * that package that reads one of its entities. It lives in a package of its own because the rule + * selects by package, and a fixture inside the leaf would pass for the wrong reason. + */ +public final class OrderEntityReader { + + private OrderEntityReader() {} + + /** Reads the entity's identifier, which is all it takes to depend on it. */ + public static Long idOf(OrderEntity order) { + return order.id(); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionDeadlineTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionDeadlineTest.java new file mode 100644 index 00000000..66d31a50 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionDeadlineTest.java @@ -0,0 +1,152 @@ +package dev.caskeleton.adapter.outbound.persistence.transaction; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator; +import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; +import dev.caskeleton.shared.error.OperationalError; +import dev.caskeleton.shared.error.PersistenceFailureException; +import jakarta.persistence.Entity; +import jakarta.persistence.EntityManager; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.time.Duration; +import java.util.List; +import java.util.UUID; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.SharedEntityManagerCreator; + +/** + * A transaction deadline that expires on the JPA path, where the production transaction manager + * runs (review RR-03-03). + * + *

        Past the deadline Hibernate refuses the next statement itself, before any JDBC call, with an + * {@code org.hibernate.TransactionException} that carries no SQLState and is not Spring's {@code + * TransactionTimedOutException}. The JDBC path's {@code 57014} never happens, so the failure used + * to reach the web catch-all as a 500. The H2 database here only gives Hibernate somewhere to + * connect: the refusal is Hibernate's and does not depend on the vendor. + */ +class SpringTransactionDeadlineTest { + + private static final SpringTransaction.Timeouts ONE_SECOND = + new SpringTransaction.Timeouts(Duration.ofSeconds(1), Duration.ofSeconds(1)); + private static final Duration PAST_THE_DEADLINE = Duration.ofMillis(1_200); + + private SessionFactory sessionFactory; + private EntityManager entityManager; + private SpringTransaction port; + + @BeforeEach + void openHibernate() { + DriverManagerDataSource dataSource = + new DriverManagerDataSource( + "jdbc:h2:mem:deadline-" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1", "sa", ""); + Configuration configuration = new Configuration(); + configuration.getProperties().put("hibernate.connection.datasource", dataSource); + configuration.setProperty("hibernate.hbm2ddl.auto", "create"); + configuration.addAnnotatedClass(DeadlineRow.class); + sessionFactory = configuration.buildSessionFactory(); + entityManager = SharedEntityManagerCreator.createSharedEntityManager(sessionFactory); + port = + new SpringTransaction( + new JpaTransactionManager(sessionFactory), + new PersistenceExceptionTranslator(List.of(new StandardSqlStateErrorMapping())), + ONE_SECOND); + } + + @AfterEach + void closeHibernate() { + sessionFactory.close(); + } + + @Test + @DisplayName("마감이 지난 뒤 본문의 flush를 Hibernate가 거부하면 DB_QUERY_CANCELED로 알린다") + void aFlushHibernateRefusesPastTheDeadlineIsAQueryCancellation() { + // when + Throwable thrown = + catchThrowable( + () -> + port.inWrite( + () -> { + sleep(PAST_THE_DEADLINE); + entityManager.persist(new DeadlineRow(1L)); + entityManager.flush(); + return null; + })); + + // then + assertThat(thrown).isInstanceOf(PersistenceFailureException.class); + assertThat(((PersistenceFailureException) thrown).errorCode()) + .isEqualTo(OperationalError.DB_QUERY_CANCELED); + } + + @Test + @DisplayName("마감이 지난 뒤 커밋의 flush를 Hibernate가 거부해도 DB_QUERY_CANCELED로 알린다") + void aCommitFlushHibernateRefusesPastTheDeadlineIsAQueryCancellation() { + // when + Throwable thrown = + catchThrowable( + () -> + port.inWrite( + () -> { + sleep(PAST_THE_DEADLINE); + entityManager.persist(new DeadlineRow(2L)); + return null; + })); + + // then + assertThat(thrown).isInstanceOf(PersistenceFailureException.class); + assertThat(((PersistenceFailureException) thrown).errorCode()) + .isEqualTo(OperationalError.DB_QUERY_CANCELED); + } + + @Test + @DisplayName("마감이 지난 뒤라도 업무 코드가 던진 예외는 바꾸지 않고 그대로 전한다") + void aBusinessFailurePastTheDeadlineIsNotRelabelled() { + // given + IllegalStateException businessFailure = new IllegalStateException("the order is closed"); + + // when + Throwable thrown = + catchThrowable( + () -> + port.inWrite( + () -> { + sleep(PAST_THE_DEADLINE); + throw businessFailure; + })); + + // then + assertThat(thrown).isSameAs(businessFailure); + } + + private static void sleep(Duration duration) { + try { + Thread.sleep(duration); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + /** The row the scenarios write; its table exists only to give the flush a statement. */ + @Entity + @Table(name = "deadline_row") + static class DeadlineRow { + @Id Long id; + + protected DeadlineRow() {} + + DeadlineRow(Long id) { + this.id = id; + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 index ca048746..bf86884e 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 +++ b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 @@ -40,7 +40,8 @@ b8f571e6cada72a8f2776f4462509ce4b535c964c75b1c3cfb34b9dc07446d59 postgresql/V17 44cacbde7d1381ca5290fb8ec28005e8127ff6b453ff84277ec8d1b3293d76c8 postgresql/V18__outbox_event_unpublished_aggregate_order.sql a0306e5b0fbcaf43984d256362dc4244aec57a0ce5031e4f5263be3762fe1caf postgresql/V19__outbox_event_canonical_only.sql c997fa20e10b68e0ca1b30cd7275018deaadc99bb0370b7b806332e9826e5217 postgresql/V20__outbox_event_deferred_attempt_count.sql -f830cda5a8cb72378c5af5d98810db61dc0dc36e416758c5da0de2ac34a68e27 postgresql/V21__outbox_aggregate_sequence.sql +21744ea1aab2b29fbb3417b9a5c4389522199413048cc7035aa649ffcdd852cf postgresql/V21__outbox_aggregate_sequence.sql +459942722c69d43b15fdab34849c6e34bbca35727e800eca18fbc5b3eebe5f4c postgresql/V22__outbox_event_last_failure_code.sql 8ab106731d4d04d3719da0692069947736dc490ca46aa5a3ea9bdf65a5d956dc postgresql/V1__idempotency_record.sql 6b62a01a4eeb792b81015b4810ecc6f3f021e0a17dea50c871493f7694d4f0b9 postgresql/V3__outbox_event.sql c57ab8a35a10079190ad8a563be58fae4147c9406c5bb752debb6998324ccdf6 postgresql/V4__int_lock.sql diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRules.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRules.java index 42c1f5ae..a35d8ef4 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRules.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRules.java @@ -1,9 +1,12 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.arch; +import static com.tngtech.archunit.core.domain.properties.CanBeAnnotated.Predicates.annotatedWith; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods; 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.lang.ArchRule; import jakarta.persistence.Embeddable; import jakarta.persistence.Entity; @@ -144,4 +147,36 @@ public final class JpaArchitectureRules { + " use a unidirectional @ManyToOne or an ID reference, and a repository query for" + " the collection"); } + + /** + * The entities of the leaf rooted at {@code leafPackage} are used by that leaf's classes only. + * + *

        A capability persistence leaf splits its entities and its stores into two packages (review + * 04-16), so the entity constructors and mutators the stores call are public, and Java can no + * longer say "this row never leaves the leaf". The ports carry records instead; this rule is what + * holds that line now that visibility does not (review RR-03-09). Nothing outside the leaf may + * name one of its {@code @Entity}, {@code @MappedSuperclass} or {@code @Embeddable} types. + * + * @param leafPackage the leaf's root package, e.g. {@code + * dev.caskeleton.adapter.outbound.persistence.notification} + */ + public static ArchRule entitiesAreUsedOnlyInsideTheirLeaf(String leafPackage) { + DescribedPredicate leafEntity = + JavaClass.Predicates.resideInAPackage(leafPackage + "..") + .and( + annotatedWith(Entity.class) + .or(annotatedWith(MappedSuperclass.class)) + .or(annotatedWith(Embeddable.class))) + .as("an entity of " + leafPackage); + return noClasses() + .that() + .resideOutsideOfPackage(leafPackage + "..") + .should() + .dependOnClassesThat(leafEntity) + .as("the entities of " + leafPackage + " are used inside that leaf only") + .because( + "the stores map them to the records the ports carry; an entity used elsewhere is" + + " mutable persistence state reached through its public mutators") + .allowEmptyShould(true); + } } diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java index 0456c877..cbe87cde 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java @@ -2,69 +2,179 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.arch; import com.tngtech.archunit.core.domain.JavaAnnotation; import com.tngtech.archunit.core.domain.JavaClass; +import com.tngtech.archunit.core.domain.JavaField; import com.tngtech.archunit.core.domain.JavaMember; +import com.tngtech.archunit.core.domain.JavaMethod; +import com.tngtech.archunit.core.domain.JavaParameterizedType; +import com.tngtech.archunit.core.domain.JavaType; import com.tngtech.archunit.lang.ArchCondition; import com.tngtech.archunit.lang.ConditionEvents; import com.tngtech.archunit.lang.SimpleConditionEvent; import jakarta.persistence.ManyToMany; +import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; +import java.lang.annotation.Annotation; import java.util.List; +import java.util.Optional; import java.util.stream.Stream; /** - * Reports every association declared with {@code mappedBy} — the inverse half of a bidirectional - * pair. + * Reports every association that is one half of a bidirectional pair. * - *

        {@code mappedBy} is the one attribute that says "this field is a second copy of a link the - * other side owns". JPA writes only the owning side, so the inverse copy is correct only while - * application code remembers to update both — and nothing fails when it forgets: the row is left - * unlinked, or the in-memory graph disagrees with the database until the next load. Checking the - * attribute rather than the annotation keeps a unidirectional {@code @OneToMany} with its own - * {@code @JoinColumn}, which has nothing to keep in step, out of the report. + *

        A pair is two entities whose associations point at each other. JPA writes the link from one + * place only, so the second copy is correct only while application code remembers to update both — + * and nothing fails when it forgets: the row is left unlinked, or the in-memory graph disagrees + * with the database until the next load. There are two ways to write the pair: * - *

        Fields and methods are both inspected, because property access puts the mapping on the getter. + *

          + *
        • With {@code mappedBy}: the inverse half says so. Only that half is reported, because the + * foreign key belongs to the owning {@code @ManyToOne} either way. + *
        • Without it: both halves map the same join column, one of them usually {@code insertable = + * false, updatable = false} (Hibernate's {@code @JoinColumn} form). Neither half says it is + * the copy, so both are reported (review RR-03-04). Reading the attribute alone let this form + * pass. + *
        + * + *

        A unidirectional {@code @OneToMany} with its own {@code @JoinColumn}, or a {@code @ManyToOne} + * nobody points back at, has nothing to keep in step and passes. A self-reference is a pair only + * when a second member of the same class points back the other way ({@code @ManyToOne parent} and + * {@code @OneToMany children}); two {@code @ManyToOne} links of a class to itself are two one-way + * links. Fields and methods are both inspected, because property access puts the mapping on the + * getter. */ public final class SingleSidedAssociationCondition extends ArchCondition { - private static final List> INVERSE_CAPABLE = - List.of(OneToMany.class, OneToOne.class, ManyToMany.class); + private static final List> ASSOCIATIONS = + List.of(OneToMany.class, ManyToOne.class, OneToOne.class, ManyToMany.class); + + private static final String ALTERNATIVE = + " Map each association from one side only: keep the owning @ManyToOne (LAZY) or hold the" + + " other aggregate's ID, and load the collection with a repository query" + + " (docs/jpa/entity-mapping-guide.md, Associations)"; public SingleSidedAssociationCondition() { - super("map each association from one side only (no mappedBy)"); + super("map each association from one side only (no bidirectional pair)"); } @Override public void check(JavaClass mappedType, ConditionEvents events) { - Stream.concat(mappedType.getFields().stream(), mappedType.getMethods().stream()) - .forEach(member -> reportInverseSide(mappedType, member, events)); + members(mappedType).forEach(member -> report(mappedType, member, events)); } - private static void reportInverseSide( - JavaClass mappedType, JavaMember member, ConditionEvents events) { - for (Class type : INVERSE_CAPABLE) { - if (!member.isAnnotatedWith(type)) { + private static void report(JavaClass mappedType, JavaMember member, ConditionEvents events) { + Optional association = Association.of(member); + if (association.isEmpty()) { + return; + } + Association own = association.get(); + if (!own.mappedBy().isEmpty()) { + events.add( + SimpleConditionEvent.violated( + mappedType, + name(mappedType, member) + + " is @" + + own.annotation() + + "(mappedBy = \"" + + own.mappedBy() + + "\"), the inverse side of a bidirectional association." + + ALTERNATIVE)); + return; + } + JavaClass target = own.target(); + boolean selfReference = target.getName().equals(mappedType.getName()); + for (JavaMember counterpart : members(target).toList()) { + if (counterpart.equals(member)) { continue; } - JavaAnnotation annotation = member.getAnnotationOfType(type.getName()); - String mappedBy = String.valueOf(annotation.get("mappedBy").orElse("")); - if (mappedBy.isEmpty()) { + Optional back = Association.of(counterpart); + if (back.isEmpty() + || !back.get().target().getName().equals(mappedType.getName()) + || !back.get().mappedBy().isEmpty()) { + // No pair, or a mappedBy pair whose inverse half is reported on its own. + continue; + } + if (selfReference && !back.get().annotation().equals(inverseOf(own.annotation()))) { + // Two links of one class to itself (a manager and a mentor) are two one-way links. continue; } events.add( SimpleConditionEvent.violated( mappedType, - mappedType.getSimpleName() - + "." - + member.getName() - + " is @" - + type.getSimpleName() - + "(mappedBy = \"" - + mappedBy - + "\"), the inverse side of a bidirectional association. Map each association" - + " from one side only: keep the owning @ManyToOne (LAZY) or hold the other" - + " aggregate's ID, and load the collection with a repository query" - + " (docs/jpa/entity-mapping-guide.md, Associations)")); + name(mappedType, member) + + " (@" + + own.annotation() + + ") and " + + name(target, counterpart) + + " (@" + + back.get().annotation() + + ") point at each other without mappedBy: two fields map one link, and" + + " the read-only one does not follow a change made through the other." + + ALTERNATIVE)); + return; + } + } + + /** The annotation the other half of a pair carries. */ + private static String inverseOf(String annotation) { + return switch (annotation) { + case "ManyToOne" -> "OneToMany"; + case "OneToMany" -> "ManyToOne"; + default -> annotation; + }; + } + + private static Stream members(JavaClass type) { + return Stream.concat(type.getFields().stream(), type.getMethods().stream()); + } + + private static String name(JavaClass owner, JavaMember member) { + return owner.getSimpleName() + "." + member.getName(); + } + + /** One association member: its annotation, its {@code mappedBy}, and the entity it points at. */ + private record Association(String annotation, String mappedBy, JavaClass target) { + + static Optional of(JavaMember member) { + for (Class type : ASSOCIATIONS) { + if (!member.isAnnotatedWith(type)) { + continue; + } + JavaAnnotation annotation = member.getAnnotationOfType(type.getName()); + String mappedBy = String.valueOf(annotation.get("mappedBy").orElse("")); + return target(member, annotation) + .map(target -> new Association(type.getSimpleName(), mappedBy, target)); + } + return Optional.empty(); + } + + /** {@code targetEntity} when set, else the declared type, else a collection's element type. */ + private static Optional target(JavaMember member, JavaAnnotation annotation) { + Optional declared = + annotation + .get("targetEntity") + .filter(JavaClass.class::isInstance) + .map(JavaClass.class::cast) + .filter(type -> !type.getName().equals("void")); + if (declared.isPresent()) { + return declared; + } + JavaType type = + switch (member) { + case JavaField field -> field.getType(); + case JavaMethod method -> method.getReturnType(); + default -> null; + }; + if (type == null) { + return Optional.empty(); + } + if (type instanceof JavaParameterizedType parameterized + && !parameterized.getActualTypeArguments().isEmpty()) { + List arguments = parameterized.getActualTypeArguments(); + // Map: the entity is the value. + return Optional.of(arguments.get(arguments.size() - 1).toErasure()); + } + return Optional.of(type.toErasure()); } } } diff --git a/src/adapter/outbound/persistence-notification/CLAUDE.md b/src/adapter/outbound/persistence-notification/CLAUDE.md index e7b25f5c..9d736619 100644 --- a/src/adapter/outbound/persistence-notification/CLAUDE.md +++ b/src/adapter/outbound/persistence-notification/CLAUDE.md @@ -13,8 +13,11 @@ outbox helpers), `NotificationRecordMapper` and the payload codec. - `configuration` — the auto-configuration facade that registers the stores as beans; the leaf root holds the scan configuration and the schema stream. - Entity accessors are public because the stores read them from another package; an entity never - leaves the leaf (the ports carry records). + Entity constructors, accessors and mutators are public because the stores use them from another + package; an entity never leaves the leaf (the ports carry records). Visibility no longer says so, + so a rule does: `JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf`, run over the production + graph by `JpaProductionArchitectureTest` (app-bootstrap `architectureTest`) for this leaf and + `persistence-fileserver` (review RR-03-09). ## Where the tests are diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java index 444b180a..03d1345e 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/JdbcReconciliationJobStore.java @@ -38,6 +38,12 @@ import org.springframework.jdbc.core.RowMapper; * — open across that call is exactly what the lease exists to avoid. {@link #reschedule} and {@link * #complete} match on the fence the job was claimed with, so a holder that outlived its lease * changes nothing once somebody else has claimed the job. + * + *

        A claim whose lease ran out without a reschedule or a completion counts as an attempt: the + * claim that takes the job over adds one to {@code attempts}. {@link #reschedule} clears {@code + * claimed_until}, so a lease still set at claim time is exactly that abandoned claim. Without it a + * worker that dies on the same job every time would reclaim it every lease, forever, below the + * attempt limit — the file server's reclaim counts the same way (review RR-03-08). */ public final class JdbcReconciliationJobStore implements ReconciliationJobStorePort { @@ -64,7 +70,8 @@ public final class JdbcReconciliationJobStore implements ReconciliationJobStoreP FOR UPDATE SKIP LOCKED) UPDATE notification_reconciliation_job AS job SET claimed_until = ?, - claim_fence = job.claim_fence + 1 + claim_fence = job.claim_fence + 1, + attempts = job.attempts + CASE WHEN job.claimed_until IS NULL THEN 0 ELSE 1 END FROM claimable WHERE job.id = claimable.id RETURNING job.id, job.attempt_id, job.provider_profile_id, job.next_check_at, job.attempts, diff --git a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientClaimSql.java b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientClaimSql.java index 6d11bbb5..79a60d15 100644 --- a/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientClaimSql.java +++ b/src/adapter/outbound/persistence-notification/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/repository/RecipientClaimSql.java @@ -10,10 +10,8 @@ package dev.caskeleton.adapter.outbound.persistence.notification.platform.reposi * *

        The lease store contract ({@code RecipientLeaseStoreContract}, run on PostgreSQL by {@code * PostgreSqlRecipientLeaseStoreContractTest}) now drives this statement through the repository and - * the store, so no test retypes it or runs it beside the adapter (review 2026-11-01 04-14). - * - *

        The named parameters are Spring Data's. {@link #positional(String)} rewrites them to JDBC - * placeholders for a caller with a bare {@code Connection}. + * the store, so no test retypes it or runs it beside the adapter (review 2026-11-01 04-14). The + * named parameters are Spring Data's. */ public final class RecipientClaimSql { @@ -70,14 +68,4 @@ public final class RecipientClaimSql { + " LIMIT :batchSize)"; private RecipientClaimSql() {} - - /** - * Rewrites the named parameters to JDBC placeholders, left to right. - * - * @param namedSql one of the statements above - * @return the same statement with {@code ?} in place of every {@code :name} - */ - public static String positional(String namedSql) { - return namedSql.replaceAll("(? :expected::jsonb")) - .isEqualTo("payload::jsonb @> ?::jsonb"); - } -} diff --git a/src/adapter/outbound/redis-runtime/build.gradle b/src/adapter/outbound/redis-runtime/build.gradle index ab55a982..f6ac29d0 100644 --- a/src/adapter/outbound/redis-runtime/build.gradle +++ b/src/adapter/outbound/redis-runtime/build.gradle @@ -14,6 +14,11 @@ dependencies { implementation 'io.lettuce:lettuce-core' implementation 'io.projectreactor:reactor-core' implementation 'org.slf4j:slf4j-api' + // Per-lane wait, refusal and reconnect meters (review 2026-11-03 RR-04-02). RedisLaneMetrics in + // the config package is the only importer: the connection lifecycle reports through + // RedisLaneListener and knows nothing of Micrometer, and a context without a MeterRegistry bean + // composes no meter at all. + implementation 'io.micrometer:micrometer-core' // Test fixtures only: the in-memory gateway and the real-topology endpoint that both redis-sdk's // and cache-redis's tests drive. One fake of RedisCommandGateway, owned by the leaf that owns it. diff --git a/src/adapter/outbound/redis-runtime/gradle.lockfile b/src/adapter/outbound/redis-runtime/gradle.lockfile index a83112f9..67ed098f 100644 --- a/src/adapter/outbound/redis-runtime/gradle.lockfile +++ b/src/adapter/outbound/redis-runtime/gradle.lockfile @@ -42,6 +42,7 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnota io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor io.lettuce:lettuce-core:6.8.2.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath io.netty:netty-buffer:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath io.netty:netty-codec-base:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath @@ -90,6 +91,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.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath @@ -101,6 +103,7 @@ org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs +org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath org.objenesis:objenesis:3.3=testRuntimeClasspath diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetrics.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetrics.java new file mode 100644 index 00000000..5d4b9476 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetrics.java @@ -0,0 +1,161 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLaneListener; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.Timer; +import java.time.Duration; +import java.util.Locale; +import java.util.Objects; + +/** + * Each Redis connection lane's wait, refusals and reconnects, as meters (review 2026-11-03 + * RR-04-02). + * + *

        The question these answer is the one the cache's own lane ({@code CACHE_SCRIPT}) was made for: + * is a lane running out, and is it the lane that may run out? A refusal counted for the whole + * runtime cannot say whether the cache or idempotency ran dry, and a reconnect nobody counts is the + * extra load a discarded connection adds to a Redis that is already slow. So every meter carries + * the lane's name, and every lane the owner pools — the runtime's own, the cache's, the typed SDK's + * — has its series from startup on. + * + * + * + * + * + * + * + * + * + * + * + *
        Meters
        NameTypeTagsAnswers
        {@value #ACQUIRE_WAIT}timerlane, outcome (admitted, refused)how long a borrow waited for a connection
        {@value #ACQUIRE_REFUSED}counterlane, reason (saturated, closing, + * interrupted, connect_failed)why a borrow got no connection
        {@value #CONNECTIONS_OPENED}counterlanenew connections: + * the lane's first ones, then every reconnect
        {@value #CONNECTIONS_DISCARDED}counterlane, reason (invalidated, + * broken)connections closed instead of pooled — what the reconnects replace
        {@value #CONNECTIONS_ACTIVE}gaugelaneconnections lent out + * now
        {@value #CONNECTIONS_PENDING}gaugelaneborrows waiting for + * a connection now
        + * + *

        The lane tag is the lane's name ({@code REGULAR}, {@code SCRIPT}, {@code CACHE_SCRIPT}, the + * SDK's {@code BLOCKING}, {@code TRANSACTION}, {@code ADMIN}): a closed set of enum constants, the + * same spelling the lane refusal's log line carries. The registry rows are in {@code + * docs/registries/metrics.yaml}. + */ +public final class RedisLaneMetrics implements RedisLaneListener { + + /** How long a borrow waited for a lane permit. */ + public static final String ACQUIRE_WAIT = "redis.lane.acquire.wait.seconds"; + + /** Borrows refused before any command existed. */ + public static final String ACQUIRE_REFUSED = "redis.lane.acquire.refused.total"; + + /** Connections opened: a lane's first ones, then every reconnect. */ + public static final String CONNECTIONS_OPENED = "redis.lane.connections.opened.total"; + + /** Connections closed instead of returned to the pool. */ + public static final String CONNECTIONS_DISCARDED = "redis.lane.connections.discarded.total"; + + /** Connections lent out right now. */ + public static final String CONNECTIONS_ACTIVE = "redis.lane.connections.active"; + + /** Borrows waiting for a connection right now. */ + public static final String CONNECTIONS_PENDING = "redis.lane.connections.pending"; + + private static final String LANE = "lane"; + private static final String REASON = "reason"; + + private final MeterRegistry registry; + + /** + * Creates the meters' owner; nothing is registered until {@link #bind(RedisRuntimeOwner)}. + * + * @param registry where the meters go + */ + public RedisLaneMetrics(MeterRegistry registry) { + this.registry = Objects.requireNonNull(registry, "registry must be non-null"); + } + + /** + * Registers every lane's gauges and zero-valued counters. + * + *

        The counters up front because a rate over a series that appears with its first refusal + * misses that refusal, and an alert on "refusals above zero" is exactly about the first one. + * + * @param owner the owner whose lanes are measured + */ + public void bind(RedisRuntimeOwner owner) { + Objects.requireNonNull(owner, "owner must be non-null"); + for (RedisLane lane : owner.lanes()) { + Gauge.builder(CONNECTIONS_ACTIVE, owner, measured -> measured.outstanding(lane)) + .description("Redis connections of this lane lent out now") + .tag(LANE, lane.name()) + .register(registry); + Gauge.builder(CONNECTIONS_PENDING, owner, measured -> measured.waiting(lane)) + .description("borrows waiting for a Redis connection of this lane now") + .tag(LANE, lane.name()) + .register(registry); + for (Refusal reason : Refusal.values()) { + refusals(lane, reason); + } + for (Discard reason : Discard.values()) { + discards(lane, reason); + } + openings(lane); + } + } + + @Override + public void waited(RedisLane lane, Duration waited, boolean admitted) { + Timer.builder(ACQUIRE_WAIT) + .description("how long a borrow waited for a Redis connection of this lane") + .tag(LANE, lane.name()) + .tag("outcome", admitted ? "admitted" : "refused") + // A histogram, so the p99 of the wait is a query rather than a guess from the mean. + .publishPercentileHistogram() + .minimumExpectedValue(Duration.ofMillis(1)) + .maximumExpectedValue(Duration.ofSeconds(10)) + .register(registry) + .record(waited); + } + + @Override + public void refused(RedisLane lane, Refusal reason) { + refusals(lane, reason).increment(); + } + + @Override + public void opened(RedisLane lane) { + openings(lane).increment(); + } + + @Override + public void discarded(RedisLane lane, Discard reason) { + discards(lane, reason).increment(); + } + + private Counter refusals(RedisLane lane, Refusal reason) { + return Counter.builder(ACQUIRE_REFUSED) + .description("borrows of this Redis lane refused before any command was sent") + .tag(LANE, lane.name()) + .tag(REASON, reason.name().toLowerCase(Locale.ROOT)) + .register(registry); + } + + private Counter openings(RedisLane lane) { + return Counter.builder(CONNECTIONS_OPENED) + .description("Redis connections opened for this lane, reconnects included") + .tag(LANE, lane.name()) + .register(registry); + } + + private Counter discards(RedisLane lane, Discard reason) { + return Counter.builder(CONNECTIONS_DISCARDED) + .description("Redis connections of this lane closed instead of pooled") + .tag(LANE, lane.name()) + .tag(REASON, reason.name().toLowerCase(Locale.ROOT)) + .register(registry); + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfiguration.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfiguration.java index 9dfabc89..f7535286 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfiguration.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfiguration.java @@ -7,6 +7,7 @@ import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRunti import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisTopologyClientFactory; import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; +import io.micrometer.core.instrument.MeterRegistry; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.List; @@ -232,16 +233,23 @@ public class RedisRuntimeAutoConfiguration { * further lanes on the runtime contributes their ceilings as {@link RedisLaneContribution} beans; * the runtime pools and drains those exactly like its own, and knows nothing else about them. * + *

        With a {@link MeterRegistry} in the context every lane — the runtime's, the cache's, the + * SDK's — gets its wait, refusal and reconnect meters ({@link RedisLaneMetrics}, review + * 2026-11-03 RR-04-02). Without one the owner reports to nobody and nothing about metrics is + * created. + * * @param client the runtime client * @param settings the validated settings * @param contributedLanes lanes other modules compose on the runtime + * @param meterRegistry where the lane meters go, when the application has a registry * @return the lifecycle owner */ @Bean(destroyMethod = "close") public RedisRuntimeOwner redisRuntimeOwner( RedisRuntimeClient client, RedisRuntimeSettings settings, - ObjectProvider contributedLanes) { + ObjectProvider contributedLanes, + ObjectProvider meterRegistry) { Map limits = new LinkedHashMap<>(); limits.put(RedisConnectionKind.REGULAR, settings.getCapacity().getMaximumInFlightCommands()); limits.put(RedisConnectionKind.SCRIPT, settings.getCapacity().getMaximumScriptConnections()); @@ -255,11 +263,24 @@ public class RedisRuntimeAutoConfiguration { "Redis lane " + contribution.lane().name() + " was composed twice"); } }); - return new RedisRuntimeOwner( - client, - limits, - settings.getLifecycle().getAcquireTimeout(), - settings.getLifecycle().getDrainTimeout()); + MeterRegistry registry = meterRegistry.getIfUnique(); + if (registry == null) { + return new RedisRuntimeOwner( + client, + limits, + settings.getLifecycle().getAcquireTimeout(), + settings.getLifecycle().getDrainTimeout()); + } + RedisLaneMetrics metrics = new RedisLaneMetrics(registry); + RedisRuntimeOwner owner = + new RedisRuntimeOwner( + client, + limits, + settings.getLifecycle().getAcquireTimeout(), + settings.getLifecycle().getDrainTimeout(), + metrics); + metrics.bind(owner); + return owner; } /** diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLaneListener.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLaneListener.java new file mode 100644 index 00000000..12fa70a8 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLaneListener.java @@ -0,0 +1,77 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +import java.time.Duration; + +/** + * What happens at a lane's door: how long a borrow waited, why one was refused, and when a + * connection was opened or thrown away. + * + *

        The owner reports these; it does not count them. Turning them into meters is the composition's + * job ({@code RedisLaneMetrics}), so the connection lifecycle stays free of any metrics library and + * a context without one pays nothing. + * + *

        Called on the borrowing or returning thread, never while the owner holds its lock. An + * implementation must be cheap and must not block. One that throws is logged and ignored: a meter + * that cannot be recorded is never a reason to refuse a connection. + */ +public interface RedisLaneListener { + + /** Reports nothing. */ + RedisLaneListener NONE = new RedisLaneListener() {}; + + /** + * A borrow finished waiting for a lane permit. + * + * @param lane the lane + * @param waited how long the borrow waited; near zero when the lane had room + * @param admitted {@code true} when the borrow got a permit, {@code false} when it gave up + */ + default void waited(RedisLane lane, Duration waited, boolean admitted) {} + + /** + * A borrow was refused before any command existed. + * + * @param lane the lane + * @param reason why + */ + default void refused(RedisLane lane, Refusal reason) {} + + /** + * A new connection was opened for a lane: the lane's first ones, and every reconnect after a + * connection was thrown away. + * + * @param lane the lane + */ + default void opened(RedisLane lane) {} + + /** + * A connection was closed instead of going back to the pool. + * + * @param lane the lane + * @param reason why + */ + default void discarded(RedisLane lane, Discard reason) {} + + /** Why a borrow was refused. Every one of them is "nothing was sent". */ + enum Refusal { + /** The lane stayed at its ceiling for the whole wait. */ + SATURATED, + /** The runtime is draining or closed. */ + CLOSING, + /** The borrowing thread was interrupted while it waited. */ + INTERRUPTED, + /** A connection had to be opened and could not be. */ + CONNECT_FAILED + } + + /** Why a connection was closed instead of pooled. */ + enum Discard { + /** + * Its holder marked it unusable — a command that timed out or failed, a transaction whose + * cleanup did not land. The next borrow on the lane opens a new connection. + */ + INVALIDATED, + /** The driver reported it closed, while it sat in the pool or when it came back. */ + BROKEN + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java index 45014405..5ad8134f 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java @@ -11,9 +11,11 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,6 +57,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { private final Map permits; private final Duration acquireTimeout; private final Duration drainTimeout; + private final RedisLaneListener listener; private final AtomicReference state = new AtomicReference<>(State.OPEN); private final Object monitor = new Object(); @@ -73,6 +76,27 @@ public final class RedisRuntimeOwner implements AutoCloseable { Map limits, Duration acquireTimeout, Duration drainTimeout) { + this(client, limits, acquireTimeout, drainTimeout, RedisLaneListener.NONE); + } + + /** + * Creates the owner, reporting what happens at each lane's door. + * + * @param client the topology client whose connections this owns + * @param limits per-lane maximum connections; see {@link #RedisRuntimeOwner(RedisRuntimeClient, + * Map, Duration, Duration)} + * @param acquireTimeout how long a borrow waits for a returned connection when its lane is full + * @param drainTimeout how long shutdown waits for outstanding leases + * @param listener told of every wait, refusal, opened and discarded connection, per lane (review + * 2026-11-03 RR-04-02); {@link RedisLaneListener#NONE} to report nothing + */ + public RedisRuntimeOwner( + RedisRuntimeClient client, + Map limits, + Duration acquireTimeout, + Duration drainTimeout, + RedisLaneListener listener) { + this.listener = Objects.requireNonNull(listener, "listener must be non-null"); this.client = Objects.requireNonNull(client, "client must be non-null"); this.acquireTimeout = Objects.requireNonNull(acquireTimeout, "acquire timeout must be non-null"); @@ -175,6 +199,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { + " was never composed; the module that uses it contributes its limit"); } if (state.get() != State.OPEN) { + report(sink -> sink.refused(kind, RedisLaneListener.Refusal.CLOSING)); throw notAccepting(kind); } // The limit is the lane's connection count: a lease holds one connection for one round trip, @@ -184,13 +209,22 @@ public final class RedisRuntimeOwner implements AutoCloseable { // thread waiting here does not pin its carrier. Semaphore lane = permits.get(kind); boolean admitted; + long waitStarted = System.nanoTime(); try { admitted = lane.tryAcquire(wait.toNanos(), TimeUnit.NANOSECONDS); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); + Duration waited = Duration.ofNanos(System.nanoTime() - waitStarted); + report(sink -> sink.waited(kind, waited, false)); + report(sink -> sink.refused(kind, RedisLaneListener.Refusal.INTERRUPTED)); throw reject(kind, "interrupted while waiting for a connection on lane " + kind.name()); } + // Every borrow's wait is reported, the near-zero ones included: a lane whose admitted waits + // grow is a lane about to refuse, and only the distribution shows it before the refusals do. + Duration waited = Duration.ofNanos(System.nanoTime() - waitStarted); + report(sink -> sink.waited(kind, waited, admitted)); if (!admitted) { + report(sink -> sink.refused(kind, RedisLaneListener.Refusal.SATURATED)); throw reject( kind, "connection lane " @@ -200,12 +234,18 @@ public final class RedisRuntimeOwner implements AutoCloseable { + " and no connection was returned within " + wait); } + boolean closing; synchronized (monitor) { - if (state.get() != State.OPEN) { + closing = state.get() != State.OPEN; + if (closing) { lane.release(); - throw notAccepting(kind); + } else { + outstanding.put(kind, outstanding.get(kind) + 1); } - outstanding.put(kind, outstanding.get(kind) + 1); + } + if (closing) { + report(sink -> sink.refused(kind, RedisLaneListener.Refusal.CLOSING)); + throw notAccepting(kind); } RedisRuntimeClient.RedisLaneConnection connection = null; try { @@ -219,6 +259,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { // would otherwise get a failure that looks like theirs. closeQuietly(connection); connection = null; + report(sink -> sink.discarded(kind, RedisLaneListener.Discard.BROKEN)); } if (connection == null) { connection = openLane(kind, routingKey); @@ -228,7 +269,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { if (connection != null) { closeQuietly(connection); } - release(kind, null, false); + release(kind, null, false, false); throw failure; } } @@ -244,27 +285,43 @@ public final class RedisRuntimeOwner implements AutoCloseable { */ private RedisRuntimeClient.RedisLaneConnection openLane( RedisLane kind, Optional routingKey) { + RedisRuntimeClient.RedisLaneConnection opened; try { - return client.openLane(kind, routingKey); + opened = client.openLane(kind, routingKey); } catch (RedisLaneUnavailableException refused) { + report(sink -> sink.refused(kind, RedisLaneListener.Refusal.CONNECT_FAILED)); throw refused; } catch (RuntimeException failure) { + report(sink -> sink.refused(kind, RedisLaneListener.Refusal.CONNECT_FAILED)); throw new RedisLaneUnavailableException( kind.name(), "a connection for lane " + kind.name() + " could not be opened; nothing was sent", failure); } + // Counted per lane because every one after the lane's first few is a reconnect: a connection + // was thrown away (see discarded) and a slow Redis now also pays for a new handshake. + report(sink -> sink.opened(kind)); + return opened; } private void release( - RedisLane kind, RedisRuntimeClient.RedisLaneConnection connection, boolean reusable) { + RedisLane kind, + RedisRuntimeClient.RedisLaneConnection connection, + boolean pooled, + boolean invalidated) { boolean drained; + RedisLaneListener.Discard discarded = null; synchronized (monitor) { outstanding.put(kind, outstanding.get(kind) - 1); if (connection != null) { - if (reusable && state.get() == State.OPEN && connection.open()) { + boolean open = connection.open(); + if (pooled && !invalidated && state.get() == State.OPEN && open) { idle.get(kind).addLast(connection); connection = null; + } else if (invalidated) { + discarded = RedisLaneListener.Discard.INVALIDATED; + } else if (!open) { + discarded = RedisLaneListener.Discard.BROKEN; } } drained = state.get() == State.DRAINING && totalOutstanding() == 0; @@ -279,6 +336,23 @@ public final class RedisRuntimeOwner implements AutoCloseable { } // After the counter, so a waiter admitted by this permit never sees the lane over its limit. permits.get(kind).release(); + if (discarded != null) { + RedisLaneListener.Discard reason = discarded; + report(sink -> sink.discarded(kind, reason)); + } + } + + /** + * Tells the listener, outside the lock, and never lets it fail the borrow or the return. + * + * @param event what to tell it + */ + private void report(Consumer event) { + try { + event.accept(listener); + } catch (RuntimeException failure) { + LOG.debug("a Redis lane listener failed; the borrow is unaffected", failure); + } } private int totalOutstanding() { @@ -357,6 +431,31 @@ public final class RedisRuntimeOwner implements AutoCloseable { } } + /** + * Returns how many borrows are waiting for a connection of a lane right now. + * + *

        An estimate, as {@link Semaphore#getQueueLength()} is: meant for a gauge, not for control. + * + * @param lane the lane + * @return the waiting borrows + */ + public int waiting(RedisLane lane) { + Semaphore permit = permits.get(Objects.requireNonNull(lane, "lane must be non-null")); + if (permit == null) { + throw new IllegalArgumentException("connection lane " + lane.name() + " was never composed"); + } + return permit.getQueueLength(); + } + + /** + * Returns every lane this owner pools: the runtime's own and the ones other modules composed. + * + * @return the lanes + */ + public Set lanes() { + return limits.keySet(); + } + /** * Returns the bound deployment mode. * @@ -371,14 +470,15 @@ public final class RedisRuntimeOwner implements AutoCloseable { private final RedisLane kind; private final RedisRuntimeClient.RedisLaneConnection connection; - private boolean reusable; + private final boolean pooled; + private boolean invalidated; private boolean closed; private Lease( - RedisLane kind, RedisRuntimeClient.RedisLaneConnection connection, boolean reusable) { + RedisLane kind, RedisRuntimeClient.RedisLaneConnection connection, boolean pooled) { this.kind = kind; this.connection = connection; - this.reusable = reusable; + this.pooled = pooled; } @Override @@ -409,7 +509,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { // A connection whose cleanup failed — a transaction whose DISCARD did not land, a window // that may still be open — must not go back into the pool. The next borrower would queue // their command into somebody else's MULTI. - reusable = false; + invalidated = true; } @Override @@ -418,7 +518,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { return; } closed = true; - release(kind, connection, reusable); + release(kind, connection, pooled, invalidated); } } } diff --git a/src/adapter/outbound/redis-runtime/src/main/resources/config/module-defaults/redis-runtime.yml b/src/adapter/outbound/redis-runtime/src/main/resources/config/module-defaults/redis-runtime.yml new file mode 100644 index 00000000..2dc63100 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/resources/config/module-defaults/redis-runtime.yml @@ -0,0 +1,13 @@ +# redis-runtime 의 redisOptional 은 Redis 에 닿지 못하면 DEGRADED 를 보고한다. Boot 기본 순서 +# (DOWN, OUT_OF_SERVICE, UP, UNKNOWN)에 없는 상태는 DOWN 보다 앞에 정렬돼, 다른 contributor 가 DOWN +# 이어도 전체 health 가 HTTP 200 DEGRADED 로 보였다(리뷰 05-23e). DEGRADED 를 DOWN 뒤, UP 앞에 둔다. +# +# 상태를 내는 이 leaf 가 순서도 싣는다. 예전에는 cache-redis 가 실었는데, redis-sdk 만 쓰는 조립은 +# redis-runtime 을 끌어오고 cache-redis 는 끌어오지 않아 순서 없이 DEGRADED 가 났다(리뷰 2026-11-03 +# RR-04-10). 이 키를 정하는 module-defaults 는 이 파일 하나뿐이다(두 파일이 같은 키를 실으면 기동이 +# 멈춘다). 서비스가 순서를 바꾸면 DEGRADED 를 넣어야 한다. +management: + endpoint: + health: + status: + order: DOWN,OUT_OF_SERVICE,DEGRADED,UP,UNKNOWN diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetricsTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetricsTest.java new file mode 100644 index 00000000..37f4bb85 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetricsTest.java @@ -0,0 +1,388 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccount; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisDriverConnection; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLaneListener; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLaneUnavailableException; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLease; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeClient; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.Timer; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The lanes' own meters: how long a borrow waited, why one was refused, and how often a connection + * was opened or thrown away (review 2026-11-03 RR-04-02). + * + *

        The cache got a lane of its own so that cache fills cannot take the connections idempotency, + * rate limiting and leases need. Whether that holds under load is a question only per-lane numbers + * answer: a refusal counted for the whole runtime cannot say which lane ran out, and a reconnect + * nobody counts is the extra load a timed-out lease adds to a Redis that is already slow. + */ +class RedisLaneMetricsTest { + + /** A lane another module composes on the runtime, the way the cache does. */ + private enum ContributedLane implements RedisLane { + EXCLUSIVE; + + @Override + public RedisAccount account() { + return RedisAccount.APPLICATION; + } + } + + private final SimpleMeterRegistry registry = new SimpleMeterRegistry(); + private final FakeClient client = new FakeClient(); + + private RedisRuntimeOwner owner(int contributedLimit, Duration acquireTimeout) { + return owner(contributedLimit, acquireTimeout, new RedisLaneMetrics(registry)); + } + + private RedisRuntimeOwner owner( + int contributedLimit, Duration acquireTimeout, RedisLaneMetrics metrics) { + RedisRuntimeOwner owner = + new RedisRuntimeOwner( + client, laneLimits(contributedLimit), acquireTimeout, Duration.ofSeconds(1), metrics); + metrics.bind(owner); + return owner; + } + + private static Map laneLimits(int contributedLimit) { + Map limits = new LinkedHashMap<>(); + limits.put(RedisConnectionKind.REGULAR, 4); + limits.put(RedisConnectionKind.SCRIPT, 4); + limits.put(ContributedLane.EXCLUSIVE, contributedLimit); + return limits; + } + + private double refused(RedisLane lane, String reason) { + Counter counter = + registry + .find(RedisLaneMetrics.ACQUIRE_REFUSED) + .tag("lane", lane.name()) + .tag("reason", reason) + .counter(); + return counter == null ? 0 : counter.count(); + } + + private Timer waited(RedisLane lane, String outcome) { + return registry + .find(RedisLaneMetrics.ACQUIRE_WAIT) + .tag("lane", lane.name()) + .tag("outcome", outcome) + .timer(); + } + + private double counted(String name, RedisLane lane) { + Counter counter = registry.find(name).tag("lane", lane.name()).counter(); + return counter == null ? 0 : counter.count(); + } + + private double discarded(RedisLane lane, String reason) { + Counter counter = + registry + .find(RedisLaneMetrics.CONNECTIONS_DISCARDED) + .tag("lane", lane.name()) + .tag("reason", reason) + .counter(); + return counter == null ? 0 : counter.count(); + } + + private double gauge(String name, RedisLane lane) { + Gauge gauge = registry.find(name).tag("lane", lane.name()).gauge(); + assertThat(gauge).as("%s{lane=%s} is registered", name, lane.name()).isNotNull(); + return gauge.value(); + } + + @Test + @DisplayName("상한에 찬 lane의 거절은 그 lane의 saturated 거절과 refused 대기로 세고 다른 lane 수치는 건드리지 않는다") + void aSaturatedLaneCountsItsOwnRefusalAndWait() { + // given + try (RedisRuntimeOwner owner = owner(1, Duration.ofMillis(30))) { + RedisLease held = owner.borrow(ContributedLane.EXCLUSIVE); + + // when + Throwable refused = catchThrowable(() -> owner.borrow(ContributedLane.EXCLUSIVE)); + + // then + assertThat(refused).isInstanceOf(RedisLaneUnavailableException.class); + assertThat(refused(ContributedLane.EXCLUSIVE, "saturated")).isEqualTo(1); + assertThat(refused(RedisConnectionKind.SCRIPT, "saturated")) + .as("a full cache lane is not a full SCRIPT lane") + .isZero(); + Timer wait = waited(ContributedLane.EXCLUSIVE, "refused"); + assertThat(wait).isNotNull(); + assertThat(wait.count()).isEqualTo(1); + assertThat(wait.totalTime(TimeUnit.MILLISECONDS)) + .as("the refused borrow waited out the acquire timeout") + .isGreaterThanOrEqualTo(25); + held.close(); + } + } + + @Test + @DisplayName("lane에서 연결을 받은 borrow는 admitted 대기로 센다") + void anAdmittedBorrowRecordsItsWait() { + // given + try (RedisRuntimeOwner owner = owner(2, Duration.ofMillis(50))) { + + // when + owner.borrow(ContributedLane.EXCLUSIVE).close(); + + // then + Timer wait = waited(ContributedLane.EXCLUSIVE, "admitted"); + assertThat(wait).isNotNull(); + assertThat(wait.count()).isEqualTo(1); + } + } + + @Test + @DisplayName("연결을 열지 못한 borrow는 그 lane의 connect_failed 거절로 센다") + void aConnectionThatCouldNotBeOpenedCountsAsConnectFailed() { + // given + client.failOpen = true; + try (RedisRuntimeOwner owner = owner(1, Duration.ofMillis(50))) { + + // when + Throwable refused = catchThrowable(() -> owner.borrow(ContributedLane.EXCLUSIVE)); + + // then + assertThat(refused).isInstanceOf(RedisLaneUnavailableException.class); + assertThat(refused(ContributedLane.EXCLUSIVE, "connect_failed")).isEqualTo(1); + assertThat(counted(RedisLaneMetrics.CONNECTIONS_OPENED, ContributedLane.EXCLUSIVE)).isZero(); + } + } + + @Test + @DisplayName("닫힌 runtime에 온 borrow는 그 lane의 closing 거절로 센다") + void aBorrowAfterShutdownCountsAsClosing() { + // given + RedisRuntimeOwner owner = owner(1, Duration.ofMillis(50)); + owner.close(); + + // when + Throwable refused = catchThrowable(() -> owner.borrow(RedisConnectionKind.REGULAR)); + + // then + assertThat(refused).isInstanceOf(RedisLaneUnavailableException.class); + assertThat(refused(RedisConnectionKind.REGULAR, "closing")).isEqualTo(1); + } + + @Test + @DisplayName("무효화된 연결은 invalidated로 버린 연결로 세고 다음 borrow가 다시 연 연결도 센다") + void anInvalidatedConnectionCountsAsDiscardedAndItsReplacementAsOpened() { + // given + try (RedisRuntimeOwner owner = owner(2, Duration.ofMillis(50))) { + RedisLease lease = owner.borrow(ContributedLane.EXCLUSIVE); + lease.invalidate(); + lease.close(); + + // when + owner.borrow(ContributedLane.EXCLUSIVE).close(); + + // then + assertThat(discarded(ContributedLane.EXCLUSIVE, "invalidated")).isEqualTo(1); + assertThat(counted(RedisLaneMetrics.CONNECTIONS_OPENED, ContributedLane.EXCLUSIVE)) + .as("the first connection and the reconnect after it was thrown away") + .isEqualTo(2); + } + } + + @Test + @DisplayName("idle 중에 끊긴 연결은 broken으로 버린 연결로 센다") + void aConnectionThatDiedWhileIdleCountsAsBroken() { + // given + try (RedisRuntimeOwner owner = owner(2, Duration.ofMillis(50))) { + owner.borrow(RedisConnectionKind.REGULAR).close(); + client.killAll(); + + // when + owner.borrow(RedisConnectionKind.REGULAR).close(); + + // then + assertThat(discarded(RedisConnectionKind.REGULAR, "broken")).isEqualTo(1); + assertThat(counted(RedisLaneMetrics.CONNECTIONS_OPENED, RedisConnectionKind.REGULAR)) + .isEqualTo(2); + } + } + + @Test + @DisplayName("lane마다 빌려 간 연결 수와 연결을 기다리는 borrow 수를 gauge로 낸다") + void eachLaneReportsActiveAndPendingBorrows() throws Exception { + // given + try (RedisRuntimeOwner owner = owner(1, Duration.ofSeconds(5))) { + RedisLease held = owner.borrow(ContributedLane.EXCLUSIVE); + Thread waiter = + Thread.ofVirtual().start(() -> owner.borrow(ContributedLane.EXCLUSIVE).close()); + long deadline = System.nanoTime() + Duration.ofSeconds(5).toNanos(); + while (owner.waiting(ContributedLane.EXCLUSIVE) == 0 && System.nanoTime() < deadline) { + Thread.onSpinWait(); + } + + // when + double active = gauge(RedisLaneMetrics.CONNECTIONS_ACTIVE, ContributedLane.EXCLUSIVE); + double pending = gauge(RedisLaneMetrics.CONNECTIONS_PENDING, ContributedLane.EXCLUSIVE); + + // then + assertThat(active).isEqualTo(1); + assertThat(pending).isEqualTo(1); + assertThat(gauge(RedisLaneMetrics.CONNECTIONS_ACTIVE, RedisConnectionKind.SCRIPT)).isZero(); + held.close(); + waiter.join(Duration.ofSeconds(5)); + } + } + + @Test + @DisplayName("거절이 한 번도 없던 lane도 0인 거절 series를 처음부터 낸다") + void everyLaneStartsWithZeroRefusalSeries() { + // given + try (RedisRuntimeOwner owner = owner(1, Duration.ofMillis(50))) { + + // when + Counter saturated = + registry + .find(RedisLaneMetrics.ACQUIRE_REFUSED) + .tag("lane", RedisConnectionKind.SCRIPT.name()) + .tag("reason", "saturated") + .counter(); + + // then + assertThat(saturated) + .as("an alert on a rate needs the series before the first refusal, not after it") + .isNotNull(); + assertThat(saturated.count()).isZero(); + } + } + + @Test + @DisplayName("지표 기록이 실패해도 borrow는 그대로 연결을 빌려 주고 돌려받는다") + void aFailingListenerNeverFailsABorrow() { + // given + RedisLaneListener failing = + new RedisLaneListener() { + @Override + public void waited(RedisLane lane, Duration waited, boolean admitted) { + throw new IllegalStateException("meter registry rejected the sample"); + } + + @Override + public void opened(RedisLane lane) { + throw new IllegalStateException("meter registry rejected the sample"); + } + + @Override + public void discarded(RedisLane lane, Discard reason) { + throw new IllegalStateException("meter registry rejected the sample"); + } + }; + try (RedisRuntimeOwner owner = + new RedisRuntimeOwner( + client, laneLimits(1), Duration.ofMillis(50), Duration.ofSeconds(1), failing)) { + + // when + Throwable failure = + catchThrowable( + () -> { + RedisLease lease = owner.borrow(ContributedLane.EXCLUSIVE); + lease.invalidate(); + lease.close(); + }); + + // then + assertThat(failure).isNull(); + assertThat(owner.outstanding(ContributedLane.EXCLUSIVE)).isZero(); + } + } + + @Test + @DisplayName("listener 없이 만든 owner는 아무 지표도 내지 않는다") + void anOwnerWithoutAListenerRecordsNothing() { + // given + try (RedisRuntimeOwner owner = + new RedisRuntimeOwner( + client, + laneLimits(1), + Duration.ofMillis(50), + Duration.ofSeconds(1), + RedisLaneListener.NONE)) { + + // when + owner.borrow(RedisConnectionKind.REGULAR).close(); + + // then + assertThat(registry.getMeters()).isEmpty(); + } + } + + /** A driver stand-in: opens connections that can be made to fail or die. */ + private static final class FakeClient implements RedisRuntimeClient { + + private final List live = new ArrayList<>(); + private boolean failOpen; + + void killAll() { + live.forEach(connection -> connection.alive = false); + } + + @Override + public RedisDeploymentMode mode() { + return RedisDeploymentMode.STANDALONE; + } + + @Override + public RedisLaneConnection openLane(RedisLane lane, Optional routingKey) { + if (failOpen) { + throw new IllegalStateException("connection refused"); + } + FakeConnection connection = new FakeConnection(); + live.add(connection); + return connection; + } + + @Override + public void close() {} + } + + private static final class FakeConnection implements RedisRuntimeClient.RedisLaneConnection { + + private boolean alive = true; + + @Override + public SemanticRedisCommands commands() { + return null; + } + + @Override + public RedisDriverConnection driver() { + return null; + } + + @Override + public boolean open() { + return alive; + } + + @Override + public void close() { + alive = false; + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfigurationTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfigurationTest.java index b7d2b57e..2284aed8 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfigurationTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfigurationTest.java @@ -7,6 +7,8 @@ import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccou import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeClient; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -404,6 +406,29 @@ class RedisRuntimeAutoConfigurationTest { }); } + @Test + @DisplayName("MeterRegistry가 있으면 runtime lane과 다른 모듈이 기여한 lane마다 연결 지표를 등록한다") + void aMeterRegistryGetsTheMetersOfEveryComposedLane() { + authenticated + .withPropertyValues("app.redis.enabled=true") + .withBean(MeterRegistry.class, SimpleMeterRegistry::new) + .withBean( + RedisLaneContribution.class, + () -> new RedisLaneContribution(ContributedLane.EXCLUSIVE, 3)) + .run( + context -> { + // when + MeterRegistry registry = context.getBean(MeterRegistry.class); + + // then + assertThat(context).hasNotFailed(); + assertThat( + registry.find(RedisLaneMetrics.CONNECTIONS_ACTIVE).gauges().stream() + .map(gauge -> gauge.getId().getTag("lane"))) + .containsExactlyInAnyOrder("REGULAR", "SCRIPT", "EXCLUSIVE"); + }); + } + @Test void aLaneComposedTwiceFailsTheContext() { authenticated diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeHealthStatusOrderTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeHealthStatusOrderTest.java new file mode 100644 index 00000000..cb9520f6 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeHealthStatusOrderTest.java @@ -0,0 +1,51 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.health.actuate.endpoint.SimpleStatusAggregator; +import org.springframework.boot.health.contributor.Status; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.ClassPathResource; + +/** + * The leaf that reports {@code DEGRADED} ships the order that ranks it (review 2026-11-03 + * RR-04-10). + * + *

        {@code redisOptional} is created by this leaf whenever {@code app.redis.enabled=true}. The + * order that puts {@code DEGRADED} after {@code DOWN} used to ship with cache-redis, so an assembly + * that used Redis only through the typed SDK (redis-sdk pulls this leaf in, not cache-redis) had a + * status Boot's default order does not know — and an unknown status sorts before {@code DOWN}, + * which reported a real outage as HTTP 200 {@code DEGRADED} (review 05-23e). + */ +class RedisRuntimeHealthStatusOrderTest { + + private static final String MODULE_DEFAULTS = "config/module-defaults/redis-runtime.yml"; + + @Test + @DisplayName("DEGRADED를 내는 redis-runtime이 DOWN 뒤·UP 앞 순서를 직접 싣는다") + void theLeafThatReportsDegradedShipsItsOrder() throws IOException { + // given + List> shipped = + new YamlPropertySourceLoader() + .load(MODULE_DEFAULTS, new ClassPathResource(MODULE_DEFAULTS)); + String order = + String.valueOf(shipped.get(0).getProperty("management.endpoint.health.status.order")); + SimpleStatusAggregator aggregator = + new SimpleStatusAggregator(Arrays.stream(order.split(",")).map(String::trim).toList()); + + // when + Status withAnOutage = + aggregator.getAggregateStatus(Status.UP, new Status("DEGRADED"), Status.DOWN); + + // then + assertThat(withAnOutage).isEqualTo(Status.DOWN); + assertThat(aggregator.getAggregateStatus(Status.UP, new Status("DEGRADED")).getCode()) + .isEqualTo("DEGRADED"); + } +} diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneAdmissionTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneAdmissionTest.java index bbed4f58..4addd172 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneAdmissionTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneAdmissionTest.java @@ -10,6 +10,7 @@ import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLaneU import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLease; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.StubRedisRuntimeClient; +import io.micrometer.core.instrument.MeterRegistry; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; @@ -89,7 +90,8 @@ class RedisScriptLaneAdmissionTest { .redisRuntimeOwner( StubRedisRuntimeClient.serving(null), settings, - new StaticListableBeanFactory().getBeanProvider(RedisLaneContribution.class)); + new StaticListableBeanFactory().getBeanProvider(RedisLaneContribution.class), + new StaticListableBeanFactory().getBeanProvider(MeterRegistry.class)); } /** One semantic script call: the lease is held until the test lets the script complete. */ diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneCapacityTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneCapacityTest.java index 6d8c40bf..fb69a31f 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneCapacityTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneCapacityTest.java @@ -7,6 +7,7 @@ import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLaneU import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLease; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.StubRedisRuntimeClient; +import io.micrometer.core.instrument.MeterRegistry; import java.time.Duration; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.support.StaticListableBeanFactory; @@ -25,7 +26,8 @@ class RedisScriptLaneCapacityTest { .redisRuntimeOwner( StubRedisRuntimeClient.serving(null), settings, - new StaticListableBeanFactory().getBeanProvider(RedisLaneContribution.class)); + new StaticListableBeanFactory().getBeanProvider(RedisLaneContribution.class), + new StaticListableBeanFactory().getBeanProvider(MeterRegistry.class)); RedisLease first = owner.borrow(RedisConnectionKind.SCRIPT); RedisLease second = owner.borrow(RedisConnectionKind.SCRIPT); diff --git a/src/adapter/outbound/redis-sdk/gradle.lockfile b/src/adapter/outbound/redis-sdk/gradle.lockfile index 8c5ab46a..a4b7fb69 100644 --- a/src/adapter/outbound/redis-sdk/gradle.lockfile +++ b/src/adapter/outbound/redis-sdk/gradle.lockfile @@ -42,6 +42,7 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnota io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor io.lettuce:lettuce-core:6.8.2.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-commons:1.16.7=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=runtimeClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.netty:netty-buffer:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.netty:netty-codec-base:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -90,6 +91,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.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath @@ -101,6 +103,7 @@ org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs +org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath org.objenesis:objenesis:3.3=testRuntimeClasspath diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java index b19930be..668ef1bd 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java @@ -21,6 +21,11 @@ import org.springframework.core.env.Environment; * dependencies, read only when the rule runs (the secret guard reads each module's {@code * RequiredProductionSecrets} this way). A check that needs a live connection — the datasource * version check — is not a rule; it stays a bean and is ordered before what it protects. + * + *

        The runner enforces this: when creating or running a rule brings any other singleton into + * existence — a configuration class behind a non-static {@code @Bean} method, a settings bean the + * method takes — the boot fails with that bean's name, because a bean created before the + * post-processors would keep unbound settings for the whole run (RR-06-01). */ public interface StartupRule { diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java index 55934d0e..51ebba76 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java @@ -1,8 +1,11 @@ package dev.caskeleton.adapter.outbound.support.startup; import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; +import java.util.Set; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.core.Ordered; @@ -33,6 +36,17 @@ import org.springframework.core.env.Environment; * static} {@code @Bean} method: it then pulls neither another bean nor its configuration class * forward. Rules are found without eager initialization, so no {@code FactoryBean} — an entity * manager factory, say — is created to learn its type. + * + *

        What a rule may not pull forward

        + * + *

        A bean created this early is created without the post-processors: a JavaBean + * {@code @ConfigurationProperties} class it takes is never bound and keeps its defaults for the + * whole run, and so does every other consumer of that singleton (RR-06-01). The {@code static} + * declaration used to be a sentence in Javadoc; now the runner checks it. Any singleton that comes + * into existence while a rule is created or run fails the boot with its name — unless it is itself + * a {@link StartupRule} or a {@link RequiredProductionSecrets}, the two kinds that are declared + * {@code static} and argument-free for exactly this reason (a non-static one creates its + * configuration class, which is reported). */ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordered { @@ -49,8 +63,22 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { - for (StartupRule rule : rules(beanFactory)) { - enforce(rule, environment); + IdentityHashMap names = new IdentityHashMap<>(); + List rules = new ArrayList<>(); + for (String name : beanFactory.getBeanNamesForType(StartupRule.class, true, false)) { + Set before = singletons(beanFactory); + StartupRule rule = beanFactory.getBean(name, StartupRule.class); + refusePulledForward(beanFactory, name, "creating it", before); + rules.add(rule); + names.put(rule, name); + } + AnnotationAwareOrderComparator.sort(rules); + for (StartupRule rule : rules) { + String name = names.get(rule); + Set before = singletons(beanFactory); + List violations = rule.violations(environment); + refusePulledForward(beanFactory, name, "running it", before); + raise(rule, violations); } } @@ -60,13 +88,46 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere return Ordered.HIGHEST_PRECEDENCE; } - private static List rules(ConfigurableListableBeanFactory beanFactory) { - List rules = new ArrayList<>(); - for (String name : beanFactory.getBeanNamesForType(StartupRule.class, true, false)) { - rules.add(beanFactory.getBean(name, StartupRule.class)); + private static Set singletons(ConfigurableListableBeanFactory beanFactory) { + return Set.of(beanFactory.getSingletonNames()); + } + + /** + * Fails when creating or running the rule {@code ruleName} brought a singleton into existence + * other than a rule or a {@link RequiredProductionSecrets}: that bean was built before the bean + * post-processors, so its settings are unbound and it is not proxied, for the rest of the run. + */ + private static void refusePulledForward( + ConfigurableListableBeanFactory beanFactory, + String ruleName, + String stage, + Set before) { + Set pulled = new LinkedHashSet<>(); + for (String name : beanFactory.getSingletonNames()) { + if (!before.contains(name) + && !beanFactory.isTypeMatch(name, StartupRule.class) + && !beanFactory.isTypeMatch(name, RequiredProductionSecrets.class)) { + pulled.add(name); + } } - AnnotationAwareOrderComparator.sort(rules); - return rules; + if (pulled.isEmpty()) { + return; + } + // A configuration error of the composition, so the configuration exit code (78): no + // environment fixes it, but neither does a retry, and it must not look like a crash. + throw StartupFailures.envValidation( + "startup rule '" + + ruleName + + "' created " + + pulled + + " while " + + stage + + ". Rules run before any bean post-processor exists, so a bean created then is never" + + " bound to its @ConfigurationProperties and never proxied, for the whole run. Declare" + + " the rule with a static @Bean method that takes only the Environment, the bean" + + " factory, or an ObjectProvider of RequiredProductionSecrets beans that are" + + " themselves static @Bean methods without parameters. A check that needs another" + + " bean is not a rule: keep it a bean, ordered before what it protects."); } /** @@ -77,8 +138,12 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere * @throws StartupFailureException when the rule found a violation */ public static void enforce(StartupRule rule, Environment environment) { + raise(rule, rule.violations(environment)); + } + + private static void raise(StartupRule rule, List violations) { StartupValidationContext.forPhase(rule.phase()) - .rejectAll(rule.violations(environment)) + .rejectAll(violations) .failIfViolated(rule.summary(), rule.remedy()); } } diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java index 7c193bb6..ca5d5b9e 100644 --- a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoderTest.java @@ -50,7 +50,7 @@ class JsonIntegrationEventEncoderTest { // then assertThat(new String(event.envelopeBytes(), StandardCharsets.UTF_8)) .isEqualTo( - "{\"envelopeVersion\":1,\"eventId\":\"event-1\",\"contractId\":\"testkit.encoder-sample\"," + "{\"envelopeVersion\":1,\"eventId\":\"01994e11-4d88-7000-8000-0000000000e1\",\"contractId\":\"testkit.encoder-sample\"," + "\"payloadVersion\":1,\"logicalDestination\":\"sample-events\"," + "\"aggregate\":{\"type\":\"sample\",\"id\":\"sample-1\",\"sequence\":3,\"eventIndex\":0}," + "\"occurredAt\":\"2026-09-28T01:02:03Z\",\"correlationId\":\"correlation-1\"," @@ -267,7 +267,7 @@ class JsonIntegrationEventEncoderTest { private static IntegrationEventDraft draft( SamplePayload payload, String destination) { return new IntegrationEventDraft<>( - new EventId("event-1"), + new EventId("01994e11-4d88-7000-8000-0000000000e1"), new ContractId("testkit.encoder-sample"), 1, new LogicalDestinationId(destination), diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java index c35b885f..398c108d 100644 --- a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java @@ -7,8 +7,13 @@ import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; class StartupRuleRunnerTest { @@ -103,6 +108,61 @@ class StartupRuleRunnerTest { assertThat(seen).containsExactly("resolved"); } + @Test + @DisplayName("설정 bean을 받는 non-static 규칙은 바인딩 안 된 설정으로 조용히 돌지 않고, 앞당긴 bean 이름을 대며 기동을 실패시킨다") + void aRuleThatPullsASettingsBeanForwardFailsTheBootInsteadOfReadingUnboundSettings() { + // given + ProbeRuleConfig.SEEN.clear(); + + // when + runner + .withPropertyValues("probe.name=bound") + .withUserConfiguration(ProbeRuleConfig.class) + .run( + context -> { + // then + assertThat(ProbeRuleConfig.SEEN).doesNotContainNull(); + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("probeRule") + .hasMessageContaining("probe-dev.caskeleton") + .hasMessageContaining("static"); + }); + } + + @Test + @DisplayName("규칙이 실행 중에 꺼내는 RequiredProductionSecrets가 다른 bean을 앞당기면 기동이 실패한다") + void aProductionSecretsBeanThatPullsItsConfigurationForwardFailsTheBoot() { + // when + runner + .withUserConfiguration(SecretReadingRuleConfig.class, NonStaticSecretsConfig.class) + .run( + context -> { + // then + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("secretReadingRule") + .hasMessageContaining("NonStaticSecretsConfig"); + }); + } + + @Test + @DisplayName("static이고 의존이 없는 RequiredProductionSecrets를 규칙이 실행 중에 읽는 것은 허용된다") + void aRuleMayReadStaticProductionSecretsWhenItRuns() { + // given + SecretReadingRuleConfig.SEEN.clear(); + + // when + runner + .withUserConfiguration(SecretReadingRuleConfig.class, StaticSecretsConfig.class) + .run( + context -> { + // then + assertThat(context).hasNotFailed(); + assertThat(SecretReadingRuleConfig.SEEN).containsExactly("APP_PROBE_SECRET"); + }); + } + private static StartupRule rule(StartupPhase phase, String summary, List violations) { return new StartupRule() { @Override @@ -121,4 +181,87 @@ class StartupRuleRunnerTest { } }; } + + /** The shape RR-06-01 found: a JavaBean settings class, and a rule that takes it. */ + @ConfigurationProperties("probe") + public static class ProbeSettings { + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + @Configuration(proxyBeanMethods = false) + @EnableConfigurationProperties(ProbeSettings.class) + static class ProbeRuleConfig { + static final List SEEN = new ArrayList<>(); + + @Bean + StartupRule probeRule(ProbeSettings settings) { + return new StartupRule() { + @Override + public StartupPhase phase() { + return StartupPhase.ENV_VALIDATION; + } + + @Override + public String summary() { + return "probe"; + } + + @Override + public List violations(Environment environment) { + SEEN.add(settings.getName()); + return List.of(); + } + }; + } + } + + @Configuration(proxyBeanMethods = false) + static class SecretReadingRuleConfig { + static final List SEEN = new ArrayList<>(); + + @Bean + static StartupRule secretReadingRule(ObjectProvider secrets) { + return new StartupRule() { + @Override + public StartupPhase phase() { + return StartupPhase.ENV_VALIDATION; + } + + @Override + public String summary() { + return "secrets"; + } + + @Override + public List violations(Environment environment) { + secrets.orderedStream().forEach(each -> SEEN.addAll(each.requiredSecrets(environment))); + return List.of(); + } + }; + } + } + + @Configuration(proxyBeanMethods = false) + static class StaticSecretsConfig { + @Bean + static RequiredProductionSecrets probeSecrets() { + return environment -> List.of("APP_PROBE_SECRET"); + } + } + + @Configuration(proxyBeanMethods = false) + static class NonStaticSecretsConfig { + @Bean + RequiredProductionSecrets probeSecrets() { + return environment -> List.of("APP_PROBE_SECRET"); + } + } } diff --git a/src/app-bootstrap/CLAUDE.md b/src/app-bootstrap/CLAUDE.md index 98ba21c7..4d816bcb 100644 --- a/src/app-bootstrap/CLAUDE.md +++ b/src/app-bootstrap/CLAUDE.md @@ -87,7 +87,9 @@ configurations, Redis as one 376-line class. this leaf. `runtime/startup/` keeps only `StartupFailureExceptionReporter`. - **An environment-only guard is a `StartupRule` bean** (`support.startup`): it returns violations, and the one `StartupRuleRunner` raises them before any other singleton exists (declare it with a - parameterless `static` `@Bean` method). A guard that needs another bean stays a bean. A + `static` `@Bean` method that takes only the `Environment`, the bean factory or an `ObjectProvider` + of static `RequiredProductionSecrets`; the runner fails the boot naming any other bean a rule + creates). A guard that needs another bean stays a bean. A capability's production secrets are the capability's: its module contributes a `RequiredProductionSecrets` bean, and `SecretSourceValidator` checks the names without knowing which roles exist. diff --git a/src/app-bootstrap/README.md b/src/app-bootstrap/README.md index 56902f31..3f6fc3ab 100644 --- a/src/app-bootstrap/README.md +++ b/src/app-bootstrap/README.md @@ -129,7 +129,11 @@ README의 "startup" 절에 있다. ### SecretSourceValidator - **prod 에서 깨지면 부팅 자체를 거부하는 fail-fast 가드다.** 두 가지 prod 불변식을 context refresh 완료 전에 강제한다. (1) `__LOCAL_DEV_` 접두사를 가진 dev/local 가짜 자격증명 값이 prod 프로파일에 - 도달하는 것은 잘못 로드된 사고이므로 부팅을 중단시킨다. (2) 레지스트리에서 `secret` + + 도달하는 것은 잘못 로드된 사고이므로 부팅을 중단시킨다. `fixture-` 접두사 값도 같다. 이 저장소가 + lane용으로 적어 둔 공개 비밀번호(`infra/redis-sdk/acl`의 Redis ACL fixture, compose lane의 + `REDIS_LANE_*`)라서, lane 환경이나 lane ACL 파일을 베낀 배포가 그대로 운영에 뜨는 것을 막는다 + (review 2026-11-03 RR-07-04). 비밀이 아닌 설정값이라도 prod에서 `fixture-`로 시작하면 거부되니 이름을 + 바꾼다. 실패 메시지는 변수 이름만 적고 값은 적지 않는다. (2) 레지스트리에서 `secret` + `prod_default: null`로 분류된 모든 키는 prod 에서 비어 있지 않게 주입돼야 한다 — 빈 시크릿으로 부팅하는 것은 금지다. dev/local 프로파일은 두 검사를 건너뛴다(`__LOCAL_DEV_*`가 의도된 로컬 폴백이므로). diff --git a/src/app-bootstrap/build.gradle b/src/app-bootstrap/build.gradle index 8b312763..8d093f16 100644 --- a/src/app-bootstrap/build.gradle +++ b/src/app-bootstrap/build.gradle @@ -122,10 +122,11 @@ sourceSets { } // Every capability a service can select — the commented runtimeOnly lines below — listed once. -// Two consumers read it: the whole-repository ArchUnit import (spec §7: the architecture suite sees +// Three consumers read it — the environment contract's metadata classpath (verifyEnvKeys, below) +// and these two: the whole-repository ArchUnit import (spec §7: the architecture suite sees // every module of this build and the sample, the shipped runtime only the selected ones; the // optional-platforms build is held by its own Gradle direction gate instead) and the qualification artifact the -// Compose lanes boot (qualificationBootJar, below). Neither reaches `bootJar`, `test` or +// Compose lanes boot (qualificationBootJar, below). None of them reaches `bootJar`, `test` or // `systemTest`, because a capability on a classpath is switched on there by its mere presence. // A new capability leaf is added here and as a commented line below; nowhere else. def capabilityProjects = [ @@ -479,6 +480,12 @@ def qualificationClasspath = compositionRuntimeClasspath('qualificationRuntimeCl dependencies { capabilityProjects.each { qualificationRuntimeClasspath project(it) } } +// The environment contract reads every selectable capability's configuration metadata from this +// classpath, so a module that ships typed settings is checked because it can be selected, and the +// task names no leaf (review 2026-11-03 RR-06-10). +tasks.named('verifyEnvKeys') { + metadataClasspath.from(qualificationClasspath) +} def qualificationBootJar = tasks.register('qualificationBootJar', org.springframework.boot.gradle.tasks.bundling.BootJar) { group = 'build' description = 'Assembles the Compose qualification jar: the default composition plus every capability.' diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java index 7017eacc..d64f500f 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java @@ -1,5 +1,7 @@ package dev.caskeleton.bootstrap.architecture; +import static com.tngtech.archunit.core.domain.AccessTarget.Predicates.declaredIn; +import static com.tngtech.archunit.core.domain.JavaCall.Predicates.target; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; @@ -20,6 +22,8 @@ import com.tngtech.archunit.lang.ArchRule; import com.tngtech.archunit.lang.ConditionEvents; import com.tngtech.archunit.lang.SimpleConditionEvent; import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import dev.caskeleton.application.messaging.event.IntegrationEventDrafts; import dev.caskeleton.application.security.RequiresPermission; import dev.caskeleton.application.security.SystemInvoked; import dev.caskeleton.application.usecase.CommandUseCase; @@ -442,6 +446,44 @@ class ApplicationBoundaryArchitectureTest { + "Authentication, so the gate would be decoration") .allowEmptyShould(true); + /** + * A {@link SystemInvoked} use case is a write with no permission check, so no transport may reach + * it. A bean of one fails startup ({@code PermissionEnforcementGuard}); this closes the other + * path, an inbound adapter that constructs or calls one itself (review 2026-11-03 RR-01-02). + */ + @ArchTest + static final ArchRule INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES = + noClasses() + .that() + .resideInAPackage("..adapter.inbound..") + .should() + .dependOnClassesThat() + .areAnnotatedWith(SystemInvoked.class) + .as( + "INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES: a @SystemInvoked use case " + + "declares no permission because only the system calls it; an inbound adapter " + + "that reaches it runs a write with no authorization check. Its composition " + + "constructs it and hands it to the scheduler that calls it.") + .allowEmptyShould(true); + + /** + * {@link IntegrationEventDrafts} is where contract id, version, destination and correlation are + * decided for every feature. A feature that calls the ten-field draft constructor itself restates + * those rules, which is the drift review 2026-11-01 01-09 removed (RR-01-03). + */ + @ArchTest + static final ArchRule INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER = + noClasses() + .that() + .doNotBelongToAnyOf(IntegrationEventDrafts.class, IntegrationEventDraft.class) + .should() + .callConstructorWhere(target(declaredIn(IntegrationEventDraft.class))) + .as( + "INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER: production code builds an " + + "IntegrationEventDraft only through IntegrationEventDrafts.draft(...), which " + + "owns the contract fields, the correlation fallback and the single-tenant scope") + .allowEmptyShould(true); + @ArchTest static final ArchRule APPLICATION_AND_DOMAIN_DO_NOT_DEPEND_ON_SPRING_SECURITY = noClasses() 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 916d9945..b4da42bc 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 @@ -114,9 +114,11 @@ class ArchRuleDiscoveryContractTest { "IDENTIFIER_ADAPTER_DOES_NOT_DEPEND_ON_OTHER_ADAPTERS_OR_BOOTSTRAP", "INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES", "INBOUND_ADAPTERS_DO_NOT_DEPEND_ON_OUTBOUND_ADAPTERS", + "INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES", "INBOUND_PORT_IMPLEMENTATIONS_DECLARE_A_CAPABILITY", "INBOUND_PORT_IMPLEMENTATIONS_DECLARE_CAPABILITY", "INBOUND_PORT_IMPLEMENTATIONS_END_WITH_USE_CASE", + "INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER", "MANAGEMENT_SECURITY_DOES_NOT_DEPEND_ON_HEALTH_INTERNALS", "MAPPERS_DO_NOT_DEPEND_ON_WEB_OR_APPLICATION_BOUNDARIES", "MESSAGING_OUTBOUND_PUBLIC_INSTANCE_METHODS_DO_NOT_LEAK_ADAPTER_TYPES_THROUGH_GENERICS", diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java index 369966ef..2eb2d35f 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java @@ -8,16 +8,19 @@ import com.tngtech.archunit.lang.EvaluationResult; import dev.caskeleton.application.architecture.violations.ApplicationDiagnosticFrameworkViolation; import dev.caskeleton.bootstrap.architecture.allowed.application.CleanProjectionQueryPort; import dev.caskeleton.bootstrap.architecture.fixtures.application.RootWriteTransactionBoundaryUseCase; +import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemInvokedCallingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.RawExternalResponseFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.messaging.GenericTypeLeakingAdapterFixture; import dev.caskeleton.bootstrap.architecture.violations.application.BulkWriteWithoutWriteAccessUseCase; import dev.caskeleton.bootstrap.architecture.violations.application.FixtureRepository; import dev.caskeleton.bootstrap.architecture.violations.application.GenericLeakQueryPort; +import dev.caskeleton.bootstrap.architecture.violations.application.HandBuiltIntegrationEventDraftFixture; import dev.caskeleton.bootstrap.architecture.violations.application.JakartaValidationApplicationFixture; import dev.caskeleton.bootstrap.architecture.violations.application.MissingTransactionBoundaryUseCase; import dev.caskeleton.bootstrap.architecture.violations.application.OutboundWithoutPermissionUseCase; import dev.caskeleton.bootstrap.architecture.violations.application.RawLeakQueryPort; import dev.caskeleton.bootstrap.architecture.violations.application.ReadOnlyRepositoryWriteUseCase; +import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; import dev.caskeleton.bootstrap.architecture.violations.domain.AnnotatedPublicNoArgValueObjectFixture; import dev.caskeleton.bootstrap.architecture.violations.domain.JakartaValidationDomainFixture; import dev.caskeleton.bootstrap.architecture.violations.domain.entity.FakeDomainEntity; @@ -154,6 +157,35 @@ class ArchitectureViolationFixtureTest { new ClassFileImporter() .importPackages("dev.caskeleton.bootstrap.architecture.violations.secrets"); + // Review 2026-11-03 RR-01-02: the controller and the use case it reaches, and nothing else, so + // the rule is proven on the one dependency it forbids. + private static final JavaClasses SYSTEM_INVOKED_FROM_TRANSPORT_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + SystemInvokedCallingControllerFixture.class, SystemInvokedFixtureUseCase.class); + + // Review 2026-11-03 RR-01-03: one class that builds the draft by hand. + private static final JavaClasses HAND_BUILT_DRAFT_FIXTURE_ONLY = + new ClassFileImporter().importClasses(HandBuiltIntegrationEventDraftFixture.class); + + @Test + void anInboundAdapterThatCallsASystemInvokedUseCaseIsCaught() { + EvaluationResult result = + ApplicationBoundaryArchitectureTest.INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES + .evaluate(SYSTEM_INVOKED_FROM_TRANSPORT_FIXTURE_ONLY); + + assertThat(result.hasViolation()).isTrue(); + } + + @Test + void aFeatureThatBuildsAnIntegrationEventDraftByHandIsCaught() { + EvaluationResult result = + ApplicationBoundaryArchitectureTest.INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER + .evaluate(HAND_BUILT_DRAFT_FIXTURE_ONLY); + + assertThat(result.hasViolation()).isTrue(); + } + @Test void noRefreshScopeAnywhereCatchesRefreshScopeAnnotation() { EvaluationResult result = diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java index db694f5a..2411cf6e 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java @@ -6,6 +6,7 @@ import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ClassFileImporter; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.JpaArchitectureRules; import jakarta.persistence.Entity; +import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -101,6 +102,29 @@ class JpaProductionArchitectureTest { JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(productionClasses); } + @Test + @DisplayName("알림·파일 서버 저장소 leaf의 엔티티는 그 leaf 밖의 운영 코드가 쓰지 않는다") + void capabilityPersistenceEntitiesAreUsedOnlyInsideTheirLeaf() { + // given: both leaves' entities are in the import, so the rule cannot pass by finding nothing + List leaves = + List.of( + "dev.caskeleton.adapter.outbound.persistence.notification", + "dev.caskeleton.adapter.outbound.persistence.fileserver"); + assertThat(leaves) + .allSatisfy( + leaf -> + assertThat(productionClasses.stream()) + .anyMatch( + type -> + type.getPackageName().startsWith(leaf) + && type.isAnnotatedWith(Entity.class))); + + // then + leaves.forEach( + leaf -> + JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf(leaf).check(productionClasses)); + } + @Test @DisplayName("no entity uses two audit mechanisms at once") void noEntityUsesTwoAuditMechanismsAtOnce() { diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemInvokedCallingControllerFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemInvokedCallingControllerFixture.java new file mode 100644 index 00000000..dfe5f538 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemInvokedCallingControllerFixture.java @@ -0,0 +1,17 @@ +package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller; + +import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; + +/** + * Negative fixture for {@code INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES}: an inbound + * adapter that calls a {@code @SystemInvoked} use case, a write with no permission gate, straight + * from a transport (review 2026-11-03 RR-01-02). + */ +public class SystemInvokedCallingControllerFixture { + + private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase(); + + public void trigger() { + useCase.handle(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/HandBuiltIntegrationEventDraftFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/HandBuiltIntegrationEventDraftFixture.java new file mode 100644 index 00000000..d95d3634 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/HandBuiltIntegrationEventDraftFixture.java @@ -0,0 +1,40 @@ +package dev.caskeleton.bootstrap.architecture.violations.application; + +import dev.caskeleton.application.messaging.contract.ContractId; +import dev.caskeleton.application.messaging.contract.IntegrationPayload; +import dev.caskeleton.application.messaging.contract.LogicalDestinationId; +import dev.caskeleton.application.messaging.event.AggregateIdentity; +import dev.caskeleton.application.messaging.event.AggregateOrder; +import dev.caskeleton.application.messaging.event.EventId; +import dev.caskeleton.application.messaging.event.IntegrationEventDraft; +import java.time.Instant; +import java.util.Optional; + +/** + * Negative fixture for {@code INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER}: a feature + * that assembles the ten-field draft itself and so restates the correlation and tenant rules {@code + * IntegrationEventDrafts} owns (review 2026-11-01 01-09, 2026-11-03 RR-01-03). + */ +public final class HandBuiltIntegrationEventDraftFixture { + + private HandBuiltIntegrationEventDraftFixture() {} + + public static

        IntegrationEventDraft

        draft( + EventId eventId, + ContractId contractId, + LogicalDestinationId destination, + AggregateIdentity aggregate, + P payload) { + return new IntegrationEventDraft<>( + eventId, + contractId, + 1, + destination, + aggregate, + AggregateOrder.first(), + Instant.EPOCH, + eventId.value(), + Optional.empty(), + payload); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/SystemInvokedFixtureUseCase.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/SystemInvokedFixtureUseCase.java new file mode 100644 index 00000000..00e5fc4d --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/SystemInvokedFixtureUseCase.java @@ -0,0 +1,16 @@ +package dev.caskeleton.bootstrap.architecture.violations.application; + +import dev.caskeleton.application.security.SystemInvoked; + +/** + * A use case only the system calls. Not a violation on its own: it is what {@code + * SystemInvokedCallingControllerFixture} reaches, the transport path {@code + * INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES} forbids. + */ +@SystemInvoked(reason = "fixture: a scheduler calls it") +public final class SystemInvokedFixtureUseCase { + + public void handle() { + // fixture + } +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java index 807cda18..7d4c1662 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java @@ -6,8 +6,10 @@ import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; import dev.caskeleton.adapter.outbound.support.startup.StartupRule; import dev.caskeleton.application.secret.SecretSourcePort; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Supplier; @@ -32,6 +34,25 @@ public final class SecretSourceValidator implements StartupRule { /** Prefix marking a dev/local fake credential; forbidden to reach the prod profile. */ static final String LOCAL_DEV_SENTINEL_PREFIX = "__LOCAL_DEV_"; + /** + * Prefix of the passwords this repository writes down for its lanes: the Redis ACL fixtures in + * {@code infra/redis-sdk/acl} and the Compose lanes' {@code REDIS_LANE_*} values that connect + * with them. They are public — anyone who can read the repository has them — so under {@code + * prod} they are refused like the sentinel (review 2026-11-03 RR-07-04). A deployment that copied + * a lane's environment — which is also what an application needs to authenticate against a Redis + * that loaded the lane ACL file — would start with credentials it does not own; this is the one + * place that sees every value before anything connects. It cannot see a Redis server that loaded + * that file while the application uses real passwords; the ACL README says why no deployment + * loads it. + */ + static final String REPOSITORY_FIXTURE_PREFIX = "fixture-"; + + /** Values that are public by construction and so can never be a production secret. */ + private static final Map PUBLIC_CREDENTIAL_PREFIXES = + Map.of( + LOCAL_DEV_SENTINEL_PREFIX, "sentinel credential", + REPOSITORY_FIXTURE_PREFIX, "repository fixture password (public, infra/redis-sdk/acl)"); + /** * Secret keys that must be injected under the {@code prod} profile whatever the deployment * selected. The relational credential is not one of them: persistence-jpa contributes it while it @@ -68,7 +89,8 @@ public final class SecretSourceValidator implements StartupRule { @Override public String remedy() { return "inject real non-blank secrets from the secret manager / mounted environment; " - + "local/dev sentinel credentials are forbidden in prod."; + + "local/dev sentinel credentials and the repository's fixture-* passwords are forbidden" + + " in prod."; } @Override @@ -77,31 +99,44 @@ public final class SecretSourceValidator implements StartupRule { return List.of(); } List violations = new ArrayList<>(); - collectLocalDevSentinelViolations(environment, violations); + collectPublicCredentialViolations(environment, violations); collectMissingSecretViolations(environment, violations); return violations; } - private static void collectLocalDevSentinelViolations( + /** + * Names every property whose value is public by construction. Every property source is read, the + * process environment included, because a credential reference ({@code + * secret://@environment/}) may point at any variable name. The value itself is + * never put in the message. + */ + private static void collectPublicCredentialViolations( Environment environment, List violations) { if (!(environment instanceof ConfigurableEnvironment configurable)) { return; } - Set offenders = new LinkedHashSet<>(); + Map offenders = new LinkedHashMap<>(); for (PropertySource source : configurable.getPropertySources()) { if (source instanceof EnumerablePropertySource enumerable) { for (String name : enumerable.getPropertyNames()) { - Object value = enumerable.getProperty(name); - if (value instanceof String text && text.startsWith(LOCAL_DEV_SENTINEL_PREFIX)) { - offenders.add(name); + if (enumerable.getProperty(name) instanceof String text) { + PUBLIC_CREDENTIAL_PREFIXES.keySet().stream() + .filter(text::startsWith) + .findFirst() + .ifPresent(prefix -> offenders.putIfAbsent(name, prefix)); } } } } - for (String offender : offenders) { - violations.add( - "'" + LOCAL_DEV_SENTINEL_PREFIX + "' sentinel credential is configured for " + offender); - } + offenders.forEach( + (offender, prefix) -> + violations.add( + "'" + + prefix + + "' " + + PUBLIC_CREDENTIAL_PREFIXES.get(prefix) + + " is configured for " + + offender)); } private void collectMissingSecretViolations(Environment environment, List violations) { diff --git a/src/app-bootstrap/src/main/resources/config/observability.yml b/src/app-bootstrap/src/main/resources/config/observability.yml index 5b5b6d1a..6aedc565 100644 --- a/src/app-bootstrap/src/main/resources/config/observability.yml +++ b/src/app-bootstrap/src/main/resources/config/observability.yml @@ -111,8 +111,9 @@ logging: # DEBUG here prints SQL once JPA/jdbc is wired in org.hibernate.SQL: ${APP_LOG_LEVEL_SQL:INFO} -# Module-scoped knobs. Each block is bound into a *Settings @ConfigurationProperties -# record in the corresponding module, which is where allowed-value validation lives. +# Module-scoped knobs, each read and validated by the module that owns it (a settings record bound +# by StrictSettingsBinder, which refuses an unknown key). `app.logging` has no settings record: +# logback-spring.xml reads it () and LoggingConfigurationRule validates it. app: logging: file: diff --git a/src/app-bootstrap/src/main/resources/config/runtime.yml b/src/app-bootstrap/src/main/resources/config/runtime.yml index 3309b75c..e1ca9d8f 100644 --- a/src/app-bootstrap/src/main/resources/config/runtime.yml +++ b/src/app-bootstrap/src/main/resources/config/runtime.yml @@ -19,7 +19,8 @@ app: async: # feature-background-job-async-contract D7 — @Async ThreadPoolTaskExecutor pool sizing. # Registry SSOT: docs/registries/env-keys.yaml (APP_ASYNC_EXECUTOR_* rows 1337-1377). - # Bound into AsyncExecutorSettings @ConfigurationProperties(prefix = "app.async.executor"). + # Bound into the AsyncExecutorSettings record by StrictSettingsBinder (prefix "app.async.executor"), + # which refuses an unknown key under the prefix instead of ignoring it. # Bounded queue is mandatory (D7) — an unbounded queue makes max-size unreachable. executor: # int >= 1 (positive_int). Always-alive worker count. diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/BootstrapCapabilityReachabilitySystemTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/BootstrapCapabilityReachabilitySystemTest.java index adce9ed6..f6a89f02 100644 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/BootstrapCapabilityReachabilitySystemTest.java +++ b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/BootstrapCapabilityReachabilitySystemTest.java @@ -27,7 +27,7 @@ class BootstrapCapabilityReachabilitySystemTest { try (ConfigurableApplicationContext context = ShippedCompositionHarness.shippedComposition("local") .run(ShippedCompositionHarness.allOffArguments())) { - assertThat(context.containsBean("outboxLeaderElection")).isFalse(); + assertThat(context.containsBean("outboxSettings")).isFalse(); assertThat(context.containsBean("distributedLockProvider")).isFalse(); assertThat(context.getBeansOfType(IdempotencyExecutor.class)).isEmpty(); assertThat( diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java index 8ff57184..546ec57d 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java @@ -8,6 +8,7 @@ import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Duration; import java.util.List; import java.util.Map; import java.util.regex.Matcher; @@ -15,6 +16,7 @@ import java.util.regex.Pattern; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.springframework.boot.convert.DurationStyle; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; @@ -407,7 +409,13 @@ class DeveloperExperienceContractTest { // given Map app = requireMap(requireMap(parseYamlMap(read("docker-compose.yml")), "services"), "app"); - int webDrainSeconds = 30; + // The web drain is the value this service runs with — APP_SERVER_SHUTDOWN_TIMEOUT's fallback in + // the same Compose service — not a number copied here, so a changed default changes the sum + // (review 2026-11-03 RR-06-08). + long webDrainSeconds = + composeFallback( + requireString(requireMap(app, "environment"), "APP_SERVER_SHUTDOWN_TIMEOUT")) + .toSeconds(); int preStopSeconds = 5; int marginSeconds = 5; @@ -417,7 +425,7 @@ class DeveloperExperienceContractTest { // then // Spring finishes the lifecycle phase (the web server's graceful drain) before it destroys the // async executor, which then waits for its queue: the two run one after the other (07-07). - assertThat(Integer.parseInt(grace.replace("s", ""))) + assertThat(Long.parseLong(grace.replace("s", ""))) .isGreaterThanOrEqualTo( webDrainSeconds + AsyncExecutorConfig.AWAIT_TERMINATION_SECONDS @@ -621,6 +629,15 @@ class DeveloperExperienceContractTest { return (List) value; } + /** The fallback of a Compose interpolation {@code ${NAME:-30s}}, as a duration. */ + private static Duration composeFallback(String interpolation) { + Matcher fallback = Pattern.compile("^\\$\\{[A-Z0-9_]+:-([^}]+)}$").matcher(interpolation); + assertThat(fallback.matches()) + .as("a ${NAME:-default} interpolation: " + interpolation) + .isTrue(); + return DurationStyle.detectAndParse(fallback.group(1)); + } + private static List requireStringList(Map owner, String key) { List values = requireList(owner, key); assertThat(values).allMatch(String.class::isInstance); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SampleRuntimeDefaultsContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SampleRuntimeDefaultsContractTest.java index 543e31cb..805a300f 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SampleRuntimeDefaultsContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SampleRuntimeDefaultsContractTest.java @@ -4,12 +4,21 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.IOException; +import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -19,8 +28,10 @@ import org.yaml.snakeyaml.constructor.SafeConstructor; /** * The sample keeps the default composition's runtime defaults, so a number measured on the sample — - * thread count, pool wait — says something about the composition a service ships (09-08). It reads - * two configuration files, so it runs in the pull-request {@code repository-contract} lane (08-03). + * thread count, pool wait — says something about the composition a service ships (09-08), and it + * carries only settings something on its classpath reads. It reads configuration files, build + * scripts and production sources, so it runs in the pull-request {@code repository-contract} lane + * (08-03). */ @Tag("repository-contract") class SampleRuntimeDefaultsContractTest { @@ -69,6 +80,101 @@ class SampleRuntimeDefaultsContractTest { assertThat(connectionTimeout).isNull(); } + @Test + @DisplayName("샘플 application.yml의 app.* 설정 묶음은 샘플 classpath에 있는 모듈 코드가 읽는다") + void everySampleAppSettingGroupIsReadByAModuleOnTheSampleClasspath() throws IOException { + // given + Set groups = new TreeSet<>(); + for (Object document : loadAll("src/sample-portfolio/src/main/resources/application.yml")) { + if (document instanceof Map map && map.get("app") instanceof Map app) { + app.keySet().forEach(key -> groups.add(String.valueOf(key))); + } + } + Set classpath = sampleRuntimeModules(); + + // when + Set unread = new TreeSet<>(); + for (String group : groups) { + Pattern reader = Pattern.compile("app\\." + Pattern.quote(group) + "[\".}]"); + if (classpath.stream().noneMatch(module -> anyMainSourceMatches(module, reader))) { + unread.add("app." + group); + } + } + + // then + // The sample is copied first. A block nothing on its classpath reads — the HTTP client's + // timeouts with no HTTP client module, a messaging broker with no messaging module — is a + // setting the copier believes is in force and is not (review 2026-11-03 RR-06-06, 09-08). + assertThat(unread) + .as("app.* groups in the sample's application.yml that nothing reads") + .isEmpty(); + } + + /** The source directories of the sample and every project its production configurations reach. */ + private static Set sampleRuntimeModules() throws IOException { + String registry = + Files.readString(REPOSITORY_ROOT.resolve("src/config/architecture/modules.json")); + Map sourceOf = new LinkedHashMap<>(); + Matcher module = + Pattern.compile("\"gradle_path\":\\s*\"([^\"]+)\",\\s*\"source_path\":\\s*\"([^\"]+)\"") + .matcher(registry); + while (module.find()) { + sourceOf.put(module.group(1), module.group(2)); + } + sourceOf.put(":sample-portfolio", "src/sample-portfolio"); + Pattern edge = + Pattern.compile( + "(?m)^\\s*(?:api|implementation|runtimeOnly)\\s*\\(?\\s*project\\(\\s*['\"](:[^'\"]+)['\"]"); + Set reached = new LinkedHashSet<>(); + Deque pending = new ArrayDeque<>(List.of(":sample-portfolio")); + Set seen = new LinkedHashSet<>(); + while (!pending.isEmpty()) { + String path = pending.pop(); + String source = sourceOf.get(path); + if (!seen.add(path) || source == null) { + continue; + } + Path directory = REPOSITORY_ROOT.resolve(source); + reached.add(directory); + Matcher dependency = edge.matcher(Files.readString(directory.resolve("build.gradle"))); + while (dependency.find()) { + pending.add(dependency.group(1)); + } + } + return reached; + } + + private static boolean anyMainSourceMatches(Path module, Pattern reader) { + Path sources = module.resolve("src/main/java"); + if (!Files.isDirectory(sources)) { + return false; + } + try (Stream files = Files.walk(sources)) { + return files + .filter(file -> file.toString().endsWith(".java")) + .anyMatch( + file -> { + try { + return reader.matcher(Files.readString(file)).find(); + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + }); + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + } + + private static List loadAll(String relative) throws IOException { + LoaderOptions options = new LoaderOptions(); + options.setMaxAliasesForCollections(0); + List documents = new ArrayList<>(); + new Yaml(new SafeConstructor(options)) + .loadAll(Files.readString(REPOSITORY_ROOT.resolve(relative))) + .forEach(documents::add); + return documents; + } + private static String defaultOf(Object value) { if (value == null) { return null; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/outbox/OutboxStatusRegistryContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/outbox/OutboxStatusRegistryContractTest.java index d8bf639c..eed9079e 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/outbox/OutboxStatusRegistryContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/outbox/OutboxStatusRegistryContractTest.java @@ -3,24 +3,28 @@ package dev.caskeleton.bootstrap.contract.outbox; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxRelayResult; import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import dev.caskeleton.shared.error.OperationalError; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; /** - * Contract test — {@link OutboxEventStatus} 5 values ↔ {@code metrics.yaml} {@code - * outbox.pending.size} allowed_values, and {@code OUTBOX_*} 2 error codes ↔ {@code - * error-codes.yaml} category/retryable. + * Contract test — {@link OutboxEventStatus} values ↔ {@code metrics.yaml} {@code + * outbox.pending.size} allowed_values, {@link OutboxRelayResult.Outcome} values ↔ {@code + * outbox.publisher.published.total} {@code outcome} allowed_values, and {@code OUTBOX_*} 2 error + * codes ↔ {@code error-codes.yaml} category/retryable. */ @Tag("document-contract") class OutboxStatusRegistryContractTest { @@ -79,6 +83,43 @@ class OutboxStatusRegistryContractTest { .containsExactlyInAnyOrderElementsOf(registryStatuses); } + /** + * The relay counts every cycle outcome under {@code outcome}; the registry is what a dashboard or + * an alert reads the allowed values from. {@code RELEASED} was counted and not registered, and + * {@code IN_FLIGHT}, which no cycle produces, was registered (re-review 2026-11-03 RR-05-06). + */ + @Test + @DisplayName("relay 회차 결과 값과 metrics.yaml의 published.total outcome 허용 값이 같다") + void relayOutcomesMatchMetricsYamlPublishedTotalOutcomeAllowedValues() { + // given + Set enumOutcomes = + Arrays.stream(OutboxRelayResult.Outcome.values()) + .map(Enum::name) + .collect(Collectors.toSet()); + + // when + List registered = allowedValues("outbox.publisher.published.total", "outcome"); + + // then + assertThat(registered).containsExactlyInAnyOrderElementsOf(enumOutcomes); + } + + @SuppressWarnings("unchecked") + private static List allowedValues(String metric, String tag) { + List> metrics = (List>) metricsRoot.get("metrics"); + Map row = + metrics.stream() + .filter(m -> metric.equals(m.get("name"))) + .findFirst() + .orElseThrow(() -> new AssertionError(metric + " must exist in metrics.yaml")); + return ((List>) row.get("tags")) + .stream() + .filter(t -> tag.equals(t.get("name"))) + .findFirst() + .map(t -> (List) t.get("allowed_values")) + .orElseThrow(() -> new AssertionError(metric + " must have a '" + tag + "' tag")); + } + @Test void outboxErrorCodesMatchRegistryCategoryAndRetryable() { Map> codeIndex = 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 8b347bbe..a44749ba 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 @@ -68,7 +68,8 @@ class ErrorDetailExposureSafetyValidatorTest { static class ValidatorConfig { @Bean - ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator(Environment environment) { + static ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator( + Environment environment) { return new ErrorDetailExposureSafetyValidator(); } } 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 0d594af4..9a242e87 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 @@ -78,7 +78,7 @@ class RuntimeNumericBoundsValidatorTest { @Configuration static class ValidatorConfig { @Bean - RuntimeNumericBoundsValidator runtimeNumericBoundsValidator(Environment environment) { + static RuntimeNumericBoundsValidator runtimeNumericBoundsValidator(Environment environment) { return new RuntimeNumericBoundsValidator(); } } 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 4b193fcf..aaeabb20 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 @@ -103,6 +103,53 @@ class SecretSourceValidatorTest { .run(context -> assertThat(context).hasNotFailed()); } + // ---- repository fixture passwords (review 2026-11-03 RR-07-04) -------------------------- + + @Test + @DisplayName("prod에서 비밀값이 저장소 fixture 비밀번호(fixture-)면 그 변수를 짚어 기동을 거부한다") + void prodProfileWithARepositoryFixturePasswordFailsStartup() { + // given + ApplicationContextRunner prodWithLaneFixture = + runner + .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) + .withPropertyValues(allRequiredSecretsPresent()) + // The Compose Redis lanes' value: a public password from infra/redis-sdk/acl, which a + // deployment that copied the lane's environment would carry into production. + .withPropertyValues("REDIS_LANE_APPLICATION_PASSWORD=fixture-application"); + + // when + prodWithLaneFixture.run( + context -> { + // then + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .isInstanceOfSatisfying( + StartupFailureException.class, + e -> + assertThat(e.errorCode()) + .isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) + .hasStackTraceContaining("fixture-") + .hasStackTraceContaining("REDIS_LANE_APPLICATION_PASSWORD"); + }); + } + + @Test + @DisplayName("prod가 아니면 저장소 fixture 비밀번호(fixture-)로도 기동한다") + void nonProdProfileWithARepositoryFixturePasswordStarts() { + // given + ApplicationContextRunner localWithLaneFixture = + runner + .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("local")) + .withPropertyValues("REDIS_LANE_APPLICATION_PASSWORD=fixture-application"); + + // when + localWithLaneFixture.run( + context -> { + // then + assertThat(context).hasNotFailed(); + }); + } + // ---- required-secret presence guard (§테스트 계약) ----------------------- @Test diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index 917d0a4b..93780a35 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -69,7 +69,9 @@ Package root: `dev.caskeleton.application`. | `capability.Idempotency` | `IDEMPOTENT` / `KEYED` / `NOT_IDEMPOTENT`. | | `capability.RepositoryAccess` | `NONE` / `READ_REPOSITORY` / `WRITE_REPOSITORY`. | | `messaging.contract.IntegrationEventContractContribution

        ` | Closed exact-record payload type, canonical component order, local schema identity/hash and provider-neutral descriptor contribution. | -| `messaging.event.IntegrationEventDraft

        ` | Typed semantic event before local encoding; never JSON, Kafka or persistence state. | +| `messaging.event.IntegrationEventDraft

        ` | Typed semantic event before local encoding; never JSON, Kafka or persistence state. Built only through `IntegrationEventDrafts` (`INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`). | +| `messaging.event.IntegrationEventDrafts` | The one way a feature builds a draft: contract id, version and destination from the contract, correlation from the request when canonical (else the event id), `SINGLE_TENANT_SCOPE` for a feature without tenants. | +| `messaging.event.IntegrationIdentity` | The one grammar and the length bounds of event, correlation/causation and aggregate ids. Test a value with `isCanonical(value, bound)`; never copy the pattern. | | `messaging.event.ValidatedIntegrationEvent` | Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. | | `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter (the template's: `adapter:outbound:support` `JsonIntegrationEventEncoder`). | | `outbox.OutboxAppendPort` | The one outbox append: a `ValidatedIntegrationEvent`, in the caller's write transaction. | @@ -77,9 +79,10 @@ Package root: `dev.caskeleton.application`. ## Notification (NOTIF-ADR-005) -`..notification.platform..` (leaf `application-notification`) is canonical. The R1 types directly -under `dev.caskeleton.application.notification` were removed on 2026-09-25; only the simple -`NotificationPort`, `Notification` and `NotificationChannel` remain there. +None of the notification types are in this leaf. `..notification.platform..` and the simple +`NotificationPort`, `Notification` and `NotificationChannel` directly under +`dev.caskeleton.application.notification` all belong to leaf `application-notification`; the shared +package prefix is the only link. The R1 orchestration types were removed on 2026-09-25. ## Naming convention @@ -197,9 +200,12 @@ application-core never self-registers with a DI framework. It is **not final**: declares `@RequiresPermission`, the web adapter enforces it through a CGLIB proxy, and CGLIB cannot subclass a final class (`RequiresPermissionProxyabilityTest`). It is registered as a bean for the same reason — a use case built with `new` is never checked. A use case only the system calls (a -scheduler, a relay) carries `@SystemInvoked(reason = ...)` instead of a permission and is not a bean. -A composition with `@RequiresPermission` beans but no enforcing advisor fails startup -(`composition:service-runtime` `PermissionEnforcementGuard`). +scheduler, a relay) carries `@SystemInvoked(reason = ...)` instead of a permission and is not a bean: +it is a write with no permission check, so a transport must not reach it. Both halves are enforced — +a `@SystemInvoked` bean fails startup, and an inbound adapter that depends on one fails +`INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES`. A composition with `@RequiresPermission` +beans but no enforcing advisor fails startup too (`composition:service-runtime` +`PermissionEnforcementGuard`, both checks). ## Allowed transactional shapes diff --git a/src/application-core/README.md b/src/application-core/README.md index a11b353b..b86059ed 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -32,7 +32,16 @@ Cache도 같은 원칙을 따른다. `cache` 패키지에는 cache-redis가 구 - `IntegrationEventDraft`는 canonical event/aggregate/order/correlation identity와 typed payload를 보유한다. tenant가 없는 모드도 null 대신 canonical system tenant scope를 `AggregateIdentity`에 넣어 dedupe/order identity가 PostgreSQL nullable uniqueness에 기대지 - 않게 한다. + 않게 한다. 새 event의 event id와 causation id는 정규 소문자 UUIDv7이어야 한다 + (`IntegrationIdentity.isCanonicalUuidV7`). messaging platform의 `MessageId`가 그것만 바꾸지 않고 + 싣기 때문이다. draft가 거부하므로 그런 id는 업무 트랜잭션 안에서 실패하고, 커밋된 뒤 relay에서 + DEAD가 되지 않는다(리뷰 2026-11-01 06-06, 재리뷰 2026-11-03 RR-05-04). 저장 문법 `EventId`는 + 이 규칙 전에 쓰인 행을 읽으려고 넓게 남아 있다. +- draft는 `IntegrationEventDrafts.draft(...)`로만 만든다. 계약 id·버전·목적지, correlation + fallback(요청 값이 `IntegrationIdentity` 문법에 맞지 않으면 event id), tenant 없는 기능의 + `SINGLE_TENANT_SCOPE`가 거기 한 번 있다. 운영 코드가 생성자를 직접 부르면 + `INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`가 막는다. 식별자 문법·길이는 + `IntegrationIdentity`가 정본이고, 값을 미리 검사할 때는 `isCanonical(value, bound)`를 부른다. - `IntegrationEventEncoderPort` 뒤의 adapter가 deterministic encoding을 수행하고 `ValidatedIntegrationEvent`를 돌려준다. 템플릿의 구현은 `adapter:outbound:support`의 `JsonIntegrationEventEncoder`다(envelope v1 + payload record의 결정적 JSON, 선언한 schema hash를 @@ -43,9 +52,38 @@ Cache도 같은 원칙을 따른다. `cache` 패키지에는 cache-redis가 구 payload/envelope byte limit, sensitivity classification, same-event requeue horizon만 표현한다. physical topic, Kafka cluster/security topology는 deployment binding의 책임이다. -이 단계의 완성 범위는 **framework-free semantic contract R1**이다. JSON Schema validator와 -deterministic writer, Kafka ACK producer, PostgreSQL outbox append/relay는 후속 R2 작업이며 여기서 -구현되었거나 검증됐다고 주장하지 않는다. +이 절의 타입은 framework-free semantic contract다. 결정적 writer는 `adapter:outbound:support`의 +`JsonIntegrationEventEncoder`, outbox append·claim은 `adapter:outbound:persistence-jpa`, relay 조립은 +`composition:outbox-relay`, 발행은 `adapter:outbound:messaging`의 platform bridge가 맡는다. payload를 +JSON Schema로 매번 검증하는 validator는 템플릿에 없다(서비스가 encoder bean을 바꿔 둔다). + +### payload version 올리기 (리뷰 2026-11-01 06-10) + +payload schema는 version마다 `contracts/messaging//v.schema.json` 파일 하나다. 한 번 +출시한 version 파일은 고치지 않는다. 이미 그 version으로 쓰인 event가 outbox·broker·DLQ에 남아 있고, +소비자는 그 schema로 만들어져 있다. 그래서 schema를 가진 leaf는 출시한 version의 SHA-256을 +`src/test/resources/contracts/released-payload-schemas.sha256`에 고정하고, testFixtures의 +`ReleasedPayloadSchemaContract`를 상속한 테스트가 두 가지를 막는다. + +- 출시한 version 파일의 바이트가 바뀌면 실패한다(필드 삭제·타입 변경 같은 깨지는 변경 포함). +- 고정되지 않은 version 파일이 있으면 실패한다. 새 version은 manifest에 한 줄을 더하는 순간 출시된다. + +필드를 바꾸거나 지우거나 더하는 변경은 새 version으로 낸다(설계 문서 2026-07-28 §14.4 STRICT_VERSIONED). + +1. 새 version 추가: `v.schema.json`, 새 payload record, 새 `IntegrationEventContractContribution`. + 옛 version의 contribution은 그대로 둔다. encoder catalog는 `(contractId, payloadVersion)`마다 하나라 + 두 version이 함께 등록된다. +2. 소비자 배포: 모든 소비자가 v과 v을 둘 다 읽게 한다. outbox에 이미 쌓인 v 행은 저장된 + 바이트 그대로 나가므로, 생산자를 바꾼 뒤에도 한동안 두 version이 함께 도착한다. +3. 생산자 전환: draft를 v contract로 만든다. 이 커밋에서 manifest에 v 줄을 더한다. +4. 옛 version 제거: outbox·broker·DLQ·archive에 v이 더 남지 않았을 때만 contribution과 파일을 지우고 + manifest 줄도 지운다. 지우는 줄은 리뷰에서 보이는 변경이다. + +고른 방법과 버린 대안: 출시한 version 파일의 해시 고정(위). 버린 대안 — 직전 version과 새 version의 +JSON Schema diff로 호환성을 검사하는 fixture: payload schema가 닫혀 있어(`unevaluatedProperties: false`) +필드 하나를 더해도 옛 소비자의 검증이 깨지므로, diff는 거의 모든 새 version을 "깨짐"으로 판정한다. +설계도 diff heuristic으로 호환성을 주장하지 않기로 했다(§14.4). 외부 schema registry 도입 — 이 템플릿 +범위에 비해 운영 비용이 크다. --- @@ -367,9 +405,14 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. - 발행 성공(`CONFIRMED`) → `inWrite { markPublished }` → `PUBLISHED`. - 확정 거부(`REJECTED_BEFORE_SEND`·`REJECTED_AFTER_BROKER`) → 시도 예산과 무관하게 바로 `markDead`. - 일시적 실패(`AMBIGUOUS`·`REJECTED_RETRYABLE`, 즉 `OutboxPublishOutcome.retryable()`) → - 시도 예산을 쓰지 않고 항상 `markDeferred(nextAttemptAt)`(FAILED 전이 + 미룬 시도로 기록). broker 정지·종료 중·permit 부족· + 시도 예산을 쓰지 않고 항상 `markDeferred(nextAttemptAt, failureCode)`(FAILED 전이 + 미룬 시도로 기록). broker 정지·종료 중·permit 부족· credential 교체는 모든 행을 같은 방식으로 실패시키고 저절로 끝나므로, 예산을 쓰게 하면 몇 분 - 장애가 aggregate 머리마다 DEAD 행을 남긴다(2026-11-01 리뷰 06-01·06-03). + 장애가 aggregate 머리마다 DEAD 행을 남긴다(2026-11-01 리뷰 06-01·06-03). 대가로 끝이 없다 — + 저절로 풀리지 않는 원인(진짜 credential 오류, Kafka adapter가 이름을 모르는 broker 거부)이면 + 영원히 재시도된다. 그래서 모든 실패 전이는 원인 코드를 함께 적는다(`OutboxPublishAttempt.failureCode`: + publisher가 붙인 코드, 없으면 결과 이름, 던진 예외면 그 타입 이름 → 행 `last_failure_code`, 보고 + `failureCode`). 오래 미룬 행은 `OutboxStorePort.longRetries`로 세고, 운영자는 그 행을 `PARKED`로 + 보류할 수 있다(재리뷰 2026-11-03 RR-05-03, publish-failed runbook §4.1). - 발행 예외(`RuntimeException`, adapter가 분류하지 못한 실패): `budgetedAttemptCount() >= maxAttempts` 면 `markDead`, 아니면 `markFailed(nextAttemptAt)`. 예산은 이 경우에만 쓴다 — payload 자체 결함일 수 있는 실패가 aggregate를 영원히 막지 않게 하는 장치다. @@ -411,6 +454,10 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. `@RequiresPermission("outbox:relay")`는 D4 규칙을 통과시키려고 붙인 장식이었다(빈이 아니라 한 번도 검사되지 않았고, 빈이었다면 매 tick 거부됐다). ArchUnit D4는 `@SystemInvoked`를 권한 선언 대신 받고, `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`이 둘을 함께 다는 것을 막는다. + 면제의 전제(전송 계층이 닿지 않는다)도 코드가 지킨다: `@SystemInvoked` 빈은 + `PermissionEnforcementGuard`가 기동을 실패시키고, inbound adapter가 그 클래스에 의존하면 + `INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES`가 빌드를 실패시킨다(review 2026-11-03 + RR-01-02). ### OutboxBackoffPolicy @@ -439,7 +486,9 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. - `OutboxEventStatus` — 행 상태 머신(D5). `PENDING → IN_FLIGHT → {PUBLISHED | FAILED | DEAD}`, `FAILED → IN_FLIGHT`(재claim), `IN_FLIGHT 고아 → IN_FLIGHT`(I6). `DEAD` 는 FIFO 형제를 막는다 — - 같은 aggregate 의 뒤 행 claim 을 차단하므로 runbook 개입이 필요하다. + 같은 aggregate 의 뒤 행 claim 을 차단하므로 runbook 개입이 필요하다. `PARKED` 는 운영자만 만든다 + (`FAILED → PARKED`, runbook SQL): claim 되지 않고 DEAD 처럼 FIFO 형제를 막는다. 재개는 + `PARKED → FAILED`, 버리기는 `PARKED → PUBLISHED`. relay 의 어떤 전이도 `PARKED` 로 가거나 나오지 않는다. - append 는 `OutboxAppendPort.append(ValidatedIntegrationEvent)` 하나다(2026-09-28, 소유자 결정 7). use case 가 `IntegrationEventDraft` 를 만들고 `IntegrationEventEncoderPort` 로 encode 한 뒤 같은 write 트랜잭션 안에서 append 한다. consumer 의 중복 제거 키는 event id 다. @@ -448,11 +497,11 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. 다음 실패 시 dead-letter 여부를 결정한다. 옛 `OutboxEvent`/`NewOutboxEvent`/`LegacyOutboxAppendPort` (free-text payload 모델)는 삭제됐다. - `OutboxRelayResult` — relay 한 사이클의 결과. `claimedCount` + per-event outcome 목록. 내부 - `Outcome` enum 이 `OutboxEventStatus` 의 5값을 재사용하지 않고 4값(PUBLISHED/FAILED/DEAD/ - STALE — 마지막은 lease 를 잃어 결과를 쓰지 못한 경우)을 + `Outcome` enum 이 `OutboxEventStatus` 를 재사용하지 않고 5값(PUBLISHED/FAILED/DEAD/STALE/RELEASED — + STALE 은 lease 를 잃어 결과를 쓰지 못한 경우, RELEASED 는 멈추는 relay 가 쓰지 않은 claim 을 놓은 경우)을 따로 두는 이유: relay 관점은 "이번 실행에서 무슨 일이 있었나" 이지 "행의 현재 영속 상태" 가 - 아니다(후자는 store 가 5값으로 추적). 별도 enum 이 메트릭·스케줄러 로깅 consumer 에게 relay API - 를 깔끔하게 유지해 준다. + 아니다(후자는 store 가 `OutboxEventStatus` 로 추적). 이 5값이 `outbox.publisher.published.total` 의 + `outcome` label 이다(`docs/registries/metrics.yaml`, 계약 테스트가 비교). - `PublishPendingOutboxEventsCommand` — relay 커맨드 마커. 스케줄러 구동이라 caller 파라미터가 없고, 모든 운영 파라미터는 생성 시점에 주입된다(IdempotencyExecutor 선례). 호출마다 새 인스턴스를 만들 필요가 없게 `INSTANCE` 싱글톤을 제공한다. @@ -522,40 +571,12 @@ application 계층은 락 획득/해제 계약만 알고, 실제 구현은 adapt --- -## Notification R1 +## 알림 타입은 이 leaf에 없다 (application-notification) -R1 오케스트레이션 타입(`dev.caskeleton.application.notification` 직속, production consumer 0건)은 -2026-09-25에 삭제했다. canonical은 `..notification.platform..`이다(NOTIF-ADR-005). 직속 패키지에는 -단순 알림 포트 `NotificationPort`·`Notification`·`NotificationChannel`만 남았다. - -## 알림 포트 (notification) - -### NotificationPort - -- named channel + 논리 route 로 알림을 전달하는 outbound 포트. -- 2-인자 overload 는 관례적 `"default"` route 를 쓰는 편의 메서드다. adapter 가 - `app.notification.routes..` 에서 구체 provider 목록을 해석하므로, application - 계층은 provider 선택과 분리된다(호출부에 provider id 가 없다). -- fan-out(route 당 여러 provider)은 adapter 관심사다. 어떤 provider 가 실패하면 adapter 가 - fail-open 정책(관측만, 전파 안 함)을 적용하고, route 자체가 unbound 면 - `AdapterDisabledException("notification", ...)` 을 던진다. -- outbound 포트의 `*Port` 접미사 명명 규칙을 따른다(CLAUDE.md). - -### Notification (값 객체) - -- transport-중립 알림 값으로, routing target 과 내용만 운반한다. -- **절대 logger(또는 dependency logger)에 넘기면 안 된다** — recipient 주소·body 가 로그 라인에 - 닿을 수 없게 하기 위함(PII 계약). -- `adapter-outbound` 에서 `application-core` 로 옮긴 이유: 유스케이스가 adapter 타입을 import 하지 - 않고도 알림을 만들어 `NotificationPort` 로 전달할 수 있게 하기 위함(clean-architecture - HARD-STOP #3). - -### Channel - -- 알림 채널 판별자(`EMAIL`/`SLACK`). provider 와 독립적으로 전달 매체를 식별한다. -- caller 가 `Channel` 값(compile-safe) + 논리 route 이름을 `NotificationPort` 에 넘기면 adapter 가 - `app.notification.routes..` 로 provider 목록을 해석한다 — 도메인은 provider - 세부를 들여다보지 않는다(HARD-STOP #4). +`NotificationPort`·`Notification`·`NotificationChannel`과 알림 플랫폼(`..notification.platform..`, +NOTIF-ADR-005)은 leaf `application-notification`(`src/application-notification`)이 소유한다. 패키지 +이름이 `dev.caskeleton.application.notification`이라 이 leaf의 것처럼 보일 뿐이다. 설명과 규칙은 그 +leaf의 코드 Javadoc과 `docs/notification/`이 정본이다. R1 오케스트레이션 타입은 2026-09-25에 삭제했다. --- @@ -593,9 +614,11 @@ R1 오케스트레이션 타입(`dev.caskeleton.application.notification` 직속 벽시계(예전 샘플의 epoch 마이크로초)는 인스턴스 사이 시계 차이·NTP 되돌림·같은 마이크로초 두 건에서 커밋 순서와 달라진다. - 계약(`OutboxAggregateSequenceContract`, fake `InMemoryOutboxAggregateSequences`와 JPA 구현이 공유): - aggregate마다 1부터 하나씩 커지고 aggregate끼리 독립이다. JPA 구현(`JpaOutboxStore`, V21 - `outbox_aggregate_sequence`)은 counter row lock으로 같은 aggregate 쓰기를 직렬화하고, 기존 outbox - row의 최대 번호 다음에서 시작하며, reaper가 row를 지워도 번호를 다시 쓰지 않는다. 같은 + aggregate마다 첫 번호부터 하나씩 커지고, 첫 쓰기 두 개가 겹쳐도 둘 다 성공하며, aggregate끼리 + 독립이다. 첫 번호는 구현마다 다르다(fake는 1). JPA 구현(`JpaOutboxStore`, V21 + `outbox_aggregate_sequence`)은 counter row lock으로 같은 aggregate 쓰기를 직렬화하고, 남은 outbox + row의 최대 번호와 V21이 기록한 floor(적용 시각의 epoch 마이크로초) 중 큰 값 다음에서 시작한다. + 그래서 reaper가 지웠거나 identity가 바뀐 aggregate도 옛 벽시계 번호보다 뒤에서 시작한다. 같은 `(tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index)` 두 번째 append는 V21 유일 인덱스가 append 시점에 거부한다. - aggregate가 자체 version 열(낙관적 락)을 가지면 그 값을 써도 된다. 이 포트는 counter가 없는 diff --git a/src/application-core/build.gradle b/src/application-core/build.gradle index 2317c633..b077bf43 100644 --- a/src/application-core/build.gradle +++ b/src/application-core/build.gradle @@ -28,7 +28,8 @@ strictTestLanes { description = 'Runs exact Messaging application contract qualification tests.' requires 'dev.caskeleton.application.messaging.contract.IntegrationEventContractContributionTest', 'dev.caskeleton.application.messaging.event.IntegrationEventDraftTest', - 'dev.caskeleton.application.messaging.event.ValidatedIntegrationEventTest' + 'dev.caskeleton.application.messaging.event.ValidatedIntegrationEventTest', + 'dev.caskeleton.application.messaging.contract.ApplicationPayloadSchemaReleaseTest' rejectSkipped = true } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompletionUnknownException.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompletionUnknownException.java new file mode 100644 index 00000000..2d067c1b --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompletionUnknownException.java @@ -0,0 +1,32 @@ +package dev.caskeleton.application.idempotency; + +import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.OperationalError; + +/** + * The action ran, and the store did not answer when its result was being recorded. + * + *

        Not {@link IdempotencyUnavailableException}: that one is raised before the action, so the + * request certainly did not apply. Here it may have. Effects inside the action's own transaction + * roll back with this exception; anything else the action did — a call to another system, a message + * — has happened. Telling the client "not applied" would invite a resend under a new key, which is + * the duplicate the key exists to prevent (re-review 2026-11-03, RR-02-03). + * + *

        A resend with the same key is safe: the server judges it as a replay when the result was in + * fact recorded, as in-flight while the attempt's lease lasts, and as recovery-required after that. + */ +public final class IdempotencyCompletionUnknownException extends RuntimeException + implements ApiErrorCarrier { + + private static final long serialVersionUID = 1L; + + public IdempotencyCompletionUnknownException() { + super("idempotency store did not answer while recording a completed action; outcome unknown"); + } + + @Override + public ApiErrorCode errorCode() { + return OperationalError.IDEMPOTENCY_COMPLETION_UNKNOWN; + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java index f7f2ab9c..6dae5a62 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java @@ -16,9 +16,26 @@ import java.util.Optional; * *

        The action runs only after a confirmed start. This preserves request-replay evidence; it does * not create a cross-store exactly-once boundary, and nothing here should be read as claiming one. + * + *

        A store that does not answer is reported by when it stopped answering: before the action it is + * {@link IdempotencyUnavailableException} (not applied), after it {@link + * IdempotencyCompletionUnknownException} (outcome unknown). {@code docs/web/http-contract.md} §2 + * gives the client behaviour for each. */ public final class IdempotencyExecutor { + /** + * How long a refused duplicate is told to wait before resending with the same key: the {@code + * Retry-After} of the in-flight 409, and the one value every transport and the lease check read. + * The executor does not wait itself; it refuses at once (docs/web/http-contract.md §2). + * + *

        It must stay below the processing lease, so the resend arrives while the first attempt can + * still finish; an early one costs only another 409. {@code IdempotencySettings} refuses to start + * with a lease no longer than this, so the rule is enforced where the lease is configured rather + * than remembered (re-review 2026-11-03, RR-02-05). + */ + public static final Duration IN_FLIGHT_RETRY_AFTER = Duration.ofSeconds(2); + private final IdempotencyStorePort store; private final Duration processingLeaseTtl; private final Duration replayTtl; @@ -230,7 +247,8 @@ public final class IdempotencyExecutor { return switch (store.complete( owner, response, replayTtl, request.claimAttempt().operationId())) { case COMPLETED, ALREADY_COMPLETED_SAME_RESULT -> result; - case UNAVAILABLE -> throw new IdempotencyUnavailableException(); + // The action has run. Reporting "unavailable" here would tell the client it did not. + case UNAVAILABLE -> throw new IdempotencyCompletionUnknownException(); case INDETERMINATE -> reconcileCompletion(request, result, codec, alreadyRetried); default -> throw recovery("completion was not confirmed"); }; @@ -265,7 +283,7 @@ public final class IdempotencyExecutor { } yield complete(request, requireOwner(inspection), result, codec, true); } - case UNAVAILABLE -> throw new IdempotencyUnavailableException(); + case UNAVAILABLE -> throw new IdempotencyCompletionUnknownException(); default -> throw recovery("the completion response is indeterminate and was not reconciled"); }; } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java index 802cce5b..dbb8d236 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java @@ -8,7 +8,8 @@ import dev.caskeleton.shared.error.OperationalError; * Raised when another attempt still holds the same {@link IdempotencyScopeDigest}. Framework-free, * application-owned; every transport maps it to a {@code IDEMPOTENT_IN_FLIGHT} 409 (retryable=true * — the result is unknown and the client resends with the same key, never a new one; {@code - * docs/web/http-contract.md}). The message carries only the opaque scope digest, for logs. + * docs/web/http-contract.md}). The message carries only the opaque scope digest, for logs. How long + * the client waits before resending is {@link IdempotencyExecutor#IN_FLIGHT_RETRY_AFTER}. */ public class IdempotencyInFlightException extends RuntimeException implements ApiErrorCarrier { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyUnavailableException.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyUnavailableException.java index 7d0352f2..53249eea 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyUnavailableException.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyUnavailableException.java @@ -4,7 +4,12 @@ import dev.caskeleton.shared.error.ApiErrorCarrier; import dev.caskeleton.shared.error.ApiErrorCode; import dev.caskeleton.shared.error.OperationalError; -/** Fail-closed signal raised before an action when request-replay coordination is unavailable. */ +/** + * Fail-closed signal raised before an action when request-replay coordination is unavailable. + * + *

        Only before the action: the request certainly did not apply. A store that stops answering + * after the action ran is {@link IdempotencyCompletionUnknownException} instead. + */ public final class IdempotencyUnavailableException extends RuntimeException implements ApiErrorCarrier { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDraft.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDraft.java index b09a2360..c949d2ab 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDraft.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDraft.java @@ -6,7 +6,16 @@ import dev.caskeleton.application.messaging.contract.LogicalDestinationId; import java.time.Instant; import java.util.Optional; -/** Feature-owned semantic event before local encoding and schema validation. */ +/** + * Feature-owned semantic event before local encoding and schema validation. + * + *

        A new event's id and causation id are canonical lower-case UUIDv7s ({@link + * IntegrationIdentity#isCanonicalUuidV7}). The messaging bridge sends the event under its id as the + * platform's message id and refuses any other spelling; refused there, the event was already + * committed and the relay could only park it, with every later event of its aggregate behind it. + * Refused here, the write that announces it fails instead (review 06-06, re-review 2026-11-03 + * RR-05-04). + */ public record IntegrationEventDraft

        ( EventId eventId, ContractId contractId, @@ -33,11 +42,24 @@ public record IntegrationEventDraft

        ( if (occurredAt == null) { throw new IllegalArgumentException("occurredAt must not be null"); } + if (!IntegrationIdentity.isCanonicalUuidV7(eventId.value())) { + throw new IllegalArgumentException( + "eventId must be a canonical lower-case UUIDv7, the id the messaging platform carries;" + + " was " + + eventId.value()); + } IntegrationIdentity.requireCorrelation("correlationId", correlationId); if (causationId == null) { throw new IllegalArgumentException("causationId Optional must not be null"); } - causationId.ifPresent(value -> IntegrationIdentity.requireCorrelation("causationId", value)); + causationId.ifPresent( + value -> { + if (!IntegrationIdentity.isCanonicalUuidV7(value)) { + throw new IllegalArgumentException( + "causationId must be a canonical lower-case UUIDv7, the id of the event that caused" + + " this one"); + } + }); if (featurePayload == null) { throw new IllegalArgumentException("featurePayload must not be null"); } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventPublishPort.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventPublishPort.java index 5ead377c..535a146d 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventPublishPort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventPublishPort.java @@ -1,16 +1,31 @@ package dev.caskeleton.application.messaging.event; -import dev.caskeleton.application.outbox.OutboxPublishOutcome; +import dev.caskeleton.application.outbox.OutboxPublishAttempt; +import java.time.Duration; +import java.util.Optional; import java.util.concurrent.CompletionStage; /** * Application-owned boundary for publishing one fully validated integration event. * *

        The application exposes its canonical event model and outcome vocabulary only. Broker, - * transport, codec, and messaging-platform types remain on the outbound side of the boundary. + * transport, codec, and messaging-platform types remain on the outbound side of the boundary; a + * publisher that knows why an attempt was not confirmed translates its reason into the attempt's + * failure code ({@link OutboxPublishAttempt}) rather than handing the platform's type across. */ @FunctionalInterface public interface IntegrationEventPublishPort { - CompletionStage publish(ValidatedIntegrationEvent event); + CompletionStage publish(ValidatedIntegrationEvent event); + + /** + * The longest one publish can take before the returned stage completes, when the publisher knows + * it. The outbox relay sizes its batch against it (see {@code + * OutboxMessagePublishPort#longestAttempt}). + * + * @return the longest attempt, or empty when unknown + */ + default Optional longestAttempt() { + return Optional.empty(); + } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java index dd1663bd..adc509c3 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationIdentity.java @@ -48,6 +48,31 @@ public final class IntegrationIdentity { && PATTERN.matcher(value).matches(); } + /** + * The spelling of a new event's id and causation id: a canonical lower-case UUIDv7, the only id + * the messaging platform's {@code MessageId} carries unchanged. A UUID in upper case or in the + * short form reads back as a different string, and any other version is refused outright. + */ + public static final String UUID_V7_GRAMMAR = + "[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"; + + private static final Pattern UUID_V7 = Pattern.compile(UUID_V7_GRAMMAR); + + /** + * Whether {@code value} is a canonical lower-case UUIDv7 ({@link #UUID_V7_GRAMMAR}). + * + *

        The stored identity grammar ({@link #GRAMMAR}) is wider, because rows appended before this + * rule may hold other ids and must still be read back. A new event is held to this one where it + * is drafted ({@link IntegrationEventDraft}), so an id the platform would refuse fails in the + * writer's transaction instead of parking the committed event in the relay (review 06-06). + * + * @param value the candidate; {@code null} is not one + * @return true for a canonical lower-case UUIDv7 + */ + public static boolean isCanonicalUuidV7(String value) { + return value != null && UUID_V7.matcher(value).matches(); + } + /** Refuses a correlation or causation id outside the grammar or the bound. */ static void requireCorrelation(String field, String value) { if (!isCanonical(value, CORRELATION_MAX_LENGTH)) { 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 5f3e7469..e5d8719c 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 @@ -17,8 +17,10 @@ import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.CommandUseCase; import dev.caskeleton.shared.digest.Sha256; import java.time.Clock; +import java.time.Instant; import java.util.Objects; import java.util.Optional; +import java.util.UUID; /** * Accepts long-running work: one transaction that writes the operation row and the outbox row. @@ -141,7 +143,7 @@ public class SubmitDurableOperationUseCase */ private static IntegrationEventDraft submittedEvent( DurableOperation operation) { - String identity = canonicalIdentity(operation.operationId()); + String identity = canonicalIdentity(operation.operationId(), operation.submittedAt()); // Single-tenant scope even when the command names a tenant: the event only wakes a worker, the // tenant travels in the stored operation, and mapping a TenantId into the lower-case scope // grammar is the messaging platform's decision, not this use case's. @@ -158,18 +160,34 @@ public class SubmitDurableOperationUseCase } /** - * The operation id itself when it fits the integration-event identity grammar — every id the HTTP - * adapter mints does — and otherwise a digest of it. + * The operation id itself when it is a canonical lower-case UUIDv7 — every id the HTTP adapter + * mints is — and otherwise a UUIDv7 derived from it. * - *

        An operation id may contain {@code ~} or run to 128 characters, and an event id may do - * neither. The digest keeps the event deterministic for the operation, so a retry still produces - * the same event, and the payload carries the id unchanged for the worker. + *

        The event id is the messaging platform's message id, which is a canonical lower-case UUIDv7; + * the draft refuses anything else, so an operation id a client chose ({@code ~report}, a v4, an + * upper-case spelling) cannot be the event id. The derived id keeps the event deterministic for + * the operation — the same id and submission time always give the same event id — and the payload + * carries the operation id unchanged for the worker. Its time field is the submission time, so it + * orders like a minted one; its other 74 bits are the SHA-256 of the operation id. + * + *

        It replaced an {@code operation-} digest, which fit the stored identity grammar and + * passed the append, and which the bridge then refused, parking the committed event (review + * 06-06, re-review 2026-11-03 RR-05-04). */ - static String canonicalIdentity(DurableOperationId operationId) { + static String canonicalIdentity(DurableOperationId operationId, Instant submittedAt) { String value = operationId.value(); - if (IntegrationIdentity.isCanonical(value, IntegrationIdentity.EVENT_ID_MAX_LENGTH)) { + if (IntegrationIdentity.isCanonicalUuidV7(value)) { return value; } - return "operation-" + Sha256.ofUtf8(value).hex(); + byte[] digest = Sha256.ofUtf8(value).bytes(); + long millis = submittedAt.toEpochMilli() & 0xFFFF_FFFF_FFFFL; + long randA = ((digest[0] & 0x0FL) << 8) | (digest[1] & 0xFFL); + long mostSignificant = (millis << 16) | (0x7L << 12) | randA; + long randB = 0; + for (int i = 2; i < 10; i++) { + randB = (randB << 8) | (digest[i] & 0xFFL); + } + long leastSignificant = (randB & 0x3FFF_FFFF_FFFF_FFFFL) | 0x8000_0000_0000_0000L; + return new UUID(mostSignificant, leastSignificant).toString(); } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java index a042012f..73a17469 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java @@ -14,7 +14,9 @@ import dev.caskeleton.application.messaging.event.AggregateIdentity; * version column already counts its writes may use that instead; this port is for the aggregates * that keep no counter. * - *

        Contract, which {@code OutboxAggregateSequenceContract} holds every implementation to: + *

        Contract, which {@code OutboxAggregateSequenceContract} holds every implementation to (one + * case per item; the reaper and seed half of the second item needs outbox rows and is a PostgreSQL + * case, {@code PostgreSqlOutboxAggregateSequenceIntegrationTest}): * *

          *
        • Called inside the caller's write transaction ({@code TransactionPort.inWrite}), the same @@ -22,8 +24,14 @@ import dev.caskeleton.application.messaging.event.AggregateIdentity; * a second writer of the same aggregate waits for the first to commit or roll back; a rolled * back number is handed out again. *
        • Strictly greater than every number this port returned for the aggregate before, including - * for events the retention reaper has since deleted, and greater than any number an earlier - * outbox row of the aggregate carries. + * for events the retention reaper has since deleted, and greater than any number an outbox + * row of the aggregate carries when the call is made. + *
        • Where an implementation replaced an earlier numbering (the sample's wall clock), greater + * than any number that numbering could have sent for the aggregate — also for rows deleted + * since, or written under an identity that has since changed. The first number is therefore + * not necessarily 1: the JPA counter starts above the moment its migration ran, in epoch + * microseconds (review RR-03-02). + *
        • Two first calls for one aggregate that overlap both succeed, with consecutive numbers. *
        • Independent per aggregate identity: one aggregate's numbers say nothing about another's. *
        */ diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxEventStatus.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxEventStatus.java index 355633b6..b4b13a0d 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxEventStatus.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxEventStatus.java @@ -1,8 +1,9 @@ package dev.caskeleton.application.outbox; /** - * Status state machine for a transactional outbox event row. {@code DEAD} blocks its aggregate's - * FIFO siblings until manually resolved. See README for the full transition diagram. + * Status state machine for a transactional outbox event row. {@code DEAD} and {@code PARKED} block + * their aggregate's FIFO siblings until manually resolved. See README for the full transition + * diagram. */ public enum OutboxEventStatus { @@ -25,6 +26,9 @@ public enum OutboxEventStatus { /** * Publish failed transiently; {@code next_attempt_at} carries the backoff deadline. The row will * be re-claimed once {@code now >= next_attempt_at}. + * + *

        A row that failed for a reason of the moment (deferred, {@link + * OutboxStorePort#markDeferred}) stays here without end; {@code last_failure_code} says why. */ FAILED, @@ -33,5 +37,16 @@ public enum OutboxEventStatus { * see {@code OperationalError.OUTBOX_DEAD_LETTER}. While a row is DEAD its aggregate's FIFO queue * is blocked. */ - DEAD + DEAD, + + /** + * Held by an operator: a FAILED row the relay would retry without end, taken out of the retry + * loop while its cause is found ({@code runbook://outbox/publish-failed}, "끝나지 않는 재시도"). + * + *

        No relay transition leads here and none leaves: only the runbook's park and resume SQL do. + * The claim never takes a parked row, and the row still blocks its aggregate's later events, so + * parking stops the retries without letting the aggregate's order slip. Resuming returns it to + * FAILED, due at once; skipping marks it PUBLISHED with the same approval a DEAD skip needs. + */ + PARKED } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxLongRetries.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxLongRetries.java new file mode 100644 index 00000000..8de5f6ad --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxLongRetries.java @@ -0,0 +1,24 @@ +package dev.caskeleton.application.outbox; + +/** + * The outbox rows that have been retrying for a long time ({@link OutboxStorePort#longRetries}). + * + * @param rows how many FAILED rows have collected at least the asked-for number of deferred claims + * @param oldestAgeSeconds the oldest such row's age since it occurred, in seconds; 0 when there is + * none + */ +public record OutboxLongRetries(long rows, long oldestAgeSeconds) { + + /** No row is retrying long. */ + public static final OutboxLongRetries NONE = new OutboxLongRetries(0, 0); + + public OutboxLongRetries { + if (rows < 0 || oldestAgeSeconds < 0) { + throw new IllegalArgumentException( + "rows and oldestAgeSeconds must be >= 0, were " + rows + " and " + oldestAgeSeconds); + } + if (rows == 0 && oldestAgeSeconds != 0) { + throw new IllegalArgumentException("no row has no age, was " + oldestAgeSeconds); + } + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxMessagePublishPort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxMessagePublishPort.java index 39cb6972..3255b3d7 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxMessagePublishPort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxMessagePublishPort.java @@ -1,5 +1,8 @@ package dev.caskeleton.application.outbox; +import java.time.Duration; +import java.util.Optional; + /** * Outbound port for publishing a claimed outbox event to the message broker. * Fail-closed: any publish failure MUST be surfaced by throwing a {@link @@ -19,7 +22,8 @@ public interface OutboxMessagePublishPort { void publish(ClaimedOutboxEvent event); /** - * Publishes and reports what was achieved. + * Publishes and reports what was achieved, and the publisher's code for why when it was not a + * confirmation. * *

        The throwing method above cannot express an ambiguous publish: a broker that accepted the * frame and never confirmed it is reported the same way as one that refused it outright, and the @@ -29,11 +33,26 @@ public interface OutboxMessagePublishPort { * @param event the claimed outbox event * @return what the attempt achieved */ - default OutboxPublishOutcome publishForOutcome(ClaimedOutboxEvent event) { + default OutboxPublishAttempt publishForOutcome(ClaimedOutboxEvent event) { publish(event); // A method that either returns or throws can only report these two. Reporting CONFIRMED here // is honest for such an adapter — it is what "returned without throwing" has always meant — // and an adapter that can tell an ambiguous publish apart overrides this. - return OutboxPublishOutcome.CONFIRMED; + return OutboxPublishAttempt.confirmed(); + } + + /** + * The longest one publish can take before this port answers, when the port knows it. + * + *

        The relay holds a whole batch under one lease while it publishes the rows one after another, + * so a batch whose worst case outlasts the lease is reclaimed and sent again by another instance. + * Only the port knows its worst case, so the relay's assembly asks it and refuses a batch size + * that does not fit (review 2026-11-01 06-12). Empty when the port cannot say; the check is then + * skipped, not guessed. + * + * @return the longest attempt, or empty when unknown + */ + default Optional longestAttempt() { + return Optional.empty(); } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishAttempt.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishAttempt.java new file mode 100644 index 00000000..af161a42 --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishAttempt.java @@ -0,0 +1,103 @@ +package dev.caskeleton.application.outbox; + +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Pattern; + +/** + * What one publish attempt achieved, and — when it did not achieve a confirmation — the publisher's + * code for why. + * + *

        The outcome decides what the relay does next; the code is for the operator. A refusal for now + * and an unanswered publish are retried without end (review 2026-11-01 README 15), so a row can + * keep failing for a reason no one sees: a credential that is really wrong, a topic policy the + * broker client has no name for. The outcome alone cannot tell those apart — a shutdown, a closed + * transport and a refused credential are all {@link OutboxPublishOutcome#REJECTED_RETRYABLE}. The + * code can, and the relay writes it on the row and into its failure report (re-review 2026-11-03 + * RR-05-03). + * + *

        The code is the publisher's stable, machine-readable name for the failure — a messaging + * platform failure code such as {@code KAFKA_AUTHENTICATIONEXCEPTION} or {@code + * PUBLISH_DEADLINE_EXCEEDED} — never a message: a message can carry an endpoint, a statement or a + * credential, and the row and the log are read by more people than the broker is. + * + * @param outcome what the attempt achieved + * @param failureCode the publisher's code for an attempt that was not confirmed; empty when the + * publisher named none, and always empty for a confirmed attempt + */ +public record OutboxPublishAttempt(OutboxPublishOutcome outcome, Optional failureCode) { + + /** The longest code a row keeps: the width of {@code outbox_event.last_failure_code}. */ + public static final int FAILURE_CODE_MAX_LENGTH = 120; + + /** Letters and digits, then any of {@code . _ : -}: a name, not a sentence. */ + private static final Pattern FAILURE_CODE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]*"); + + public OutboxPublishAttempt { + Objects.requireNonNull(outcome, "outcome must not be null"); + Objects.requireNonNull(failureCode, "failureCode must not be null"); + if (outcome == OutboxPublishOutcome.CONFIRMED && failureCode.isPresent()) { + throw new IllegalArgumentException("a confirmed publish has no failure code"); + } + failureCode.ifPresent( + code -> { + if (!isFailureCode(code)) { + throw new IllegalArgumentException( + "failureCode must be 1-" + + FAILURE_CODE_MAX_LENGTH + + " characters matching " + + FAILURE_CODE.pattern()); + } + }); + } + + /** A publish the broker acknowledged. */ + public static OutboxPublishAttempt confirmed() { + return new OutboxPublishAttempt(OutboxPublishOutcome.CONFIRMED, Optional.empty()); + } + + /** + * An attempt whose publisher reported only the outcome. + * + * @param outcome what the attempt achieved + * @return the attempt + */ + public static OutboxPublishAttempt of(OutboxPublishOutcome outcome) { + return new OutboxPublishAttempt(outcome, Optional.empty()); + } + + /** + * An attempt that was not confirmed, with the publisher's code for why. + * + * @param outcome what the attempt achieved; not {@link OutboxPublishOutcome#CONFIRMED} + * @param failureCode the publisher's code, see {@link #isFailureCode} + * @return the attempt + */ + public static OutboxPublishAttempt failed(OutboxPublishOutcome outcome, String failureCode) { + return new OutboxPublishAttempt(outcome, Optional.of(failureCode)); + } + + /** + * Whether {@code candidate} can be kept as a failure code. A publisher translating a foreign code + * asks first and falls back to a name of its own when the answer is no. + * + * @param candidate the code; {@code null} is not one + * @return true when it is 1-{@value #FAILURE_CODE_MAX_LENGTH} characters of the code grammar + */ + public static boolean isFailureCode(String candidate) { + return candidate != null + && !candidate.isEmpty() + && candidate.length() <= FAILURE_CODE_MAX_LENGTH + && FAILURE_CODE.matcher(candidate).matches(); + } + + /** + * The code the relay records for this attempt: the publisher's, or the outcome's own name when + * the publisher gave none. + * + * @return a code that is never empty + */ + public String recordedFailureCode() { + return failureCode.orElse(outcome.name()); + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishOutcome.java index d895ef23..5539682c 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxPublishOutcome.java @@ -12,12 +12,14 @@ package dev.caskeleton.application.outbox; * two outbox models is real: * *

          - *
        • the legacy {@code OutboxEventStatus.FAILED} is retryable and {@code DEAD} is - * terminal; - *
        • the platform's {@code OutboxStatus.FAILED} is a definite rejection and terminal, - * while {@code AMBIGUOUS} is the retryable one. + *
        • this application's {@code OutboxEventStatus.FAILED} ({@code outbox_event}) is + * retryable and {@code DEAD} is terminal; + *
        • the vendored platform's {@code OutboxStatus.FAILED} ({@code messaging_outbox}) is a + * definite rejection and terminal, while {@code AMBIGUOUS} is the retryable one. *
        * + *

        The full correspondence is one table, at the head of {@code docs/messaging/outbox-inbox.md}. + * *

        Mapping those by name inverts both meanings: a definitely-rejected message would be retried * forever and an unknown one would be parked. This type exists so no bridge is ever tempted to map * enum names. @@ -43,7 +45,7 @@ public enum OutboxPublishOutcome { * Refused before anything was transmitted — validation, routing, an unknown destination. * *

        Definite: nothing was stored anywhere, so a retry of the same payload fails the same way. - * This is what the legacy model calls {@code DEAD}, not what it calls {@code FAILED}. + * This is what this application's outbox calls {@code DEAD}, not what it calls {@code FAILED}. */ REJECTED_BEFORE_SEND, diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReport.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReport.java index f0723dc6..405d5c82 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReport.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReport.java @@ -17,6 +17,12 @@ import java.util.Objects; * survives is the exception's class name and, when the exception carries a platform code, that one: * enough to group failures and route a runbook, and nothing that is business content. The bounded * code is {@link #code()}, which this allowlist already owned. + * + *

        {@link #failureCode()} is the code the row records for the failure ({@code + * last_failure_code}): the publisher's own name for a refusal or an unanswered publish, or the + * outcome or exception type when it gave none. The cause type of a returned outcome is one of this + * package's carrier exceptions and says only which outcome it was; the failure code is what tells a + * refused credential from a closed transport (re-review 2026-11-03 RR-05-03). */ public record OutboxRelayFailureReport( OperationalError code, @@ -26,7 +32,8 @@ public record OutboxRelayFailureReport( String correlationId, int attemptCount, Instant nextAttemptAt, - String causeType) { + String causeType, + String failureCode) { public OutboxRelayFailureReport { Objects.requireNonNull(code, "code must not be null"); @@ -35,6 +42,9 @@ public record OutboxRelayFailureReport( requireNonBlank(aggregateId, "aggregateId"); requireNonBlank(correlationId, "correlationId"); requireNonBlank(causeType, "causeType"); + if (!OutboxPublishAttempt.isFailureCode(failureCode)) { + throw new IllegalArgumentException("failureCode must be a bounded failure code"); + } if (attemptCount < 1) { throw new IllegalArgumentException("attemptCount must be >= 1, was " + attemptCount); } @@ -58,7 +68,8 @@ public record OutboxRelayFailureReport( String correlationId, int attemptCount, Instant nextAttemptAt, - RuntimeException cause) { + RuntimeException cause, + String failureCode) { return new OutboxRelayFailureReport( OperationalError.OUTBOX_PUBLISH_FAILED, eventId, @@ -67,7 +78,8 @@ public record OutboxRelayFailureReport( correlationId, attemptCount, nextAttemptAt, - causeTypeOf(cause)); + causeTypeOf(cause), + failureCode); } public static OutboxRelayFailureReport deadLetter( @@ -76,7 +88,8 @@ public record OutboxRelayFailureReport( String aggregateId, String correlationId, int attemptCount, - RuntimeException cause) { + RuntimeException cause, + String failureCode) { return new OutboxRelayFailureReport( OperationalError.OUTBOX_DEAD_LETTER, eventId, @@ -85,7 +98,8 @@ public record OutboxRelayFailureReport( correlationId, attemptCount, null, - causeTypeOf(cause)); + causeTypeOf(cause), + failureCode); } /** diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java index 3f2ce264..90be859a 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java @@ -5,8 +5,9 @@ import java.util.Objects; /** * Result returned by {@link PublishPendingOutboxEventsUseCase} after one relay cycle: the number of - * events claimed and a per-event {@link Outcome} list. See README for why {@code Outcome} is a - * separate 3-value enum rather than reusing {@link OutboxEventStatus}. + * events claimed and a per-event {@link Outcome} list. {@code Outcome} is the cycle's result, not a + * row status, which is why it does not reuse {@link OutboxEventStatus}: a row is never left {@code + * STALE} or {@code RELEASED}, and no cycle ends {@code IN_FLIGHT} or {@code PARKED}. * * @param claimedCount total number of events claimed from the store in this cycle * @param outcomes per-event outcomes in the order they were processed @@ -47,20 +48,21 @@ public record OutboxRelayResult(int claimedCount, List outcomes) { /** * Per-event relay cycle outcome. * - *

        Three values mirror the three terminal states reachable in a single relay cycle: broker ack - * ({@link #PUBLISHED}), transient failure below the retry cap ({@link #FAILED}), or retry cap - * exhausted ({@link #DEAD}). The fourth, {@link #STALE}, records a result this relay was no - * longer allowed to write. + *

        Three values are the row transitions a cycle writes: broker ack ({@link #PUBLISHED}), a + * failure that will be retried ({@link #FAILED}), or one that will not ({@link #DEAD}). {@link + * #STALE} records a result this relay was no longer allowed to write, and {@link #RELEASED} a + * claim a stopping relay gave back unused. The counter {@code outbox.publisher.published.total} + * carries exactly these five as its {@code outcome} label. */ public enum Outcome { /** Broker acknowledged the publish; row transitions to PUBLISHED. */ PUBLISHED, - /** Publish failed transiently; row transitions to FAILED with a backoff window. */ + /** Publish failed and will be retried; row transitions to FAILED with a backoff window. */ FAILED, - /** All retry attempts exhausted; row transitions to DEAD. */ + /** Refused for good, or the attempt budget is spent; row transitions to DEAD. */ DEAD, /** diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java index fc2b49fc..b96ac1da 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java @@ -7,11 +7,12 @@ import java.util.Map; /** * Outbound port for relay-side access to the outbox store. All mutating operations ({@link - * #claimBatch}, {@link #markPublished}, {@link #markFailed}, {@link #markDead}) must be called - * inside a {@code TransactionPort.inWrite(...)} boundary owned by the relay; implementations must - * not open their own transaction. A completion applies only while the relay's {@link OutboxLease} - * still holds the row, so a relay that stalled past its claim cannot overwrite the relay that took - * the row over. See README for the claim/FIFO/in-flight-timeout/lease semantics. + * #claimBatch}, {@link #markPublished}, {@link #markFailed}, {@link #markDeferred}, {@link + * #releaseLease}, {@link #markDead}) must be called inside a {@code TransactionPort.inWrite(...)} + * boundary owned by the relay; implementations must not open their own transaction. A completion + * applies only while the relay's {@link OutboxLease} still holds the row, so a relay that stalled + * past its claim cannot overwrite the relay that took the row over. See README for the + * claim/FIFO/in-flight-timeout/lease semantics. */ public interface OutboxStorePort { @@ -47,9 +48,11 @@ public interface OutboxStorePort { * * @param lease the claim this relay holds * @param nextAttemptAt the earliest instant at which the event may be re-claimed + * @param failureCode why the attempt failed, kept on the row for the operator (see {@link + * OutboxPublishAttempt}); never a message * @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row */ - OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt); + OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt, String failureCode); /** * Marks the leased event as failed for a reason that belongs to the moment — the broker did not @@ -59,11 +62,16 @@ public interface OutboxStorePort { * ClaimedOutboxEvent#budgetedAttemptCount()}). Must be called inside {@code * TransactionPort.inWrite(...)}. * + *

        A deferred row is retried without end, so its failure code is what tells an operator a row + * that waits out an outage from one the broker will never take — a credential that is really + * wrong, a topic policy the broker client has no name for (re-review 2026-11-03 RR-05-03). + * * @param lease the claim this relay holds * @param nextAttemptAt the earliest instant at which the event may be re-claimed + * @param failureCode the publisher's code for the refusal or the unanswered publish * @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row */ - OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt); + OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt, String failureCode); /** * Gives a claimed row back without having tried to publish it: the row is claimable again from @@ -84,9 +92,11 @@ public interface OutboxStorePort { * manually resolved (see README). * * @param lease the claim this relay holds + * @param failureCode why the row was dead-lettered: the refusal's code, or the type of the last + * unclassified failure * @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row */ - OutboxCompletion markDead(OutboxLease lease); + OutboxCompletion markDead(OutboxLease lease, String failureCode); /** * Returns a count of unpublished rows grouped by {@link OutboxEventStatus} — gauge source for the @@ -107,4 +117,21 @@ public interface OutboxStorePort { * @return map from event type to oldest-unpublished-row age in seconds; absent when none */ Map oldestUnpublishedAgeSecondsByEventType(Instant now); + + /** + * The rows that have been retrying for a long time — FAILED, with at least {@code + * minDeferredClaims} claims deferred — counted, with the age of the oldest. Gauge source for + * {@code outbox.retry.long.size} and {@code outbox.retry.long.age}. Called outside a transaction + * (read-only). + * + *

        Deferred claims are the ones that do not spend the attempt budget, so they are also the ones + * with no end: a row that keeps collecting them is retried until someone looks. Counting them is + * how someone is told to look (re-review 2026-11-03 RR-05-03). + * + * @param minDeferredClaims how many deferred claims make a row long-retrying; at least 1 + * @param now current wall-clock time used to compute age + * @return the count and the oldest row's age since it occurred; {@link OutboxLongRetries#NONE} + * when no row qualifies + */ + OutboxLongRetries longRetries(int minDeferredClaims, Instant now); } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java index cb7060e0..68ae05cf 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java @@ -43,6 +43,9 @@ import java.util.function.Supplier; public final class PublishPendingOutboxEventsUseCase implements CommandUseCase { + /** The failure code of a thrown failure whose type has no simple name. */ + static final String UNNAMED_FAILURE = "UNNAMED_EXCEPTION"; + private final OutboxStorePort store; private final OutboxMessagePublishPort publishPort; private final OutboxRelayFailureReportPort failureReporter; @@ -168,34 +171,56 @@ public final class PublishPendingOutboxEventsUseCase */ private OutboxRelayResult.Outcome publishOne(OutboxLease lease) { ClaimedOutboxEvent event = lease.event(); - OutboxPublishOutcome achieved; + OutboxPublishAttempt attempt; try { // The outcome-valued call, not the throwing one. An adapter that cannot tell an ambiguous // publish apart still throws and is handled below exactly as before; one that can no longer // has to pretend a message it may have stored was definitely not stored. - achieved = publishPort.publishForOutcome(event); + attempt = publishPort.publishForOutcome(event); } catch (RuntimeException publishEx) { // Publish failure: drive FAILED/DEAD state machine + typed report; do NOT rethrow. return handlePublishFailure(lease, clock.instant(), publishEx); } + OutboxPublishOutcome achieved = attempt.outcome(); if (achieved == OutboxPublishOutcome.AMBIGUOUS) { // The message left this process and no acknowledgement arrived, so it may be stored. Treated // as retryable and reported as such: the duplicate risk is the caller's to bound with an // idempotency key, and the alternative — parking it — loses a message that was delivered. // It does not spend the attempt budget: a broker that stopped answering fails every row this // way, and parking them after three tries is what turned a short outage into DEAD rows. - return retryLater(lease, clock.instant(), new OutboxPublishAmbiguousException(), false); + // + // The same branch has no end for a refusal the broker client could not name. The Kafka + // adapter classifies a failure it does not recognise as ambiguous, so a record the broker + // will never take — a topic timestamp policy, a topic that does not exist — is retried here + // five minutes apart for as long as nobody looks, and its aggregate waits behind it. That is + // the price of not parking a delivered message, and it is paid in the open: the publisher's + // code is written on the row, outbox.retry.long.size counts the row once it has been deferred + // long enough, and the publish-failed runbook parks it (re-review 2026-11-03 RR-05-03). + return retryLater( + lease, + clock.instant(), + new OutboxPublishAmbiguousException(), + attempt.recordedFailureCode(), + false); } if (achieved == OutboxPublishOutcome.REJECTED_RETRYABLE) { // Refused for a reason that is about the moment — shutdown, saturation, a closed transport, // a credential being rotated — not about the message. Retried like an ambiguous outcome and - // for the same reason; the cause says it was a refusal, so no duplicate is suspected. - return retryLater(lease, clock.instant(), new OutboxPublishRefusedException(achieved), false); + // for the same reason; the cause says it was a refusal, so no duplicate is suspected. A + // credential that is really wrong ends up here too, for ever; the failure code is what tells + // it from a rotation. + return retryLater( + lease, + clock.instant(), + new OutboxPublishRefusedException(achieved), + attempt.recordedFailureCode(), + false); } if (achieved != OutboxPublishOutcome.CONFIRMED) { // Definite refusal. Retrying the same payload fails the same way, so the attempt budget is // not spent on it; the row is dead-lettered now rather than after the timer runs out. - return deadLetter(lease, new OutboxPublishRefusedException(achieved)); + return deadLetter( + lease, new OutboxPublishRefusedException(achieved), attempt.recordedFailureCode()); } // markPublished failure (if any) propagates: the row stays IN_FLIGHT and is // recovered via the orphan visibility-timeout reclaim path. @@ -220,11 +245,22 @@ public final class PublishPendingOutboxEventsUseCase */ private OutboxRelayResult.Outcome handlePublishFailure( OutboxLease lease, Instant failedAt, RuntimeException cause) { + String failureCode = failureCodeOf(cause); if (lease.event().budgetedAttemptCount() >= backoffPolicy.maxAttempts()) { // All attempts exhausted — DEAD-letter the event. - return deadLetter(lease, cause); + return deadLetter(lease, cause, failureCode); } - return retryLater(lease, failedAt, cause, true); + return retryLater(lease, failedAt, cause, failureCode, true); + } + + /** + * The code a thrown failure is recorded under: its type's simple name, which is a type and not + * content. A type with no usable name — an anonymous class — is recorded as {@value + * #UNNAMED_FAILURE}. + */ + private static String failureCodeOf(RuntimeException cause) { + String name = cause.getClass().getSimpleName(); + return OutboxPublishAttempt.isFailureCode(name) ? name : UNNAMED_FAILURE; } /** @@ -234,15 +270,19 @@ public final class PublishPendingOutboxEventsUseCase * only a {@code budgeted} failure is recorded as spending the budget. */ private OutboxRelayResult.Outcome retryLater( - OutboxLease lease, Instant failedAt, RuntimeException cause, boolean budgeted) { + OutboxLease lease, + Instant failedAt, + RuntimeException cause, + String failureCode, + boolean budgeted) { ClaimedOutboxEvent event = lease.event(); Instant nextAttemptAt = backoffPolicy.nextAttemptAt(event.attemptCount(), failedAt); OutboxCompletion completion = tx.inWrite( () -> budgeted - ? store.markFailed(lease, nextAttemptAt) - : store.markDeferred(lease, nextAttemptAt)); + ? store.markFailed(lease, nextAttemptAt, failureCode) + : store.markDeferred(lease, nextAttemptAt, failureCode)); if (completion == OutboxCompletion.STALE) { return stale(lease, OutboxRelayResult.Outcome.FAILED); } @@ -255,13 +295,15 @@ public final class PublishPendingOutboxEventsUseCase event.correlationId(), event.attemptCount(), nextAttemptAt, - cause)); + cause, + failureCode)); return OutboxRelayResult.Outcome.FAILED; } - private OutboxRelayResult.Outcome deadLetter(OutboxLease lease, RuntimeException cause) { + private OutboxRelayResult.Outcome deadLetter( + OutboxLease lease, RuntimeException cause, String failureCode) { ClaimedOutboxEvent event = lease.event(); - if (tx.inWrite(() -> store.markDead(lease)) == OutboxCompletion.STALE) { + if (tx.inWrite(() -> store.markDead(lease, failureCode)) == OutboxCompletion.STALE) { return stale(lease, OutboxRelayResult.Outcome.DEAD); } reportFailure( @@ -272,7 +314,8 @@ public final class PublishPendingOutboxEventsUseCase event.aggregateId(), event.correlationId(), event.attemptCount(), - cause)); + cause, + failureCode)); return OutboxRelayResult.Outcome.DEAD; } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java b/src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java index 3b642c04..54b9cb18 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java @@ -16,8 +16,13 @@ import java.lang.annotation.Target; * architecture rule that otherwise requires a permission on every {@code WRITE_REPOSITORY} use case * accepts it in place of one. * - *

        A use case marked this way must not become a Spring bean that a transport can reach; the - * composition that runs it constructs it directly. + *

        A use case marked this way is a write with no permission check, so a transport must never + * reach it. The composition that runs it constructs it directly and hands it to its system caller. + * Both ways a transport could reach it are refused: a bean of it fails startup ({@code + * composition:service-runtime} {@code PermissionEnforcementGuard}), and an inbound adapter that + * depends on it fails the architecture rule {@code + * INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES}. It is not a way to silence the rule that + * a mutating use case declares a permission: a write a user triggers declares one. */ @Documented @Retention(RetentionPolicy.RUNTIME) diff --git a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyExecutorTest.java b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyExecutorTest.java index 9975c742..73f2062d 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyExecutorTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyExecutorTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.transaction.OperationId; +import dev.caskeleton.shared.error.ApiErrorCarrier; import java.time.Duration; import java.time.Instant; import java.util.Optional; @@ -156,6 +157,94 @@ class IdempotencyExecutorTest { assertThat(store.completeCalls).isEqualTo(1); } + @Test + @DisplayName("claim 단계에서 저장소가 응답하지 않으면 action 을 돌리지 않고 실행 전 거부(IDEMPOTENCY_UNAVAILABLE)로 알린다") + void anUnavailableClaimIsARefusalBeforeTheActionRuns() { + // given + FakeStore store = new FakeStore(); + store.claim = new IdempotencyClaimOutcome.Unavailable(); + AtomicBoolean ran = new AtomicBoolean(); + + // when + Throwable thrown = + catchThrowable( + () -> + executor(store) + .execute( + SCOPE, + FINGERPRINT, + ATTEMPT, + () -> { + ran.set(true); + return new IdempotentAction.Outcome.Success<>("created"); + }, + codec())); + + // then + assertThat(errorCodeOf(thrown)).isEqualTo("IDEMPOTENCY_UNAVAILABLE"); + assertThat(ran).isFalse(); + } + + /** + * The action already ran when completion fails, so "refused before the action" would be false. + * Effects in the action's own transaction roll back with the exception; anything else it did has + * happened. The client must hear "outcome unknown" and resend with the same key, never "not + * applied" (re-review 2026-11-03 decision, RR-02-03). + */ + @Test + @DisplayName( + "action 뒤 complete 에서 저장소가 응답하지 않으면 실행 전 거부가 아니라 결과 불명(IDEMPOTENCY_COMPLETION_UNKNOWN)이다") + void anUnavailableCompletionAfterTheActionRanIsAnUnknownOutcome() { + // given + FakeStore store = startedStore(); + store.complete = IdempotencyCompleteOutcome.UNAVAILABLE; + AtomicBoolean ran = new AtomicBoolean(); + + // when + Throwable thrown = + catchThrowable( + () -> + executor(store) + .execute( + SCOPE, + FINGERPRINT, + ATTEMPT, + () -> { + ran.set(true); + return new IdempotentAction.Outcome.Success<>("created"); + }, + codec())); + + // then + assertThat(ran).isTrue(); + assertThat(errorCodeOf(thrown)).isEqualTo("IDEMPOTENCY_COMPLETION_UNKNOWN"); + } + + @Test + @DisplayName("응답을 잃은 complete 를 확인하려는데 저장소가 응답하지 않아도 결과 불명(IDEMPOTENCY_COMPLETION_UNKNOWN)이다") + void anUnavailableInspectionOfALostCompletionIsAnUnknownOutcome() { + // given + FakeStore store = startedStore(); + store.complete = IdempotencyCompleteOutcome.INDETERMINATE; + store.inspectionAfterComplete = + IdempotencyInspection.outcome(IdempotencyInspectionOutcome.UNAVAILABLE); + + // when + Throwable thrown = + catchThrowable( + () -> + executor(store) + .execute( + SCOPE, + FINGERPRINT, + ATTEMPT, + () -> new IdempotentAction.Outcome.Success<>("created"), + codec())); + + // then + assertThat(errorCodeOf(thrown)).isEqualTo("IDEMPOTENCY_COMPLETION_UNKNOWN"); + } + @Test @DisplayName("a replayed response that disagrees with this caller's is a recovery, not a result") void aConflictingReplayIsNotReturned() { @@ -282,6 +371,11 @@ class IdempotencyExecutorTest { return store; } + private static String errorCodeOf(Throwable thrown) { + assertThat(thrown).isInstanceOf(ApiErrorCarrier.class); + return ((ApiErrorCarrier) thrown).errorCode().code(); + } + private static IdempotencyExecutor executor(FakeStore store) { return new IdempotencyExecutor( store, Duration.ofSeconds(30), Duration.ofHours(1), Duration.ofHours(1), "json-v2", 1); diff --git a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyFailureCodeTest.java b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyFailureCodeTest.java index 951216b0..d778f7b5 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyFailureCodeTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyFailureCodeTest.java @@ -21,6 +21,9 @@ class IdempotencyFailureCodeTest { OperationalError.IDEMPOTENT_REQUEST_MISMATCH), Arguments.of( new IdempotencyUnavailableException(), OperationalError.IDEMPOTENCY_UNAVAILABLE), + Arguments.of( + new IdempotencyCompletionUnknownException(), + OperationalError.IDEMPOTENCY_COMPLETION_UNKNOWN), Arguments.of( new IdempotencyRecoveryRequiredException("outcome unknown"), OperationalError.IDEMPOTENCY_RECOVERY_REQUIRED)); diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/ApplicationPayloadSchemaReleaseTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/ApplicationPayloadSchemaReleaseTest.java new file mode 100644 index 00000000..7703a689 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/ApplicationPayloadSchemaReleaseTest.java @@ -0,0 +1,18 @@ +package dev.caskeleton.application.messaging.contract; + +import dev.caskeleton.application.messaging.contract.testkit.ReleasedPayloadSchemaContract; +import java.nio.file.Path; + +/** The payload schemas application-core publishes ({@code durable-operation.submitted}). */ +class ApplicationPayloadSchemaReleaseTest extends ReleasedPayloadSchemaContract { + + @Override + protected Path schemaRoot() { + return Path.of("src/main/resources/contracts/messaging"); + } + + @Override + protected Path manifest() { + return Path.of("src/test/resources/contracts/released-payload-schemas.sha256"); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftTest.java index 96155e73..ca0e5d39 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftTest.java @@ -2,16 +2,83 @@ package dev.caskeleton.application.messaging.event; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.IntegrationPayload; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; import java.time.Instant; import java.util.Optional; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; class IntegrationEventDraftTest { + /** A canonical lower-case UUIDv7: the only spelling the messaging platform carries. */ + private static final String EVENT_ID = "01994e11-4d88-7000-8000-0000000000e1"; + + private static final String CAUSATION_ID = "01994e11-4d88-7000-8000-0000000000c1"; + + /** + * The bridge sends an event under its id as the platform's {@code MessageId}, a canonical + * lower-case UUIDv7, and refuses any other — after the business transaction committed, as a DEAD + * row that blocks the aggregate. A draft is where such an id is refused first, in the writer's + * transaction (review 06-06, re-review 2026-11-03 RR-05-04). + */ + @ParameterizedTest + @ValueSource( + strings = { + "event-1", + "01994E11-4D88-7000-8000-0000000000E1", + "6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b", + "1-2-3-4-5" + }) + @DisplayName("정규 소문자 UUIDv7이 아닌 event id로는 draft를 만들지 않는다") + void aDraftRefusesAnEventIdThatIsNotACanonicalUuidV7(String eventId) { + // given + EventId id = new EventId(eventId); + + // when + Throwable thrown = catchThrowable(() -> draftWithIds(id, Optional.empty())); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventId must be a canonical lower-case UUIDv7"); + } + + @Test + @DisplayName("정규 소문자 UUIDv7이 아닌 causation id로는 draft를 만들지 않는다") + void aDraftRefusesACausationIdThatIsNotACanonicalUuidV7() { + // given + Optional causation = Optional.of("cause-1"); + + // when + Throwable thrown = catchThrowable(() -> draftWithIds(new EventId(EVENT_ID), causation)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("causationId must be a canonical lower-case UUIDv7"); + } + + private static IntegrationEventDraft draftWithIds( + EventId eventId, Optional causationId) { + return new IntegrationEventDraft<>( + eventId, + new ContractId("portfolio.worklog.reserved"), + 1, + new LogicalDestinationId("portfolio-domain-events"), + new AggregateIdentity("tenant-a", "worklog", "worklog-42"), + new AggregateOrder(17, 0), + Instant.parse("2026-07-28T05:10:30.123Z"), + "corr-1", + causationId, + new TestPayload("worklog-42")); + } + @Test void eventIdAcceptsOnlyBoundedCanonicalUsAscii() { assertThat(new EventId("A0:event.id-1").value()).isEqualTo("A0:event.id-1"); @@ -53,14 +120,14 @@ class IntegrationEventDraftTest { @Test void draftRequiresPositiveVersionTimeCanonicalCorrelationAndTypedPayload() { TestPayload payload = new TestPayload("worklog-42"); - IntegrationEventDraft draft = draft(payload, Optional.of("cause-1")); + IntegrationEventDraft draft = draft(payload, Optional.of(CAUSATION_ID)); assertThat(draft.featurePayload()).isSameAs(payload); assertThat(draft.occurredAt()).isEqualTo(Instant.parse("2026-07-28T05:10:30.123Z")); assertThatThrownBy( () -> new IntegrationEventDraft<>( - new EventId("event-1"), + new EventId(EVENT_ID), new ContractId("portfolio.worklog.reserved"), 0, new LogicalDestinationId("portfolio-domain-events"), @@ -74,7 +141,7 @@ class IntegrationEventDraftTest { assertThatThrownBy( () -> new IntegrationEventDraft<>( - new EventId("event-1"), + new EventId(EVENT_ID), new ContractId("portfolio.worklog.reserved"), 1, new LogicalDestinationId("portfolio-domain-events"), @@ -103,7 +170,7 @@ class IntegrationEventDraftTest { private static IntegrationEventDraft draft( TestPayload payload, Optional causationId) { return new IntegrationEventDraft<>( - new EventId("event-1"), + new EventId(EVENT_ID), new ContractId("portfolio.worklog.reserved"), 1, new LogicalDestinationId("portfolio-domain-events"), diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftsTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftsTest.java index 2e73b071..adedd81d 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftsTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationEventDraftsTest.java @@ -13,7 +13,7 @@ import org.junit.jupiter.params.provider.ValueSource; class IntegrationEventDraftsTest { - private static final EventId EVENT_ID = new EventId("event-1"); + private static final EventId EVENT_ID = new EventId("01994e11-4d88-7000-8000-0000000000e1"); private static final Instant OCCURRED_AT = Instant.parse("2026-11-01T00:00:00.000001Z"); private static final AggregateIdentity AGGREGATE = new AggregateIdentity(IntegrationEventDrafts.SINGLE_TENANT_SCOPE, "kit", "kit-1"); diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationIdentityTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationIdentityTest.java index e044c662..39e42db9 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationIdentityTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/event/IntegrationIdentityTest.java @@ -74,7 +74,7 @@ class IntegrationIdentityTest { private static IntegrationEventDraft draftWithCorrelation(String correlationId) { return new IntegrationEventDraft<>( - new EventId("event-1"), + new EventId("01994e11-4d88-7000-8000-0000000000e1"), new ContractId("portfolio.worklog.reserved"), 1, new LogicalDestinationId("portfolio-domain-events"), 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 d26132f1..ac469e2d 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 @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.messaging.event.IntegrationIdentity; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore; @@ -18,6 +19,8 @@ import java.time.ZoneOffset; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * The two writes that must not come apart. @@ -30,7 +33,11 @@ import org.junit.jupiter.api.Test; class SubmitDurableOperationUseCaseTest { private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final DurableOperationId ID = new DurableOperationId("op-1"); + + /** An id the HTTP adapter mints: a canonical lower-case UUIDv7, used as the event id itself. */ + private static final String OPERATION_UUID = "01994e11-4d88-7000-8000-0000000000a1"; + + private static final DurableOperationId ID = new DurableOperationId(OPERATION_UUID); // Both stores join the in-memory port's transactions and undo their writes when one rolls back, // as the database does. A port that simply ran the action would let rollbackLeavesNothing pass @@ -151,8 +158,8 @@ class SubmitDurableOperationUseCaseTest { e -> e.contractId(), e -> e.logicalDestinationId()) .containsExactly( - "op-1", - "op-1", + OPERATION_UUID, + OPERATION_UUID, DurableOperationSubmittedContract.CONTRACT_ID, DurableOperationSubmittedContract.DESTINATION); } @@ -166,21 +173,46 @@ class SubmitDurableOperationUseCaseTest { // The worker reads what to run from the submission it claims; the request never travels. assertThat(encoder.drafts()) .extracting(draft -> draft.featurePayload()) - .containsExactly(new DurableOperationSubmitted("op-1", "reports.generate")); + .containsExactly(new DurableOperationSubmitted(OPERATION_UUID, "reports.generate")); + } + + /** + * An event id is the platform's message id, a canonical lower-case UUIDv7, or the bridge parks + * the event after the operation committed. An operation id that is anything else — a client's own + * id, {@code ~} included — becomes a UUIDv7 derived from it and the submission time: the same + * operation always gets the same event id (review 06-06, re-review 2026-11-03 RR-05-04). + */ + @ParameterizedTest + @ValueSource(strings = {"~report", "op-1", "01994E11-4D88-7000-8000-0000000000A1"}) + @DisplayName("UUIDv7이 아닌 operation id는 그 id에서 만든 같은 UUIDv7 event id가 된다") + void anOperationIdThatIsNotAUuidV7BecomesAStableUuidV7DerivedFromIt(String operationId) { + // given + DurableOperationId id = new DurableOperationId(operationId); + + // when + String identity = SubmitDurableOperationUseCase.canonicalIdentity(id, NOW); + + // then + assertThat(List.of(identity, SubmitDurableOperationUseCase.canonicalIdentity(id, NOW))) + .allMatch(IntegrationIdentity::isCanonicalUuidV7) + .containsOnly(identity) + .doesNotContain(operationId); } @Test - void anOperationIdOutsideTheEventIdGrammarBecomesAStableDigestIdentity() { + @DisplayName("UUIDv7이 아닌 operation id로 받은 작업도 outbox에 발행할 수 있는 event로 남는다") + void aSubmissionUnderAClientChosenIdStillAppendsAPublishableEvent() { // given - DurableOperationId tilde = new DurableOperationId("~report"); + DurableOperationId clientChosen = new DurableOperationId("~report"); // when - String identity = SubmitDurableOperationUseCase.canonicalIdentity(tilde); + useCase.handle(command(clientChosen, "c".repeat(64))); // then - assertThat(List.of(identity, SubmitDurableOperationUseCase.canonicalIdentity(tilde))) - .allMatch(value -> value.matches("operation-[0-9a-f]{64}")) - .containsOnly(identity); + assertThat(outbox.appended()) + .singleElement() + .extracting(event -> event.eventId().value()) + .matches(IntegrationIdentity::isCanonicalUuidV7); } /** The in-memory outbox, failing its next append when told to. */ diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPublishOutcomeTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPublishOutcomeTest.java index a64468b8..4b486185 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPublishOutcomeTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxPublishOutcomeTest.java @@ -72,6 +72,6 @@ class OutboxPublishOutcomeTest { assertThat(legacy.publishForOutcome(null)) .as("'returned without throwing' has always meant confirmed for such an adapter") - .isEqualTo(OutboxPublishOutcome.CONFIRMED); + .isEqualTo(OutboxPublishAttempt.confirmed()); } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxRelayFailureReportTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxRelayFailureReportTest.java index 008f9a52..f01055af 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxRelayFailureReportTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutboxRelayFailureReportTest.java @@ -7,12 +7,14 @@ import dev.caskeleton.shared.error.OperationalError; import java.lang.reflect.RecordComponent; import java.time.Instant; import java.util.Arrays; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class OutboxRelayFailureReportTest { private static final Instant NEXT_ATTEMPT_AT = Instant.parse("2026-07-25T01:02:03Z"); private static final RuntimeException CAUSE = new RuntimeException("broker unavailable"); + private static final String CODE = "KAFKA_TIMEOUTEXCEPTION"; @Test void recordComponentsAreAnExactSafeAllowlist() { @@ -29,14 +31,16 @@ class OutboxRelayFailureReportTest { "nextAttemptAt", // Not "cause": a Throwable component is a Throwable in the operational JSON, and the // allowlist that guards every other field had no say over its message or stack. - "causeType"); + "causeType", + // A bounded code, never a message (re-review 2026-11-03 RR-05-03). + "failureCode"); } @Test void retryableFailureFactoryCreatesPublishFailedReport() { OutboxRelayFailureReport report = OutboxRelayFailureReport.retryableFailure( - "evt-1", "WorkLogReserved", "agg-1", "corr-1", 2, NEXT_ATTEMPT_AT, CAUSE); + "evt-1", "WorkLogReserved", "agg-1", "corr-1", 2, NEXT_ATTEMPT_AT, CAUSE, CODE); assertThat(report.code()).isEqualTo(OperationalError.OUTBOX_PUBLISH_FAILED); assertThat(report.eventId()).isEqualTo("evt-1"); @@ -54,7 +58,7 @@ class OutboxRelayFailureReportTest { void deadLetterFactoryCreatesTerminalReportWithoutRetryTime() { OutboxRelayFailureReport report = OutboxRelayFailureReport.deadLetter( - "evt-1", "WorkLogReserved", "agg-1", "corr-1", 3, CAUSE); + "evt-1", "WorkLogReserved", "agg-1", "corr-1", 3, CAUSE, CODE); assertThat(report.code()).isEqualTo(OperationalError.OUTBOX_DEAD_LETTER); assertThat(report.nextAttemptAt()).isNull(); @@ -75,7 +79,8 @@ class OutboxRelayFailureReportTest { "corr-1", 1, null, - CAUSE.getClass().getName())) + CAUSE.getClass().getName(), + CODE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("code"); } @@ -83,19 +88,26 @@ class OutboxRelayFailureReportTest { @Test void rejectsBlankIdentifiersAndEventType() { assertThatThrownBy( - () -> OutboxRelayFailureReport.deadLetter(" ", "Event", "agg-1", "corr-1", 1, CAUSE)) + () -> + OutboxRelayFailureReport.deadLetter( + " ", "Event", "agg-1", "corr-1", 1, CAUSE, CODE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("eventId"); assertThatThrownBy( - () -> OutboxRelayFailureReport.deadLetter("evt-1", "", "agg-1", "corr-1", 1, CAUSE)) + () -> + OutboxRelayFailureReport.deadLetter("evt-1", "", "agg-1", "corr-1", 1, CAUSE, CODE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("eventType"); assertThatThrownBy( - () -> OutboxRelayFailureReport.deadLetter("evt-1", "Event", "\t", "corr-1", 1, CAUSE)) + () -> + OutboxRelayFailureReport.deadLetter( + "evt-1", "Event", "\t", "corr-1", 1, CAUSE, CODE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("aggregateId"); assertThatThrownBy( - () -> OutboxRelayFailureReport.deadLetter("evt-1", "Event", "agg-1", "\n", 1, CAUSE)) + () -> + OutboxRelayFailureReport.deadLetter( + "evt-1", "Event", "agg-1", "\n", 1, CAUSE, CODE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("correlationId"); } @@ -104,7 +116,8 @@ class OutboxRelayFailureReportTest { void rejectsAttemptCountBelowOne() { assertThatThrownBy( () -> - OutboxRelayFailureReport.deadLetter("evt-1", "Event", "agg-1", "corr-1", 0, CAUSE)) + OutboxRelayFailureReport.deadLetter( + "evt-1", "Event", "agg-1", "corr-1", 0, CAUSE, CODE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("attemptCount"); } @@ -121,7 +134,8 @@ class OutboxRelayFailureReportTest { "corr-1", 1, null, - CAUSE.getClass().getName())) + CAUSE.getClass().getName(), + CODE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("nextAttemptAt"); } @@ -138,15 +152,29 @@ class OutboxRelayFailureReportTest { "corr-1", 1, NEXT_ATTEMPT_AT, - CAUSE.getClass().getName())) + CAUSE.getClass().getName(), + CODE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("nextAttemptAt"); } + @Test + @DisplayName("원인 코드 자리에 문장을 넣으면 보고를 만들지 않는다") + void aSentenceIsRefusedAsAFailureCode() { + assertThatThrownBy( + () -> + OutboxRelayFailureReport.deadLetter( + "evt-1", "Event", "agg-1", "corr-1", 1, CAUSE, "connect to 10.0.0.7 failed")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("failureCode"); + } + @Test void causeIsRequired() { assertThatThrownBy( - () -> OutboxRelayFailureReport.deadLetter("evt-1", "Event", "agg-1", "corr-1", 1, null)) + () -> + OutboxRelayFailureReport.deadLetter( + "evt-1", "Event", "agg-1", "corr-1", 1, null, CODE)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("cause"); } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java index 5c664c0d..e6d7d2a0 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java @@ -131,7 +131,8 @@ class PublishPendingOutboxEventsUseCaseTest { "correlation-evt-fail", 1, nextAttemptAt, - brokerDown)); + brokerDown, + "RuntimeException")); } @Test @@ -155,7 +156,8 @@ class PublishPendingOutboxEventsUseCaseTest { "agg-1", "correlation-evt-dead", 3, - brokerDown)); + brokerDown, + "RuntimeException")); } // ---- failure NOT swallowed ---- @@ -476,15 +478,15 @@ class PublishPendingOutboxEventsUseCaseTest { } @Override - public OutboxCompletion markFailed(OutboxLease lease, Instant retryAt) { + public OutboxCompletion markFailed(OutboxLease lease, Instant retryAt, String failureCode) { markFailedCalls++; - return super.markFailed(lease, retryAt); + return super.markFailed(lease, retryAt, failureCode); } @Override - public OutboxCompletion markDead(OutboxLease lease) { + public OutboxCompletion markDead(OutboxLease lease, String failureCode) { markDeadCalls++; - return super.markDead(lease); + return super.markDead(lease, failureCode); } OutboxEventStatus currentStatus() { @@ -519,19 +521,20 @@ class PublishPendingOutboxEventsUseCaseTest { } @Override - public OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { + public OutboxCompletion markFailed( + OutboxLease lease, Instant nextAttemptAt, String failureCode) { if (markFailedException != null) { throw markFailedException; } - return super.markFailed(lease, nextAttemptAt); + return super.markFailed(lease, nextAttemptAt, failureCode); } @Override - public OutboxCompletion markDead(OutboxLease lease) { + public OutboxCompletion markDead(OutboxLease lease, String failureCode) { if (markDeadException != null) { throw markDeadException; } - return super.markDead(lease); + return super.markDead(lease, failureCode); } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java index 04fbc520..40104494 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/TransientPublishFailureRelayTest.java @@ -85,6 +85,58 @@ class TransientPublishFailureRelayTest { .isNotNull(); } + @Test + @DisplayName("다시 시도할 거부는 publisher가 붙인 원인 코드를 행과 실패 보고에 남긴다") + void aRetryableRefusalLeavesThePublishersFailureCodeOnTheRowAndInTheReport() { + // given: the broker refused this producer's credentials + store.addClaimable(OutboxEvents.claimed("evt-credential", START.minusSeconds(1), 1)); + port.answering( + OutboxPublishAttempt.failed( + OutboxPublishOutcome.REJECTED_RETRYABLE, "KAFKA_AUTHENTICATIONEXCEPTION")); + + // when + relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then: what the outcome cannot say — a credential, not a shutdown — is on both + assertThat( + List.of( + store.lastFailureCode("evt-credential"), + reports.getFirst().failureCode(), + reports.getFirst().causeType())) + .containsExactly( + "KAFKA_AUTHENTICATIONEXCEPTION", + "KAFKA_AUTHENTICATIONEXCEPTION", + OutboxPublishRefusedException.class.getName()); + } + + @Test + @DisplayName("원인 코드 없이 응답이 없던 발행은 결과 이름을 원인 코드로 남긴다") + void anUnansweredPublishWithoutACodeIsRecordedUnderItsOutcomesName() { + // given + store.addClaimable(OutboxEvents.claimed("evt-silent", START.minusSeconds(1), 1)); + port.answering(OutboxPublishAttempt.of(OutboxPublishOutcome.AMBIGUOUS)); + + // when + relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then + assertThat(store.lastFailureCode("evt-silent")).isEqualTo("AMBIGUOUS"); + } + + @Test + @DisplayName("분류되지 않고 던져진 실패는 예외 타입 이름을 원인 코드로 남긴다") + void anUnclassifiedThrownFailureIsRecordedUnderItsTypesName() { + // given + store.addClaimable(OutboxEvents.claimed("evt-thrown", START.minusSeconds(1), 1)); + port.throwing(new IllegalStateException("driver said: host=10.0.0.7 password=hunter2")); + + // when + relay.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then: the type, never the message + assertThat(store.lastFailureCode("evt-thrown")).isEqualTo("IllegalStateException"); + } + @Test @DisplayName("일시적 실패는 시도 예산을 다 쓴 행도 DEAD로 보내지 않는다") void aTransientFailureNeverDeadLettersEvenPastTheAttemptBudget() { diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisherContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisherContractTest.java index 96ff3a23..f9f82d6b 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisherContractTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisherContractTest.java @@ -37,7 +37,7 @@ class FakeOutboxMessagePublisherContractTest extends OutboxMessagePublishContrac .answering(CLAIMED_EVENT_ID, OutboxPublishOutcome.REJECTED_BEFORE_SEND); // when - OutboxPublishOutcome outcome = publisher.publishForOutcome(claimedRow()); + OutboxPublishOutcome outcome = publisher.publishForOutcome(claimedRow()).outcome(); // then assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND); @@ -68,7 +68,7 @@ class FakeOutboxMessagePublisherContractTest extends OutboxMessagePublishContrac .answering(OutboxPublishOutcome.REJECTED_RETRYABLE); // when - OutboxPublishOutcome outcome = publisher.publishForOutcome(claimedRow()); + OutboxPublishOutcome outcome = publisher.publishForOutcome(claimedRow()).outcome(); // then assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_RETRYABLE); diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequenceContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequenceContractTest.java index 499a43cb..c8fdde54 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequenceContractTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequenceContractTest.java @@ -6,7 +6,9 @@ import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; class InMemoryOutboxAggregateSequenceContractTest extends OutboxAggregateSequenceContract { - private final InMemoryOutboxAggregateSequences sequences = new InMemoryOutboxAggregateSequences(); + private final DirectTransactionPort transactions = new DirectTransactionPort(); + private final InMemoryOutboxAggregateSequences sequences = + new InMemoryOutboxAggregateSequences(transactions); @Override protected OutboxAggregateSequencePort sequences() { @@ -15,6 +17,6 @@ class InMemoryOutboxAggregateSequenceContractTest extends OutboxAggregateSequenc @Override protected TransactionPort transactions() { - return new DirectTransactionPort(); + return transactions; } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreLeaseFencingContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreLeaseFencingContractTest.java index 49f51433..be1a30cc 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreLeaseFencingContractTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreLeaseFencingContractTest.java @@ -29,4 +29,9 @@ class InMemoryOutboxStoreLeaseFencingContractTest extends OutboxLeaseFencingCont protected OutboxEventStatus statusOf(String eventId) { return store.status(eventId); } + + @Override + protected String lastFailureCodeOf(String eventId) { + return store.lastFailureCode(eventId); + } } diff --git a/src/application-core/src/test/resources/contracts/released-payload-schemas.sha256 b/src/application-core/src/test/resources/contracts/released-payload-schemas.sha256 new file mode 100644 index 00000000..b2f1e29a --- /dev/null +++ b/src/application-core/src/test/resources/contracts/released-payload-schemas.sha256 @@ -0,0 +1,4 @@ +# SHA-256 (LF-normalized) of every released payload schema version in src/main/resources/contracts/messaging. +# A released version is never edited: a change goes into a new version (application-core README). +# Add a line when a version is released; change a line only for a version no one can have consumed. +4d2f780bf6c23fa548fc2b0e6ef02302e17fca44a20f21ebf5ba07aaac11a245 durable-operation.submitted/v1.schema.json diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/CacheRegionContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/CacheRegionContract.java index 3d03e322..63fbd552 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/CacheRegionContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/cache/testkit/CacheRegionContract.java @@ -179,6 +179,25 @@ public abstract class CacheRegionContract { assertThat(valueOf(region.lookup("k"))).isEqualTo("at-10"); } + /** + * 2^53 + 1 against 2^53: a floating-point parse reads both as the same number, so a provider that + * compares revisions as doubles refuses the newer one (review 2026-11-03 RR-01-06). + */ + @Test + @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 2^53보다 큰 revision도 한 자리 차이를 구분한다") + void onlyIfSourceRevisionNewerTellsApartRevisionsAboveTwoToTheFiftyThird() { + // given + CacheRegionPort region = region(); + region.record("k", "at-2^53", upsert("9007199254740992")); + + // when + CacheRecordOutcome outcome = + region.record("k", "at-2^53+1", newerThanStored("9007199254740993")); + + // then + assertThat(outcome).isEqualTo(CacheRecordOutcome.RECORDED); + } + @Test @DisplayName("ONLY_IF_SOURCE_REVISION_NEWER는 비어 있는 키에 기록한다") void onlyIfSourceRevisionNewerRecordsIntoAnEmptyKey() { diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java index 297ce65f..29bfef2f 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java @@ -22,6 +22,7 @@ import dev.caskeleton.application.idempotency.StoredResponse; import dev.caskeleton.application.transaction.OperationId; import java.time.Duration; import java.util.function.Supplier; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -34,7 +35,10 @@ import org.junit.jupiter.api.Test; * trusts, and those cases stay with each store's own tests. The one timed case is the one a caller * relies on whichever store is composed — {@code renew} really extends the lease (review 05-02: the * Redis store answered a renew as already applied and let the lease run out). A store reaches time - * through {@link #elapse(Duration)}; the in-memory fake has no expiry and leaves it a no-op. + * through {@link #elapse(Duration)}. A store that cannot move its clock — the in-memory fake, which + * models no expiry, and the Redis store over the command fake — keeps the default, which aborts the + * timed case so the report shows it skipped instead of passing a case that never ran its clock + * (review 2026-11-03 RR-01-06). * *

        Every call goes through {@link #inTransaction(Supplier)}, the way the store's callers make it: * the PostgreSQL store refuses to run outside an application-owned write transaction. @@ -81,12 +85,16 @@ public abstract class IdempotencyStoreContract { } /** - * Lets {@code duration} pass on the clock the store trusts. A store without lease expiry keeps - * the default no-op. + * Lets {@code duration} pass on the clock the store trusts. The default aborts the calling test: + * a store without a clock the contract can move cannot run a timed case, and a no-op here would + * let that case pass without time ever passing. * * @param duration how long to let pass */ - protected void elapse(Duration duration) {} + protected void elapse(Duration duration) { + Assumptions.abort( + "this store has no clock the contract can move, so the timed case does not run against it"); + } private IdempotencyStorePort subject() { return new EachCallInTransaction(store()); @@ -360,6 +368,30 @@ public abstract class IdempotencyStoreContract { assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class); } + @Test + @DisplayName("renew한 처리 lease는 claim이 정한 replay TTL보다 길어도 그동안 기록이 사라져 다른 요청에 넘어가지 않는다") + void aLeaseRenewedPastTheReplayTtlKeepsTheRecord() { + // given + IdempotencyStorePort store = subject(); + Duration lease = processingLease(); + IdempotencyClaimRequest shortReplay = + new IdempotencyClaimRequest( + SCOPE, FINGERPRINT, store.newClaimAttempt(OPERATION), lease, lease, "json-v2", 1); + IdempotencyOwner claimed = + ((IdempotencyClaimOutcome.Acquired) store.claim(shortReplay)).owner(); + IdempotencyOwner executing = + store.markExecutionStarted(claimed, OPERATION).owner().orElseThrow(); + store.renew(executing, lease.multipliedBy(3), OPERATION); + elapse(lease.multipliedBy(2)); + + // when + IdempotencyClaimOutcome other = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT, lease)); + + // then + assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class); + } + /** Routes every call of the store through {@link #inTransaction(Supplier)}. */ private final class EachCallInTransaction implements IdempotencyStorePort { diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/contract/testkit/ReleasedPayloadSchemaContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/contract/testkit/ReleasedPayloadSchemaContract.java new file mode 100644 index 00000000..fc35a68e --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/contract/testkit/ReleasedPayloadSchemaContract.java @@ -0,0 +1,115 @@ +package dev.caskeleton.application.messaging.contract.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.shared.digest.Sha256; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.TreeMap; +import java.util.regex.Pattern; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * A released payload schema version is never edited (review 2026-11-01 06-10). + * + *

        An event's payload schema is {@code contracts/messaging//v.schema.json}. Once a + * version has been published, consumers have been built against it and the outbox and the broker + * hold events written under it, so changing its bytes — a field removed, a type changed — breaks + * them in an order that depends on who deploys first. The encoder checks only that the declared + * hash is the file's hash, and both move together in one edit. The rule the messaging design sets + * (strict versioning: "같은 version file의 checksum 변경은 CI 실패") had nothing enforcing it. + * + *

        The leaf that owns schemas pins each released version's SHA-256 in a manifest, as the + * persistence leaves pin applied migrations: an edited version fails, and a new version fails until + * it is pinned, which is the moment it is released. A change goes into a new version, and the + * version procedure (application-core README "payload version 올리기") is how consumers get it. + * + *

        What this deliberately does not do is diff a version against the one before. A new version may + * change anything — that is why it is a new version, read by consumers that support it before a + * producer emits it — and the design does not claim compatibility from a JSON Schema diff. + */ +public abstract class ReleasedPayloadSchemaContract { + + private static final Pattern SCHEMA_FILE = Pattern.compile("[^/]+/v[1-9][0-9]*\\.schema\\.json"); + + /** The directory holding {@code /v.schema.json}, relative to the leaf. */ + protected abstract Path schemaRoot(); + + /** + * The manifest of released versions: {@code /v.schema.json} per line, + * {@code #} comments allowed. + */ + protected abstract Path manifest(); + + @Test + @DisplayName("이미 출시한 payload schema 버전 파일은 바이트가 바뀌지 않는다") + void aReleasedPayloadSchemaVersionKeepsItsBytes() { + // given + Map released = released(); + + // when + Map current = current(); + + // then + assertThat(current) + .as( + "a released payload schema changed; put the change in a new version (%s)", + "application-core README, payload version 올리기") + .containsAllEntriesOf(released); + } + + @Test + @DisplayName("모든 payload schema 버전 파일은 출시 목록에 고정돼 있다") + void everyPayloadSchemaVersionIsPinnedInTheManifest() { + // given + Map released = released(); + + // when + Map current = current(); + + // then + assertThat(released.keySet()) + .as("pin a new payload schema version in %s when it is released", manifest()) + .containsAll(current.keySet()); + } + + private Map released() { + Map pinned = new TreeMap<>(); + try { + for (String line : Files.readAllLines(manifest(), StandardCharsets.UTF_8)) { + String trimmed = line.strip(); + if (trimmed.isEmpty() || trimmed.startsWith("#")) { + continue; + } + String[] fields = trimmed.split("\\s+", 2); + pinned.put(fields[1], fields[0]); + } + } catch (IOException exception) { + throw new UncheckedIOException(exception); + } + return pinned; + } + + /** Every version file under the root, by relative path, with the SHA-256 of its LF bytes. */ + private Map current() { + Map hashes = new TreeMap<>(); + try (Stream files = Files.walk(schemaRoot())) { + for (Path file : files.filter(Files::isRegularFile).toList()) { + String relative = schemaRoot().relativize(file).toString().replace('\\', '/'); + if (SCHEMA_FILE.matcher(relative).matches()) { + String content = Files.readString(file, StandardCharsets.UTF_8).replace("\r\n", "\n"); + hashes.put(relative, Sha256.ofUtf8(content).hex()); + } + } + } catch (IOException exception) { + throw new UncheckedIOException(exception); + } + return hashes; + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisher.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisher.java index 4d2a5ad4..b7fe8a5c 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisher.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/FakeIntegrationEventPublisher.java @@ -2,6 +2,7 @@ package dev.caskeleton.application.messaging.event.testkit; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.OutboxPublishAttempt; import dev.caskeleton.application.outbox.OutboxPublishOutcome; import java.util.ArrayList; import java.util.List; @@ -17,21 +18,32 @@ import java.util.concurrent.CompletionStage; public final class FakeIntegrationEventPublisher implements IntegrationEventPublishPort { private final List published = new ArrayList<>(); - private OutboxPublishOutcome answer = OutboxPublishOutcome.CONFIRMED; + private OutboxPublishAttempt answer = OutboxPublishAttempt.confirmed(); /** - * Answers every later publish with {@code outcome}. + * Answers every later publish with {@code outcome}, and for anything but a confirmation the + * outcome's own name as its failure code. * * @param outcome the outcome to report * @return this fake */ public FakeIntegrationEventPublisher answering(OutboxPublishOutcome outcome) { - this.answer = Objects.requireNonNull(outcome, "outcome"); + return answering(attemptOf(outcome)); + } + + /** + * Answers every later publish with {@code attempt}, failure code included. + * + * @param attempt the attempt to report + * @return this fake + */ + public FakeIntegrationEventPublisher answering(OutboxPublishAttempt attempt) { + this.answer = Objects.requireNonNull(attempt, "attempt"); return this; } @Override - public CompletionStage publish(ValidatedIntegrationEvent event) { + public CompletionStage publish(ValidatedIntegrationEvent event) { published.add(Objects.requireNonNull(event, "event must not be null")); return CompletableFuture.completedFuture(answer); } @@ -57,4 +69,17 @@ public final class FakeIntegrationEventPublisher implements IntegrationEventPubl case REFUSES_AFTER_RECEIVING -> OutboxPublishOutcome.REJECTED_AFTER_BROKER; }; } + + /** + * The attempt a publisher that names its failures reports for {@code outcome}: the outcome, and + * unless it is a confirmation, a code — the outcome's name, standing in for a broker's own. + * + * @param outcome the outcome + * @return the attempt + */ + public static OutboxPublishAttempt attemptOf(OutboxPublishOutcome outcome) { + return outcome == OutboxPublishOutcome.CONFIRMED + ? OutboxPublishAttempt.confirmed() + : OutboxPublishAttempt.failed(outcome, outcome.name()); + } } diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventEncoderContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventEncoderContract.java index 2f5a4182..510937b9 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventEncoderContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventEncoderContract.java @@ -132,7 +132,7 @@ public abstract class IntegrationEventEncoderContract { LogicalDestinationId destination, IntegrationPayload payload) { ContractId contractId = EncoderContractKitContract.CONTRACT_ID; return new IntegrationEventDraft<>( - new EventId("event-1"), + new EventId("01994e11-4d88-7000-8000-0000000000e1"), contractId, 1, destination, diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventPublishContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventPublishContract.java index 7863777b..a1231f37 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventPublishContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/messaging/event/testkit/IntegrationEventPublishContract.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; +import dev.caskeleton.application.outbox.OutboxPublishAttempt; import dev.caskeleton.application.outbox.OutboxPublishOutcome; import dev.caskeleton.application.outbox.testkit.OutboxEvents; import java.time.Instant; @@ -15,12 +16,16 @@ import org.junit.jupiter.api.Test; * What every {@link IntegrationEventPublishPort} promises, run by the platform bridge's test and * the fake's test alike (review 2026-11-01 TEST-F-1). * - *

        The relay acts on the outcome alone: it marks a row published, retries it, or parks it. So the + *

        The relay acts on the outcome: it marks a row published, retries it, or parks it. So the * promise is the translation — each thing a broker can do with a message arrives as the one outcome * that leads the relay to the right action. A bridge that reported a refusal of the moment as a * definite rejection parked a committed event and its aggregate behind it (06-01); the bridge's own * test caught it, the fake every use-case test ran on did not have to. * + *

        An attempt that was not confirmed also carries the publisher's code for why. The relay writes + * it on the row, and it is the only thing that tells a refused credential from a closed transport + * once both have been translated into the same outcome (re-review 2026-11-03 RR-05-03). + * *

        The event id is a canonical UUIDv7, the only spelling the platform carries. */ public abstract class IntegrationEventPublishContract { @@ -106,9 +111,22 @@ public abstract class IntegrationEventPublishContract { assertThat(outcome.retryable()).isFalse(); } - /** The contract's event, published and waited for. */ + @Test + @DisplayName("확인되지 않은 발행은 publisher가 붙인 원인 코드를 함께 알린다") + void anUnconfirmedPublishCarriesThePublishersFailureCode() { + // given + IntegrationEventPublishPort port = publisherOverABrokerThat(BrokerAnswer.REFUSES_FOR_NOW); + + // when + OutboxPublishAttempt attempt = port.publish(contractEvent()).toCompletableFuture().join(); + + // then + assertThat(attempt.failureCode()).isPresent(); + } + + /** The contract's event, published and waited for; the outcome is what these scenarios read. */ private static OutboxPublishOutcome publish(IntegrationEventPublishPort port) { - return port.publish(contractEvent()).toCompletableFuture().join(); + return port.publish(contractEvent()).toCompletableFuture().join().outcome(); } /** The event every scenario publishes. */ diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisher.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisher.java index e3ddc929..64cdac98 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisher.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/FakeOutboxMessagePublisher.java @@ -1,8 +1,10 @@ package dev.caskeleton.application.outbox.testkit; +import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventPublisher; import dev.caskeleton.application.outbox.ClaimedOutboxEvent; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.application.outbox.OutboxPublishAmbiguousException; +import dev.caskeleton.application.outbox.OutboxPublishAttempt; import dev.caskeleton.application.outbox.OutboxPublishOutcome; import dev.caskeleton.application.outbox.OutboxPublishRefusedException; import java.util.ArrayList; @@ -19,18 +21,19 @@ import java.util.function.Consumer; * it. * *

        The relay's tests script it four ways: one outcome for every publish ({@link - * #answering(OutboxPublishOutcome)}), one outcome for one event ({@link #answering(String, - * OutboxPublishOutcome)}), an exception the broker client raised instead of answering ({@link - * #throwing}), and something that happens while the broker call is in progress ({@link - * #whenPublishing}) — a clock that moves, a stop request that arrives. A per-event script wins over - * the shared answer, and a thrown exception wins over both. + * #answering(OutboxPublishOutcome)}, or {@link #answering(OutboxPublishAttempt)} with the + * publisher's own failure code; an outcome alone carries its name as the code), one outcome for one + * event ({@link #answering(String, OutboxPublishOutcome)}), an exception the broker client raised + * instead of answering ({@link #throwing}), and something that happens while the broker call is in + * progress ({@link #whenPublishing}) — a clock that moves, a stop request that arrives. A per-event + * script wins over the shared answer, and a thrown exception wins over both. */ public final class FakeOutboxMessagePublisher implements OutboxMessagePublishPort { private final List published = new ArrayList<>(); - private final Map answerPerEvent = new HashMap<>(); + private final Map answerPerEvent = new HashMap<>(); private final Map failurePerEvent = new HashMap<>(); - private OutboxPublishOutcome answer = OutboxPublishOutcome.CONFIRMED; + private OutboxPublishAttempt answer = OutboxPublishAttempt.confirmed(); private RuntimeException failure; private Consumer duringPublish = event -> {}; @@ -42,7 +45,18 @@ public final class FakeOutboxMessagePublisher implements OutboxMessagePublishPor * @return this fake */ public FakeOutboxMessagePublisher answering(OutboxPublishOutcome outcome) { - this.answer = Objects.requireNonNull(outcome, "outcome"); + return answering(FakeIntegrationEventPublisher.attemptOf(Objects.requireNonNull(outcome))); + } + + /** + * Answers every later publish with {@code attempt} — an outcome with the publisher's own failure + * code — and stops throwing a failure set by {@link #throwing(RuntimeException)}. + * + * @param attempt the attempt to report + * @return this fake + */ + public FakeOutboxMessagePublisher answering(OutboxPublishAttempt attempt) { + this.answer = Objects.requireNonNull(attempt, "attempt"); this.failure = null; return this; } @@ -57,7 +71,8 @@ public final class FakeOutboxMessagePublisher implements OutboxMessagePublishPor */ public FakeOutboxMessagePublisher answering(String eventId, OutboxPublishOutcome outcome) { answerPerEvent.put( - Objects.requireNonNull(eventId, "eventId"), Objects.requireNonNull(outcome, "outcome")); + Objects.requireNonNull(eventId, "eventId"), + FakeIntegrationEventPublisher.attemptOf(Objects.requireNonNull(outcome, "outcome"))); return this; } @@ -101,7 +116,7 @@ public final class FakeOutboxMessagePublisher implements OutboxMessagePublishPor @Override public void publish(ClaimedOutboxEvent event) { - OutboxPublishOutcome outcome = publishForOutcome(event); + OutboxPublishOutcome outcome = publishForOutcome(event).outcome(); if (outcome == OutboxPublishOutcome.CONFIRMED) { return; } @@ -112,7 +127,7 @@ public final class FakeOutboxMessagePublisher implements OutboxMessagePublishPor } @Override - public OutboxPublishOutcome publishForOutcome(ClaimedOutboxEvent event) { + public OutboxPublishAttempt publishForOutcome(ClaimedOutboxEvent event) { published.add(Objects.requireNonNull(event, "event must not be null")); // The answer is read after the side effect: a side effect that moves a clock past an outage or // re-scripts the fake decides what this very call reports, as a broker that came back would. diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequences.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequences.java index dff55d5b..bf05860a 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequences.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxAggregateSequences.java @@ -2,16 +2,61 @@ package dev.caskeleton.application.outbox.testkit; import dev.caskeleton.application.messaging.event.AggregateIdentity; import dev.caskeleton.application.outbox.OutboxAggregateSequencePort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.util.HashMap; import java.util.Map; +import java.util.Objects; -/** In-memory {@link OutboxAggregateSequencePort}: one counter per aggregate identity. */ +/** + * In-memory {@link OutboxAggregateSequencePort}: one counter per aggregate identity. + * + *

        Built over a {@link DirectTransactionPort}, it keeps the JPA counter's transaction rules, and + * {@link OutboxAggregateSequenceContract} holds it to them: a number is refused outside a write + * transaction, and a number taken by a transaction that rolls back is handed out again. Built with + * no port, it hands out numbers with or without a transaction and keeps them on rollback — for + * tests that seed events directly and do not model transactions, as {@code new + * InMemoryOutboxStore()} does. + */ public final class InMemoryOutboxAggregateSequences implements OutboxAggregateSequencePort { private final Map last = new HashMap<>(); + private final DirectTransactionPort transactions; + + /** A counter that does not look at transactions. */ + public InMemoryOutboxAggregateSequences() { + this.transactions = null; + } + + /** + * A counter that joins {@code transactions} as the JPA counter joins the caller's. + * + * @param transactions the port the use case under test opens its transactions through + */ + public InMemoryOutboxAggregateSequences(DirectTransactionPort transactions) { + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } @Override public synchronized long nextSequence(AggregateIdentity aggregate) { - return last.merge(aggregate, 1L, Long::sum); + Objects.requireNonNull(aggregate, "aggregate must not be null"); + if (transactions == null) { + return last.merge(aggregate, 1L, Long::sum); + } + if (!transactions.active() || transactions.readOnly()) { + throw new IllegalStateException( + "outbox nextSequence requires an active caller transaction (a write one)"); + } + Long previous = last.get(aggregate); + long next = last.merge(aggregate, 1L, Long::sum); + transactions.onRollback(() -> restore(aggregate, previous)); + return next; + } + + private synchronized void restore(AggregateIdentity aggregate, Long previous) { + if (previous == null) { + last.remove(aggregate); + } else { + last.put(aggregate, previous); + } } } diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java index a9442c84..26311043 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java @@ -6,6 +6,7 @@ import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxCompletion; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; +import dev.caskeleton.application.outbox.OutboxLongRetries; import dev.caskeleton.application.outbox.OutboxStorePort; import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import java.time.Duration; @@ -126,7 +127,7 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { @Override public OutboxCompletion markPublished(OutboxLease lease) { - OutboxCompletion completion = complete(lease, OutboxEventStatus.PUBLISHED, null); + OutboxCompletion completion = complete(lease, OutboxEventStatus.PUBLISHED, null, null); if (completion == OutboxCompletion.APPLIED) { published.add(lease.eventId()); } @@ -134,8 +135,9 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { } @Override - public OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { - OutboxCompletion completion = complete(lease, OutboxEventStatus.FAILED, nextAttemptAt); + public OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt, String failureCode) { + OutboxCompletion completion = + complete(lease, OutboxEventStatus.FAILED, nextAttemptAt, failureCode); if (completion == OutboxCompletion.APPLIED) { failed.put(lease.eventId(), nextAttemptAt); } @@ -143,8 +145,10 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { } @Override - public OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt) { - OutboxCompletion completion = complete(lease, OutboxEventStatus.FAILED, nextAttemptAt); + public OutboxCompletion markDeferred( + OutboxLease lease, Instant nextAttemptAt, String failureCode) { + OutboxCompletion completion = + complete(lease, OutboxEventStatus.FAILED, nextAttemptAt, failureCode); if (completion == OutboxCompletion.APPLIED) { rows.get(lease.eventId()).deferredAttemptCount++; failed.put(lease.eventId(), nextAttemptAt); @@ -154,7 +158,7 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { @Override public OutboxCompletion releaseLease(OutboxLease lease, Instant claimableAt) { - OutboxCompletion completion = complete(lease, OutboxEventStatus.PENDING, claimableAt); + OutboxCompletion completion = complete(lease, OutboxEventStatus.PENDING, claimableAt, null); if (completion == OutboxCompletion.APPLIED) { Row row = rows.get(lease.eventId()); row.attemptCount--; @@ -164,17 +168,20 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { } @Override - public OutboxCompletion markDead(OutboxLease lease) { - OutboxCompletion completion = complete(lease, OutboxEventStatus.DEAD, null); + public OutboxCompletion markDead(OutboxLease lease, String failureCode) { + OutboxCompletion completion = complete(lease, OutboxEventStatus.DEAD, null, failureCode); if (completion == OutboxCompletion.APPLIED) { dead.add(lease.eventId()); } return completion; } - /** The same predicate the SQL completion carries: still IN_FLIGHT, same owner, same token. */ + /** + * The same predicate the SQL completion carries: still IN_FLIGHT, same owner, same token. A + * failure code, when given, replaces the row's last one, as the SQL completion's does. + */ private OutboxCompletion complete( - OutboxLease lease, OutboxEventStatus status, Instant nextAttemptAt) { + OutboxLease lease, OutboxEventStatus status, Instant nextAttemptAt, String failureCode) { Row row = rows.get(lease.eventId()); if (row == null || row.status != OutboxEventStatus.IN_FLIGHT @@ -187,6 +194,9 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { if (nextAttemptAt != null) { row.nextAttemptAt = nextAttemptAt; } + if (failureCode != null) { + row.lastFailureCode = failureCode; + } return OutboxCompletion.APPLIED; } @@ -211,10 +221,38 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { return ages; } + @Override + public OutboxLongRetries longRetries(int minDeferredClaims, Instant now) { + List retrying = + rows.values().stream() + .filter(row -> row.status == OutboxEventStatus.FAILED) + .filter(row -> row.deferredAttemptCount >= minDeferredClaims) + .toList(); + if (retrying.isEmpty()) { + return OutboxLongRetries.NONE; + } + long oldest = + retrying.stream() + .mapToLong(row -> Duration.between(row.event.occurredAt(), now).toSeconds()) + .max() + .orElseThrow(); + return new OutboxLongRetries(retrying.size(), Math.max(0, oldest)); + } + public OutboxEventStatus status(String eventId) { return row(eventId).status; } + /** + * The code the row's last failed completion recorded, or {@code null} before any failed. + * + * @param eventId the row + * @return the last failure code + */ + public String lastFailureCode(String eventId) { + return row(eventId).lastFailureCode; + } + public int attemptCount(String eventId) { return row(eventId).attemptCount; } @@ -262,6 +300,7 @@ public class InMemoryOutboxStore implements OutboxStorePort, OutboxAppendPort { private int attemptCount; private int deferredAttemptCount; private Instant nextAttemptAt; + private String lastFailureCode; private String leaseOwner; private long leaseToken; diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAggregateSequenceContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAggregateSequenceContract.java index 1a3cd869..27fce80a 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAggregateSequenceContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAggregateSequenceContract.java @@ -1,10 +1,12 @@ package dev.caskeleton.application.outbox.testkit; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.messaging.event.AggregateIdentity; import dev.caskeleton.application.outbox.OutboxAggregateSequencePort; import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.OverlappingWrites; import java.util.ArrayList; import java.util.List; import java.util.UUID; @@ -14,6 +16,10 @@ import org.junit.jupiter.api.Test; /** * What every {@link OutboxAggregateSequencePort} promises, run against the in-memory fake and the * JPA adapter alike. Each test uses aggregates of its own, so a subclass may share one store. + * + *

        Where an aggregate's numbers start is the implementation's: the fake starts at 1, the JPA + * counter above every number the replaced wall-clock scheme could have issued (V21). What every + * implementation promises is the step and the independence. */ public abstract class OutboxAggregateSequenceContract { @@ -22,8 +28,8 @@ public abstract class OutboxAggregateSequenceContract { protected abstract TransactionPort transactions(); @Test - @DisplayName("같은 aggregate의 순서 번호는 1부터 커밋마다 하나씩 커진다") - void anAggregatesNumbersStartAtOneAndGrowByOnePerCommittedWrite() { + @DisplayName("같은 aggregate의 순서 번호는 첫 번호부터 커밋마다 하나씩 커진다") + void anAggregatesNumbersGrowByOnePerCommittedWriteFromItsFirst() { // given AggregateIdentity aggregate = aggregate(); List numbers = new ArrayList<>(); @@ -34,23 +40,110 @@ public abstract class OutboxAggregateSequenceContract { } // then - assertThat(numbers).containsExactly(1L, 2L, 3L); + long first = numbers.get(0); + assertThat(List.of(first >= 1, numbers)) + .containsExactly(true, List.of(first, first + 1, first + 2)); } @Test - @DisplayName("aggregate마다 순서 번호를 따로 센다") - void eachAggregateCountsOnItsOwn() { + @DisplayName("다른 aggregate의 쓰기는 이 aggregate의 첫 번호를 바꾸지 않는다") + void anotherAggregatesWritesDoNotMoveThisAggregatesFirstNumber() { // given AggregateIdentity first = aggregate(); AggregateIdentity second = aggregate(); - transactions().inWrite(() -> sequences().nextSequence(first)); + long firstsFirst = transactions().inWrite(() -> sequences().nextSequence(first)); transactions().inWrite(() -> sequences().nextSequence(first)); // when long secondsFirst = transactions().inWrite(() -> sequences().nextSequence(second)); // then - assertThat(secondsFirst).isEqualTo(1L); + assertThat(secondsFirst).isEqualTo(firstsFirst); + } + + /** + * The first two writes of an aggregate overlap: both find no counter. A store that creates the + * counter with a plain insert fails the second one on the primary key (review RR-03-01), which + * rejects a valid business write that no caller retries. + */ + @Test + @DisplayName("카운터가 없는 aggregate에 두 쓰기가 겹쳐도 둘 다 성공하고 커밋 순서대로 연속 번호를 받는다") + void twoOverlappingFirstWritesBothSucceedWithConsecutiveNumbers() { + // given + AggregateIdentity aggregate = aggregate(); + + // when + List numbers = + OverlappingWrites.run( + work -> transactions().inWrite(work), + () -> sequences().nextSequence(aggregate), + () -> sequences().nextSequence(aggregate)); + + // then + assertThat(numbers.get(1)).isEqualTo(numbers.get(0) + 1); + } + + /** + * Outside the caller's write transaction the number would commit apart from the event it numbers + * (review 2026-11-03 RR-01-06). + */ + @Test + @DisplayName("쓰기 트랜잭션 밖에서는 순서 번호를 주지 않는다") + void aNumberIsRefusedOutsideTheCallersWriteTransaction() { + // given + AggregateIdentity aggregate = aggregate(); + + // when + Throwable thrown = catchThrowable(() -> sequences().nextSequence(aggregate)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires an active caller transaction"); + } + + /** + * The number is taken under the counter's lock and goes back with a rollback, so the next commit + * reuses it rather than leaving a gap (review 2026-11-03 RR-01-06). Relative to the first number, + * so a store that seeds a new counter above 1 is held to the same case. + */ + @Test + @DisplayName("롤백된 쓰기가 받은 순서 번호는 다음 쓰기가 다시 받는다") + void aNumberTakenByARolledBackWriteIsHandedOutAgain() { + // given + AggregateIdentity aggregate = aggregate(); + long first = transactions().inWrite(() -> sequences().nextSequence(aggregate)); + long rolledBack = numberTakenByARolledBackWrite(aggregate); + + // when + long next = transactions().inWrite(() -> sequences().nextSequence(aggregate)); + + // then + assertThat(List.of(rolledBack, next)).containsExactly(first + 1, first + 1); + } + + private long numberTakenByARolledBackWrite(AggregateIdentity aggregate) { + long[] taken = new long[1]; + try { + transactions() + .inWrite( + () -> { + taken[0] = sequences().nextSequence(aggregate); + throw new RollBack(); + }); + } catch (RollBack expected) { + // the write rolled back, as this case needs + } + return taken[0]; + } + + /** Thrown inside a write so that its transaction rolls back. */ + private static final class RollBack extends RuntimeException { + private static final long serialVersionUID = 1L; + + RollBack() { + super("roll the write back"); + } } private static AggregateIdentity aggregate() { diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java index ff17746b..279640f2 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java @@ -7,6 +7,7 @@ import dev.caskeleton.application.outbox.OutboxBackoffPolicy; import dev.caskeleton.application.outbox.OutboxCompletion; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; +import dev.caskeleton.application.outbox.OutboxLongRetries; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.application.outbox.OutboxRelayFailureReport; import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort; @@ -54,6 +55,13 @@ public abstract class OutboxLeaseFencingContract { /** Reads the row's persisted status, bypassing anything the store caches. */ protected abstract OutboxEventStatus statusOf(String eventId); + /** + * Reads the row's persisted {@code last_failure_code}, bypassing anything the store caches. + * + * @return the code, or {@code null} when no failed completion wrote one + */ + protected abstract String lastFailureCodeOf(String eventId); + @Test void lateFailureFromASupersededRelayIsStaleAndThePublishedRowStays() { // given @@ -149,7 +157,8 @@ public abstract class OutboxLeaseFencingContract { transactions().inWrite(() -> store().markPublished(lease)); // when - OutboxCompletion second = transactions().inWrite(() -> store().markDead(lease)); + OutboxCompletion second = + transactions().inWrite(() -> store().markDead(lease, "REJECTED_BEFORE_SEND")); // then assertThat(Map.entry(second, statusOf(eventId))) @@ -201,7 +210,9 @@ public abstract class OutboxLeaseFencingContract { Instant retryAt = CLAIMED_AT.plusSeconds(30); // when - OutboxCompletion deferred = transactions().inWrite(() -> store().markDeferred(first, retryAt)); + OutboxCompletion deferred = + transactions() + .inWrite(() -> store().markDeferred(first, retryAt, "KAFKA_TRANSPORT_CLOSED")); // then OutboxLease second = claim("relay-a", retryAt); @@ -214,6 +225,95 @@ public abstract class OutboxLeaseFencingContract { .containsExactly(2, 1, 1); } + @Test + @DisplayName("미룬 시도는 publisher가 붙인 원인 코드를 행에 남긴다") + void aDeferredClaimLeavesThePublishersFailureCodeOnTheRow() { + // given + String eventId = appendEvent("deferred-code"); + OutboxLease lease = claim("relay-a", CLAIMED_AT); + + // when + transactions() + .inWrite( + () -> + store() + .markDeferred( + lease, CLAIMED_AT.plusSeconds(30), "KAFKA_AUTHENTICATIONEXCEPTION")); + + // then + assertThat(List.of(statusOf(eventId), lastFailureCodeOf(eventId))) + .containsExactly(OutboxEventStatus.FAILED, "KAFKA_AUTHENTICATIONEXCEPTION"); + } + + @Test + @DisplayName("DEAD로 옮긴 시도는 그 원인 코드를 행에 남긴다") + void aDeadLetteredClaimLeavesItsFailureCodeOnTheRow() { + // given + String eventId = appendEvent("dead-code"); + OutboxLease lease = claim("relay-a", CLAIMED_AT); + + // when + transactions().inWrite(() -> store().markDead(lease, "KAFKA_RECORDTOOLARGEEXCEPTION")); + + // then + assertThat(List.of(statusOf(eventId), lastFailureCodeOf(eventId))) + .containsExactly(OutboxEventStatus.DEAD, "KAFKA_RECORDTOOLARGEEXCEPTION"); + } + + @Test + @DisplayName("넘겨받힌 claim의 실패는 행의 원인 코드를 바꾸지 않는다") + void aSupersededLeasesFailureDoesNotOverwriteTheRowsFailureCode() { + // given + String eventId = appendEvent("stale-code"); + OutboxLease expired = claim("relay-a", CLAIMED_AT); + OutboxLease current = claim("relay-b", AFTER_EXPIRY); + transactions() + .inWrite(() -> store().markDeferred(current, AFTER_EXPIRY.plusSeconds(30), "CURRENT_CODE")); + + // when + OutboxCompletion late = + transactions() + .inWrite(() -> store().markFailed(expired, AFTER_EXPIRY.plusSeconds(30), "LATE_CODE")); + + // then + assertThat(List.of(late, lastFailureCodeOf(eventId))) + .containsExactly(OutboxCompletion.STALE, "CURRENT_CODE"); + } + + @Test + @DisplayName("미룬 claim이 기준 수 이상 쌓인 FAILED 행만 오래 재시도 중인 행으로 센다") + void onlyFailedRowsWithEnoughDeferredClaimsCountAsLongRetrying() { + // given: one row deferred twice (due again at +60s), one deferred once (claimed at +59s, when + // it is the only row due), measured an hour after both occurred + String twice = appendEvent("long-twice"); + deferTwice(twice); + appendEvent("long-once"); + OutboxLease once = claim("relay-a", CLAIMED_AT.plusSeconds(59)); + transactions().inWrite(() -> store().markDeferred(once, CLAIMED_AT.plusSeconds(89), "ONCE")); + Instant anHourLater = CLAIMED_AT.minusSeconds(1).plusSeconds(3600); + + // when + OutboxLongRetries longRetries = store().longRetries(2, anHourLater); + + // then + assertThat(longRetries).isEqualTo(new OutboxLongRetries(1, 3600)); + } + + /** Claims and defers the only claimable row twice; it ends FAILED with two deferred claims. */ + private void deferTwice(String eventId) { + Instant at = CLAIMED_AT; + for (int i = 0; i < 2; i++) { + OutboxLease lease = claim("relay-a", at); + if (!lease.eventId().equals(eventId)) { + throw new IllegalStateException( + "expected to claim " + eventId + ", got " + lease.eventId()); + } + Instant retryAt = at.plusSeconds(30); + transactions().inWrite(() -> store().markDeferred(lease, retryAt, "TWICE")); + at = retryAt; + } + } + private OutboxLease claim(String owner, Instant now) { return transactions() .inWrite(() -> store().claimBatch(owner, 1, now, IN_FLIGHT_TIMEOUT)) @@ -302,13 +402,15 @@ public abstract class OutboxLeaseFencingContract { } @Override - public OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { - return count(delegate.markFailed(lease, nextAttemptAt)); + public OutboxCompletion markFailed( + OutboxLease lease, Instant nextAttemptAt, String failureCode) { + return count(delegate.markFailed(lease, nextAttemptAt, failureCode)); } @Override - public OutboxCompletion markDeferred(OutboxLease lease, Instant nextAttemptAt) { - return count(delegate.markDeferred(lease, nextAttemptAt)); + public OutboxCompletion markDeferred( + OutboxLease lease, Instant nextAttemptAt, String failureCode) { + return count(delegate.markDeferred(lease, nextAttemptAt, failureCode)); } @Override @@ -317,8 +419,8 @@ public abstract class OutboxLeaseFencingContract { } @Override - public OutboxCompletion markDead(OutboxLease lease) { - return count(delegate.markDead(lease)); + public OutboxCompletion markDead(OutboxLease lease, String failureCode) { + return count(delegate.markDead(lease, failureCode)); } private OutboxCompletion count(OutboxCompletion completion) { @@ -337,5 +439,10 @@ public abstract class OutboxLeaseFencingContract { public Map oldestUnpublishedAgeSecondsByEventType(Instant now) { return delegate.oldestUnpublishedAgeSecondsByEventType(now); } + + @Override + public OutboxLongRetries longRetries(int minDeferredClaims, Instant now) { + return delegate.longRetries(minDeferredClaims, now); + } } } diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxMessagePublishContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxMessagePublishContract.java index 3f7d39cf..0686110a 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxMessagePublishContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxMessagePublishContract.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.messaging.event.testkit.BrokerAnswer; import dev.caskeleton.application.outbox.ClaimedOutboxEvent; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.application.outbox.OutboxPublishAttempt; import dev.caskeleton.application.outbox.OutboxPublishOutcome; import java.time.Instant; import java.util.List; @@ -40,7 +41,7 @@ public abstract class OutboxMessagePublishContract { OutboxMessagePublishPort port = publisherOverABrokerThat(BrokerAnswer.CONFIRMS); // when - OutboxPublishOutcome outcome = port.publishForOutcome(claimedRow()); + OutboxPublishOutcome outcome = port.publishForOutcome(claimedRow()).outcome(); // then assertThat(outcome).isEqualTo(OutboxPublishOutcome.CONFIRMED); @@ -54,7 +55,7 @@ public abstract class OutboxMessagePublishContract { OutboxMessagePublishPort port = publisherOverABrokerThat(BrokerAnswer.NEVER_CONFIRMS); // when - OutboxPublishOutcome outcome = port.publishForOutcome(claimedRow()); + OutboxPublishOutcome outcome = port.publishForOutcome(claimedRow()).outcome(); // then assertThat(outcome).isEqualTo(OutboxPublishOutcome.AMBIGUOUS); @@ -67,12 +68,25 @@ public abstract class OutboxMessagePublishContract { OutboxMessagePublishPort port = publisherOverABrokerThat(BrokerAnswer.REFUSES_AFTER_RECEIVING); // when - OutboxPublishOutcome outcome = port.publishForOutcome(claimedRow()); + OutboxPublishOutcome outcome = port.publishForOutcome(claimedRow()).outcome(); // then assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_AFTER_BROKER); } + @Test + @DisplayName("broker의 거부는 그 거부에 붙은 원인 코드를 함께 알린다") + void aBrokerRefusalCarriesItsFailureCode() { + // given + OutboxMessagePublishPort port = publisherOverABrokerThat(BrokerAnswer.REFUSES_FOR_NOW); + + // when + OutboxPublishAttempt attempt = port.publishForOutcome(claimedRow()); + + // then + assertThat(attempt.failureCode()).isPresent(); + } + @Test @DisplayName("예외로 알리는 발행은 broker가 확인했을 때만 정상 반환한다") void theThrowingPublishReturnsWhenTheBrokerConfirmed() { diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/OverlappingWrites.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/OverlappingWrites.java similarity index 89% rename from src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/OverlappingWrites.java rename to src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/OverlappingWrites.java index 6ce99191..6d1ab721 100644 --- a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/OverlappingWrites.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/OverlappingWrites.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.notification.platform.policy.testkit; +package dev.caskeleton.application.transaction.testkit; import java.time.Duration; import java.util.List; @@ -21,8 +21,11 @@ import java.util.function.Supplier; * has no transactions simply runs the two one after the other, which is the answer it must give * anyway. * - *

        Public because every store contract with an insert-or-find has the same race to show: the - * suppression and preference contracts here, and the admin operation claim. + *

        Public, and here beside the transaction port's own fake, because every store contract with an + * insert-or-find has the same race to show: the outbox order counter's first number, and the + * notification suppression, preference, deduplication, request and admin operation stores. It lived + * in application-notification until the outbox contract needed it too; one copy, not two that + * drift. */ public final class OverlappingWrites { diff --git a/src/application-fileserver/build.gradle b/src/application-fileserver/build.gradle index 41282aad..aa3128b5 100644 --- a/src/application-fileserver/build.gradle +++ b/src/application-fileserver/build.gradle @@ -11,10 +11,11 @@ dependencies { // The port owner's test fixtures: one hand-rolled fake per port, and the abstract port // contracts (`*Contract`) that a fake and the real adapter both extend (AGENTS.md test rule 6, - // capability criterion 5). A use-case test that passes against a fake is passing against the - // behaviour the JPA adapters in persistence-fileserver are held to. Adapters reach them with - // `testImplementation testFixtures(...)`. FileserverException's error code is a shared-contract - // type; the contracts assert on it. + // capability criterion 5). Every store port persistence-fileserver implements has one, and so + // does the access policy (docs/testing/TESTING_STRATEGY.md 9.3), so a use-case test that passes + // against a fake is passing against the behaviour the JPA adapters are held to on PostgreSQL. + // Adapters reach them with `testImplementation testFixtures(...)`. FileserverException's error + // code is a shared-contract type; the contracts assert on it. testFixturesImplementation project(':application-core') // DirectTransactions records and injects faults around application-core's shared fake rather // than being a second transaction port of its own. diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/security/FileAccessSubject.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/security/FileAccessSubject.java index d37e884e..b1e34c2e 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/security/FileAccessSubject.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/security/FileAccessSubject.java @@ -1,5 +1,6 @@ package dev.caskeleton.application.fileserver.api.security; +import dev.caskeleton.application.fileserver.api.metadata.FileDescriptor; import dev.caskeleton.application.fileserver.api.metadata.FileOwner; import java.util.Map; import java.util.Objects; @@ -45,4 +46,21 @@ public record FileAccessSubject( public FileOwner asOwner() { return new FileOwner(principalId, tenant()); } + + /** + * Whether this caller created {@code file}, in this caller's tenant: the one ownership rule every + * {@link FileAccessPolicyPort} applies to an operation on an existing file (owner decision 14). + * + *

        A file with no recorded owner predates ownership and belongs to nobody. A file created + * without a tenant is not owned by the same principal calling with one, and the other way round. + * Policies call this instead of comparing owners themselves, so the fake and every production + * policy cannot drift apart (review 2026-11-03 RR-07-06); {@code FileAccessPolicyPortContract} + * holds each of them to it. + * + * @param file the file the operation targets + * @return true when this caller owns it + */ + public boolean owns(FileDescriptor file) { + return file.owner().filter(asOwner()::equals).isPresent(); + } } diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/QuotaReclaimPort.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/QuotaReclaimPort.java index 0a63a6f5..2829f3a4 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/QuotaReclaimPort.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/cleanup/QuotaReclaimPort.java @@ -6,7 +6,9 @@ import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; * Returns committed capacity after content is physically gone. * *

        Reclaim happens after the delete, never before: giving the quota back first would let a tenant - * over-allocate against space that has not actually been freed. + * over-allocate against space that has not actually been freed. The one other caller is a move to + * another namespace, which reclaims the file's bytes from the source in the same transaction that + * commits them to the target — the bytes stay counted, only their namespace changes. */ public interface QuotaReclaimPort { diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java index ba23d23f..348faf9a 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java @@ -4,21 +4,44 @@ import dev.caskeleton.application.capability.Idempotency; import dev.caskeleton.application.capability.RepositoryAccess; import dev.caskeleton.application.capability.UseCaseCapability; import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.StorageNamespace; import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; import dev.caskeleton.application.fileserver.api.metadata.FileRecord; import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.metadata.QuotaReservation; +import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort; import dev.caskeleton.application.fileserver.port.in.MoveFileCommand; import dev.caskeleton.application.fileserver.port.in.MoveFileUseCase; import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.fileserver.upload.UploadPolicies; +import dev.caskeleton.application.fileserver.upload.UploadPolicy; import dev.caskeleton.application.security.RequiresPermission; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import java.util.Objects; import java.util.Optional; -/** Moves a readable file to another namespace that {@link TargetNamespacePolicy} opens. */ +/** + * Moves a readable file to another namespace that {@link TargetNamespacePolicy} opens, and its + * bytes' quota with it. + * + *

        Quota usage is booked per namespace, so a move that only relocated the record left the bytes + * counted where the file no longer is and uncounted where it now lives: the target could pass its + * limit through moves, the source carried the departed file forever, and deleting the moved file + * reclaimed from the target what the target never booked (review 2026-11-03 RR-01-05). A move + * across namespaces therefore does, in the one transaction that relocates the record, what an + * upload into the target and a delete from the source would: {@link + * dev.caskeleton.application.fileserver.quota.NamespaceQuota#requireRoom} against the target, + * reserve and commit the file's bytes there, and reclaim the same bytes from the source. A refused + * move changes nothing. A move within the namespace leaves the ledger alone. + * + *

        Copy-then-delete was the other way to close it, and was not taken: a move would stop being + * atomic and would rewrite bytes the content key already addresses. + */ @RequiresPermission("file:move") @UseCaseCapability( transactionMode = TransactionMode.WRITE, @@ -30,17 +53,25 @@ public class MoveFileApplicationUseCase implements MoveFileUseCase { private final FileMetadataPort metadataStore; private final FileAccessPolicyPort accessPolicy; + private final UploadPolicy uploadPolicy; private final TargetNamespacePolicy targetNamespaces; + private final FileQuotaPort quota; + private final QuotaReclaimPort reclaims; private final TransactionPort transactions; public MoveFileApplicationUseCase( FileMetadataPort metadataStore, - FileAccessPolicyPort accessPolicy, + UploadPolicies policies, TargetNamespacePolicy targetNamespaces, + FileQuotaPort quota, + QuotaReclaimPort reclaims, TransactionPort transactions) { this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore"); - this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.accessPolicy = policies.access(); + this.uploadPolicy = policies.upload(); this.targetNamespaces = Objects.requireNonNull(targetNamespaces, "targetNamespaces"); + this.quota = Objects.requireNonNull(quota, "quota"); + this.reclaims = Objects.requireNonNull(reclaims, "reclaims"); this.transactions = Objects.requireNonNull(transactions, "transactions"); } @@ -57,7 +88,28 @@ public class MoveFileApplicationUseCase implements MoveFileUseCase { return FileView.of( transactions .inWrite( - () -> metadataStore.relocate(fileId, record.version(), command.targetNamespace())) + () -> { + transferQuota(record, command.targetNamespace()); + return metadataStore.relocate( + fileId, record.version(), command.targetNamespace()); + }) .toDescriptor()); } + + /** Books the file's bytes on {@code target} and takes them off the namespace it leaves. */ + private void transferQuota(FileRecord record, StorageNamespace target) { + if (record.namespace().equals(target)) { + return; + } + long bytes = record.actualSize().orElseThrow(MoveFileApplicationUseCase::readyWithoutSize); + QuotaScope targetScope = QuotaScope.ofNamespace(target.value()); + uploadPolicy.namespaceQuota().requireRoom(quota, targetScope, bytes); + QuotaReservation reservation = quota.reserve(targetScope, bytes, uploadPolicy.reservationTtl()); + quota.commit(reservation, bytes); + reclaims.reclaim(QuotaScope.ofNamespace(record.namespace().value()), bytes); + } + + private static IllegalStateException readyWithoutSize() { + return new IllegalStateException("READY record has no size"); + } } diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/cleanup/CleanupServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/cleanup/CleanupServiceTest.java index c0d4b042..dd0bd88d 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/cleanup/CleanupServiceTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/cleanup/CleanupServiceTest.java @@ -17,6 +17,7 @@ import dev.caskeleton.application.fileserver.api.transfer.UploadMode; import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort; import dev.caskeleton.application.fileserver.testkit.DirectTransactions; import dev.caskeleton.application.fileserver.testkit.FakeCleanupContentGateway; +import dev.caskeleton.application.fileserver.testkit.FakeFileQuotaService; import dev.caskeleton.application.fileserver.testkit.FileserverFixtures; import dev.caskeleton.application.fileserver.testkit.InMemoryCleanupQueue; import dev.caskeleton.application.fileserver.testkit.InMemoryFileMetadataStore; @@ -40,7 +41,8 @@ class CleanupServiceTest { private final FakeCleanupContentGateway content = new FakeCleanupContentGateway(); private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore(); private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore(); - private final RecordingQuotaReclaimGateway quota = new RecordingQuotaReclaimGateway(); + private final RecordingQuotaReclaimGateway quota = + new RecordingQuotaReclaimGateway(new FakeFileQuotaService()); private final DirectTransactions transactions = new DirectTransactions(); private final CleanupService cleanup = diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java index db33316f..5849351e 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java @@ -35,6 +35,7 @@ import dev.caskeleton.application.fileserver.testkit.InMemoryCleanupQueue; import dev.caskeleton.application.fileserver.testkit.InMemoryFileMetadataStore; import dev.caskeleton.application.fileserver.testkit.InMemoryUploadSessionStore; import dev.caskeleton.application.fileserver.testkit.ReadyFileFixture; +import dev.caskeleton.application.fileserver.testkit.RecordingQuotaReclaimGateway; import dev.caskeleton.application.fileserver.testkit.SequentialUploadIdentifierFactory; import dev.caskeleton.application.fileserver.upload.FileView; import dev.caskeleton.application.fileserver.upload.UploadPolicies; @@ -83,8 +84,20 @@ class FileLifecycleUseCasesTest { private final CopyFileApplicationUseCase copy = copyUnder(UploadPolicy.standard(FileserverFixtures.NAMESPACE)); + private final RecordingQuotaReclaimGateway reclaims = new RecordingQuotaReclaimGateway(quota); + private final MoveFileApplicationUseCase move = - new MoveFileApplicationUseCase(metadata, accessPolicy, TARGETS, transactions); + moveUnder(UploadPolicy.standard(FileserverFixtures.NAMESPACE)); + + private MoveFileApplicationUseCase moveUnder(UploadPolicy policy) { + return new MoveFileApplicationUseCase( + metadata, + new UploadPolicies(accessPolicy, OriginalFilenamePolicy.standard(), policy), + TARGETS, + quota, + reclaims, + transactions); + } private CopyFileApplicationUseCase copyUnder(UploadPolicy policy) { return new CopyFileApplicationUseCase( @@ -449,6 +462,56 @@ class FileLifecycleUseCasesTest { .containsExactly(FileserverErrorCode.ACCESS_DENIED, ready.namespace()); } + @Test + @DisplayName("이동은 파일의 바이트를 출발 namespace 사용량에서 대상 namespace 사용량으로 옮긴다") + void moveTransfersTheFilesBytesFromTheSourceNamespaceToTheTarget() { + // given + FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + QuotaScope source = QuotaScope.ofNamespace(ready.namespace().value()); + QuotaScope target = QuotaScope.ofNamespace(TARGET.value()); + quota.alreadyHolds(source, SIZE); + + // when + move.handle( + new MoveFileCommand( + ready.fileId(), TARGET, Optional.empty(), FileserverFixtures.context())); + + // then + assertThat(List.of(quota.usedBytes(source), quota.usedBytes(target))).containsExactly(0L, SIZE); + } + + @Test + @DisplayName("대상 namespace 쿼터 상한을 넘기는 이동은 QUOTA_EXCEEDED로 거절되고 파일과 사용량은 그대로다") + void moveThatWouldTakeTheTargetNamespacePastItsQuotaIsRefused() { + // given + FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + QuotaScope source = QuotaScope.ofNamespace(ready.namespace().value()); + QuotaScope target = QuotaScope.ofNamespace(TARGET.value()); + quota.alreadyHolds(source, SIZE); + quota.alreadyHolds(target, 15); + MoveFileApplicationUseCase limited = + moveUnder( + UploadPolicy.standard(FileserverFixtures.NAMESPACE) + .withNamespaceQuota(NamespaceQuota.ofBytes(24))); + + // when + Throwable failure = + catchThrowable( + () -> + limited.handle( + new MoveFileCommand( + ready.fileId(), TARGET, Optional.empty(), FileserverFixtures.context()))); + + // then + assertThat( + List.of( + codeOf(failure), + metadata.find(ready.fileId()).orElseThrow().namespace(), + quota.usedBytes(source), + quota.usedBytes(target))) + .containsExactly(FileserverErrorCode.QUOTA_EXCEEDED, ready.namespace(), SIZE, 15L); + } + private static Object codeOf(Throwable failure) { if (failure == null) { return "no failure"; diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/recovery/FileReconciliationServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/recovery/FileReconciliationServiceTest.java index b352eb9e..f0d836a9 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/recovery/FileReconciliationServiceTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/recovery/FileReconciliationServiceTest.java @@ -11,6 +11,7 @@ import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft; import dev.caskeleton.application.fileserver.api.transfer.UploadMode; import dev.caskeleton.application.fileserver.testkit.DirectTransactions; +import dev.caskeleton.application.fileserver.testkit.FakeFileQuotaService; import dev.caskeleton.application.fileserver.testkit.FakeQuotaCommitGateway; import dev.caskeleton.application.fileserver.testkit.FakeReconciliationContentProbe; import dev.caskeleton.application.fileserver.testkit.FileserverFixtures; @@ -33,7 +34,8 @@ class FileReconciliationServiceTest { private final FakeReconciliationContentProbe probe = new FakeReconciliationContentProbe(); private final InMemoryRecoveryQueue recovery = new InMemoryRecoveryQueue(); private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore(); - private final FakeQuotaCommitGateway quota = new FakeQuotaCommitGateway(); + private final FakeQuotaCommitGateway quota = + new FakeQuotaCommitGateway(new FakeFileQuotaService(), metadata); private final FileReconciliationService service = new DefaultFileReconciliationService( diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicyContractTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicyContractTest.java new file mode 100644 index 00000000..106c3b45 --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicyContractTest.java @@ -0,0 +1,25 @@ +package dev.caskeleton.application.fileserver.testkit; + +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileAccessSubject; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +class FakeFileAccessPolicyContractTest extends FileAccessPolicyPortContract { + + private final FakeFileAccessPolicy policy = new FakeFileAccessPolicy(); + + @Override + protected FileAccessPolicyPort policy() { + return policy; + } + + @Override + protected FileAccessSubject permittedSubject(String principalId, Optional tenant) { + return new FileAccessSubject( + principalId, + Set.of("uploader"), + tenant.map(value -> Map.of(FileAccessSubject.TENANT_ATTRIBUTE, value)).orElse(Map.of())); + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryContentReferenceLedgerContractTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryContentReferenceLedgerContractTest.java new file mode 100644 index 00000000..08546dc9 --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryContentReferenceLedgerContractTest.java @@ -0,0 +1,19 @@ +package dev.caskeleton.application.fileserver.testkit; + +import dev.caskeleton.application.fileserver.admin.ContentReferenceLedgerPort; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; + +class InMemoryContentReferenceLedgerContractTest extends ContentReferenceLedgerPortContract { + + private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore(); + + @Override + protected ContentReferenceLedgerPort ledger() { + return metadata; + } + + @Override + protected FileMetadataPort metadata() { + return metadata; + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryQuotaLedgerContractTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryQuotaLedgerContractTest.java new file mode 100644 index 00000000..2494b443 --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryQuotaLedgerContractTest.java @@ -0,0 +1,58 @@ +package dev.caskeleton.application.fileserver.testkit; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecordDraft; +import dev.caskeleton.application.fileserver.api.metadata.UploadSession; +import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort; +import dev.caskeleton.application.fileserver.upload.QuotaCommitPort; +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; +import java.util.OptionalLong; +import java.util.UUID; + +class InMemoryQuotaLedgerContractTest extends FileQuotaLedgerContract { + + private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore(); + private final FakeFileQuotaService ledger = new FakeFileQuotaService(); + private final FakeQuotaCommitGateway commits = new FakeQuotaCommitGateway(ledger, metadata); + private final RecordingQuotaReclaimGateway reclaims = new RecordingQuotaReclaimGateway(ledger); + private Instant now = FileserverFixtures.NOW; + + @Override + protected FileQuotaPort quota() { + return ledger; + } + + @Override + protected QuotaCommitPort commits() { + return commits; + } + + @Override + protected QuotaReclaimPort reclaims() { + return reclaims; + } + + @Override + protected UploadSession uploadIn(StorageNamespace namespace) { + FileId fileId = FileId.of(UUID.randomUUID()); + metadata.insert( + new FileRecordDraft( + fileId, + namespace, + "report.bin", + Optional.empty(), + OptionalLong.of(1_000), + FileserverFixtures.context().subject().asOwner())); + return FileserverFixtures.session(fileId, 1_000, 1_000); + } + + @Override + protected void elapse(Duration duration) { + now = now.plus(duration); + ledger.advanceTo(now); + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueueContractTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueueContractTest.java new file mode 100644 index 00000000..0712a18e --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueueContractTest.java @@ -0,0 +1,20 @@ +package dev.caskeleton.application.fileserver.testkit; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.recovery.RecoveryQueuePort; +import java.util.UUID; + +class InMemoryRecoveryQueueContractTest extends RecoveryQueuePortContract { + + private final InMemoryRecoveryQueue queue = new InMemoryRecoveryQueue(); + + @Override + protected RecoveryQueuePort queue() { + return queue; + } + + @Override + protected FileId recordedFile() { + return FileId.of(UUID.randomUUID()); + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryStagingUploadLocatorContractTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryStagingUploadLocatorContractTest.java new file mode 100644 index 00000000..1cd78eca --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryStagingUploadLocatorContractTest.java @@ -0,0 +1,40 @@ +package dev.caskeleton.application.fileserver.testkit; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort; +import java.time.Duration; +import java.time.Instant; +import java.util.UUID; + +class InMemoryStagingUploadLocatorContractTest extends StagingUploadLocatorPortContract { + + private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore(); + private Instant now = FileserverFixtures.NOW; + + @Override + protected StagingUploadLocatorPort locator() { + return sessions; + } + + @Override + protected UploadSessionPort sessions() { + return sessions; + } + + @Override + protected FileId recordedFile() { + return FileId.of(UUID.randomUUID()); + } + + @Override + protected Instant now() { + return now; + } + + @Override + protected void elapse(Duration duration) { + now = now.plus(duration); + sessions.advanceTo(now); + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStoreContractTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStoreContractTest.java new file mode 100644 index 00000000..2c6d86c6 --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStoreContractTest.java @@ -0,0 +1,34 @@ +package dev.caskeleton.application.fileserver.testkit; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import java.time.Duration; +import java.time.Instant; +import java.util.UUID; + +class InMemoryUploadSessionStoreContractTest extends UploadSessionPortContract { + + private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore(); + private Instant now = FileserverFixtures.NOW; + + @Override + protected UploadSessionPort sessions() { + return sessions; + } + + @Override + protected FileId recordedFile() { + return FileId.of(UUID.randomUUID()); + } + + @Override + protected Instant now() { + return now; + } + + @Override + protected void elapse(Duration duration) { + now = now.plus(duration); + sessions.advanceTo(now); + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCaseTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCaseTest.java index 48fcd04c..b2cb6d51 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCaseTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCaseTest.java @@ -21,6 +21,7 @@ import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator; import dev.caskeleton.application.fileserver.port.in.FinalizeUploadCommand; import dev.caskeleton.application.fileserver.testkit.DirectTransactions; import dev.caskeleton.application.fileserver.testkit.FakeFileAccessPolicy; +import dev.caskeleton.application.fileserver.testkit.FakeFileQuotaService; import dev.caskeleton.application.fileserver.testkit.FakeQuotaCommitGateway; import dev.caskeleton.application.fileserver.testkit.FakeUploadContentGateway; import dev.caskeleton.application.fileserver.testkit.FileserverFixtures; @@ -43,7 +44,8 @@ class FinalizeUploadApplicationUseCaseTest { private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore(); private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore(); private final FakeUploadContentGateway content = new FakeUploadContentGateway(); - private final FakeQuotaCommitGateway quota = new FakeQuotaCommitGateway(); + private final FakeQuotaCommitGateway quota = + new FakeQuotaCommitGateway(new FakeFileQuotaService(), metadata); private final InMemoryCleanupQueue cleanup = new InMemoryCleanupQueue(); private final InMemoryRecoveryQueue recovery = new InMemoryRecoveryQueue(); private final FakeFileAccessPolicy accessPolicy = new FakeFileAccessPolicy(); diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/ContentReferenceLedgerPortContract.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/ContentReferenceLedgerPortContract.java new file mode 100644 index 00000000..bcf1d46b --- /dev/null +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/ContentReferenceLedgerPortContract.java @@ -0,0 +1,123 @@ +package dev.caskeleton.application.fileserver.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.fileserver.admin.ContentReferenceLedgerPort; +import dev.caskeleton.application.fileserver.api.ContentKey; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.FileState; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link ContentReferenceLedgerPort} promises, run against the in-memory metadata store + * and the JPA ledger on real PostgreSQL (review 2026-11-03 RR-01-04). + * + *

        A key is referenced while any record names it, in any state: an orphan scan that deleted the + * object of a record mid-delete would race the cleanup worker. + */ +public abstract class ContentReferenceLedgerPortContract { + + protected abstract ContentReferenceLedgerPort ledger(); + + /** The metadata store the ledger answers from, to record files with. */ + protected abstract FileMetadataPort metadata(); + + /** Runs one store call inside the caller transaction the adapter requires, and commits it. */ + protected T inTransaction(Supplier work) { + return work.get(); + } + + @Test + @DisplayName("어느 레코드도 가리키지 않는 키는 참조되지 않는다") + void aKeyNoRecordNamesIsNotReferenced() { + // given + ContentKey key = newKey(); + + // when + boolean referenced = inTransaction(() -> ledger().isReferenced(key)); + + // then + assertThat(referenced).isFalse(); + } + + @Test + @DisplayName("공개된 레코드가 가리키는 키는 참조된다") + void aKeyAPublishedRecordNamesIsReferenced() { + // given + ContentKey key = newKey(); + publish(key); + + // when + boolean referenced = inTransaction(() -> ledger().isReferenced(key)); + + // then + assertThat(referenced).isTrue(); + } + + @Test + @DisplayName("지우는 중인 레코드가 가리키는 키도 참조된다") + void aKeyStaysReferencedWhileItsRecordIsBeingDeleted() { + // given + ContentKey key = newKey(); + FileRecord ready = publish(key); + inTransaction(() -> metadata().markDeleting(ready.fileId(), ready.version())); + + // when + boolean referenced = inTransaction(() -> ledger().isReferenced(key)); + + // then + assertThat(referenced).isTrue(); + } + + /** Walks a fresh record to READY under {@code key} through the edges an upload takes. */ + private FileRecord publish(ContentKey key) { + FileId fileId = FileId.of(UUID.randomUUID()); + return inTransaction( + () -> { + FileRecord created = metadata().insert(FileserverFixtures.draft(fileId, 10)); + FileRecord uploading = + metadata() + .transition( + fileId, + created.version(), + FileState.CREATED, + FileState.UPLOADING, + FileRecordMutation.none()); + FileRecord uploaded = + metadata() + .transition( + fileId, + uploading.version(), + FileState.UPLOADING, + FileState.UPLOADED, + FileRecordMutation.uploaded(10, FileserverFixtures.DIGEST)); + FileRecord verifying = + metadata() + .transition( + fileId, + uploaded.version(), + FileState.UPLOADED, + FileState.VERIFYING, + FileRecordMutation.none()); + return metadata() + .transition( + fileId, + verifying.version(), + FileState.VERIFYING, + FileState.READY, + FileRecordMutation.publishAt( + key, 10, FileserverFixtures.DIGEST, FileserverFixtures.NOW)); + }); + } + + private static ContentKey newKey() { + String flat = UUID.randomUUID().toString().replace("-", ""); + return ContentKey.of(flat.substring(0, 2) + '/' + flat.substring(2, 4) + '/' + flat); + } +} diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java index 4c00435f..7e4bc000 100644 --- a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileAccessPolicy.java @@ -18,7 +18,9 @@ import java.util.Set; * *

        It keeps the one rule every production policy owes the port: an operation on an existing file * is refused unless the caller created it, in the same tenant (owner decision 14). Without it a use - * case that stopped passing the file's descriptor would still pass every test. + * case that stopped passing the file's descriptor would still pass every test. The rule is {@link + * FileAccessSubject#owns}, the same call the production policy makes, and {@link + * FileAccessPolicyPortContract} holds both to it. */ public final class FakeFileAccessPolicy implements FileAccessPolicyPort { @@ -42,8 +44,7 @@ public final class FakeFileAccessPolicy implements FileAccessPolicyPort { "operation denied by policy", FileserverFailureContext.of(FileserverErrorCode.ACCESS_DENIED, false)); } - if (descriptor.isPresent() - && !descriptor.get().owner().equals(Optional.of(subject.asOwner()))) { + if (descriptor.isPresent() && !subject.owns(descriptor.get())) { throw new FileserverException( "subject does not own the file", FileserverFailureContext.of(FileserverErrorCode.ACCESS_DENIED, false)); diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java index 3e3170db..7a5e189b 100644 --- a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java @@ -1,84 +1,115 @@ package dev.caskeleton.application.fileserver.testkit; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; import dev.caskeleton.application.fileserver.api.metadata.QuotaReservation; import dev.caskeleton.application.fileserver.api.metadata.QuotaReservationStatus; import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; /** - * Hand-rolled quota service recording reservations, commits, and releases. + * The in-memory quota ledger: the fake of {@link FileQuotaPort}, and the ledger that {@link + * FakeQuotaCommitGateway} and {@link RecordingQuotaReclaimGateway} write, as the three JPA adapters + * share one reservation table. * - *

        It keeps the ledger the durable adapter keeps: a live reservation counts toward its scope's - * usage until it is committed (then the committed bytes count instead) or released (then nothing - * counts). That is what a configured namespace limit is compared against. + *

        It keeps the rows the durable adapters keep and answers the way they do, which {@link + * FileQuotaLedgerContract} holds it to on the same cases as PostgreSQL: a live reservation counts + * until it expires, is committed (then the committed bytes count) or is released (then nothing + * counts); an expired or released reservation cannot be extended and a released one cannot be + * committed ({@code QUOTA_EXCEEDED}). Time is {@link FileserverFixtures#NOW} until {@link + * #advanceTo} moves it. + * + *

        It also records what it was asked, for use-case tests that check which calls a flow made. */ public final class FakeFileQuotaService implements FileQuotaPort { + private final Map rows = new LinkedHashMap<>(); private final List reserved = new ArrayList<>(); private final List released = new ArrayList<>(); private final List committed = new ArrayList<>(); - private final Map liveBytes = new HashMap<>(); - private final Map scopes = new HashMap<>(); - private final Map committedUsage = new HashMap<>(); + private Instant now = FileserverFixtures.NOW; + private long writes; + + /** Moves the ledger's clock; reservations whose TTL ends by then stop counting. */ + public void advanceTo(Instant instant) { + this.now = instant; + } /** Books usage the scope already holds, as if earlier uploads had committed it. */ public void alreadyHolds(QuotaScope scope, long bytes) { - committedUsage.merge(scope, bytes, Long::sum); + Row row = newRow(scope, bytes, now); + row.commit(bytes, ++writes); } @Override public QuotaReservation reserve(QuotaScope scope, long expectedBytes, Duration ttl) { - QuotaReservation reservation = - new QuotaReservation( - UUID.randomUUID(), - scope, - expectedBytes, - 0, - FileserverFixtures.NOW.plus(ttl), - QuotaReservationStatus.RESERVED, - 0); + requireNotNegative(expectedBytes, "expectedBytes"); + Row row = newRow(scope, expectedBytes, now.plus(ttl)); + QuotaReservation reservation = row.view(); reserved.add(reservation); - liveBytes.put(reservation.reservationId(), expectedBytes); - scopes.put(reservation.reservationId(), scope); return reservation; } @Override public void extend(QuotaReservation reservation, long additionalBytes) { + requireNotNegative(additionalBytes, "additionalBytes"); // The recorded reservation identity stays the same; the live total grows as the durable // adapter's does. reserved.add(reservation); - liveBytes.computeIfPresent(reservation.reservationId(), (id, bytes) -> bytes + additionalBytes); + Row row = rows.get(reservation.reservationId()); + if (row == null || !row.isLiveAt(now)) { + throw quotaConflict("reservation is no longer extendable"); + } + row.reservedBytes += additionalBytes; + row.updatedAt = ++writes; } @Override public void commit(QuotaReservation reservation, long actualBytes) { + requireNotNegative(actualBytes, "actualBytes"); committed.add(actualBytes); - if (liveBytes.remove(reservation.reservationId()) != null) { - committedUsage.merge(scopes.get(reservation.reservationId()), actualBytes, Long::sum); + Row row = rows.get(reservation.reservationId()); + // Expiry does not stop a commit: bytes that were written are durable usage whether or not the + // reservation outlived its TTL. Only a settled reservation is refused. + if (row == null || row.status != QuotaReservationStatus.RESERVED) { + throw quotaConflict("reservation is no longer committable"); } + row.commit(actualBytes, ++writes); } @Override public void release(QuotaReservation reservation) { released.add(reservation); - liveBytes.remove(reservation.reservationId()); + Row row = rows.get(reservation.reservationId()); + if (row != null && row.status == QuotaReservationStatus.RESERVED) { + row.release(++writes); + } } @Override public long usedBytes(QuotaScope scope) { - long live = - liveBytes.entrySet().stream() - .filter(entry -> scope.equals(scopes.get(entry.getKey()))) - .mapToLong(Map.Entry::getValue) - .sum(); - return live + committedUsage.getOrDefault(scope, 0L); + long total = 0; + for (Row row : rows.values()) { + if (!row.scope.equals(scope)) { + continue; + } + if (row.isLiveAt(now)) { + total += row.reservedBytes; + } else if (row.status == QuotaReservationStatus.COMMITTED) { + total += row.committedBytes; + } + } + return total; } public List reservedScopes() { @@ -96,4 +127,113 @@ public final class FakeFileQuotaService implements FileQuotaPort { public List committedBytes() { return List.copyOf(committed); } + + /** + * Settles an upload's share as {@code JpaQuotaCommit} does: the scope's oldest live reservation + * is committed, and with none left the bytes are still booked as committed usage. + */ + void settleOldestLive(QuotaScope scope, long actualBytes) { + requireNotNegative(actualBytes, "actualBytes"); + Optional oldest = oldestLive(scope); + if (oldest.isPresent()) { + oldest.get().commit(actualBytes, ++writes); + } else if (actualBytes > 0) { + newRow(scope, actualBytes, now).commit(actualBytes, ++writes); + } + } + + /** Releases the scope's oldest live reservation, as {@code JpaQuotaCommit.release} does. */ + void releaseOldestLive(QuotaScope scope) { + oldestLive(scope).ifPresent(row -> row.release(++writes)); + } + + /** + * Gives committed bytes back as {@code JpaQuotaReclaim} does: newest committed rows first, never + * below zero, a remainder no row can absorb dropped. Live reservations are not touched. + */ + void reclaim(QuotaScope scope, long bytes) { + requireNotNegative(bytes, "bytes"); + long outstanding = bytes; + List newestFirst = + rows.values().stream() + .filter(row -> row.scope.equals(scope)) + .filter(row -> row.status == QuotaReservationStatus.COMMITTED) + .filter(row -> row.committedBytes > 0) + .sorted(Comparator.comparingLong((Row row) -> row.updatedAt).reversed()) + .toList(); + for (Row row : newestFirst) { + if (outstanding == 0) { + return; + } + long draw = Math.min(outstanding, row.committedBytes); + row.committedBytes -= draw; + row.updatedAt = ++writes; + outstanding -= draw; + } + } + + private Optional oldestLive(QuotaScope scope) { + return rows.values().stream() + .filter(row -> row.scope.equals(scope)) + .filter(row -> row.isLiveAt(now)) + .findFirst(); + } + + private Row newRow(QuotaScope scope, long reservedBytes, Instant expiresAt) { + Row row = new Row(UUID.randomUUID(), scope, reservedBytes, expiresAt, ++writes); + rows.put(row.id, row); + return row; + } + + private static void requireNotNegative(long bytes, String name) { + if (bytes < 0) { + throw new IllegalArgumentException(name + " must not be negative"); + } + } + + private static FileserverException quotaConflict(String message) { + return new FileserverException( + message, FileserverFailureContext.of(FileserverErrorCode.QUOTA_EXCEEDED, false)); + } + + /** One reservation row, in insertion order; {@code updatedAt} is a write counter. */ + private static final class Row { + + private final UUID id; + private final QuotaScope scope; + private final Instant expiresAt; + private long reservedBytes; + private long committedBytes; + private QuotaReservationStatus status = QuotaReservationStatus.RESERVED; + private long updatedAt; + + private Row(UUID id, QuotaScope scope, long reservedBytes, Instant expiresAt, long createdAt) { + this.id = id; + this.scope = scope; + this.reservedBytes = reservedBytes; + this.expiresAt = expiresAt; + this.updatedAt = createdAt; + } + + private boolean isLiveAt(Instant instant) { + return status == QuotaReservationStatus.RESERVED && expiresAt.isAfter(instant); + } + + private void commit(long actualBytes, long write) { + status = QuotaReservationStatus.COMMITTED; + committedBytes = actualBytes; + reservedBytes = 0; + updatedAt = write; + } + + private void release(long write) { + status = QuotaReservationStatus.RELEASED; + reservedBytes = 0; + updatedAt = write; + } + + private QuotaReservation view() { + return new QuotaReservation(id, scope, reservedBytes, committedBytes, expiresAt, status, 0); + } + } } diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeQuotaCommitGateway.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeQuotaCommitGateway.java index cd6f422c..053baecc 100644 --- a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeQuotaCommitGateway.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeQuotaCommitGateway.java @@ -1,24 +1,57 @@ package dev.caskeleton.application.fileserver.testkit; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; import dev.caskeleton.application.fileserver.api.metadata.UploadSession; import dev.caskeleton.application.fileserver.upload.QuotaCommitPort; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Objects; -/** Hand-rolled quota gateway recording committed and released byte counts. */ +/** + * The fake of {@link QuotaCommitPort}: settles an upload's share of its file's namespace on the + * in-memory ledger, as {@code JpaQuotaCommit} does on the reservation table, and records what it + * was asked. A session whose file has no record settles nothing. {@link FileQuotaLedgerContract} + * holds it to the JPA adapter's cases. + */ public final class FakeQuotaCommitGateway implements QuotaCommitPort { + private final FakeFileQuotaService ledger; + private final FileMetadataPort metadata; private final Map committed = new LinkedHashMap<>(); private final Map released = new LinkedHashMap<>(); + /** + * A gateway over {@code ledger}, resolving each session's namespace from {@code metadata}. + * + * @param ledger the ledger the reservations live in + * @param metadata the records the sessions' files are found in + */ + public FakeQuotaCommitGateway(FakeFileQuotaService ledger, FileMetadataPort metadata) { + this.ledger = Objects.requireNonNull(ledger, "ledger"); + this.metadata = Objects.requireNonNull(metadata, "metadata"); + } + @Override public void commit(UploadSession session, long actualBytes) { + if (actualBytes < 0) { + throw new IllegalArgumentException("actualBytes must not be negative"); + } committed.put(session, actualBytes); + metadata + .find(session.fileId()) + .map(FakeQuotaCommitGateway::scopeOf) + .ifPresent(scope -> ledger.settleOldestLive(scope, actualBytes)); } @Override public void release(UploadSession session) { released.put(session, Boolean.TRUE); + metadata + .find(session.fileId()) + .map(FakeQuotaCommitGateway::scopeOf) + .ifPresent(ledger::releaseOldestLive); } public long committedBytes() { @@ -32,4 +65,8 @@ public final class FakeQuotaCommitGateway implements QuotaCommitPort { public boolean anyReleased() { return !released.isEmpty(); } + + private static QuotaScope scopeOf(FileRecord record) { + return QuotaScope.ofNamespace(record.namespace().value()); + } } diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileAccessPolicyPortContract.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileAccessPolicyPortContract.java new file mode 100644 index 00000000..5288a309 --- /dev/null +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileAccessPolicyPortContract.java @@ -0,0 +1,175 @@ +package dev.caskeleton.application.fileserver.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.FileState; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.metadata.FileDescriptor; +import dev.caskeleton.application.fileserver.api.metadata.FileOwner; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileAccessSubject; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The ownership rule every {@link FileAccessPolicyPort} owes the port (owner decision 14), run + * against the fake and every production policy alike. + * + *

        The rule itself is written once, {@link FileAccessSubject#owns(FileDescriptor)}; this contract + * is what keeps a policy from dropping or loosening its use of it. Use-case tests that prove a + * stranger cannot reach a file run on the fake, so they only mean something while the fake refuses + * exactly what the production policy refuses (review 2026-11-03 RR-07-06). + * + *

        Roles are each policy's own business; a subclass hands the contract a subject its role rules + * let through every data-plane operation, and the cases vary only who owns the file. + */ +public abstract class FileAccessPolicyPortContract { + + /** The policy under test. */ + protected abstract FileAccessPolicyPort policy(); + + /** + * A subject the policy's role rules permit for every data-plane operation. + * + * @param principalId the caller + * @param tenant the caller's tenant, empty when the request was not tenant scoped + * @return that caller + */ + protected abstract FileAccessSubject permittedSubject( + String principalId, Optional tenant); + + @Test + @DisplayName("소유자는 자기 파일을 내려받고 지울 수 있다") + void theOwnerMayDownloadAndDeleteTheirFile() { + // given + FileAccessSubject owner = permittedSubject("user-1", Optional.of("tenant-1")); + Optional file = fileOwnedBy("user-1", Optional.of("tenant-1")); + + // when + Throwable refused = + catchThrowable( + () -> { + policy().authorize(FileOperation.DOWNLOAD, owner, file); + policy().authorize(FileOperation.DELETE, owner, file); + }); + + // then + assertThat(refused).isNull(); + } + + @Test + @DisplayName("같은 역할을 가진 다른 사용자의 파일은 ACCESS_DENIED다") + void anotherPrincipalsFileIsRefused() { + // given + FileAccessSubject stranger = permittedSubject("user-2", Optional.of("tenant-1")); + + // when + Throwable refused = + catchThrowable( + () -> + policy() + .authorize( + FileOperation.DOWNLOAD, + stranger, + fileOwnedBy("user-1", Optional.of("tenant-1")))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.ACCESS_DENIED); + } + + @Test + @DisplayName("같은 사용자라도 다른 tenant에서 만든 파일은 ACCESS_DENIED다") + void theSamePrincipalInAnotherTenantIsRefused() { + // given + FileAccessSubject elsewhere = permittedSubject("user-1", Optional.of("tenant-2")); + + // when + Throwable refused = + catchThrowable( + () -> + policy() + .authorize( + FileOperation.DOWNLOAD, + elsewhere, + fileOwnedBy("user-1", Optional.of("tenant-1")))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.ACCESS_DENIED); + } + + @Test + @DisplayName("tenant 없이 만든 파일은 tenant가 있는 같은 사용자에게도 ACCESS_DENIED다") + void aFileCreatedWithoutATenantIsRefusedToTheSamePrincipalWithOne() { + // given + FileAccessSubject scoped = permittedSubject("user-1", Optional.of("tenant-1")); + + // when + Throwable refused = + catchThrowable( + () -> + policy() + .authorize( + FileOperation.DELETE, scoped, fileOwnedBy("user-1", Optional.empty()))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.ACCESS_DENIED); + } + + @Test + @DisplayName("소유자가 기록되지 않은 파일은 누구에게도 ACCESS_DENIED다") + void aFileWithNoRecordedOwnerIsRefused() { + // given + FileAccessSubject caller = permittedSubject("user-1", Optional.empty()); + + // when + Throwable refused = + catchThrowable( + () -> policy().authorize(FileOperation.DOWNLOAD, caller, descriptor(Optional.empty()))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.ACCESS_DENIED); + } + + @Test + @DisplayName("파일이 생기기 전의 연산은 소유자 없이 역할로만 판단한다") + void anOperationBeforeTheFileExistsIsDecidedWithoutAnOwner() { + // given + FileAccessSubject caller = permittedSubject("user-1", Optional.of("tenant-1")); + + // when + Throwable refused = + catchThrowable(() -> policy().authorize(FileOperation.CREATE, caller, Optional.empty())); + + // then + assertThat(refused).isNull(); + } + + private static Optional fileOwnedBy(String principalId, Optional tenant) { + return descriptor(Optional.of(new FileOwner(principalId, tenant))); + } + + private static Optional descriptor(Optional owner) { + return Optional.of( + new FileDescriptor( + FileId.of(UUID.randomUUID()), + FileserverFixtures.NAMESPACE, + FileState.READY, + "report.bin", + "application/octet-stream", + 10, + FileserverFixtures.DIGEST, + FileserverFixtures.NOW, + owner, + 3)); + } + + private static Object codeOf(Throwable failure) { + return failure instanceof FileserverException refused ? refused.code() : failure; + } +} diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileQuotaLedgerContract.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileQuotaLedgerContract.java new file mode 100644 index 00000000..b217dad1 --- /dev/null +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileQuotaLedgerContract.java @@ -0,0 +1,346 @@ +package dev.caskeleton.application.fileserver.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; +import dev.caskeleton.application.fileserver.api.metadata.QuotaReservation; +import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; +import dev.caskeleton.application.fileserver.api.metadata.UploadSession; +import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort; +import dev.caskeleton.application.fileserver.upload.QuotaCommitPort; +import java.time.Duration; +import java.util.List; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The quota ledger, through all three ports that write it: {@link FileQuotaPort} reserves and + * settles reservations, {@link QuotaCommitPort} settles an upload's share, {@link QuotaReclaimPort} + * gives committed bytes back. They are one contract because they are one ledger — what a commit or + * a reclaim did is only visible as {@link FileQuotaPort#usedBytes}, the number a configured + * namespace limit is compared against (review 2026-11-03 RR-01-04). + * + *

        Run against the in-memory ledger and the JPA adapters on real PostgreSQL. Every test works in + * namespaces of its own, so a subclass may share one store across tests. + */ +public abstract class FileQuotaLedgerContract { + + private static final Duration TTL = Duration.ofHours(1); + + protected abstract FileQuotaPort quota(); + + protected abstract QuotaCommitPort commits(); + + protected abstract QuotaReclaimPort reclaims(); + + /** + * An upload of a file recorded in {@code namespace}, as the finalize path holds one: the commit + * port settles against the namespace of the file the session belongs to. + */ + protected abstract UploadSession uploadIn(StorageNamespace namespace); + + /** Lets {@code duration} pass on the clock the ledger reads. */ + protected abstract void elapse(Duration duration); + + /** Runs one ledger call inside the caller transaction the adapters require, and commits it. */ + protected T inTransaction(Supplier work) { + return work.get(); + } + + @Test + @DisplayName("살아 있는 예약은 그 scope의 사용량에 들어간다") + void aLiveReservationCountsTowardItsScope() { + // given + QuotaScope scope = newScope(); + + // when + reserve(scope, 100); + + // then + assertThat(usedBytes(scope)).isEqualTo(100); + } + + @Test + @DisplayName("예약을 늘리면 늘린 만큼 사용량이 커진다") + void extendingAReservationGrowsTheUsage() { + // given + QuotaScope scope = newScope(); + QuotaReservation reservation = reserve(scope, 100); + + // when + run(() -> quota().extend(reservation, 50)); + + // then + assertThat(usedBytes(scope)).isEqualTo(150); + } + + @Test + @DisplayName("확정하면 예약한 바이트 대신 실제 바이트가 사용량이 된다") + void committingCountsTheActualBytesInsteadOfTheReserved() { + // given + QuotaScope scope = newScope(); + QuotaReservation reservation = reserve(scope, 100); + + // when + run(() -> quota().commit(reservation, 60)); + + // then + assertThat(usedBytes(scope)).isEqualTo(60); + } + + @Test + @DisplayName("해제한 예약은 사용량에서 빠진다") + void releasingAReservationGivesItBack() { + // given + QuotaScope scope = newScope(); + QuotaReservation reservation = reserve(scope, 100); + + // when + run(() -> quota().release(reservation)); + + // then + assertThat(usedBytes(scope)).isZero(); + } + + @Test + @DisplayName("만료된 예약은 사용량에서 빠진다") + void anExpiredReservationNoLongerCounts() { + // given + QuotaScope scope = newScope(); + reserve(scope, 100); + + // when + elapse(TTL.plusMinutes(1)); + + // then + assertThat(usedBytes(scope)).isZero(); + } + + @Test + @DisplayName("만료된 예약은 늘릴 수 없고 QUOTA_EXCEEDED로 거절된다") + void anExpiredReservationCannotBeExtended() { + // given + QuotaReservation reservation = reserve(newScope(), 100); + elapse(TTL.plusMinutes(1)); + + // when + Throwable refused = catchThrowable(() -> run(() -> quota().extend(reservation, 10))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.QUOTA_EXCEEDED); + } + + @Test + @DisplayName("해제한 예약은 늘릴 수 없고 QUOTA_EXCEEDED로 거절된다") + void aReleasedReservationCannotBeExtended() { + // given + QuotaReservation reservation = reserve(newScope(), 100); + run(() -> quota().release(reservation)); + + // when + Throwable refused = catchThrowable(() -> run(() -> quota().extend(reservation, 10))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.QUOTA_EXCEEDED); + } + + @Test + @DisplayName("해제한 예약은 확정할 수 없고 QUOTA_EXCEEDED로 거절된다") + void aReleasedReservationCannotBeCommitted() { + // given + QuotaReservation reservation = reserve(newScope(), 100); + run(() -> quota().release(reservation)); + + // when + Throwable refused = catchThrowable(() -> run(() -> quota().commit(reservation, 60))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.QUOTA_EXCEEDED); + } + + /** + * Bytes that were written are durable usage whether or not the reservation outlived its TTL; + * dropping them because the reservation expired is how a ledger drifts below the truth. + */ + @Test + @DisplayName("만료됐지만 해제되지 않은 예약을 확정하면 실제 바이트가 사용량이 된다") + void committingAnExpiredReservationStillRecordsTheActualBytes() { + // given + QuotaScope scope = newScope(); + QuotaReservation reservation = reserve(scope, 100); + elapse(TTL.plusMinutes(1)); + + // when + run(() -> quota().commit(reservation, 60)); + + // then + assertThat(usedBytes(scope)).isEqualTo(60); + } + + @Test + @DisplayName("scope마다 사용량을 따로 센다") + void eachScopeIsCountedOnItsOwn() { + // given + QuotaScope scope = newScope(); + reserve(scope, 100); + + // when + reserve(newScope(), 30); + + // then + assertThat(usedBytes(scope)).isEqualTo(100); + } + + @Test + @DisplayName("음수 바이트 예약은 IllegalArgumentException으로 거절된다") + void aNegativeReservationIsRefused() { + // when + Throwable refused = catchThrowable(() -> reserve(newScope(), -1)); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("업로드 확정은 그 파일 namespace의 살아 있는 예약을 실제 바이트로 확정한다") + void settlingAnUploadCommitsItsNamespacesLiveReservation() { + // given + StorageNamespace namespace = newNamespace(); + UploadSession upload = uploadIn(namespace); + reserve(scopeOf(namespace), 1_000); + + // when + run(() -> commits().commit(upload, 600)); + + // then + assertThat(usedBytes(scopeOf(namespace))).isEqualTo(600); + } + + @Test + @DisplayName("살아 있는 예약이 없어도 업로드 확정은 실제 바이트를 사용량으로 남긴다") + void settlingAnUploadWithNoLiveReservationStillRecordsTheUsage() { + // given + StorageNamespace namespace = newNamespace(); + UploadSession upload = uploadIn(namespace); + + // when + run(() -> commits().commit(upload, 450)); + + // then + assertThat(usedBytes(scopeOf(namespace))).isEqualTo(450); + } + + @Test + @DisplayName("업로드 해제는 그 파일 namespace의 살아 있는 예약을 돌려준다") + void releasingAnUploadGivesItsNamespacesReservationBack() { + // given + StorageNamespace namespace = newNamespace(); + UploadSession upload = uploadIn(namespace); + reserve(scopeOf(namespace), 2_000); + + // when + run(() -> commits().release(upload)); + + // then + assertThat(usedBytes(scopeOf(namespace))).isZero(); + } + + @Test + @DisplayName("회수는 여러 확정분에 걸쳐 확정 사용량을 줄인다") + void reclaimingDrawsCommittedUsageDownAcrossCommits() { + // given + QuotaScope scope = newScope(); + commit(scope, 300); + commit(scope, 700); + + // when + run(() -> reclaims().reclaim(scope, 800)); + + // then + assertThat(usedBytes(scope)).isEqualTo(200); + } + + @Test + @DisplayName("기록보다 많이 회수하면 사용량은 0에서 멈춘다") + void reclaimingMoreThanIsRecordedStopsAtZero() { + // given + QuotaScope scope = newScope(); + commit(scope, 100); + + // when + run(() -> reclaims().reclaim(scope, 5_000)); + + // then + assertThat(usedBytes(scope)).isZero(); + } + + @Test + @DisplayName("회수는 살아 있는 예약과 다른 scope를 건드리지 않는다") + void reclaimingLeavesLiveReservationsAndOtherScopesAlone() { + // given + QuotaScope scope = newScope(); + QuotaScope other = newScope(); + reserve(scope, 100); + commit(scope, 50); + commit(other, 70); + + // when + run(() -> reclaims().reclaim(scope, 500)); + + // then + assertThat(List.of(usedBytes(scope), usedBytes(other))).containsExactly(100L, 70L); + } + + @Test + @DisplayName("음수 바이트 회수는 IllegalArgumentException으로 거절된다") + void aNegativeReclaimIsRefused() { + // when + Throwable refused = catchThrowable(() -> run(() -> reclaims().reclaim(newScope(), -1))); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + private QuotaReservation reserve(QuotaScope scope, long bytes) { + return inTransaction(() -> quota().reserve(scope, bytes, TTL)); + } + + private void commit(QuotaScope scope, long bytes) { + QuotaReservation reservation = reserve(scope, bytes); + run(() -> quota().commit(reservation, bytes)); + } + + private long usedBytes(QuotaScope scope) { + return inTransaction(() -> quota().usedBytes(scope)); + } + + private void run(Runnable work) { + inTransaction( + () -> { + work.run(); + return null; + }); + } + + private static StorageNamespace newNamespace() { + return StorageNamespace.of("q-" + UUID.randomUUID().toString().substring(0, 12)); + } + + private static QuotaScope newScope() { + return scopeOf(newNamespace()); + } + + private static QuotaScope scopeOf(StorageNamespace namespace) { + return QuotaScope.ofNamespace(namespace.value()); + } + + private static Object codeOf(Throwable failure) { + return failure instanceof FileserverException refused ? refused.code() : failure; + } +} diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStore.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStore.java index f55836d9..dd00e088 100644 --- a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStore.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryFileMetadataStore.java @@ -1,5 +1,7 @@ package dev.caskeleton.application.fileserver.testkit; +import dev.caskeleton.application.fileserver.admin.ContentReferenceLedgerPort; +import dev.caskeleton.application.fileserver.api.ContentKey; import dev.caskeleton.application.fileserver.api.FileId; import dev.caskeleton.application.fileserver.api.FileState; import dev.caskeleton.application.fileserver.api.StorageNamespace; @@ -25,8 +27,13 @@ import java.util.concurrent.atomic.AtomicInteger; *

        Application tests must observe identical conflict behaviour, so this fake enforces the * expected state and version rather than accepting any write. It is held to {@link * FileMetadataPortContract}, the contract the JPA adapter passes against PostgreSQL. + * + *

        Also answers {@link ContentReferenceLedgerPort} from the same records, as the JPA ledger reads + * the file table: a key is referenced while a record in any state names it ({@link + * ContentReferenceLedgerPortContract}). */ -public final class InMemoryFileMetadataStore implements FileMetadataPort { +public final class InMemoryFileMetadataStore + implements FileMetadataPort, ContentReferenceLedgerPort { private final Map records = new LinkedHashMap<>(); private final AtomicInteger transitionFailuresToInject = new AtomicInteger(); @@ -70,6 +77,12 @@ public final class InMemoryFileMetadataStore implements FileMetadataPort { return record; } + @Override + public boolean isReferenced(ContentKey key) { + return records.values().stream() + .anyMatch(record -> record.contentKey().filter(key::equals).isPresent()); + } + @Override public Optional find(FileId fileId) { return Optional.ofNullable(records.get(fileId)); diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueue.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueue.java index 61a526bb..8de863df 100644 --- a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueue.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryRecoveryQueue.java @@ -8,7 +8,12 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -/** Hand-rolled recovery queue that records every escalation reason. */ +/** + * Hand-rolled recovery queue that records every escalation reason. + * + *

        Answers as the JPA queue does ({@link RecoveryQueuePortContract}): one open entry per file, + * oldest first, resolved entries out of the pending list and raisable again. + */ public final class InMemoryRecoveryQueue implements RecoveryQueuePort { private final Map pending = new LinkedHashMap<>(); @@ -21,6 +26,9 @@ public final class InMemoryRecoveryQueue implements RecoveryQueuePort { @Override public List pending(int limit) { + if (limit < 1) { + throw new IllegalArgumentException("limit must be positive"); + } return List.copyOf( new ArrayList<>(pending.keySet()).subList(0, Math.min(limit, pending.size()))); } diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java index 3a1be230..abc28e98 100644 --- a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java @@ -12,7 +12,7 @@ import dev.caskeleton.application.fileserver.api.metadata.WriterLease; import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort; import java.time.Duration; import java.time.Instant; -import java.util.ArrayList; +import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -28,6 +28,11 @@ import java.util.UUID; * *

        Also answers {@link StagingUploadLocatorPort} from the same sessions, as the JPA locator reads * the session table: the newest session recorded for a file. + * + *

        {@link UploadSessionPortContract} and {@link StagingUploadLocatorPortContract} hold it to the + * JPA store's cases on PostgreSQL, including the two that read time: no lease on an upload past its + * expiry, and no offset commit once the writer's lease has lapsed ({@link #advanceTo} moves the + * store's clock). */ public final class InMemoryUploadSessionStore implements UploadSessionPort, StagingUploadLocatorPort { @@ -107,7 +112,8 @@ public final class InMemoryUploadSessionStore UploadSession current = require(uploadId); boolean leaseFree = current.leaseUntil().isEmpty() || !current.leaseUntil().get().isAfter(clockNow); - if (current.terminal() || current.version() != expectedVersion || !leaseFree) { + boolean uploadOpen = current.expiresAt().isAfter(clockNow); + if (current.terminal() || current.version() != expectedVersion || !leaseFree || !uploadOpen) { throw new FileserverException( "writer lease is held by another owner", FileserverFailureContext.forUpload( @@ -156,7 +162,13 @@ public final class InMemoryUploadSessionStore UploadId uploadId, WriterLease lease, long expectedOffset, long committedOffset) { UploadSession current = require(uploadId); boolean tokenMatches = current.leaseToken().map(lease.token()::equals).orElse(false); - if (current.terminal() || !tokenMatches || current.committedOffset() != expectedOffset) { + // The JPA statement reads its own clock here, not the caller's: a writer whose lease lapsed + // cannot advance the offset even when nobody has taken the lease over yet. + boolean stillHeld = current.leaseUntil().map(now::isBefore).orElse(false); + if (current.terminal() + || !tokenMatches + || !stillHeld + || current.committedOffset() != expectedOffset) { throw new FileserverException( "offset commit rejected", FileserverFailureContext.forOffset( @@ -222,13 +234,13 @@ public final class InMemoryUploadSessionStore @Override public List findExpired(Instant cutoff, int limit) { - List expired = new ArrayList<>(); - for (UploadSession session : sessions.values()) { - if (!session.terminal() && session.isExpiredAt(cutoff) && expired.size() < limit) { - expired.add(session); - } - } - return List.copyOf(expired); + // Strictly before the cutoff and earliest expiry first, as the JPA query reads them. + return sessions.values().stream() + .filter(session -> !session.terminal()) + .filter(session -> session.expiresAt().isBefore(cutoff)) + .sorted(Comparator.comparing(UploadSession::expiresAt)) + .limit(limit) + .toList(); } private UploadSession require(UploadId uploadId) { diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/RecordingQuotaReclaimGateway.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/RecordingQuotaReclaimGateway.java index b7369c7a..25001840 100644 --- a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/RecordingQuotaReclaimGateway.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/RecordingQuotaReclaimGateway.java @@ -4,12 +4,28 @@ import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort; import java.util.ArrayList; import java.util.List; +import java.util.Objects; -/** Records every reclaim so a test can prove capacity is returned exactly once. */ +/** + * The fake of {@link QuotaReclaimPort}: gives committed bytes back on the in-memory ledger as + * {@code JpaQuotaReclaim} does (newest first, floor zero), and records every reclaim so a test can + * prove capacity is returned exactly once. {@link FileQuotaLedgerContract} holds it to the JPA + * adapter's cases. + */ public final class RecordingQuotaReclaimGateway implements QuotaReclaimPort { + private final FakeFileQuotaService ledger; private final List reclaimed = new ArrayList<>(); + /** + * A gateway over {@code ledger}. + * + * @param ledger the ledger the committed usage lives in + */ + public RecordingQuotaReclaimGateway(FakeFileQuotaService ledger) { + this.ledger = Objects.requireNonNull(ledger, "ledger"); + } + public List reclaimed() { return List.copyOf(reclaimed); } @@ -20,6 +36,7 @@ public final class RecordingQuotaReclaimGateway implements QuotaReclaimPort { @Override public void reclaim(QuotaScope scope, long bytes) { + ledger.reclaim(scope, bytes); reclaimed.add(bytes); } } diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/RecoveryQueuePortContract.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/RecoveryQueuePortContract.java new file mode 100644 index 00000000..a10b339b --- /dev/null +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/RecoveryQueuePortContract.java @@ -0,0 +1,137 @@ +package dev.caskeleton.application.fileserver.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.recovery.ReconciliationStatus; +import dev.caskeleton.application.fileserver.recovery.RecoveryQueuePort; +import java.time.Duration; +import java.util.List; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link RecoveryQueuePort} promises, run against the in-memory queue and the JPA queue + * on real PostgreSQL (review 2026-11-03 RR-01-04). + * + *

        An entry is a request for an operator's decision: one open entry per file however often it is + * reported, gone from the pending list once resolved, and raisable again afterwards. + */ +public abstract class RecoveryQueuePortContract { + + /** The queue under test, empty at the start of each test. */ + protected abstract RecoveryQueuePort queue(); + + /** A file that has a record, which an entry may name. */ + protected abstract FileId recordedFile(); + + /** + * Lets {@code duration} pass on the clock the queue stamps entries with. The pending list is + * oldest first; a store that orders by insertion keeps the default. + */ + protected void elapse(Duration duration) {} + + /** Runs one queue call inside the caller transaction the adapter requires, and commits it. */ + protected T inTransaction(Supplier work) { + return work.get(); + } + + @Test + @DisplayName("올린 파일은 대기 목록에 있다") + void anEnqueuedFileIsPending() { + // given + FileId file = recordedFile(); + + // when + run(() -> queue().enqueue(file, "READY_DIGEST_MISMATCH")); + + // then + assertThat(pending(10)).containsExactly(file); + } + + @Test + @DisplayName("같은 파일을 두 번 올려도 대기 항목은 하나다") + void theSameFileReportedTwiceIsPendingOnce() { + // given + FileId file = recordedFile(); + run(() -> queue().enqueue(file, "READY_DIGEST_MISMATCH")); + + // when + run(() -> queue().enqueue(file, "READY_SIZE_MISMATCH")); + + // then + assertThat(pending(10)).containsExactly(file); + } + + @Test + @DisplayName("처리한 파일은 대기 목록에서 빠진다") + void aResolvedFileLeavesThePendingList() { + // given + FileId file = recordedFile(); + run(() -> queue().enqueue(file, "PUBLISH_EVIDENCE_INCOMPLETE")); + + // when + run(() -> queue().resolve(file, ReconciliationStatus.QUARANTINE_REQUIRED)); + + // then + assertThat(pending(10)).isEmpty(); + } + + @Test + @DisplayName("처리한 파일도 나중에 다시 올릴 수 있다") + void aResolvedFileCanBeRaisedAgain() { + // given + FileId file = recordedFile(); + run(() -> queue().enqueue(file, "FIRST")); + run(() -> queue().resolve(file, ReconciliationStatus.UNRESOLVED)); + + // when + run(() -> queue().enqueue(file, "SECOND")); + + // then + assertThat(pending(10)).containsExactly(file); + } + + @Test + @DisplayName("대기 목록은 먼저 올린 파일부터 한도만큼 준다") + void thePendingListIsOldestFirstUpToTheLimit() { + // given + FileId first = recordedFile(); + FileId second = recordedFile(); + FileId third = recordedFile(); + for (FileId file : List.of(first, second, third)) { + run(() -> queue().enqueue(file, "UNSETTLED")); + elapse(Duration.ofSeconds(1)); + } + + // when + List pending = pending(2); + + // then + assertThat(pending).containsExactly(first, second); + } + + @Test + @DisplayName("한도가 1보다 작으면 IllegalArgumentException으로 거절된다") + void aLimitBelowOneIsRefused() { + // when + Throwable refused = catchThrowable(() -> pending(0)); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + private List pending(int limit) { + return inTransaction(() -> queue().pending(limit)); + } + + private void run(Runnable work) { + inTransaction( + () -> { + work.run(); + return null; + }); + } +} diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/StagingUploadLocatorPortContract.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/StagingUploadLocatorPortContract.java new file mode 100644 index 00000000..401043b6 --- /dev/null +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/StagingUploadLocatorPortContract.java @@ -0,0 +1,92 @@ +package dev.caskeleton.application.fileserver.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.transfer.UploadMode; +import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort; +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; +import java.util.OptionalLong; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link StagingUploadLocatorPort} promises, run against the in-memory session store and + * the JPA locator on real PostgreSQL (review 2026-11-03 RR-01-04). + * + *

        Only the newest upload of a file is returned: an older one names a staging object that has + * since been reclaimed, and treating it as live evidence would tell reconciliation the upload is + * resumable when it is not. + */ +public abstract class StagingUploadLocatorPortContract { + + protected abstract StagingUploadLocatorPort locator(); + + /** The session store the locator reads, to record uploads with. */ + protected abstract UploadSessionPort sessions(); + + /** A file that has a record, which an upload may belong to. */ + protected abstract FileId recordedFile(); + + /** The instant the store reads as now. */ + protected abstract Instant now(); + + /** Lets {@code duration} pass on the clock the store stamps sessions with. */ + protected abstract void elapse(Duration duration); + + /** Runs one store call inside the caller transaction the adapter requires, and commits it. */ + protected T inTransaction(Supplier work) { + return work.get(); + } + + @Test + @DisplayName("업로드가 없던 파일은 아무것도 찾지 않는다") + void aFileThatWasNeverStagedLocatesNothing() { + // given + FileId file = recordedFile(); + + // when + Optional located = inTransaction(() -> locator().locate(file)); + + // then + assertThat(located).isEmpty(); + } + + @Test + @DisplayName("업로드가 여럿인 파일은 가장 최근 업로드를 찾는다") + void aFileStagedTwiceLocatesItsNewestUpload() { + // given + FileId file = recordedFile(); + stage(file); + elapse(Duration.ofSeconds(1)); + UploadId newest = stage(file); + + // when + Optional located = inTransaction(() -> locator().locate(file)); + + // then + assertThat(located).contains(newest); + } + + private UploadId stage(FileId file) { + UploadId uploadId = UploadId.of(UUID.randomUUID()); + inTransaction( + () -> + sessions() + .create( + new UploadSessionDraft( + uploadId, + file, + UploadMode.SINGLE_SHOT, + OptionalLong.of(100), + now().plus(Duration.ofHours(1))))); + return uploadId; + } +} diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/UploadSessionPortContract.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/UploadSessionPortContract.java new file mode 100644 index 00000000..ae49d7a7 --- /dev/null +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/UploadSessionPortContract.java @@ -0,0 +1,367 @@ +package dev.caskeleton.application.fileserver.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.metadata.UploadSession; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.metadata.WriterLease; +import dev.caskeleton.application.fileserver.api.transfer.UploadMode; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.OptionalLong; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link UploadSessionPort} promises, run against the in-memory store and the JPA store + * on real PostgreSQL (review 2026-11-03 RR-01-04). + * + *

        The writer lease is the only thing that keeps two instances from appending to one upload, so + * the cases are its rules: who may take a lease, who may renew it, who may advance the offset, and + * when an upload stops being writable at all. + */ +public abstract class UploadSessionPortContract { + + private static final Duration LEASE = Duration.ofMinutes(1); + private static final Duration UPLOAD_LIFETIME = Duration.ofHours(1); + + /** The store under test, holding no session at the start of each test. */ + protected abstract UploadSessionPort sessions(); + + /** A file that has a record, which an upload may belong to. */ + protected abstract FileId recordedFile(); + + /** The instant the store reads as now. */ + protected abstract Instant now(); + + /** Lets {@code duration} pass on the clock the store reads. */ + protected abstract void elapse(Duration duration); + + /** Runs one store call inside the caller transaction the adapter requires, and commits it. */ + protected T inTransaction(Supplier work) { + return work.get(); + } + + @Test + @DisplayName("새 업로드는 offset 0, lease 없음, 열린 상태로 다시 읽힌다") + void aCreatedUploadIsReadBackOpenAtOffsetZeroWithNoLease() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + + // when + UploadSession found = find(uploadId); + + // then + assertThat(List.of(found.committedOffset(), found.leaseToken().isPresent(), found.terminal())) + .containsExactly(0L, false, false); + } + + @Test + @DisplayName("다른 writer가 lease를 쥐고 있으면 lease를 주지 않는다") + void aLeaseIsRefusedWhileAnotherWriterHoldsIt() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + acquire(uploadId, "node-a"); + + // when + Throwable refused = catchThrowable(() -> acquire(uploadId, "node-b")); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION); + } + + @Test + @DisplayName("만료된 lease는 다른 writer가 넘겨받는다") + void anExpiredLeaseIsTakenOverByAnotherWriter() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + acquire(uploadId, "node-a"); + elapse(LEASE.plusSeconds(1)); + + // when + WriterLease taken = acquire(uploadId, "node-b"); + + // then + assertThat(find(uploadId).leaseToken()).contains(taken.token()); + } + + @Test + @DisplayName("기대한 버전이 지난 것이면 lease를 주지 않는다") + void aLeaseIsRefusedOnAStaleVersion() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + long stale = find(uploadId).version(); + WriterLease first = acquire(uploadId, "node-a"); + inTransaction( + () -> { + sessions().releaseLease(uploadId, first); + return null; + }); + + // when + Throwable refused = + catchThrowable( + () -> + inTransaction( + () -> sessions().acquireLease(uploadId, "node-b", now(), LEASE, stale))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION); + } + + @Test + @DisplayName("업로드 기한이 지나면 lease를 주지 않는다") + void aLeaseIsRefusedOnceTheUploadHasExpired() { + // given + UploadId uploadId = create(Duration.ofMinutes(5)); + elapse(Duration.ofMinutes(6)); + + // when + Throwable refused = catchThrowable(() -> acquire(uploadId, "node-a")); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION); + } + + @Test + @DisplayName("갱신한 lease는 처음 만료 시각이 지나도 다른 writer에게 넘어가지 않는다") + void aRenewedLeaseOutlivesItsFirstExpiry() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + WriterLease lease = acquire(uploadId, "node-a"); + elapse(LEASE.dividedBy(2)); + inTransaction(() -> sessions().renewLease(lease, now(), LEASE)); + elapse(LEASE.dividedBy(2).plusSeconds(1)); + + // when + Throwable refused = catchThrowable(() -> acquire(uploadId, "node-b")); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION); + } + + @Test + @DisplayName("이미 만료된 lease는 갱신하지 않는다") + void aLapsedLeaseCannotBeRenewed() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + WriterLease lease = acquire(uploadId, "node-a"); + elapse(LEASE.plusSeconds(1)); + + // when + Throwable refused = + catchThrowable(() -> inTransaction(() -> sessions().renewLease(lease, now(), LEASE))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION); + } + + @Test + @DisplayName("lease를 쥔 writer는 기대한 offset에서 offset을 올린다") + void theLeaseHolderAdvancesTheOffsetFromTheExpectedOne() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + WriterLease lease = acquire(uploadId, "node-a"); + + // when + UploadSession advanced = inTransaction(() -> sessions().commitOffset(uploadId, lease, 0, 40)); + + // then + assertThat(advanced.committedOffset()).isEqualTo(40); + } + + @Test + @DisplayName("기대한 offset이 다르면 offset을 올리지 않는다") + void anOffsetCommitFromTheWrongOffsetIsRefused() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + WriterLease lease = acquire(uploadId, "node-a"); + + // when + Throwable refused = + catchThrowable(() -> inTransaction(() -> sessions().commitOffset(uploadId, lease, 10, 40))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION); + } + + @Test + @DisplayName("lease를 빼앗긴 writer는 offset을 올리지 못한다") + void aWriterWhoseLeaseWasTakenOverCannotAdvanceTheOffset() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + WriterLease stale = acquire(uploadId, "node-a"); + elapse(LEASE.plusSeconds(1)); + acquire(uploadId, "node-b"); + + // when + Throwable refused = + catchThrowable(() -> inTransaction(() -> sessions().commitOffset(uploadId, stale, 0, 40))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION); + } + + @Test + @DisplayName("lease가 만료된 writer는 아무도 넘겨받지 않았어도 offset을 올리지 못한다") + void aWriterWhoseLeaseLapsedCannotAdvanceTheOffset() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + WriterLease lease = acquire(uploadId, "node-a"); + elapse(LEASE.plusSeconds(1)); + + // when + Throwable refused = + catchThrowable(() -> inTransaction(() -> sessions().commitOffset(uploadId, lease, 0, 40))); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION); + } + + @Test + @DisplayName("다른 writer의 토큰으로 해제해도 쥐고 있는 lease는 남는다") + void releasingWithAnotherWritersTokenLeavesTheLeaseHeld() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + WriterLease held = acquire(uploadId, "node-a"); + WriterLease other = new WriterLease(uploadId, "node-b", UUID.randomUUID(), now(), 0); + + // when + inTransaction( + () -> { + sessions().releaseLease(uploadId, other); + return null; + }); + + // then + assertThat(find(uploadId).leaseToken()).contains(held.token()); + } + + @Test + @DisplayName("업로드를 끝내는 호출은 처음 한 번만 끝냈다고 답한다") + void terminatingAnUploadAnswersTrueOnlyTheFirstTime() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + boolean first = inTransaction(() -> sessions().terminate(uploadId)); + + // when + boolean second = inTransaction(() -> sessions().terminate(uploadId)); + + // then + assertThat(List.of(first, second)).containsExactly(true, false); + } + + @Test + @DisplayName("끝난 업로드에는 lease를 주지 않는다") + void aTerminatedUploadRefusesANewLease() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + inTransaction(() -> sessions().terminate(uploadId)); + + // when + Throwable refused = catchThrowable(() -> acquire(uploadId, "node-a")); + + // then + assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION); + } + + @Test + @DisplayName("끝났지만 writer가 아직 lease를 쥔 업로드는 정리 대상으로 잡지 않는다") + void aTerminatedUploadWhoseWriterStillHoldsTheLeaseIsNotClaimedForCleanup() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + acquire(uploadId, "node-a"); + inTransaction(() -> sessions().terminate(uploadId)); + + // when + boolean claimed = inTransaction(() -> sessions().claimForCleanup(uploadId, now())); + + // then + assertThat(claimed).isFalse(); + } + + @Test + @DisplayName("끝났고 lease가 만료된 업로드는 정리 대상으로 잡힌다") + void aTerminatedUploadWithALapsedLeaseIsClaimedForCleanup() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + acquire(uploadId, "node-a"); + inTransaction(() -> sessions().terminate(uploadId)); + elapse(LEASE.plusSeconds(1)); + + // when + boolean claimed = inTransaction(() -> sessions().claimForCleanup(uploadId, now())); + + // then + assertThat(claimed).isTrue(); + } + + @Test + @DisplayName("열린 업로드는 정리 대상으로 잡지 않는다") + void anOpenUploadIsNotClaimedForCleanup() { + // given + UploadId uploadId = create(UPLOAD_LIFETIME); + + // when + boolean claimed = inTransaction(() -> sessions().claimForCleanup(uploadId, now())); + + // then + assertThat(claimed).isFalse(); + } + + @Test + @DisplayName("기한이 지난 열린 업로드만 기한이 이른 것부터 찾는다") + void expiredOpenUploadsAreFoundEarliestExpiryFirst() { + // given + UploadId later = create(Duration.ofMinutes(50)); + UploadId earlier = create(Duration.ofMinutes(20)); + create(Duration.ofHours(3)); + UploadId ended = create(Duration.ofMinutes(10)); + inTransaction(() -> sessions().terminate(ended)); + Instant cutoff = now().plus(Duration.ofHours(1)); + + // when + List expired = inTransaction(() -> sessions().findExpired(cutoff, 10)); + + // then + assertThat(expired).extracting(UploadSession::uploadId).containsExactly(earlier, later); + } + + private UploadId create(Duration lifetime) { + UploadId uploadId = UploadId.of(UUID.randomUUID()); + FileId file = recordedFile(); + inTransaction( + () -> + sessions() + .create( + new UploadSessionDraft( + uploadId, + file, + UploadMode.RESUMABLE, + OptionalLong.of(100), + now().plus(lifetime)))); + return uploadId; + } + + private UploadSession find(UploadId uploadId) { + return inTransaction(() -> sessions().find(uploadId)).orElseThrow(); + } + + private WriterLease acquire(UploadId uploadId, String owner) { + long version = find(uploadId).version(); + return inTransaction(() -> sessions().acquireLease(uploadId, owner, now(), LEASE, version)); + } + + private static Object codeOf(Throwable failure) { + return failure instanceof FileserverException refused ? refused.code() : failure; + } +} diff --git a/src/application-notification/build.gradle b/src/application-notification/build.gradle index 71aaa736..d0e46d03 100644 --- a/src/application-notification/build.gradle +++ b/src/application-notification/build.gradle @@ -16,6 +16,9 @@ dependencies { // so a provider adapter in any leaf extends the same contract (capability criterion 5). testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' testFixturesImplementation 'org.assertj:assertj-core' + // OverlappingWrites (two transactions of one key, overlapped on purpose) lives beside + // application-core's transaction fake: the outbox counter contract needs it too. + testFixturesImplementation testFixtures(project(':application-core')) // Use-case tests run over application-core's shared transaction fake (DirectTransactionPort), // the one held to the transaction port contract, not a hand-written port per test class. diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJobStorePort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJobStorePort.java index 5c3929bd..acfee9c9 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJobStorePort.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationJobStorePort.java @@ -35,7 +35,9 @@ public interface ReconciliationJobStorePort { *

        The claim is ownership that outlives the statement that took it: until {@code now + lease} * no other caller is handed the same job, whether or not a transaction is open. That is what lets * the caller ask a provider about each job with no database transaction held across the call. A - * job whose lease has passed is claimable again, so the lease must cover the whole pass. + * job whose lease has passed is claimable again, so the lease must cover the whole pass. Taking + * over such a job counts the abandoned claim as one attempt, so a job its worker dies on every + * time still reaches the attempt limit. * * @param limit how many to take * @param now the current instant diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/AdminOperationStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/AdminOperationStoreContract.java index 86409ca8..f186787e 100644 --- a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/AdminOperationStoreContract.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/admin/testkit/AdminOperationStoreContract.java @@ -12,7 +12,7 @@ import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.NotificationId; import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; import dev.caskeleton.application.notification.platform.api.TenantId; -import dev.caskeleton.application.notification.platform.policy.testkit.OverlappingWrites; +import dev.caskeleton.application.transaction.testkit.OverlappingWrites; import java.util.List; import java.util.Optional; import java.util.Set; diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStore.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStore.java index f937cffb..18e877ea 100644 --- a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStore.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/InMemoryReconciliationJobStore.java @@ -81,6 +81,10 @@ public final class InMemoryReconciliationJobStore implements ReconciliationJobSt .toList(); List claimed = new ArrayList<>(); for (Row row : due) { + if (row.claimedUntil != null) { + // The previous claim's lease ran out with no reschedule or completion: it was an attempt. + row.attempts++; + } row.claimedUntil = now.plus(lease); row.claimFence++; claimed.add(row.copy()); diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRequestStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRequestStoreContract.java index 96238b7f..fbf2a2d6 100644 --- a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRequestStoreContract.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/NotificationRequestStoreContract.java @@ -12,7 +12,7 @@ import dev.caskeleton.application.notification.platform.dispatch.NotificationReq import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestRecord; import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; -import dev.caskeleton.application.notification.platform.policy.testkit.OverlappingWrites; +import dev.caskeleton.application.transaction.testkit.OverlappingWrites; import java.time.Instant; import java.util.List; import java.util.Optional; diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ReconciliationJobStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ReconciliationJobStoreContract.java index d50ab68e..a27d5cae 100644 --- a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ReconciliationJobStoreContract.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/dispatch/testkit/ReconciliationJobStoreContract.java @@ -118,6 +118,25 @@ public abstract class ReconciliationJobStoreContract { .containsExactly(id); } + /** + * A worker that dies on the same job every time never reschedules it, so the lease expiry is the + * only trace its attempt leaves. Counting it is what lets the attempt limit end the loop, as the + * file server's reclaim does (review RR-03-08). + */ + @Test + @DisplayName("lease가 지나 다시 가져간 job은 끝내지 못한 이전 claim을 시도 한 번으로 센다") + void reclaimingAJobWhoseLeasePassedCountsTheAbandonedClaimAsAnAttempt() { + // given + scheduleDueJob(); + store().claimDue(10, NOW, LEASE); + + // when + List reclaimed = store().claimDue(10, NOW.plus(LEASE), LEASE); + + // then + assertThat(reclaimed).extracting(ReconciliationJob::attempts).containsExactly(1); + } + @Test @DisplayName("lease가 1마이크로초라도 남은 job은 다른 인스턴스가 가져가지 못한다") void aJobWhoseLeaseHasNotPassedIsNotClaimed() { @@ -161,11 +180,12 @@ public abstract class ReconciliationJobStoreContract { // when store().reschedule(stale, "STILL_UNKNOWN", NOW.plus(Duration.ofHours(1))); - // then + // then: two abandoned leases count, the stale reschedule does not (it would also have moved + // the job an hour out of this claim) assertThat(store().claimDue(10, NOW.plus(LEASE.multipliedBy(2)), LEASE)) .as("two holders counting one question would reach the attempt limit early") .extracting(ReconciliationJob::attempts) - .containsExactly(0); + .containsExactly(2); } @Test diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/DeduplicationStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/DeduplicationStoreContract.java index 73ddfe82..5c6cbef3 100644 --- a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/DeduplicationStoreContract.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/DeduplicationStoreContract.java @@ -7,6 +7,7 @@ import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.policy.DeduplicationResult; import dev.caskeleton.application.notification.platform.policy.DeduplicationStorePort; import dev.caskeleton.application.notification.platform.policy.RecipientIdentity; +import dev.caskeleton.application.transaction.testkit.OverlappingWrites; import java.util.List; import java.util.UUID; import java.util.function.Supplier; diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/PreferenceStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/PreferenceStoreContract.java index 995732d5..c7e5691b 100644 --- a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/PreferenceStoreContract.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/PreferenceStoreContract.java @@ -6,6 +6,7 @@ import dev.caskeleton.application.notification.platform.api.TenantId; import dev.caskeleton.application.notification.platform.api.routing.Channel; import dev.caskeleton.application.notification.platform.policy.PreferenceRecord; import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort; +import dev.caskeleton.application.transaction.testkit.OverlappingWrites; import java.time.Instant; import java.util.List; import java.util.Optional; diff --git a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/SuppressionStoreContract.java b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/SuppressionStoreContract.java index e48b15f2..58cfd4a6 100644 --- a/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/SuppressionStoreContract.java +++ b/src/application-notification/src/testFixtures/java/dev/caskeleton/application/notification/platform/policy/testkit/SuppressionStoreContract.java @@ -9,6 +9,7 @@ import dev.caskeleton.application.notification.platform.policy.SuppressionReason import dev.caskeleton.application.notification.platform.policy.SuppressionScope; import dev.caskeleton.application.notification.platform.policy.SuppressionSource; import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; +import dev.caskeleton.application.transaction.testkit.OverlappingWrites; import java.time.Duration; import java.time.Instant; import java.util.List; diff --git a/src/build-logic/README.md b/src/build-logic/README.md index e4e20312..97afbfdb 100644 --- a/src/build-logic/README.md +++ b/src/build-logic/README.md @@ -16,7 +16,7 @@ capability, and the files it reads are declared as that test task's inputs. | `ca.java-library` / `ca.spring-library` / `ca.spring-config` | leaf-level composition of the Java/quality conventions for plain and Spring libraries | | `ca.platform-module` / `ca.grpc-platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library`, plus the gRPC BOM for the leaves that had it | | `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason. Extra test source sets are Gradle `jvm-test-suite` suites declared in the leaf (`testing { suites { … } }`); a lane named after its suite makes the suite's own `Test` task strict, and `ca.java-conventions` gives every suite the BOM's JUnit | -| `ca.strict-lane-stages` (root) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow (a `--dry-run` or `-p ` command does not count). The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01) | +| `ca.strict-lane-stages` (root of each build with strict lanes: the main build and optional-platforms) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane of that build that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow. A `--dry-run`, a command for another build (`workflowProjectDirectory` names the `-p` value that starts this one), and a command under `continue-on-error` or an `if:` other than `always()`/`success()`/`!cancelled()` do not count, and a lane the command removes with `-x` is not covered. The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01, 2026-11-03 RR-06-03/04) | | `ca.redis-topology-lane` | the Redis topology lane (mode selection, `-P` property validation, per-mode required classes) the redis-sdk-topology workflow drives | | `ca.api-surface` | read-only public API surface verification with a separate update task, wired into the leaf's `check` (owner decision 20); optionally holds other leaves' imports to a reviewed adopter subset (`adopterBaseline`) | | `ca.config-contract` | app-bootstrap's `verifyEnvKeys` (moved from the deleted build-tools included build; owner decision 4 keeps the task in app-bootstrap) | @@ -61,7 +61,8 @@ cd src The lane and registry conventions are covered by Gradle TestKit against real builds rather than by reading the plugin source, because the properties that matter — a lane that discovers nothing fails, -a lane never reports up-to-date, a malformed registry is refused before any project is included — are +a lane reuses a result only when its classes and its lane policy (`rejectSkipped`, `requires`, tag, +category) are unchanged and it starts no server, a malformed registry is refused before any project is included — are runtime behaviour rather than text in a script. Two of those tests exist because the obvious reading of the Gradle documentation was wrong: `failOnNoDiscoveredTests` does not fire when a tag filter matches nothing, and `failOnNoMatchingTests` does not fire when only *some* of the named tests are diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java index 8b36b456..19aa949a 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java @@ -21,7 +21,6 @@ public final class ConfigContractPlugin implements Plugin { task.setGroup("verification"); task.setDescription( "Verifies shipped configuration APP_ references, src/.env.example, and env-keys.yaml stay registered."); - task.dependsOn(":adapter:outbound:redis-runtime:compileJava"); task.getEnvFile().fileValue(root.file(".env.example")); task.getConfigurationFiles() .from( @@ -43,8 +42,11 @@ public final class ConfigContractPlugin implements Plugin { tree.exclude("app-bootstrap/**"); tree.exclude("**/build/**"); })); - // What an operator edits or runs: the root Compose files and the Logback - // configuration. Their APP_ names must be registered and read (07-10). + // What an operator edits or runs: the root Compose files, the Logback + // configuration, and the Compose lane contract with the smoke wrapper that drives it + // (each lane's activationEnv, the wrapper's CAPABILITIES_OFF). Their APP_ names must + // be registered and read (07-10; RR-06-07: an unread CASKELETON_GRPC_ENABLED-style + // switch in a lane was found by hand, not by this task). task.getOperatorFiles() .from( root.fileTree( @@ -55,13 +57,13 @@ public final class ConfigContractPlugin implements Plugin { // clients and other services, not to this application. tree.exclude("docker-compose.infra.yml"); }), - root.file("app-bootstrap/src/main/resources/logback-spring.xml")); + root.file("app-bootstrap/src/main/resources/logback-spring.xml"), + root.file("config/runtime/compose-profile-contracts.json"), + root.file("../scripts/run-compose-runtime-smoke.sh")); task.getRegistryFile().fileValue(root.file("../docs/registries/env-keys.yaml")); - task.getRedisSdkMetadata() - .fileValue( - root.file( - "adapter/outbound/redis-runtime/build/classes/java/main/" - + "META-INF/spring-configuration-metadata.json")); + // No module path here: the typed properties come from the configuration metadata on + // the classpath the composition root wires (metadataClasspath), so this task knows no + // leaf by name (review 2026-11-03 RR-06-10). task.getProductionSources() .from( root.fileTree( diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigurationMetadataClasspath.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigurationMetadataClasspath.java new file mode 100644 index 00000000..624be5be --- /dev/null +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigurationMetadataClasspath.java @@ -0,0 +1,87 @@ +package dev.caskeleton.buildlogic.config; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * The typed configuration properties a classpath declares, read from each entry's {@code + * META-INF/spring-configuration-metadata.json} (the file the configuration processor writes into a + * module's classes and jar). + * + *

        The environment contract used to read one leaf's metadata by its build path and depend on that + * leaf's {@code compileJava} — the env contract task knew the Redis runtime module by name + * (review 2026-11-03 RR-06-10, capability criterion 7). Reading the composition's classpath instead, + * a module that ships metadata is checked because it is selected, and one that is removed takes its + * metadata with it. No Gradle API. + */ +public final class ConfigurationMetadataClasspath { + static final String METADATA = "META-INF/spring-configuration-metadata.json"; + + private static final ObjectMapper JSON = + JsonMapper.builder().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build(); + + private ConfigurationMetadataClasspath() {} + + /** + * Every property name starting with {@code prefix} that some classpath entry's metadata declares. + * + * @param classpath jars and class directories; entries without metadata are skipped + * @param prefix the property prefix, for example {@code app.redis.} + * @return the names, sorted + */ + public static Set propertiesUnder(Collection classpath, String prefix) { + Set properties = new TreeSet<>(); + for (File entry : classpath) { + for (MetadataProperty property : read(entry)) { + if (property.name() != null && property.name().startsWith(prefix)) { + properties.add(property.name()); + } + } + } + return properties; + } + + private static List read(File entry) { + try { + if (entry.isDirectory()) { + File metadata = new File(entry, METADATA); + return metadata.isFile() ? parse(Files.readAllBytes(metadata.toPath())) : List.of(); + } + if (entry.isFile() && entry.getName().endsWith(".jar")) { + try (ZipFile jar = new ZipFile(entry)) { + ZipEntry metadata = jar.getEntry(METADATA); + if (metadata == null) { + return List.of(); + } + try (InputStream in = jar.getInputStream(metadata)) { + return parse(in.readAllBytes()); + } + } + } + return List.of(); + } catch (IOException failure) { + throw new UncheckedIOException("failed to read configuration metadata of " + entry, failure); + } + } + + private static List parse(byte[] json) { + Metadata metadata = JSON.readValue(json, Metadata.class); + return metadata.properties() == null ? List.of() : metadata.properties(); + } + + private record Metadata(List properties) {} + + private record MetadataProperty(String name) {} +} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java index 07b645ec..c6cd6192 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java @@ -36,6 +36,18 @@ public final class EnvContractVerifier { /** A variable Logback reads directly: {@code }. */ private static final Pattern LOGBACK_SOURCE = Pattern.compile("source=\"(APP_[A-Z][A-Z0-9_]*)\""); + /** + * A variable a JSON object sets: the {@code activationEnv} maps of the Compose lane contract, and + * the smoke wrapper's {@code CAPABILITIES_OFF} literal. An {@code "APP_X=value"} string (an + * argument the wrapper passes on) is not a key and is not matched. + */ + private static final Pattern JSON_KEY = Pattern.compile("\"(APP_[A-Z][A-Z0-9_]*)\"\\s*:"); + /** + * A list element ({@code APP_HTTPCLIENT_CLIENTS_0_NAME}). Its field template is registered by the + * owning module's field registry ({@code docs/httpclient/env-fields.yaml}, held by that module's + * manifest test and strict binder), not as a row here. + */ + private static final Pattern INDEXED_KEY = Pattern.compile(".*_[0-9]+(_.*)?"); private static final ObjectMapper JSON = JsonMapper.builder().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build(); @@ -62,8 +74,10 @@ public final class EnvContractVerifier { * Verifies the contract, and also every {@code APP_*} name the operator-facing files set. * *

        Operator files are what an operator edits or runs to supply values — the root Compose files - * that run the application and {@code logback-spring.xml}. A Compose file contributes the keys of - * its {@code environment:} maps, Logback its {@code springProperty} sources. A name there must be registered, and something must read it: + * that run the application, {@code logback-spring.xml}, the Compose lane contract and the smoke + * wrapper that drives it. A Compose file contributes the keys of its {@code environment:} maps, + * Logback its {@code springProperty} sources, a JSON file or a shell script the keys of its JSON + * objects (review 2026-11-03 RR-06-07). A name there must be registered, and something must read it: * a shipped-configuration placeholder, a production source, or a typed property. A variable set * in a Compose file that nothing reads is a setting the operator believes is in force and is not * ({@code APP_LOG_JSON_ENABLED} in the prod-smoke file, 07-10). @@ -197,17 +211,17 @@ public final class EnvContractVerifier { Set operatorReferences = new TreeSet<>(); for (File operatorFile : operatorFiles) { requireFile(operatorFile, "missing operator file " + operatorFile); - Matcher matcher = - (operatorFile.getName().endsWith(".xml") ? LOGBACK_SOURCE : COMPOSE_ENVIRONMENT_KEY) - .matcher(read(operatorFile)); + Matcher matcher = operatorKeyPattern(operatorFile.getName()).matcher(read(operatorFile)); while (matcher.find()) { - operatorReferences.add(matcher.group(1)); + if (!INDEXED_KEY.matcher(matcher.group(1)).matches()) { + operatorReferences.add(matcher.group(1)); + } } } failUnlessEmpty( difference(operatorReferences, registryAppKeys), - "operator files (Compose, logback-spring.xml) set APP_ keys absent from " - + "docs/registries/env-keys.yaml: "); + "operator files (Compose, logback-spring.xml, the Compose lane contract, the smoke wrapper)" + + " set APP_ keys absent from docs/registries/env-keys.yaml: "); Set typedRows = new TreeSet<>(); registryRows.stream() .filter(row -> row.property().isPresent()) @@ -220,8 +234,9 @@ public final class EnvContractVerifier { } failUnlessEmpty( unreadOperatorReferences, - "operator files (Compose, logback-spring.xml) set APP_ keys nothing reads — no shipped " - + "configuration placeholder, production source or typed property: "); + "operator files (Compose, logback-spring.xml, the Compose lane contract, the smoke" + + " wrapper) set APP_ keys nothing reads — no shipped configuration placeholder," + + " production source or typed property: "); Set unconsumed = new TreeSet<>(); for (EnvRegistryRow row : registryRows) { @@ -263,6 +278,16 @@ public final class EnvContractVerifier { warnings); } + private static Pattern operatorKeyPattern(String fileName) { + if (fileName.endsWith(".xml")) { + return LOGBACK_SOURCE; + } + if (fileName.endsWith(".json") || fileName.endsWith(".sh")) { + return JSON_KEY; + } + return COMPOSE_ENVIRONMENT_KEY; + } + private static SpringConfigurationMetadata parseMetadata(File file) { SpringConfigurationMetadata metadata = JSON.readValue(file, SpringConfigurationMetadata.class); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java index ce79b83a..9ff45763 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java @@ -1,13 +1,20 @@ package dev.caskeleton.buildlogic.config; +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; import java.util.List; +import java.util.Set; import org.gradle.api.DefaultTask; import org.gradle.api.GradleException; import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.tasks.Classpath; import org.gradle.api.tasks.InputFile; import org.gradle.api.tasks.InputFiles; -import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.PathSensitive; import org.gradle.api.tasks.PathSensitivity; import org.gradle.api.tasks.TaskAction; @@ -24,6 +31,12 @@ public abstract class VerifyEnvKeysTask extends DefaultTask { "APP_LEASE_REDIS_", "APP_SESSION_REDIS_"); + /** + * The property trees whose every typed property needs a registry row. A policy of the registry, + * not a module location: the metadata is found on {@link #getMetadataClasspath()}. + */ + private static final List TYPED_PREFIXES = List.of("app.redis."); + @InputFile public abstract RegularFileProperty getEnvFile(); @@ -34,9 +47,12 @@ public abstract class VerifyEnvKeysTask extends DefaultTask { @InputFile public abstract RegularFileProperty getRegistryFile(); - @Optional - @InputFile - public abstract RegularFileProperty getRedisSdkMetadata(); + /** + * The composition's classpath with every capability a service can select; the typed properties + * under {@link #TYPED_PREFIXES} are read from its configuration metadata. + */ + @Classpath + public abstract ConfigurableFileCollection getMetadataClasspath(); @InputFiles @PathSensitive(PathSensitivity.RELATIVE) @@ -48,17 +64,24 @@ public abstract class VerifyEnvKeysTask extends DefaultTask { @TaskAction public void verifyContract() { + if (getMetadataClasspath().isEmpty()) { + throw new GradleException( + "verifyEnvKeys: no metadata classpath. Give it the composition's every-capability" + + " classpath, or the typed-property check silently covers nothing."); + } EnvContractResult result; try { + List scopes = new ArrayList<>(); + for (String prefix : TYPED_PREFIXES) { + scopes.add(new MetadataScope(prefix, metadataOf(prefix))); + } result = EnvContractVerifier.verify( getEnvFile().get().getAsFile(), getConfigurationFiles().getFiles(), getRegistryFile().get().getAsFile(), getProductionSources().getFiles(), - List.of( - new MetadataScope( - "app.redis.", getRedisSdkMetadata().get().getAsFile())), + scopes, ENFORCED_PREFIXES, getOperatorFiles().getFiles()); } catch (IllegalStateException invalidContract) { @@ -75,4 +98,24 @@ public abstract class VerifyEnvKeysTask extends DefaultTask { result.typedPropertyCount(), result.consumedOrDeprecatedRegistryRowCount()); } + + /** The typed properties under {@code prefix}, as one metadata file the verifier reads. */ + private File metadataOf(String prefix) { + Set properties = + ConfigurationMetadataClasspath.propertiesUnder(getMetadataClasspath().getFiles(), prefix); + StringBuilder json = new StringBuilder("{\"properties\":["); + String separator = ""; + for (String property : properties) { + json.append(separator).append("{\"name\":\"").append(property).append("\"}"); + separator = ","; + } + json.append("]}"); + File file = new File(getTemporaryDir(), prefix + "metadata.json"); + try { + Files.writeString(file.toPath(), json, StandardCharsets.UTF_8); + } catch (IOException failure) { + throw new UncheckedIOException("failed to write " + file, failure); + } + return file; + } } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java index 771f8d07..ac09e803 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java @@ -2,6 +2,7 @@ package dev.caskeleton.buildlogic.strictlane; import org.gradle.api.file.DirectoryProperty; import org.gradle.api.provider.ListProperty; +import org.gradle.api.provider.Property; /** * The stages a strict lane may belong to, and where the workflows that run them live. @@ -15,6 +16,14 @@ public abstract class StrictLaneStagesExtension { public abstract DirectoryProperty getWorkflowDirectory(); + /** + * The {@code -p} directory a workflow step passes to start this build, relative to the step's + * working directory — {@code optional-platforms} for the optional build, which steps run as + * {@code ./gradlew -p optional-platforms } from {@code src}. Unset for the build a step + * starts in its working directory. Only commands that start this build execute its stages. + */ + public abstract Property getWorkflowProjectDirectory(); + public void stage(String... taskPaths) { getStages().addAll(taskPaths); } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java index fea9b6a4..64bcef82 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java @@ -29,11 +29,18 @@ import org.gradle.api.execution.TaskExecutionGraph; * stated once, here, instead of as one workflow line per lane: * *

          - *
        1. every strict lane that is not {@code explicitOnly} is in the task plan of a declared stage; - *
        2. every declared stage is executed by a workflow — a {@code --dry-run} or a {@code -p - * other-build} command does not count. + *
        3. every strict lane that is not {@code explicitOnly} is in the task plan of a declared stage + * as a workflow runs it — a lane the command removes with {@code -x} is not covered; + *
        4. every declared stage is executed by a workflow — a {@code --dry-run}, a command for another + * build, and a command under {@code continue-on-error} or an {@code if:} other than a status + * function do not count (review 2026-11-03 RR-06-04). *
        * + *

        Each build that holds strict lanes applies it at its own root: the main build, and the + * optional-platforms build, whose stages workflows start with {@code -p optional-platforms} + * ({@link StrictLaneStagesExtension#getWorkflowProjectDirectory()}). Applied to the main build only, + * it said "every strict lane" while the optional build's performance lane ran nowhere (RR-06-03).

        + * *

        The task plan is Gradle's own: {@code verifyStrictLaneStages} depends on the stages, so a * {@code --dry-run} of it builds the real plan, and the check reads it when the graph is ready. It * refuses to run without {@code --dry-run}, which would execute every stage. @@ -83,7 +90,8 @@ public final class StrictLaneStagesPlugin implements Plugin { project, graph, extension.getStages().get(), - extension.getWorkflowDirectory().get().getAsFile()); + extension.getWorkflowDirectory().get().getAsFile(), + extension.getWorkflowProjectDirectory().getOrNull()); if (!problems.isEmpty()) { throw new GradleException( TASK_NAME @@ -102,28 +110,39 @@ public final class StrictLaneStagesPlugin implements Plugin { } private static List problems( - Project root, TaskExecutionGraph graph, List stages, File workflowDirectory) { + Project root, + TaskExecutionGraph graph, + List stages, + File workflowDirectory, + String buildDirectory) { List problems = new ArrayList<>(foldedCommandBreaks(workflowDirectory)); List invocations = invocations(workflowDirectory); - List executedStages = new ArrayList<>(); + // Only an executed stage covers a lane — a stage no workflow runs is the same gap one level + // up — and only as the command runs it: what its -x removes is not covered. + Map> plans = new LinkedHashMap<>(); for (String stage : stages) { - if (invocations.stream().anyMatch(invocation -> invocation.executesInStartBuild(stage))) { - executedStages.add(stage); - } else { + List executions = + invocations.stream() + .filter(invocation -> invocation.executes(stage, buildDirectory)) + .toList(); + if (executions.isEmpty()) { problems.add( "stage " + stage + " is executed by no workflow in " + workflowDirectory.getName() - + " (a --dry-run or -p command does not count)"); + + " (a --dry-run, a command for another build, and a command under" + + " continue-on-error or an if: other than always()/success()/!cancelled() do not" + + " count)"); + continue; } - } - - // Only an executed stage covers a lane: a stage no workflow runs is the same gap one level up. - Map> plans = new LinkedHashMap<>(); - for (String stage : executedStages) { Task stageTask = root.getTasks().findByPath(stage); - plans.put(stage, stageTask == null ? Set.of() : plan(graph, stageTask)); + int run = 0; + for (WorkflowGradleInvocations.Invocation execution : executions) { + plans.put( + stage + "#" + run++, + stageTask == null ? Set.of() : plan(graph, stageTask, execution)); + } } List lanes = new ArrayList<>(); root.getAllprojects().stream() @@ -149,12 +168,14 @@ public final class StrictLaneStagesPlugin implements Plugin { return problems; } - private static Set plan(TaskExecutionGraph graph, Task stage) { + /** The tasks {@code stage} reaches as {@code execution} runs it: what its -x removes is cut off. */ + private static Set plan( + TaskExecutionGraph graph, Task stage, WorkflowGradleInvocations.Invocation execution) { Set seen = new HashSet<>(); Deque pending = new ArrayDeque<>(List.of(stage)); while (!pending.isEmpty()) { Task task = pending.pop(); - if (seen.add(task.getPath())) { + if (!execution.excludes(task.getPath()) && seen.add(task.getPath())) { pending.addAll(graph.getDependencies(task)); } } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java index 6ef01c97..104671df 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java @@ -224,6 +224,20 @@ public final class StrictTestLanePlugin implements Plugin { // build cache: the result it reuses was produced by a run that passed the checks below (no test // ran, a skip, a required test missing), with the same classes, filter and properties. A lane // whose result depends on what Gradle cannot see runs every time (review 2026-11-01 08-02). + // The verdict below reads the lane's policy, not only its test results, so the policy is an + // input: tightening it (rejectSkipped = true, another required test, another category) must + // judge the lane again rather than reuse a result produced under the looser policy. Without + // this a lane that skipped a test stayed green, up to date and from the build cache, after + // rejectSkipped was switched on (review 2026-11-03 RR-06-02). + test.getInputs().property("strictLane.rejectSkipped", project.provider(lane::isRejectSkipped)); + test.getInputs() + .property("strictLane.requiredTests", project.provider(lane::getRequiredTests)); + test.getInputs() + .property( + "strictLane.tag", project.provider(() -> lane.getTag() == null ? "" : lane.getTag())); + test.getInputs() + .property("strictLane.category", project.provider(() -> lane.getCategory().name())); + test.getInputs().property("strictLane.mainStage", project.provider(lane::isMainStage)); String rerunReason = rerunReason(lane); if (rerunReason != null) { test.getOutputs().upToDateWhen(ignored -> false); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java index 61edc631..22dc2291 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java @@ -2,6 +2,7 @@ package dev.caskeleton.buildlogic.strictlane; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -14,10 +15,21 @@ import java.util.regex.Pattern; * {@code |} or {@code >} block — and applies YAML's folding rule to the second, because a blank line * inside a folded block ends the command (the rest becomes a separate shell command). Comments are * dropped before anything is matched, so a task named only in a comment is not "run". + * + *

        A command is read with what decides whether it gates anything (review 2026-11-03 RR-06-04): + * its {@code -x} exclusions, and the {@code continue-on-error} and {@code if:} of its step and its + * job. A command whose failure cannot fail the run, or that runs only under a condition other than + * a status function, is still returned, with the reason it does not count. */ public final class WorkflowGradleInvocations { private static final Pattern RUN_KEY = Pattern.compile("^(\\s*)(?:-\\s+)?run:(.*)$"); private static final Pattern BLOCK_HEADER = Pattern.compile("^([|>])[-+]?\\d*\\s*(#.*)?$"); + private static final Pattern MAPPING_KEY = + Pattern.compile("^(\\s*)(?:-\\s+)?([A-Za-z0-9_-]+):(?:\\s+(.*?))?\\s*$"); + private static final Pattern JOB_KEY = Pattern.compile("^(\\s*)([A-Za-z0-9_-]+):\\s*(#.*)?$"); + /** Conditions under which a step still runs on every run whose earlier steps passed. */ + private static final Set STATUS_CONDITIONS = + Set.of("always()", "success()", "!cancelled()", "true"); private static final Set OPTIONS_WITH_VALUE = Set.of( "-p", @@ -46,10 +58,19 @@ public final class WorkflowGradleInvocations { * directory * @param tasks the task selectors it requests, in order * @param dryRun whether it only plans ({@code --dry-run} or {@code -m}) instead of executing + * @param excludedTasks the {@code -x} / {@code --exclude-task} selectors, in order + * @param uncountedReason why the command gates nothing although it runs — {@code + * continue-on-error}, or a condition other than a status function — or {@code null} */ - public record Invocation(String projectDir, List tasks, boolean dryRun) { + public record Invocation( + String projectDir, + List tasks, + boolean dryRun, + List excludedTasks, + String uncountedReason) { public Invocation { tasks = List.copyOf(tasks); + excludedTasks = List.copyOf(excludedTasks); } /** @@ -57,24 +78,63 @@ public final class WorkflowGradleInvocations { * build its step starts in. {@code ci} and {@code :ci} name the same root task. */ public boolean executesInStartBuild(String taskPath) { + return executes(taskPath, null); + } + + /** + * Whether this command executes, and gates on, the task at {@code taskPath} of the build a + * workflow starts with {@code -p buildDirectory} ({@code null}: the build in the step's working + * directory). + */ + public boolean executes(String taskPath, String buildDirectory) { String wanted = absolute(taskPath); - return projectDir == null + return sameDirectory(projectDir, buildDirectory) && !dryRun + && uncountedReason == null && tasks.stream().map(Invocation::absolute).anyMatch(wanted::equals); } + /** + * Whether the task at {@code taskPath} is one this command's {@code -x} removes. An absolute + * or project-qualified selector names one task; a bare name removes that task in every project, + * as Gradle does for a command started at the root. + */ + public boolean excludes(String taskPath) { + String name = taskPath.substring(taskPath.lastIndexOf(':') + 1); + for (String selector : excludedTasks) { + if (selector.contains(":") ? absolute(selector).equals(taskPath) : selector.equals(name)) { + return true; + } + } + return false; + } + + private static boolean sameDirectory(String left, String right) { + return left == null || right == null + ? left == null && right == null + : normalized(left).equals(normalized(right)); + } + + private static String normalized(String directory) { + String plain = directory.startsWith("./") ? directory.substring(2) : directory; + return plain.endsWith("/") ? plain.substring(0, plain.length() - 1) : plain; + } + private static String absolute(String selector) { return selector.startsWith(":") ? selector : ":" + selector; } } + /** The script of one {@code run:} step, and why its commands gate nothing, if they do not. */ + private record RunStep(String script, String uncountedReason) {} + private WorkflowGradleInvocations() {} public static List read(String workflow) { List invocations = new ArrayList<>(); - for (String script : runScripts(workflow)) { - for (String command : shellCommands(script)) { - Invocation invocation = gradleInvocation(command); + for (RunStep step : runSteps(workflow)) { + for (String command : shellCommands(step.script())) { + Invocation invocation = gradleInvocation(command, step.uncountedReason()); if (invocation != null) { invocations.add(invocation); } @@ -131,8 +191,12 @@ public final class WorkflowGradleInvocations { } static List runScripts(String workflow) { + return runSteps(workflow).stream().map(RunStep::script).toList(); + } + + private static List runSteps(String workflow) { List lines = workflow.lines().toList(); - List scripts = new ArrayList<>(); + List scripts = new ArrayList<>(); for (int index = 0; index < lines.size(); index++) { Matcher run = RUN_KEY.matcher(lines.get(index)); if (!run.matches()) { @@ -140,9 +204,10 @@ public final class WorkflowGradleInvocations { } int keyIndent = run.group(1).length(); String value = run.group(2).trim(); + String uncounted = uncountedReason(lines, index); Matcher header = BLOCK_HEADER.matcher(value); if (!header.matches()) { - scripts.add(stripScalarComment(value)); + scripts.add(new RunStep(stripScalarComment(value), uncounted)); continue; } List block = new ArrayList<>(); @@ -157,11 +222,139 @@ public final class WorkflowGradleInvocations { block.stream().filter(line -> !line.isBlank()).mapToInt(WorkflowGradleInvocations::indentOf).min().orElse(0); List content = block.stream().map(line -> line.isBlank() ? "" : line.substring(blockIndent)).toList(); - scripts.add(header.group(1).equals("|") ? String.join("\n", content) : fold(content)); + scripts.add( + new RunStep( + header.group(1).equals("|") ? String.join("\n", content) : fold(content), uncounted)); } return scripts; } + /** + * Why the {@code run:} key at {@code runIndex} gates nothing: a {@code continue-on-error} other + * than {@code false}, or an {@code if:} other than a status function, on its step or its job. + */ + private static String uncountedReason(List lines, int runIndex) { + Matcher run = RUN_KEY.matcher(lines.get(runIndex)); + if (!run.matches()) { + return null; + } + boolean itemLine = lines.get(runIndex).trim().startsWith("-"); + int stepKeyIndent = + itemLine + ? lines.get(runIndex).indexOf("run:") + : run.group(1).length(); + int stepStart = runIndex; + if (!itemLine) { + while (stepStart > 0) { + stepStart--; + String line = lines.get(stepStart); + if (line.isBlank() || line.trim().startsWith("#")) { + continue; + } + if (indentOf(line) < stepKeyIndent) { + break; + } + } + } + String step = gatingProblem(lines, stepStart, stepKeyIndent, "step"); + if (step != null) { + return step; + } + int jobHeader = jobHeader(lines, runIndex); + if (jobHeader < 0) { + return null; + } + int jobKeyIndent = -1; + for (int next = jobHeader + 1; next < lines.size(); next++) { + String line = lines.get(next); + if (!line.isBlank() && !line.trim().startsWith("#")) { + jobKeyIndent = indentOf(line); + break; + } + } + return jobKeyIndent <= indentOf(lines.get(jobHeader)) + ? null + : gatingProblem(lines, jobHeader + 1, jobKeyIndent, "job"); + } + + /** The first {@code continue-on-error} or {@code if:} at {@code keyIndent} in the mapping. */ + private static String gatingProblem(List lines, int start, int keyIndent, String scope) { + for (int index = start; index < lines.size(); index++) { + String line = lines.get(index); + if (line.isBlank() || line.trim().startsWith("#")) { + continue; + } + if (index > start && indentOf(line) < keyIndent) { + break; + } + Matcher key = MAPPING_KEY.matcher(line); + if (!key.matches() || keyColumn(line) != keyIndent) { + continue; + } + String value = stripScalarComment(key.group(3) == null ? "" : key.group(3)); + if (key.group(2).equals("continue-on-error") && !value.equals("false")) { + return "its " + scope + " has continue-on-error: " + value + ", so its failure fails nothing"; + } + if (key.group(2).equals("if") && !STATUS_CONDITIONS.contains(expression(value))) { + return "its " + + scope + + " runs only if: " + + value + + ", not on every run (only always(), success() and !cancelled() count)"; + } + } + return null; + } + + /** The column a mapping key starts at, after a list item's {@code - }. */ + private static int keyColumn(String line) { + int column = indentOf(line); + if (line.startsWith("-", column)) { + column++; + while (column < line.length() && line.charAt(column) == ' ') { + column++; + } + } + return column; + } + + private static String expression(String condition) { + String plain = condition.trim(); + if (plain.startsWith("${{") && plain.endsWith("}}")) { + plain = plain.substring(3, plain.length() - 2).trim(); + } + return plain.replace(" ", "").toLowerCase(Locale.ROOT); + } + + /** The line of the job containing {@code index}: the last key at the indentation under {@code jobs:}. */ + private static int jobHeader(List lines, int index) { + int jobs = -1; + for (int line = 0; line < index; line++) { + if (lines.get(line).matches("^jobs:\\s*(#.*)?$")) { + jobs = line; + } + } + if (jobs < 0) { + return -1; + } + int jobIndent = -1; + for (int line = jobs + 1; line < index; line++) { + String text = lines.get(line); + if (!text.isBlank() && !text.trim().startsWith("#")) { + jobIndent = indentOf(text); + break; + } + } + int header = -1; + for (int line = jobs + 1; line < index; line++) { + Matcher job = JOB_KEY.matcher(lines.get(line)); + if (job.matches() && job.group(1).length() == jobIndent) { + header = line; + } + } + return header; + } + /** YAML folding: adjacent lines join with a space, and each blank line is a line break. */ private static String fold(List content) { StringBuilder folded = new StringBuilder(); @@ -204,7 +397,7 @@ public final class WorkflowGradleInvocations { return commands; } - private static Invocation gradleInvocation(String command) { + private static Invocation gradleInvocation(String command, String uncountedReason) { List tokens = new ArrayList<>(); for (String token : command.trim().split("\\s+")) { if (token.startsWith("#")) { @@ -227,6 +420,7 @@ public final class WorkflowGradleInvocations { String projectDir = null; boolean dryRun = false; List tasks = new ArrayList<>(); + List excluded = new ArrayList<>(); for (int index = start + 1; index < tokens.size(); index++) { String token = tokens.get(index); if (token.equals("--dry-run") || token.equals("-m")) { @@ -236,13 +430,20 @@ public final class WorkflowGradleInvocations { index++; } else if (token.startsWith("--project-dir=")) { projectDir = token.substring("--project-dir=".length()); + } else if (token.equals("-x") || token.equals("--exclude-task")) { + if (index + 1 < tokens.size()) { + excluded.add(tokens.get(index + 1)); + } + index++; + } else if (token.startsWith("--exclude-task=")) { + excluded.add(token.substring("--exclude-task=".length())); } else if (OPTIONS_WITH_VALUE.contains(token)) { index++; } else if (!token.startsWith("-")) { tasks.add(token); } } - return new Invocation(projectDir, tasks, dryRun); + return new Invocation(projectDir, tasks, dryRun, excluded, uncountedReason); } private static String unquote(String token) { diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/ConfigurationMetadataClasspathTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/ConfigurationMetadataClasspathTest.java new file mode 100644 index 00000000..c77ba3d0 --- /dev/null +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/ConfigurationMetadataClasspathTest.java @@ -0,0 +1,48 @@ +package dev.caskeleton.buildlogic.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class ConfigurationMetadataClasspathTest { + + @Test + @DisplayName("classpath의 jar와 클래스 디렉터리에서 prefix 아래 typed property를 모두 읽는다") + void typedPropertiesUnderAPrefixAreReadFromEveryJarAndDirectoryOnTheClasspath( + @TempDir Path temp) throws Exception { + // given + Path classes = temp.resolve("classes"); + Files.createDirectories(classes.resolve("META-INF")); + Files.writeString( + classes.resolve("META-INF/spring-configuration-metadata.json"), + "{\"properties\":[{\"name\":\"app.redis.host\"},{\"name\":\"app.cache.ttl\"}]}"); + Path jar = temp.resolve("module.jar"); + try (OutputStream out = Files.newOutputStream(jar); + ZipOutputStream zip = new ZipOutputStream(out)) { + zip.putNextEntry(new ZipEntry("META-INF/spring-configuration-metadata.json")); + zip.write( + "{\"properties\":[{\"name\":\"app.redis.port\"}]}".getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + } + Path withoutMetadata = temp.resolve("plain"); + Files.createDirectories(withoutMetadata); + + // when + Set properties = + ConfigurationMetadataClasspath.propertiesUnder( + List.of(classes.toFile(), jar.toFile(), withoutMetadata.toFile()), "app.redis."); + + // then + assertThat(properties).containsExactly("app.redis.host", "app.redis.port"); + } +} diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java index bc3410be..a14483c5 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java @@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -230,6 +231,59 @@ class EnvContractVerifierTest { assertEquals(2, result.envKeyCount()); } + @Test + @DisplayName("compose lane 계약 json의 activationEnv 키가 레지스트리에 없으면 실패한다") + void aLaneActivationKeyMissingFromTheRegistryFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Path contracts = fixture.repositoryRoot().resolve("compose-profile-contracts.json"); + Files.writeString( + contracts, + "{\"lanes\":[{\"id\":\"grpc\",\"activationEnv\":{\"CASKELETON_GRPC_ENABLED\":\"true\"," + + "\"APP_GRPC_UNREGISTERED\":\"true\",\"APP_HTTPCLIENT_CLIENTS_0_NAME\":\"a\"}}]}"); + + // when + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> verifyWithOperatorFiles(fixture, contracts)); + + // then + assertTrue(failure.getMessage().contains("APP_GRPC_UNREGISTERED"), failure.getMessage()); + assertTrue(!failure.getMessage().contains("APP_HTTPCLIENT_CLIENTS_0_NAME"), failure.getMessage()); + } + + @Test + @DisplayName("smoke 래퍼가 끄는 capability 키가 레지스트리에 없으면 실패한다") + void aSmokeWrapperSwitchMissingFromTheRegistryFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Path smoke = fixture.repositoryRoot().resolve("run-compose-runtime-smoke.sh"); + Files.writeString( + smoke, + "CAPABILITIES_OFF='{\n \"APP_REQUIRED\": \"false\",\n \"APP_OBJECTSTORAGE_OFF\": \"false\"\n}'\n" + + "args+=(\"APP_NAME=ca-skeleton-${id}\")\n"); + + // when + IllegalStateException failure = + assertThrows(IllegalStateException.class, () -> verifyWithOperatorFiles(fixture, smoke)); + + // then + assertTrue(failure.getMessage().contains("APP_OBJECTSTORAGE_OFF"), failure.getMessage()); + assertTrue(!failure.getMessage().contains("APP_NAME"), failure.getMessage()); + } + + private static EnvContractResult verifyWithOperatorFiles(Fixture fixture, Path operatorFile) { + return EnvContractVerifier.verify( + fixture.envFile().toFile(), + List.of(fixture.applicationYaml().toFile()), + fixture.registry().toFile(), + List.of(), + List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())), + List.of("APP_REDIS_"), + List.of(operatorFile.toFile())); + } + private static Fixture fixture(Path temp) throws Exception { Path repositoryRoot = temp.resolve("repository/src"); Path docsRoot = temp.resolve("repository/docs/registries"); diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java index c8397e41..9c038036 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java @@ -186,6 +186,135 @@ class StrictLaneStagesFunctionalTest { assertThat(result.getOutput()).contains("main.yml line 13: '--stacktrace' follows a blank line"); } + @Test + @DisplayName("단계를 실행해도 -x로 뺀 lane은 덮이지 않으므로 그 lane 이름으로 실패한다") + void aLaneExcludedWithDashXIsNotCoveredByTheStageThatRuns() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + lane('cacheLane') { integration(); tag = 'cache'; description = 'Real cache.' } + """); + workflow( + """ + jobs: + main: + steps: + - run: ./gradlew :ci --stacktrace + - run: ./gradlew :integrationCheck -x :leaf:databaseLane --continue + """); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("strict lane :leaf:databaseLane is in no executed stage") + .doesNotContain("strict lane :leaf:cacheLane"); + } + + @Test + @DisplayName("continue-on-error job이나 단계가 부르는 단계는 실패해도 막지 못하므로 실행으로 세지 않는다") + void aStageRunUnderContinueOnErrorIsNotAnExecution() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + """); + workflow( + """ + jobs: + gate: + steps: + - run: ./gradlew :ci --stacktrace + advisory: + runs-on: ubuntu-latest + continue-on-error: true + steps: + - run: ./gradlew :integrationCheck + other: + steps: + - name: Advisory step + continue-on-error: true + run: ./gradlew :integrationCheck + """); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("stage :integrationCheck is executed by no workflow") + .contains("strict lane :leaf:databaseLane is in no executed stage"); + } + + @Test + @DisplayName("상태 함수가 아닌 if 조건 아래의 단계 실행은 매번 돈다고 볼 수 없으므로 세지 않는다") + void aStageRunUnderAConditionIsNotAnExecution() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + """); + workflow( + """ + jobs: + gate: + steps: + - run: ./gradlew :ci --stacktrace + disabled: + if: ${{ false }} + steps: + - run: ./gradlew :integrationCheck + manual: + steps: + - if: github.event_name == 'workflow_dispatch' + run: ./gradlew :integrationCheck + reported: + steps: + - if: always() + run: ./gradlew :integrationCheck --dry-run + """); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail(); + + // then + assertThat(result.getOutput()).contains("stage :integrationCheck is executed by no workflow"); + } + + @Test + @DisplayName("다른 빌드로 실행되는 빌드는 workflow가 -p 그 디렉터리로 부른 단계만 실행으로 센다") + void aBuildStartedWithDashPCountsOnlyCommandsThatNameItsDirectory() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + """); + Files.writeString( + gradleRoot.resolve("build.gradle"), + Files.readString(gradleRoot.resolve("build.gradle")) + + "strictLaneStages { workflowProjectDirectory = 'optional' }\n"); + workflow( + """ + jobs: + main: + steps: + - working-directory: src + run: ./gradlew -p optional ci --stacktrace + - working-directory: src + run: ./gradlew :integrationCheck + """); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("stage :integrationCheck is executed by no workflow") + .doesNotContain("stage :ci is executed by no workflow"); + } + private void leafLanes(String lanes) throws Exception { Files.writeString( gradleRoot.resolve("leaf/build.gradle"), diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java index 5a9aca60..5cda0950 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java @@ -546,6 +546,42 @@ class StrictTestLaneConventionTest { TaskOutcome.FROM_CACHE, TaskOutcome.FROM_CACHE, TaskOutcome.SUCCESS, TaskOutcome.SUCCESS); } + @Test + @DisplayName("lane 정책만 바꾼 다음 실행은 이전 결과를 다시 쓰지 않고 새 정책으로 판정한다") + void aLanePolicyChangeIsJudgedAgainInsteadOfReusingTheEarlierResult() throws Exception { + // given + String lane = + """ + strictTestLanes { + lane('carriedLane') { + tag = 'carried' + description = 'Selected tests.' + rejectSkipped = %s + } + } + """; + buildFile(junitDependencies() + lane.formatted("false")); + writeTest( + "CarriedTest.java", + """ + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Tag; + import org.junit.jupiter.api.Test; + class CarriedTest { + @Test @Tag("carried") void ran() {} + @Test @Tag("carried") @Disabled("skipped while the policy allowed it") void skipped() {} + } + """); + runner("carriedLane", "--build-cache").build(); + buildFile(junitDependencies() + lane.formatted("true")); + + // when + BuildResult stricter = runner("carriedLane", "--build-cache").buildAndFail(); + + // then + assertThat(stricter.getOutput()).contains("forbids skipped tests"); + } + @Test @DisplayName("서버를 띄우지 않는 TEST·ARCHITECTURE lane은 실서버 lane의 단일 슬롯을 잡지 않는다") void onlyServerLanesTakeTheExclusiveRealServerSlot() throws Exception { diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java index 155c53e6..3bd5f940 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java @@ -197,4 +197,56 @@ class WorkflowGradleInvocationsTest { // then assertThat(problems).isEmpty(); } + + @Test + @DisplayName("-x와 --exclude-task로 뺀 태스크는 경로나 이름이 맞는 태스크만 제외로 읽는다") + void excludedTasksAreReadFromBothSpellings() { + // given + String workflow = + """ + - run: ./gradlew :integrationCheck -x :leaf:databaseLane --exclude-task=test + """; + + // when + Invocation invocation = WorkflowGradleInvocations.read(workflow).get(0); + + // then + assertThat(invocation.excludes(":leaf:databaseLane")).isTrue(); + assertThat(invocation.excludes(":other:test")).isTrue(); + assertThat(invocation.excludes(":leaf:cacheLane")).isFalse(); + assertThat(invocation.executesInStartBuild(":integrationCheck")).isTrue(); + } + + @Test + @DisplayName("job의 continue-on-error와 단계의 if 조건은 명령을 실행으로 세지 않는 이유로 남는다") + void jobAndStepGatingIsKeptAsTheReasonACommandDoesNotCount() { + // given + String workflow = + """ + jobs: + advisory: + continue-on-error: true + steps: + - run: ./gradlew :ci + gated: + steps: + - name: Manual only + if: github.event_name == 'workflow_dispatch' + run: ./gradlew :ci + plain: + steps: + - if: ${{ always() }} + run: ./gradlew :ci + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).extracting(Invocation::uncountedReason) + .satisfiesExactly( + reason -> assertThat(reason).contains("job has continue-on-error: true"), + reason -> assertThat(reason).contains("step runs only if: github.event_name"), + reason -> assertThat(reason).isNull()); + } } diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java index 163f2181..b9e80d5b 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java @@ -6,6 +6,7 @@ import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; +import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort; import dev.caskeleton.application.fileserver.download.DescribeFileApplicationUseCase; import dev.caskeleton.application.fileserver.download.DownloadContentPort; import dev.caskeleton.application.fileserver.download.OpenDownloadContentApplicationUseCase; @@ -120,10 +121,12 @@ class FileserverFileUseCaseConfiguration { @ConditionalOnMissingBean MoveFileUseCase fileserverMoveFile( FileMetadataPort metadataStore, - FileAccessPolicyPort accessPolicy, + UploadPolicies policies, TargetNamespacePolicy targetNamespaces, + FileQuotaPort quotaService, + QuotaReclaimPort quotaReclaim, TransactionPort transactions) { return new MoveFileApplicationUseCase( - metadataStore, accessPolicy, targetNamespaces, transactions); + metadataStore, policies, targetNamespaces, quotaService, quotaReclaim, transactions); } } diff --git a/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java b/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java index b43ec421..e56a0ccc 100644 --- a/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java +++ b/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java @@ -2,6 +2,7 @@ package dev.caskeleton.composition.idempotency; import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder; import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; +import dev.caskeleton.application.idempotency.IdempotencyExecutor; import java.time.Duration; import java.util.Set; import org.springframework.core.env.Environment; @@ -17,7 +18,9 @@ import org.springframework.core.env.Environment; * instead of leaving its default silently in force. * * @param provider which store is composed: {@code disabled}, {@code redis} or {@code postgresql} - * @param processingLease how long one attempt holds a claim before another may take it over + * @param processingLease how long one attempt holds a claim before another may take it over; longer + * than the in-flight 409's {@code Retry-After} ({@link + * IdempotencyExecutor#IN_FLIGHT_RETRY_AFTER}) * @param replayTtl how long a completed response is replayable (at most 72h, D6) * @param failureRetention how long a failed attempt's evidence is kept * @param responseCodecId identifier of the codec the stored payload is written with @@ -49,6 +52,16 @@ public record IdempotencySettings( "processing-lease", orDefault(processingLease, Duration.ofSeconds(30)), MAX_PROCESSING_LEASE); + // A duplicate is told to come back after IN_FLIGHT_RETRY_AFTER. With a lease no longer than + // that, the resend always arrives after the attempt it was waiting for has lost its claim. + if (processingLease.compareTo(IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER) <= 0) { + throw StartupFailures.envValidation( + PREFIX + + ".processing-lease must be longer than " + + IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER + + " (the in-flight Retry-After), was " + + processingLease); + } replayTtl = bounded("replay-ttl", orDefault(replayTtl, Duration.ofHours(24)), MAX_REPLAY_TTL); failureRetention = bounded( diff --git a/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java index 37903827..1c573f2d 100644 --- a/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java +++ b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java @@ -151,6 +151,31 @@ class IdempotencySettingsTest { .hasMessageContaining("app.capabilities.idempotency." + message); } + /** + * The in-flight 409 tells the client to come back after {@code Retry-After} (2 seconds). A lease + * no longer than that sends every resend past the attempt it was meant to wait for, so the rule + * fails startup rather than living in prose (re-review 2026-11-03, RR-02-05). + */ + @ParameterizedTest + @CsvSource({"PT1S", "PT2S"}) + @DisplayName("processing-lease 가 처리 중 409 의 Retry-After 이하면 기동을 거부한다") + void aProcessingLeaseNoLongerThanTheInFlightRetryAfterIsRefused(Duration lease) { + // when + Throwable thrown = + catchThrowable( + () -> + new IdempotencySettings( + IdempotencySettings.Provider.REDIS, lease, null, null, null, null, null)); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + StartupFailureException.class, + e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) + .hasMessageContaining( + "app.capabilities.idempotency.processing-lease must be longer than PT2S"); + } + @ParameterizedTest @CsvSource({"'', response-codec-id must contain 1-64 characters", "' ', response-codec-id"}) void blankCodecIdIsRefused(String codecId, String message) { diff --git a/src/composition/outbox-relay/CLAUDE.md b/src/composition/outbox-relay/CLAUDE.md new file mode 100644 index 00000000..f63f9fa9 --- /dev/null +++ b/src/composition/outbox-relay/CLAUDE.md @@ -0,0 +1,21 @@ +# composition:outbox-relay + +- Module ID `composition-outbox-relay`, Gradle path `:composition:outbox-relay`. Registry SSOT: + `src/config/architecture/modules.json`. +- Responsibility: assemble and drive the application's outbox relay. It builds + `PublishPendingOutboxEventsUseCase` by hand from `app.outbox.*` (`OutboxSettings`, strict binding), + runs it from `OutboxRelayScheduler` (fixed-delay ticks, a `SmartLifecycle` that stops above the + messaging platform's admission phase), and owns the outbox metrics (`OutboxMetrics`: gauges on a + thread of their own, the cycle-outcome counter from the relay). +- Boundaries: it names ports only — `OutboxStorePort`, `OutboxMessagePublishPort`, + `OutboxRelayFailureReportPort`, `TransactionPort` — never a module type, so removing the + persistence or messaging line removes the relay. No business rule, no SQL, no broker type. The + relay use case is never a bean (`@SystemInvoked`, no permission gate). Allowed edges come only from + the registry entry. +- Startup refusals live here because only here do the settings meet the ports: a batch whose worst + case (`batch-size` × the publish port's `longestAttempt`) reaches `in-flight-timeout` fails startup. +- Tests: `./gradlew :composition:outbox-relay:check`. The shutdown order is pinned against the + platform's own phase constant (`OutboxRelayShutdownOrderTest`); the end-to-end relay → bridge → real + Kafka path is `:adapter:outbound:messaging-kafka:messagingKafkaRelayIntegrationTest`. +- Design and rejected alternatives: `README.md`. Operations: `docs/runbooks/outbox-publish-failed.md`, + `docs/runbooks/outbox-dead-letter.md`. diff --git a/src/composition/outbox-relay/README.md b/src/composition/outbox-relay/README.md index dc861755..87cbc7b8 100644 --- a/src/composition/outbox-relay/README.md +++ b/src/composition/outbox-relay/README.md @@ -18,12 +18,15 @@ composition:outbox-relay │ PublishPendingOutboxEventsUseCase 를 fixed-delay 로 구동, │ 발행이 이어지는 동안 한 tick 안에서 바로 다시 claim(최대 50회차), │ 종료 때 platform보다 먼저 멈추고 남은 claim을 놓음(SmartLifecycle) - ├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag(relay와 무관하게 - │ poll 주기마다 갱신) / published.total(relay 회차 결과) - ├─ OutboxRelayOffWarning 발행 포트가 있는데 relay가 꺼져 있으면 기동 시 WARN 한 줄 - └─ OutboxLeaderElectionToken SKIP LOCKED 가 리더 선출이라는 표시(로직 없음) + ├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag / outbox.retry.long.* + │ (자기 스레드에서 poll 주기마다 갱신) / published.total(relay 회차 결과) + └─ OutboxRelayOffWarning 발행 포트가 있는데 relay가 꺼져 있으면 기동 시 WARN 한 줄 ``` +여러 인스턴스가 함께 relay를 돌려도 조정자는 없다. claim SQL의 `FOR UPDATE SKIP LOCKED`가 인스턴스마다 +겹치지 않는 행을 주고, lease token이 늦은 완료를 막는다(`PostgreSqlOutboxClaimRepository`, V17). 리더를 +뽑지 않는다. + - 조립 순서: `PersistenceJpaAutoConfiguration`(store)과 `MessagingBridgeRootAutoConfiguration`(발행 포트) 뒤에 온다(`afterName`, 문자열이라 컴파일 의존이 없다). 둘 다 포트라서 이 모듈은 어떤 모듈 타입도 이름으로 부르지 않는다. @@ -73,7 +76,8 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a relay 생성자에 전달한다. - **릴레이 use case 를 독립 컨텍스트 빈으로 등록하지 않는다.** relay는 스케줄러만 부르는 `@SystemInvoked` 유스케이스라 권한 선언이 없다. 빈으로 올리면 전송 계층이 권한 검사 없이 닿을 - 수 있다. 스케줄러 스레드에는 `Authentication`이 없으므로 권한 게이트를 달아도 매 틱 거부될 뿐이다. + 수 있으므로, 빈으로 등록된 `@SystemInvoked` 유스케이스는 `composition:service-runtime`의 + `PermissionEnforcementGuard`가 기동을 실패시킨다. 스케줄러 스레드에는 `Authentication`이 없으므로 권한 게이트를 달아도 매 틱 거부될 뿐이다. - **`outboxRelayScheduler` 빈은 `app.outbox.relay-enabled=true`일 때만 만든다(기본 false).** 키가 없으면 꺼진 것으로 본다. 모듈 기본값(`persistence-jpa.yml`의 `${APP_OUTBOX_RELAY_ENABLED:false}`), `@ConditionalOnProperty`, `OutboxSettings`의 null 기본값이 @@ -90,28 +94,31 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a 코드다. driven adapter인 persistence-jpa가 use case를 만들거나 호출하면 `PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES` 규칙 위반이다. 모듈 타입은 하나도 이름으로 부르지 않고 포트만 쓰므로, persistence-jpa 한 줄을 지우면 릴레이도 함께 꺼진다. -- **`outboxLeaderElection` 토큰 빈은 outbox capability 안에서 조건 없이 등록한다.** SKIP LOCKED 는 - 멀티 인스턴스 전역 스위치와 무관하게 outbox relay 자체의 리더십/claim 메커니즘이라, outbox가 켜진 - 상태에서 별도 하위 토글로 끌 수 있게 만들지 않는다. 이 토큰은 outbox 조립의 자기 설명용 marker이지 - `APP_MULTI_INSTANCE_ENABLED`의 전역 필수 빈이 아니다. +- **`outboxLeaderElection` 토큰 빈은 지웠다(리뷰 2026-11-01 06-13).** 로직 없는 marker였고, Javadoc은 + "있기만 하면 멀티 인스턴스 조정 요구를 채운다"고 했지만 그 빈을 요구하는 검사도, 리더 선출도 없었다 + (claim은 행 단위다). 버린 대안: 이름을 실제 동작(`OutboxClaimStrategy`)으로 바꾸기 — 여전히 아무도 + 읽지 않는 marker다. 동작 설명은 위 트리 아래 문단과 `PostgreSqlOutboxClaimRepository`에 있다. +- **relay 조립은 배치가 lease 안에 다 나가는지 확인한다(06-12).** 한 회차는 batch 전체를 lease 하나로 + 잡고 차례로 발행한다. `batch-size` × 발행 포트의 `longestAttempt()`(bridge: platform 발행 기한의 두 배, + 기본 10초)가 `in-flight-timeout` 이상이면 기동을 거부한다. lease가 먼저 끝나면 다른 인스턴스가 같은 행을 + 다시 보내기 때문이다(fencing은 상태 덮어쓰기만 막는다). 기본값은 20 × 10초 = 200초 < 5분이다. 포트가 + 최악 시간을 모르면(`Optional.empty()`) 검사하지 않는다. 버린 대안: relay가 회차 중 남은 lease를 보고 + 남은 행을 놓기 — 설정 실수를 운영 중 중복 대신 기동 실패로 드러내는 쪽을 골랐다. - **`outboxMetrics` 빈은 `MeterRegistry`가 없을 때 no-op 이다.** Actuator 가 클래스패스에 없는 환경에서도 와이어링이 깨지지 않도록 `ObjectProvider`로 레지스트리를 선택적으로 주입한다. -### OutboxLeaderElectionToken -- **로직이 전혀 없는 마커(documentation artifact) 빈이다.** 이 타입은 동작을 갖지 않고, Spring - 컨텍스트에 존재한다는 사실만으로 멀티 인스턴스 조정 빈 요구사항을 충족시킨다. -- **리더 선출을 외부 코디네이터 없이 PostgreSQL `FOR UPDATE SKIP LOCKED`로 구현한다는 것을 - 표현한다.** claim 쿼리에 SKIP LOCKED 를 걸면 각 릴레이 인스턴스가 서로 겹치지 않는(disjoint) 행 - 집합을 가져가므로, 별도 코디네이터 없이도 "각 인스턴스가 자기 파티션의 리더" 형태로 리더 선출 - 의미가 성립한다. - ### OutboxMetrics - **`MeterRegistry`가 없으면 모든 메트릭 연산이 no-op 이다.** Actuator 가 없는 환경에서도 릴레이가 정상 동작해야 하므로, 생성자에서 `ObjectProvider`로 레지스트리를 조회해 없으면 게이지도 만들지 않고 기록도 건너뛴다. -- **카운터는 PUBLISHED/FAILED/DEAD 만 집계하고 IN_FLIGHT 는 제외한다.** IN_FLIGHT 는 릴레이 사이클의 - 종료 결과(terminal outcome)가 아니라 처리 중을 나타내는 일시적 상태라 카운터 outcome 으로 의미가 - 없다. +- **카운터 outcome은 relay 회차 결과(`OutboxRelayResult.Outcome`) 다섯 값이다: PUBLISHED, FAILED, DEAD, + STALE, RELEASED.** IN_FLIGHT는 행 상태이지 회차 결과가 아니라 세지 않는다. `docs/registries/metrics.yaml`의 + 허용 값과 enum이 같은지 `OutboxStatusRegistryContractTest`가 비교한다(재리뷰 2026-11-03 RR-05-06). +- **오래 재시도 중인 행을 따로 센다(RR-05-03).** 응답 없음·지금만 거부는 시도 예산을 쓰지 않아 끝이 없다. + `outbox.retry.long.size`는 미룬 claim이 `LONG_RETRY_DEFERRED_CLAIMS`(10)번 이상인 FAILED 행 수, + `outbox.retry.long.age`는 그중 가장 오래된 행의 나이다. 10번은 backoff 상한 5분 기준으로 적어도 약 35분 + 동안 실패했다는 뜻이라 broker 재시작·credential 교체는 넘긴다. publish-failed runbook §4.1의 조회가 같은 + 기준을 쓴다. - **MultiGauge 갱신 시 `overwrite=true`로 등록한다.** 매 스케줄러 틱마다 store 를 다시 조회해 게이지를 갱신하는데, 이전 틱에 있었지만 지금은 사라진 event type 같은 오래된 time-series 태그를 덮어써 제거하기 위함이다. @@ -151,13 +158,18 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a claim이 비면 tick을 끝낸다. 한 tick의 상한은 `MAX_CYCLES_PER_TICK` = 50회차다. - 처리량 상한(계산, 실측 아님): 한 aggregate는 poll 주기가 아니라 발행 왕복 시간에 묶인다(정상 broker에서 회차당 claim·완료 DB 왕복 + Kafka ack). 인스턴스 하나는 tick당 최대 50 × batch 20 = - 1,000행을 보내고 다음 tick까지 5초 쉰다. 넘는 처리량이 필요하면 batch-size(NN-12의 lease 관계 확인)나 + 1,000행을 보내고 다음 tick까지 5초 쉰다. 넘는 처리량이 필요하면 batch-size(06-12: lease보다 길면 기동이 거부된다)나 인스턴스 수로 늘린다. - 버린 대안: poll 주기만 줄이기 — 빈 tick마다 claim·지표 질의가 는다. -- **지표 게이지는 relay와 따로 갱신한다(06-05).** `outbox.pending.size`·`outbox.publisher.lag`는 - `OutboxMetrics.refreshGauges`가 poll 주기마다 갱신한다(`@Scheduled`, relay가 꺼져 있어도, 회차가 매번 - 예외로 끝나도). 예전에는 relay 회차 안에서만 갱신되어, relay가 꺼진 배포(기본값)나 매 회차 실패하는 - 장애에서 게이지가 멈췄고 `outbox_publisher_lag` 경보가 울리지 않았다. 카운터 +- **지표 게이지는 relay와 따로, 자기 스레드에서 갱신한다(06-05, RR-05-05).** `outbox.pending.size`· + `outbox.publisher.lag`·`outbox.retry.long.*`는 `OutboxMetrics`가 poll 주기마다 갱신한다(relay가 꺼져 + 있어도, 회차가 매번 예외로 끝나도). 예전에는 relay 회차 안에서만 갱신되어, relay가 꺼진 배포(기본값)나 + 매 회차 실패하는 장애에서 게이지가 멈췄다. 그다음에는 `@Scheduled`로 떼었지만 Spring의 fixed-delay 작업은 + 모두 스레드 하나(virtual thread면 `SimpleAsyncTaskScheduler`의 fixedDelayExecutor, 아니면 pool 1)에서 + 줄을 서서, relay tick이 50회차를 도는 동안(느린 broker면 몇 분) 게이지가 기다렸다 — 적체를 봐야 할 바로 + 그때다. 지금은 `OutboxMetrics`가 `SmartLifecycle`로 자기 단일 daemon 스레드(`outbox-gauges`)를 시작하고 + 멈춘다. 버린 대안: tick 상한을 회차 수 대신 시간으로 — 게이지가 여전히 relay 뒤에 줄을 선다. Micrometer + 지연 조회 gauge — scrape마다 DB 질의가 나가고, event type별 series를 덮어쓸 수 없다. 카운터 `outbox.publisher.published.total`은 회차 결과로 relay가 기록한다. 발행 포트가 있는데 relay가 꺼져 있으면 `OutboxRelayOffWarning`이 기동 시 WARN 한 줄을 남긴다(별도 worker 배포가 relay를 돌리는 구성도 있으므로 기동 실패로 만들지 않았다). diff --git a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxLeaderElectionToken.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxLeaderElectionToken.java deleted file mode 100644 index 4e4e9887..00000000 --- a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxLeaderElectionToken.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.composition.outbox; - -/** - * Marker bean: presence in the context satisfies the multi-instance coordination requirement (no - * logic; SKIP LOCKED is the leadership mechanism). See README for the design rationale. - */ -public final class OutboxLeaderElectionToken { - - private static final String STRATEGY_DESCRIPTION = - "SKIP LOCKED claim — each relay instance claims a disjoint row partition; " - + "no external coordinator required (PostgreSQL FOR UPDATE SKIP LOCKED, I3/D8)"; - - public String strategyDescription() { - return STRATEGY_DESCRIPTION; - } - - @Override - public String toString() { - return "OutboxLeaderElectionToken{strategy=SKIP_LOCKED}"; - } -} diff --git a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java index 315ba7a0..64cb3cfe 100644 --- a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java @@ -1,49 +1,91 @@ package dev.caskeleton.composition.outbox; import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings; +import dev.caskeleton.application.outbox.OutboxBackoffPolicy; import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxLongRetries; import dev.caskeleton.application.outbox.OutboxRelayResult; import dev.caskeleton.application.outbox.OutboxStorePort; import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.MultiGauge; import io.micrometer.core.instrument.Tags; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; import org.springframework.beans.factory.ObjectProvider; -import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.context.SmartLifecycle; /** * Outbox metric collector. No-op when no {@link MeterRegistry} is present (resolved via {@link * ObjectProvider}). See README for the design rationale. * - *

        The gauges ({@code outbox.pending.size}, {@code outbox.publisher.lag}) refresh on their own - * schedule, not from the relay. They are how an operator sees rows piling up, and the two moments - * rows pile up are exactly the ones a relay-driven refresh missed: the relay is off — it is by - * default, and a deployment that forgot {@code APP_OUTBOX_RELAY_ENABLED} looked idle — or every - * cycle throws, which skipped the refresh and froze the gauges at their last value. The counter - * ({@code outbox.publisher.published.total}) is still recorded by the relay, from each cycle's - * outcomes. + *

        The gauges ({@code outbox.pending.size}, {@code outbox.publisher.lag}, {@code + * outbox.retry.long.size}, {@code outbox.retry.long.age}) refresh every poll interval on a thread + * of their own, not from the relay and not on the scheduler the relay runs on. They are how an + * operator sees rows piling up, and rows pile up exactly when the relay is off — it is by default — + * when every cycle throws, or when the broker is slow: a relay tick runs up to {@link + * OutboxRelayScheduler#MAX_CYCLES_PER_TICK} cycles back to back, and every fixed-delay task of the + * application scheduler waits behind it on one thread (review 06-05, re-review 2026-11-03 + * RR-05-05). The counter ({@code outbox.publisher.published.total}) is still recorded by the relay, + * from each cycle's outcomes. */ -public final class OutboxMetrics { +public final class OutboxMetrics implements SmartLifecycle { + + /** + * How many deferred claims make a FAILED row long-retrying. A deferred claim does not spend the + * attempt budget, so such a row is retried until someone looks; ten of them, with the backoff + * capped at {@link OutboxBackoffPolicy#MAX_DELAY}, is at least about 35 minutes of failing — past + * any broker restart or credential rotation. The publish-failed runbook's query uses the same + * number. + */ + static final int LONG_RETRY_DEFERRED_CLAIMS = 10; private static final String COUNTER_NAME = "outbox.publisher.published.total"; private static final String SIZE_GAUGE = "outbox.pending.size"; private static final String LAG_GAUGE = "outbox.publisher.lag"; + private static final String LONG_RETRY_SIZE_GAUGE = "outbox.retry.long.size"; + private static final String LONG_RETRY_AGE_GAUGE = "outbox.retry.long.age"; private final OutboxStorePort store; private final Clock clock; + private final Duration refreshInterval; private final MeterRegistry registry; // null when no Actuator on classpath private final MultiGauge pendingSizeGauge; private final MultiGauge publisherLagGauge; + private final AtomicLong longRetryRows = new AtomicLong(); + private final AtomicLong longRetryOldestAge = new AtomicLong(); + private final Object monitor = new Object(); + private ScheduledExecutorService refresher; + private ScheduledFuture refreshing; + + /** + * Creates the collector. + * + * @param store the outbox store the gauges read + * @param meterRegistryProvider the registry, when Actuator is present + * @param clock wall clock for the age gauges + * @param refreshInterval how often the gauges refresh once started; the relay's poll interval + */ public OutboxMetrics( - OutboxStorePort store, ObjectProvider meterRegistryProvider, Clock clock) { + OutboxStorePort store, + ObjectProvider meterRegistryProvider, + Clock clock, + Duration refreshInterval) { this.store = store; this.clock = clock; + this.refreshInterval = Objects.requireNonNull(refreshInterval, "refreshInterval"); this.registry = meterRegistryProvider.getIfAvailable(); if (this.registry != null) { @@ -56,13 +98,26 @@ public final class OutboxMetrics { .description("Age in seconds of the oldest unpublished row per event type") .baseUnit("seconds") .register(this.registry); + Gauge.builder(LONG_RETRY_SIZE_GAUGE, longRetryRows, AtomicLong::get) + .description( + "FAILED outbox rows deferred at least " + + LONG_RETRY_DEFERRED_CLAIMS + + " times: retried without end until someone looks") + .register(this.registry); + Gauge.builder(LONG_RETRY_AGE_GAUGE, longRetryOldestAge, AtomicLong::get) + .description("Age in seconds of the oldest long-retrying outbox row; 0 when none") + .baseUnit("seconds") + .register(this.registry); } else { this.pendingSizeGauge = null; this.publisherLagGauge = null; } } - /** Counts each per-event outcome (PUBLISHED, FAILED, DEAD, STALE; never IN_FLIGHT). */ + /** + * Counts each per-event outcome of a relay cycle: PUBLISHED, FAILED, DEAD, STALE and RELEASED. + * IN_FLIGHT is a row status, never a cycle outcome. + */ public void recordRelayResult(OutboxRelayResult result) { if (registry == null || result == null) { return; @@ -84,11 +139,9 @@ public final class OutboxMetrics { } /** - * Refreshes the gauges every poll interval, whether or not the relay runs. Store failures are - * contained per gauge (a WARN through {@link RuntimeWarnings}), so a database outage leaves the - * scheduler thread alive for the next refresh. + * Refreshes the gauges once. Store failures are contained per gauge (a WARN through {@link + * RuntimeWarnings}), so a database outage leaves the refresh thread alive for the next one. */ - @Scheduled(fixedDelayString = "${app.outbox.poll-interval:PT5S}") public void refreshGauges() { refresh(clock.instant()); } @@ -97,7 +150,7 @@ public final class OutboxMetrics { * Uses {@code overwrite=true} so stale time-series tags from removed event types are replaced * rather than left dangling. * - * @param now current wall-clock instant (for the lag gauge age computation) + * @param now current wall-clock instant (for the age gauges) */ public void refresh(Instant now) { if (registry == null) { @@ -105,6 +158,57 @@ public final class OutboxMetrics { } refreshPendingSize(); refreshPublisherLag(now); + refreshLongRetries(now); + } + + /** Starts the gauges' own refresh thread; nothing to start without a registry. */ + @Override + public void start() { + synchronized (monitor) { + if (registry == null || refresher != null) { + return; + } + refresher = + Executors.newSingleThreadScheduledExecutor( + task -> { + Thread thread = new Thread(task, "outbox-gauges"); + thread.setDaemon(true); + return thread; + }); + // A periodic task that throws is never run again, silently; each gauge already contains its + // own store failure, and anything else is contained here so the next refresh still happens. + refreshing = + refresher.scheduleWithFixedDelay( + () -> { + try { + refreshGauges(); + } catch (RuntimeException unexpected) { + RuntimeWarnings.meterUnavailable("outbox", "gauge refresh", unexpected); + } + }, + 0, + refreshInterval.toMillis(), + TimeUnit.MILLISECONDS); + } + } + + @Override + public void stop() { + synchronized (monitor) { + if (refresher != null) { + refreshing.cancel(true); + refresher.shutdownNow(); + refresher = null; + refreshing = null; + } + } + } + + @Override + public boolean isRunning() { + synchronized (monitor) { + return refresher != null; + } } private void refreshPendingSize() { @@ -138,4 +242,14 @@ public final class OutboxMetrics { RuntimeWarnings.meterUnavailable("outbox", "publisher-lag gauge", ex); } } + + private void refreshLongRetries(Instant now) { + try { + OutboxLongRetries longRetries = store.longRetries(LONG_RETRY_DEFERRED_CLAIMS, now); + longRetryRows.set(longRetries.rows()); + longRetryOldestAge.set(longRetries.oldestAgeSeconds()); + } catch (Exception ex) { + RuntimeWarnings.meterUnavailable("outbox", "long-retry gauges", ex); + } + } } diff --git a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java index 1571a67b..923d6b32 100644 --- a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java @@ -20,8 +20,8 @@ import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.EnableScheduling; /** - * The transactional outbox relay: assembles the relay use case manually and registers the leader - * election token, metrics, and scheduler. + * The transactional outbox relay: assembles the relay use case manually and registers its metrics + * and scheduler. * *

        Application composition: it wires application-core ports into a use case and drives it on a * timer, which is why it is a composition module rather than part of the persistence module — a @@ -71,6 +71,9 @@ public class OutboxRelayAutoConfiguration { RandomGenerator outboxRandomGenerator, OutboxSettings properties, OutboxMetrics metrics) { + // A batch that cannot be sent within its lease is sent twice; refused here, where the port that + // knows how long a publish can take meets the settings (review 06-12). + publishPort.longestAttempt().ifPresent(properties::requireLeaseOutlastsBatch); // One lease owner per relay instance. Its claims record it, and a completion applies only while // this owner's lease still holds the row (V17 fencing). PublishPendingOutboxEventsUseCase relayUseCase = @@ -93,22 +96,22 @@ public class OutboxRelayAutoConfiguration { return new SplittableRandom(); } - /** Registered unconditionally so the SKIP LOCKED leadership mechanism is always present. */ - @Bean(name = "outboxLeaderElection") - public OutboxLeaderElectionToken outboxLeaderElection() { - return new OutboxLeaderElectionToken(); - } - /** * Outbox metrics collector; no-op when {@link MeterRegistry} is absent. Present whenever the - * store is, relay or not: its gauges refresh on their own schedule (see {@link OutboxMetrics}). + * store is, relay or not: its gauges refresh every poll interval on a thread of their own (see + * {@link OutboxMetrics}). */ @Bean public OutboxMetrics outboxMetrics( OutboxStorePort store, ObjectProvider meterRegistryProvider, - ObjectProvider clock) { - return new OutboxMetrics(store, meterRegistryProvider, clock.getIfAvailable(Clock::systemUTC)); + ObjectProvider clock, + OutboxSettings settings) { + return new OutboxMetrics( + store, + meterRegistryProvider, + clock.getIfAvailable(Clock::systemUTC), + settings.pollInterval()); } /** diff --git a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxSettings.java b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxSettings.java index 5b4ff293..2bbf5e06 100644 --- a/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxSettings.java +++ b/src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxSettings.java @@ -62,6 +62,41 @@ public record OutboxSettings( return StrictSettingsBinder.bind(environment, PREFIX, OutboxSettings.class); } + /** + * Refuses a batch whose worst case does not fit in its lease (review 2026-11-01 06-12). + * + *

        A cycle claims {@link #batchSize()} rows under one lease of {@link #inFlightTimeout()} and + * publishes them one after another. If every publish takes its longest, the last one starts + * {@code batchSize × longestAttempt} after the claim; past the lease, another instance has + * already reclaimed the row and sent it, and this one sends it again. The lease fence keeps the + * row's status right, not the broker from seeing the event twice. Each value is fine on its own, + * so only the pair can be checked, and it is checked when the relay is assembled — the publish + * port is what knows how long an attempt can take. + * + * @param longestAttempt the longest one publish can take before its port answers + * @throws dev.caskeleton.adapter.outbound.support.startup.StartupFailureException when the + * batch's worst case reaches the lease + */ + public void requireLeaseOutlastsBatch(Duration longestAttempt) { + Duration worstBatch = longestAttempt.multipliedBy(batchSize); + if (worstBatch.compareTo(inFlightTimeout) >= 0) { + throw StartupFailures.envValidation( + PREFIX + + ".in-flight-timeout (" + + inFlightTimeout + + ") must be longer than " + + PREFIX + + ".batch-size (" + + batchSize + + ") times the longest publish (" + + longestAttempt + + "), " + + worstBatch + + ": a lease that ends before its batch is sent lets another instance send the same" + + " rows again — lower batch-size or raise in-flight-timeout"); + } + } + private static Duration positive(String key, Duration value, Duration fallback) { if (value == null) { return fallback; diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxMetricsTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxMetricsTest.java index 49109dce..74e65e25 100644 --- a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxMetricsTest.java +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxMetricsTest.java @@ -3,10 +3,14 @@ package dev.caskeleton.composition.outbox; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; +import dev.caskeleton.application.outbox.OutboxLongRetries; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort; import dev.caskeleton.application.outbox.OutboxStorePort; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.search.Search; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -14,6 +18,7 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; +import java.util.List; import java.util.UUID; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -64,6 +69,83 @@ class OutboxMetricsTest { assertThat(pending(registry)).isEqualTo(2.0); } + /** + * A relay tick can run fifty cycles back to back, and against a slow broker that takes minutes — + * exactly when the backlog gauges matter. Refreshed on the scheduler's single fixed-delay thread, + * they waited for the tick to end (re-review 2026-11-03 RR-05-05). + */ + @Test + @DisplayName("relay tick이 발행 중에 멈춰 있어도 게이지는 그동안 쌓인 행을 보여 준다") + void theGaugesRefreshWhileARelayTickIsStuckInAPublish() throws Exception { + // given: a relay whose broker call blocks until the test lets it go + InMemoryOutboxStore store = new InMemoryOutboxStore(); + store.append(OutboxEvents.event(UUID.randomUUID().toString(), Instant.now().minusSeconds(5))); + java.util.concurrent.CountDownLatch publishing = new java.util.concurrent.CountDownLatch(1); + java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1); + OutboxMessagePublishPort stalled = + event -> { + publishing.countDown(); + try { + release.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + }; + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) + .withBean(OutboxStorePort.class, () -> store) + .withBean(MeterRegistry.class, () -> registry) + .withBean(OutboxMessagePublishPort.class, () -> stalled) + .withBean(OutboxRelayFailureReportPort.class, () -> report -> {}) + .withBean(TransactionPort.class, DirectTransactionPort::new) + .withBean(Clock.class, Clock::systemUTC) + .withPropertyValues( + "app.outbox.enabled=true", + "app.outbox.relay-enabled=true", + "app.outbox.poll-interval=PT0.05S"); + + // when: the tick is inside the broker call, and two more rows arrive + runner.run( + context -> { + try { + publishing.await(10, java.util.concurrent.TimeUnit.SECONDS); + store.append(OutboxEvents.event(UUID.randomUUID().toString(), Instant.now())); + store.append(OutboxEvents.event(UUID.randomUUID().toString(), Instant.now())); + await() + .atMost(Duration.ofSeconds(5)) + .until(() -> pending(registry) != null && pending(registry) == 2.0); + } finally { + release.countDown(); + } + }); + + // then + assertThat(pending(registry)).isEqualTo(2.0); + } + + @Test + @DisplayName("오래 재시도 중인 행 게이지는 저장소가 센 행 수와 가장 오래된 행의 나이를 보여 준다") + void theLongRetryGaugesShowTheStoresCountAndOldestAge() { + // given + OutboxStorePort store = Mockito.mock(OutboxStorePort.class); + Mockito.when(store.longRetries(OutboxMetrics.LONG_RETRY_DEFERRED_CLAIMS, NOW)) + .thenReturn(new OutboxLongRetries(3, 7200)); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + OutboxMetrics metrics = metrics(store, registry); + + // when + metrics.refreshGauges(); + + // then + assertThat( + List.of( + registry.get("outbox.retry.long.size").gauge().value(), + registry.get("outbox.retry.long.age").gauge().value())) + .containsExactly(3.0, 7200.0); + } + @Test @DisplayName("게이지 갱신은 PUBLISHED를 세지 않고 지연 게이지는 가장 오래된 미발행 행의 나이다") void aRefreshCountsUnpublishedRowsAndAgesTheOldest() { @@ -97,6 +179,8 @@ class OutboxMetricsTest { Mockito.when(broken.countByStatus()).thenThrow(new IllegalStateException("database down")); Mockito.when(broken.oldestUnpublishedAgeSecondsByEventType(Mockito.any())) .thenThrow(new IllegalStateException("database down")); + Mockito.when(broken.longRetries(Mockito.anyInt(), Mockito.any())) + .thenThrow(new IllegalStateException("database down")); OutboxMetrics metrics = metrics(broken, new SimpleMeterRegistry()); // when @@ -160,6 +244,9 @@ class OutboxMetricsTest { StaticListableBeanFactory registries = new StaticListableBeanFactory(); registries.addBean("meterRegistry", registry); return new OutboxMetrics( - store, registries.getBeanProvider(MeterRegistry.class), Clock.fixed(NOW, ZoneOffset.UTC)); + store, + registries.getBeanProvider(MeterRegistry.class), + Clock.fixed(NOW, ZoneOffset.UTC), + Duration.ofHours(1)); } } diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfigurationTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfigurationTest.java index 9ad94203..ca82b543 100644 --- a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfigurationTest.java +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfigurationTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.composition.outbox; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort; @@ -9,7 +10,10 @@ import dev.caskeleton.application.outbox.OutboxStorePort; import dev.caskeleton.application.transaction.TransactionPort; import java.lang.reflect.Proxy; import java.time.Clock; +import java.time.Duration; +import java.util.Optional; import java.util.random.RandomGenerator; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -84,6 +88,34 @@ class OutboxRelayAutoConfigurationTest { .run(context -> assertThat(context).hasSingleBean(OutboxRelayScheduler.class)); } + @Test + @DisplayName("발행 포트가 말한 최악 발행 시간으로 한 배치가 lease를 넘으면 relay 조립이 기동을 거부한다") + void aBatchThePublishPortCannotSendWithinTheLeaseFailsStartup() { + // given: a port whose publish can take ten seconds, forty rows a batch, a five-minute lease + OutboxMessagePublishPort tenSecondPublisher = mock(OutboxMessagePublishPort.class); + when(tenSecondPublisher.longestAttempt()).thenReturn(Optional.of(Duration.ofSeconds(10))); + ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class)) + .withBean(OutboxStorePort.class, OutboxRelayAutoConfigurationTest::unusedStore) + .withBean(OutboxRelayFailureReportPort.class, () -> report -> {}) + .withBean(TransactionPort.class, () -> mock(TransactionPort.class)) + .withBean(Clock.class, Clock::systemUTC) + .withBean(OutboxMessagePublishPort.class, () -> tenSecondPublisher) + .withPropertyValues( + "app.outbox.enabled=true", + "app.outbox.relay-enabled=true", + "app.outbox.batch-size=40", + "app.outbox.in-flight-timeout=PT5M"); + + // when & then + runner.run( + context -> + assertThat(context) + .getFailure() + .hasStackTraceContaining("app.outbox.in-flight-timeout")); + } + @Test void withoutTheRelayKeyTheRelaySchedulerIsNotAssembled() { new ApplicationContextRunner() diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerDrainTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerDrainTest.java index 7e77915e..20094488 100644 --- a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerDrainTest.java +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelaySchedulerDrainTest.java @@ -156,7 +156,8 @@ class OutboxRelaySchedulerDrainTest { new OutboxMetrics( store, registries.getBeanProvider(io.micrometer.core.instrument.MeterRegistry.class), - clock)); + clock, + Duration.ofHours(1))); } /** The fake store with the claim SQL's per-aggregate head gate. */ diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java index 1d038f0f..2be9653f 100644 --- a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxRelayShutdownOrderTest.java @@ -166,15 +166,16 @@ class OutboxRelayShutdownOrderTest { } @Override - public synchronized OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { - OutboxCompletion completion = super.markFailed(lease, nextAttemptAt); + public synchronized OutboxCompletion markFailed( + OutboxLease lease, Instant nextAttemptAt, String failureCode) { + OutboxCompletion completion = super.markFailed(lease, nextAttemptAt, failureCode); completed.set(true); return completion; } @Override - public synchronized OutboxCompletion markDead(OutboxLease lease) { - OutboxCompletion completion = super.markDead(lease); + public synchronized OutboxCompletion markDead(OutboxLease lease, String failureCode) { + OutboxCompletion completion = super.markDead(lease, failureCode); completed.set(true); return completion; } diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxSettingsTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxSettingsTest.java index 2a90ed07..371f48b1 100644 --- a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxSettingsTest.java +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxSettingsTest.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; import java.time.Duration; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -99,4 +100,48 @@ class OutboxSettingsTest { e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) .hasMessageContaining("app.outbox." + message); } + + /** + * A cycle holds every row of its batch under one lease while it publishes them one after another, + * so the batch's worst case has to fit in the lease. Past it, another instance reclaims rows this + * one is still going to send, and the event goes out twice (review 2026-11-01 06-12). + */ + @ParameterizedTest(name = "batch {0} x {1}s against a {2}s lease") + @CsvSource({"40, 10, 300", "30, 10, 300", "20, 10, 120"}) + @DisplayName("한 배치를 다 보내는 최악 시간이 lease 이상인 설정은 기동을 거부한다") + void aBatchWhoseWorstCaseReachesTheLeaseIsRefusedAtStartup( + int batchSize, long longestAttemptSeconds, long leaseSeconds) { + // given + OutboxSettings settings = + new OutboxSettings( + true, true, null, batchSize, Duration.ofSeconds(leaseSeconds), null, null); + + // when + Throwable thrown = + catchThrowable( + () -> settings.requireLeaseOutlastsBatch(Duration.ofSeconds(longestAttemptSeconds))); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + StartupFailureException.class, + failure -> + assertThat(failure.errorCode()) + .isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) + .hasMessageContaining("app.outbox.in-flight-timeout"); + } + + @Test + @DisplayName("기본값(배치 20, 발행 최악 10초, lease 5분)은 기동을 막지 않는다") + void theDefaultsLeaveTheLeaseLongerThanABatch() { + // given + OutboxSettings settings = new OutboxSettings(true, true, null, null, null, null, null); + + // when + Throwable thrown = + catchThrowable(() -> settings.requireLeaseOutlastsBatch(Duration.ofSeconds(10))); + + // then + assertThat(thrown).isNull(); + } } diff --git a/src/composition/service-runtime/README.md b/src/composition/service-runtime/README.md index e2153a24..46112736 100644 --- a/src/composition/service-runtime/README.md +++ b/src/composition/service-runtime/README.md @@ -28,7 +28,9 @@ composition:service-runtime 선언만 남은 채 정상 기동했다. 이제 `PermissionEnforcementGuard`가 선언 빈마다 pointcut이 맞는 advisor가 있는지 보고, 없으면 `REQUIRED_ADAPTER_DISABLED`(exit 72)로 기동을 멈춘다. 한계: "어떤 advisor든 pointcut이 맞으면 통과"라 인가가 아닌 advisor를 구분하지 못한다. `new`로 만든 - 유스케이스는 검사 대상이 아니다(시스템 호출용은 `@SystemInvoked`). + 유스케이스는 검사 대상이 아니다(시스템 호출용은 `@SystemInvoked`). 반대로 `@SystemInvoked` + 유스케이스가 빈으로 등록돼 있으면 같은 가드가 기동을 멈춘다 — 권한 검사가 없는 쓰기를 전송 계층이 + 닿는 곳에 두는 조립이기 때문이다(review 2026-11-03 RR-01-02). - 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(설정 브리지와 tracing 스위치는 `spring.factories`의 `EnvironmentPostProcessor`·`AutoConfigurationImportFilter`). 구성 루트의 diff --git a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java index 9f9b0e80..c671f8b8 100644 --- a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java @@ -2,6 +2,7 @@ package dev.caskeleton.composition.runtime.authorization; import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.security.SystemInvoked; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -17,16 +18,21 @@ import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.util.ClassUtils; /** - * Fails startup when a bean declares {@link RequiresPermission} and no advisor in the context - * applies to it. + * Fails startup when a write use case would run with no permission check: a bean that declares + * {@link RequiresPermission} with no advisor in the context that applies to it, or a bean of a + * {@link SystemInvoked} use case at all. * *

        "Applies" is {@link AopUtils#canApply(Advisor, Class)}: the advisor's pointcut matches the * bean's class. That is how the web adapter's advisor reaches a use case, so its absence is exactly * the case this guard is for. The check cannot tell an authorization advisor from any other advisor * whose pointcut happens to match; it closes the "adapter missing" gap, not every misconfiguration. * - *

        Only beans are checked. A use case built with {@code new} is never advised whatever the - * context holds — that is what {@code @SystemInvoked} declares for the use cases the system calls. + *

        A {@code @SystemInvoked} use case carries no permission by design — only the system calls it, + * on a thread with no {@code Authentication} — and its composition constructs it with {@code new} + * and hands it to that caller. Registered as a bean, it is a write any transport can reach with no + * check, whatever advisor the context holds, so its presence fails startup (review 2026-11-03 + * RR-01-02). {@code INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES} closes the other path, + * an inbound adapter that constructs one itself. */ final class PermissionEnforcementGuard implements SmartInitializingSingleton, BeanFactoryAware { @@ -40,6 +46,7 @@ final class PermissionEnforcementGuard implements SmartInitializingSingleton, Be @Override public void afterSingletonsInstantiated() { Collection advisors = beanFactory.getBeansOfType(Advisor.class, true, false).values(); + List systemInvoked = new ArrayList<>(); List unenforced = new ArrayList<>(); for (String name : beanFactory.getBeanDefinitionNames()) { Class type = beanFactory.getType(name, false); @@ -47,11 +54,20 @@ final class PermissionEnforcementGuard implements SmartInitializingSingleton, Be continue; } Class userClass = ClassUtils.getUserClass(type); - if (declaresPermission(userClass) + if (AnnotatedElementUtils.hasAnnotation(userClass, SystemInvoked.class)) { + systemInvoked.add(name + " (" + userClass.getName() + ")"); + } else if (declaresPermission(userClass) && advisors.stream().noneMatch(advisor -> AopUtils.canApply(advisor, userClass))) { unenforced.add(name + " (" + userClass.getName() + ")"); } } + if (!systemInvoked.isEmpty()) { + throw StartupFailures.requiredAdapterDisabled( + "@SystemInvoked use cases are registered as beans, where a transport can reach a write" + + " that has no permission check — a system-invoked use case must be constructed by" + + " its composition, not registered as a bean: " + + String.join(", ", systemInvoked)); + } if (!unenforced.isEmpty()) { throw StartupFailures.requiredAdapterDisabled( "beans declare @RequiresPermission but no advisor enforces it — the composition is" diff --git a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java index 86ea2242..e8c1acf8 100644 --- a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.security.SystemInvoked; import org.aopalliance.intercept.MethodInterceptor; import org.junit.jupiter.api.Test; import org.springframework.aop.Advisor; @@ -39,6 +40,22 @@ class PermissionEnforcementGuardTest { .run(context -> assertThat(context).hasNotFailed().hasSingleBean(GatedUseCase.class)); } + /** + * A system-invoked use case carries no permission, so a bean of it is a write a transport can + * reach with no check at all — whatever advisor the context holds (review 2026-11-03 RR-01-02). + */ + @Test + void aSystemInvokedUseCaseRegisteredAsABeanFailsStartupEvenWithAnAdvisor() { + runner + .withUserConfiguration(SystemInvokedUseCaseConfig.class, EnforcingAdvisorConfig.class) + .run( + context -> + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("must be constructed by its composition") + .hasMessageContaining(SystemInvokedUseCase.class.getName())); + } + @Test void aContextWithoutGatedBeansNeedsNoAdvisor() { runner.run(context -> assertThat(context).hasNotFailed()); @@ -57,6 +74,19 @@ class PermissionEnforcementGuardTest { } } + @SystemInvoked(reason = "a scheduler calls it") + public static class SystemInvokedUseCase { + public void handle() {} + } + + @Configuration(proxyBeanMethods = false) + static class SystemInvokedUseCaseConfig { + @Bean + SystemInvokedUseCase systemInvokedUseCase() { + return new SystemInvokedUseCase(); + } + } + @Configuration(proxyBeanMethods = false) static class EnforcingAdvisorConfig { @Bean diff --git a/src/config/runtime/compose-profile-contracts.json b/src/config/runtime/compose-profile-contracts.json index d0bef525..a5a000ab 100644 --- a/src/config/runtime/compose-profile-contracts.json +++ b/src/config/runtime/compose-profile-contracts.json @@ -795,6 +795,6 @@ "redis" ], "$vendorComment": "expectedPersistenceVendor is the vendor the application must report, not the one the lane started: info.capabilities.persistence-jpa.vendor while JPA is on, none while it is off. A reported postgresql is the database the queries go to, because the JPA module refuses to start when the selected vendor is postgresql and the datasource it reaches is not PostgreSQL (JpaDataSourceProfileValidator). local-jpa passed for a while against H2 while a PostgreSQL container it never touched sat beside it, because application-local.yml pins an in-memory URL that outranks the lane's environment.", - "$redisComment": "The lanes that switch Redis on authenticate the way a deployment does. Their Redis loads infra/redis-sdk/acl/all-accounts.acl, which turns the passwordless default user off, and the application connects as the two named accounts that file provisions: ca-skeleton-application for ordinary commands and ca-skeleton-application-advanced for registered scripts. Both references use the secret://@environment/ form; without the account part the client authenticates as the disabled default user. The two REDIS_LANE_* values are that file's fixture passwords (infra/redis-sdk/acl/README.md), not deployment credentials, and deliberately carry no APP_ prefix: they are not application settings, only what these references point at. APP_REDIS_NAMESPACE_ENVIRONMENT is prod because the fixture accounts are fenced to ~prod:*, the namespace every other test against that file uses; under the default local namespace the first key a capability wrote would be refused with NOPERM after startup had reported healthy. Before this the lanes declared anonymous-access-accepted against an open Redis, and the two startup warnings that trade prints (no credential, no advanced account) failed their startup-is-silent check — which is right, because in production both are risks. scripts/verify-compose-profile-contracts.sh check 7 holds a Redis lane's references, passwords and namespace to the account lines of the file its Redis actually mounts.", + "$redisComment": "The lanes that switch Redis on authenticate the way a deployment does. Their Redis loads infra/redis-sdk/acl/lane-fixture-accounts.acl, which turns the passwordless default user off, and the application connects as the two named accounts that file provisions: ca-skeleton-application for ordinary commands and ca-skeleton-application-advanced for registered scripts. Both references use the secret://@environment/ form; without the account part the client authenticates as the disabled default user. The two REDIS_LANE_* values are that file's fixture passwords (infra/redis-sdk/acl/README.md), not deployment credentials, and deliberately carry no APP_ prefix: they are not application settings, only what these references point at. APP_REDIS_NAMESPACE_ENVIRONMENT is prod because the fixture accounts are fenced to ~prod:*, the namespace every other test against that file uses; under the default local namespace the first key a capability wrote would be refused with NOPERM after startup had reported healthy. Before this the lanes declared anonymous-access-accepted against an open Redis, and the two startup warnings that trade prints (no credential, no advanced account) failed their startup-is-silent check — which is right, because in production both are risks. scripts/verify-compose-profile-contracts.sh check 7 holds a Redis lane's references, passwords and namespace to the account lines of the file its Redis actually mounts.", "$flywayComment": "SPRING_FLYWAY_LOCATIONS is deliberately absent. Seven lanes listed every capability stream there, and it could never have worked: the db/migration/jpa/* streams each declare a V1, so one Flyway instance over all of them fails with 'Found more than one migration with version 1'. Each stream is its own stream with its own history table by design. The setting was inert until Wave 2 stopped PostgreSqlPersistenceConfig from overriding spring.flyway.locations, and the lanes passed while their own configuration was being discarded. Applying a capability stream needs a Flyway execution per stream — the operator sequence PostgreSqlNotificationPersistenceUnitIntegrationTest and FileserverRoundTripContractTest both perform in their fixtures — and that is what the notification lanes still need." } diff --git a/src/config/spotbugs/exclude.xml b/src/config/spotbugs/exclude.xml index 7276eb5d..2a7d1e5e 100644 --- a/src/config/spotbugs/exclude.xml +++ b/src/config/spotbugs/exclude.xml @@ -16,14 +16,37 @@ - + - + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/grpc/CLAUDE.md b/src/grpc/CLAUDE.md index 19e78b30..5705281a 100644 --- a/src/grpc/CLAUDE.md +++ b/src/grpc/CLAUDE.md @@ -145,7 +145,7 @@ the repository's `.seconds` / `.total` unit naming and the corresponding validat `grpc-spring-boot-starter` does not pull the JPA ledger adapter transitively (11-M9). A deployment that needs durable operation idempotency adds `:grpc:grpc-operation-ledger-jpa` explicitly, defines a `GrpcOperationLedger` bean (`new JpaGrpcOperationLedger(repository)`), includes that adapter's Flyway -location `db/migration/grpc` (V001 table, V002 retention index), and sets the flag below. A deployment +location `db/migration/grpc` (V001 table, V002 retention index, V003 claim attempt), and sets the flag below. A deployment that does not adopt the ledger pays no Spring Data JPA classpath cost. | Key (`app.grpc.platform.*`) | Default | What it does | @@ -165,9 +165,9 @@ optional build is not part of the shipped runtime. They join the registry when a adopts the platform. **Why the starter assembles the interceptor (03-11 (b)), and not (a).** The review proposed (a): -delete the flag and judge by whether a ledger bean exists. The owner chose (b): the flag stays and -means what it says — when true, the decision function is assembled and its TTL comes from -configuration. (a) would have removed the false promise but left every adopter to rebuild the same +delete the flag and judge by whether a ledger bean exists. (b) was chosen and is recorded in +ADR-GRPC-004 (re-review 2026-11-03, RR-02-07): the flag stays and means what it says — when true, the +decision function is assembled and its TTL comes from configuration. (a) would have removed the false promise but left every adopter to rebuild the same assembly and TTL validation by hand; (b) keeps that in one place. The interceptor bean has no `@ConditionalOnMissingBean` on purpose: a replacement would silently ignore `operation-ledger-claim-ttl`. Duplicates of a running operation are refused (`REJECT_IN_PROGRESS`), not told to wait; a @@ -179,7 +179,10 @@ server, so assembling the decision does not wire the platform into `adapter:inbo The adopter injects the bean by type and calls it from its own `IDEMPOTENCY` stage interceptor (`GrpcServerInterceptorChain.builder().stage(GrpcServerInterceptorStage.IDEMPOTENCY, ...)`) or from its typed service adapter: `decide(...)` before the mutation, `recordCommit(...)` inside the mutation's -transaction, `recordFailure(...)` on a terminal failure. +transaction, `recordFailure(...)` on a terminal failure. Both record calls take the `GrpcClaimToken` +the `PROCEED` decision carried: a commit by an attempt whose claim was taken over is refused (its +transaction rolls back) and its failure is ignored, so a slow owner cannot write over the attempt that +took its claim (re-review RR-02-04, ADR-GRPC-004). **Purge scheduling is the adopter's.** `GrpcOperationLedgerRetention.purgeExpired(now)` deletes expired finished rows in bounded batches (500 per statement) until a batch comes back short. The diff --git a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcClaimToken.java b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcClaimToken.java new file mode 100644 index 00000000..7b5fe358 --- /dev/null +++ b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcClaimToken.java @@ -0,0 +1,35 @@ +package dev.caskeleton.grpc.api.ledger; + +/** + * Which attempt holds a claim: the fencing token a commit or a failure record must present. + * + *

        A claim can change hands. A stale one is taken over after the claim TTL, and a failed one is + * re-claimed by the next retry; both make a new attempt of the same operation. The owner that lost + * the claim may still be running, and when it finishes it records its outcome. Without a token that + * record lands on the new attempt's claim: an old owner's failure turned the new attempt's claim + * {@code FAILED_TERMINAL}, a third retry re-claimed it, and two attempts ran the mutation at once + * (re-review 2026-11-03, RR-02-04). With it, the ledger records an outcome only for the attempt + * that still holds the claim. + * + *

        A counter rather than the claim moment: it increases by one with every hand-over, so two + * attempts never share a value, whatever the clocks of the processes that claimed it. + * + * @param attempt one for the first claim of an operation, one more for each hand-over + */ +public record GrpcClaimToken(long attempt) { + + /** The token of the claim that created the record. */ + public static final GrpcClaimToken FIRST = new GrpcClaimToken(1); + + /** Requires a positive attempt number. */ + public GrpcClaimToken { + if (attempt < 1) { + throw new IllegalArgumentException("a claim attempt is numbered from one, was " + attempt); + } + } + + /** The token of the attempt that takes this claim over. */ + public GrpcClaimToken next() { + return new GrpcClaimToken(Math.addExact(attempt, 1)); + } +} diff --git a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java index 2c275151..381979a7 100644 --- a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java +++ b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java @@ -20,7 +20,8 @@ public interface GrpcOperationLedger { * implementation admits both concurrent attempts, which is the exact failure the ledger exists to * prevent, and it does so only under the load where it matters. * - * @return the existing record when one was already claimed, empty when this call created it + * @return the existing record when one was already claimed, empty when this call created it — the + * caller then holds the claim as {@link GrpcClaimToken#FIRST} */ Optional claim( GrpcOperationIdentity identity, String requestFingerprint, Instant now); @@ -34,11 +35,34 @@ public interface GrpcOperationLedger { *

        Called inside the business transaction wherever the datastore allows it. When the ledger and * the mutation commit separately, there is a window in which the mutation is durable and the * claim is not, and a retry in that window runs the mutation twice. + * + *

        Only the attempt that holds the claim commits it. An attempt whose claim was taken over or + * re-claimed since is refused with an exception, so its business transaction rolls back rather + * than committing beside the attempt that now owns the operation. Of two concurrent commits of + * one claim, exactly one succeeds. + * + * @param claimToken the token of the attempt committing, from the claim it won + * @throws IllegalStateException when there is no claim, it already finished, or it is no longer + * held by {@code claimToken} */ - void markCommitted(GrpcOperationIdentity identity, String outcomeReference, Instant now); + void markCommitted( + GrpcOperationIdentity identity, + GrpcClaimToken claimToken, + String outcomeReference, + Instant now); - /** Marks a claim terminally failed. */ - void markFailed(GrpcOperationIdentity identity, Instant now); + /** + * Marks a claim terminally failed, if {@code claimToken} still holds it. + * + *

        An attempt that lost its claim reports a failure the operation no longer has: another + * attempt is running it. That record is ignored rather than written over the running attempt's + * claim. + * + * @param claimToken the token of the attempt that failed, from the claim it won + * @return true when the failure was recorded; false when the claim is missing, already finished, + * or held by another attempt, in which case nothing changed + */ + boolean markFailed(GrpcOperationIdentity identity, GrpcClaimToken claimToken, Instant now); /** * Re-claims a {@code FAILED_TERMINAL} record for a new attempt of the same request. @@ -48,9 +72,11 @@ public interface GrpcOperationLedger { * request, is left untouched. A retry that proceeds without winning this leaves its commit with * no owner and runs concurrently with every other retry of the same key. * - * @return true when this call now owns the record as a fresh attempt claimed at {@code now} + * @return the new attempt's token when this call now owns the record as a fresh attempt claimed + * at {@code now}; empty otherwise */ - boolean reclaimFailed(GrpcOperationIdentity identity, String requestFingerprint, Instant now); + Optional reclaimFailed( + GrpcOperationIdentity identity, String requestFingerprint, Instant now); /** * Takes over an {@code IN_PROGRESS} claim whose owner is presumed dead, for a new attempt of the @@ -73,10 +99,15 @@ public interface GrpcOperationLedger { * When an adopter commits them separately, the abandoned attempt's outcome is unknown and a * takeover can run the mutation twice. * - * @return true when this call now owns the record as a fresh attempt claimed at {@code now} + *

        The owner taken over may be slow rather than dead. Its later commit is refused and its later + * failure ignored, because it no longer holds the claim token; that is what keeps the takeover + * from becoming a second concurrent run. + * + * @return the new attempt's token when this call now owns the record as a fresh attempt claimed + * at {@code now}; empty otherwise * @throws IllegalArgumentException when {@code claimedBefore} is after {@code now} */ - boolean reclaimStale( + Optional reclaimStale( GrpcOperationIdentity identity, String requestFingerprint, Instant claimedBefore, diff --git a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerRecord.java b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerRecord.java index 2bc0942a..22f86322 100644 --- a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerRecord.java +++ b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerRecord.java @@ -10,6 +10,9 @@ import java.util.Optional; * A caller that reuses a key for a different request has made a mistake, and returning the first * request's answer would hide it; comparing fingerprints turns that into a {@code * FAILED_PRECONDITION} the caller can act on. + * + *

        {@code claimToken} names the attempt that holds (or last held) the claim; see {@link + * GrpcClaimToken}. */ public record GrpcOperationLedgerRecord( GrpcOperationIdentity identity, @@ -17,9 +20,10 @@ public record GrpcOperationLedgerRecord( String requestFingerprint, Optional outcomeReference, Instant claimedAt, - Optional completedAt) { + Optional completedAt, + GrpcClaimToken claimToken) { - /** Requires an identity, a state, a fingerprint and a claim moment. */ + /** Requires an identity, a state, a fingerprint, a claim moment and a claim token. */ public GrpcOperationLedgerRecord { if (identity == null || state == null) { throw new IllegalArgumentException("a ledger record needs an identity and a state"); @@ -30,6 +34,9 @@ public record GrpcOperationLedgerRecord( if (claimedAt == null || outcomeReference == null || completedAt == null) { throw new IllegalArgumentException("a ledger record needs its timestamps and Optionals"); } + if (claimToken == null) { + throw new IllegalArgumentException("a ledger record names the attempt that holds it"); + } if (state.terminal() && completedAt.isEmpty()) { throw new IllegalArgumentException("a terminal ledger record records when it finished"); } @@ -40,16 +47,26 @@ public record GrpcOperationLedgerRecord( } } - /** A fresh claim. */ + /** A fresh claim, held by the first attempt. */ public static GrpcOperationLedgerRecord claim( GrpcOperationIdentity identity, String requestFingerprint, Instant claimedAt) { + return claim(identity, requestFingerprint, claimedAt, GrpcClaimToken.FIRST); + } + + /** A claim in progress, held by the attempt {@code claimToken} names. */ + public static GrpcOperationLedgerRecord claim( + GrpcOperationIdentity identity, + String requestFingerprint, + Instant claimedAt, + GrpcClaimToken claimToken) { return new GrpcOperationLedgerRecord( identity, GrpcOperationLedgerState.IN_PROGRESS, requestFingerprint, Optional.empty(), claimedAt, - Optional.empty()); + Optional.empty(), + claimToken); } /** Whether {@code candidateFingerprint} is the same request this claim was made for. */ diff --git a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java index 0c625fc6..d91f8de1 100644 --- a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java +++ b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java @@ -88,7 +88,7 @@ public abstract class GrpcOperationLedgerContract { ledger().claim(ID, FINGERPRINT, NOW); // when - ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(1)); + ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(1)); // then assertThat(ledger().find(ID)) @@ -106,7 +106,8 @@ public abstract class GrpcOperationLedgerContract { @Test void committingWithoutAClaimIsRefused() { // when - Throwable refused = catchThrowable(() -> ledger().markCommitted(ID, OUTCOME, NOW)); + Throwable refused = + catchThrowable(() -> ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW)); // then assertThat(refused) @@ -118,12 +119,15 @@ public abstract class GrpcOperationLedgerContract { void aCommittedClaimCannotBeCommittedAgain() { // given ledger().claim(ID, FINGERPRINT, NOW); - ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(1)); + ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(1)); // when Throwable refused = catchThrowable( - () -> ledger().markCommitted(ID, "outcome://document/99", NOW.plusSeconds(2))); + () -> + ledger() + .markCommitted( + ID, GrpcClaimToken.FIRST, "outcome://document/99", NOW.plusSeconds(2))); // then assertThat(refused) @@ -137,7 +141,7 @@ public abstract class GrpcOperationLedgerContract { ledger().claim(ID, FINGERPRINT, NOW); // when - ledger().markFailed(ID, NOW.plusSeconds(1)); + ledger().markFailed(ID, GrpcClaimToken.FIRST, NOW.plusSeconds(1)); // then assertThat(ledger().find(ID)) @@ -153,7 +157,8 @@ public abstract class GrpcOperationLedgerContract { // when Throwable refused = - catchThrowable(() -> ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(2))); + catchThrowable( + () -> ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(2))); // then assertThat(refused) @@ -167,10 +172,11 @@ public abstract class GrpcOperationLedgerContract { failedClaim(); // when - boolean reclaimed = ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + Optional reclaimed = + ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); // then - assertThat(reclaimed).isTrue(); + assertThat(reclaimed).isPresent(); } @Test @@ -196,10 +202,11 @@ public abstract class GrpcOperationLedgerContract { void aReclaimedClaimCanBeCommitted() { // given failedClaim(); - ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + GrpcClaimToken reclaimed = + ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)).orElseThrow(); // when - ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(3)); + ledger().markCommitted(ID, reclaimed, OUTCOME, NOW.plusSeconds(3)); // then assertThat(ledger().find(ID)) @@ -212,27 +219,28 @@ public abstract class GrpcOperationLedgerContract { void aFailedClaimIsNotReclaimedForADifferentRequest() { failedClaim(); - assertThat(ledger().reclaimFailed(ID, OTHER_FINGERPRINT, NOW.plusSeconds(2))).isFalse(); + assertThat(ledger().reclaimFailed(ID, OTHER_FINGERPRINT, NOW.plusSeconds(2))).isEmpty(); } @Test void anInProgressClaimIsNotReclaimed() { ledger().claim(ID, FINGERPRINT, NOW); - assertThat(ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(1))).isFalse(); + assertThat(ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(1))).isEmpty(); } @Test void aCommittedClaimIsNotReclaimed() { // given ledger().claim(ID, FINGERPRINT, NOW); - ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(1)); + ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(1)); // when - boolean reclaimed = ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + Optional reclaimed = + ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); // then - assertThat(reclaimed).isFalse(); + assertThat(reclaimed).isEmpty(); } @Test @@ -242,7 +250,7 @@ public abstract class GrpcOperationLedgerContract { // when List reclaimed = - concurrently(() -> ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2))); + concurrently(() -> ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)).isPresent()); // then assertThat(reclaimed).containsExactlyInAnyOrder(true, false); @@ -255,10 +263,10 @@ public abstract class GrpcOperationLedgerContract { ledger().claim(ID, FINGERPRINT, NOW); // when - boolean reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + Optional reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); // then - assertThat(reclaimed).isTrue(); + assertThat(reclaimed).isPresent(); } @Test @@ -285,10 +293,10 @@ public abstract class GrpcOperationLedgerContract { void aTakenOverStaleClaimCanBeCommitted() { // given ledger().claim(ID, FINGERPRINT, NOW); - ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + GrpcClaimToken takenOver = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER).orElseThrow(); // when - ledger().markCommitted(ID, OUTCOME, LATER.plusSeconds(1)); + ledger().markCommitted(ID, takenOver, OUTCOME, LATER.plusSeconds(1)); // then assertThat(ledger().find(ID)) @@ -304,10 +312,11 @@ public abstract class GrpcOperationLedgerContract { ledger().claim(ID, FINGERPRINT, NOW); // when - boolean reclaimed = ledger().reclaimStale(ID, FINGERPRINT, NOW, NOW.plus(CLAIM_TTL)); + Optional reclaimed = + ledger().reclaimStale(ID, FINGERPRINT, NOW, NOW.plus(CLAIM_TTL)); // then - assertThat(reclaimed).isFalse(); + assertThat(reclaimed).isEmpty(); } @Test @@ -317,10 +326,11 @@ public abstract class GrpcOperationLedgerContract { ledger().claim(ID, FINGERPRINT, NOW); // when - boolean reclaimed = ledger().reclaimStale(ID, OTHER_FINGERPRINT, CUTOFF, LATER); + Optional reclaimed = + ledger().reclaimStale(ID, OTHER_FINGERPRINT, CUTOFF, LATER); // then - assertThat(reclaimed).isFalse(); + assertThat(reclaimed).isEmpty(); } @Test @@ -328,13 +338,13 @@ public abstract class GrpcOperationLedgerContract { void aCommittedClaimIsNotTakenOverAsStale() { // given ledger().claim(ID, FINGERPRINT, NOW); - ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(1)); + ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(1)); // when - boolean reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + Optional reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); // then - assertThat(reclaimed).isFalse(); + assertThat(reclaimed).isEmpty(); } @Test @@ -344,20 +354,20 @@ public abstract class GrpcOperationLedgerContract { failedClaim(); // when - boolean reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + Optional reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); // then - assertThat(reclaimed).isFalse(); + assertThat(reclaimed).isEmpty(); } @Test @DisplayName("claim이 없으면 stale 회수는 아무것도 만들지 않는다") void takingOverAMissingClaimCreatesNothing() { // when - boolean reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + Optional reclaimed = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); // then - assertThat(reclaimed).isFalse(); + assertThat(reclaimed).isEmpty(); assertThat(ledger().find(ID)).isEmpty(); } @@ -369,10 +379,10 @@ public abstract class GrpcOperationLedgerContract { ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); // when - boolean again = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + Optional again = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); // then - assertThat(again).isFalse(); + assertThat(again).isEmpty(); } @Test @@ -383,7 +393,7 @@ public abstract class GrpcOperationLedgerContract { // when List reclaimed = - concurrently(() -> ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER)); + concurrently(() -> ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER).isPresent()); // then assertThat(reclaimed).containsExactlyInAnyOrder(true, false); @@ -402,6 +412,126 @@ public abstract class GrpcOperationLedgerContract { assertThat(refused).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("cutoff"); } + @Test + @DisplayName("claim 을 넘겨받을 때마다 claim token 은 다음 시도 번호가 된다") + void eachHandOverIssuesTheNextClaimToken() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + GrpcClaimToken takenOver = ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER).orElseThrow(); + + // then + assertThat(takenOver).isEqualTo(GrpcClaimToken.FIRST.next()); + assertThat(ledger().find(ID)) + .get() + .extracting(GrpcOperationLedgerRecord::claimToken) + .isEqualTo(takenOver); + } + + /** + * The re-review probe's sequence (2026-11-03, RR-02-04): A claims and is slow, B takes the claim + * over after the TTL, then A reports a failure. Recording it would mark B's running attempt + * failed, and the next retry would re-claim it and run beside B. + */ + @Test + @DisplayName("TTL 뒤 넘겨받은 claim 에 옛 owner 가 실패를 기록하면 무시되고 새 시도는 진행 중으로 남는다") + void aFailureReportedByTheOwnerThatLostTheClaimIsIgnored() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + + // when + boolean recorded = ledger().markFailed(ID, GrpcClaimToken.FIRST, LATER.plusSeconds(1)); + + // then + assertThat(recorded).isFalse(); + assertThat(ledger().find(ID)) + .get() + .extracting( + GrpcOperationLedgerRecord::state, + GrpcOperationLedgerRecord::claimedAt, + GrpcOperationLedgerRecord::completedAt) + .containsExactly(GrpcOperationLedgerState.IN_PROGRESS, LATER, Optional.empty()); + } + + @Test + @DisplayName("옛 owner 의 실패가 무시되므로 다음 재시도는 진행 중인 새 시도를 다시 claim 하지 못한다") + void aRetryCannotReclaimTheRunningAttemptAfterTheLostOwnerFailed() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + ledger().markFailed(ID, GrpcClaimToken.FIRST, LATER.plusSeconds(1)); + + // when + Optional third = ledger().reclaimFailed(ID, FINGERPRINT, LATER.plusSeconds(2)); + + // then + assertThat(third).isEmpty(); + } + + @Test + @DisplayName("TTL 뒤 넘겨받은 claim 에 옛 owner 가 commit 하면 거부되고 새 시도는 진행 중으로 남는다") + void aCommitByTheOwnerThatLostTheClaimIsRefused() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + + // when + Throwable refused = + catchThrowable( + () -> ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, LATER.plusSeconds(1))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no longer held by attempt 1"); + assertThat(ledger().find(ID)) + .get() + .extracting(GrpcOperationLedgerRecord::state) + .isEqualTo(GrpcOperationLedgerState.IN_PROGRESS); + } + + @Test + @DisplayName("실패 뒤 다시 claim 된 기록에 이전 시도가 commit 하면 거부된다") + void aCommitByTheAttemptBeforeAFailedReclaimIsRefused() { + // given + failedClaim(); + ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + + // when + Throwable refused = + catchThrowable( + () -> ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(3))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no longer held by attempt 1"); + } + + @Test + @DisplayName("한 claim 을 동시에 commit 하면 하나만 성공한다") + void concurrentCommitsOfOneClaimHaveExactlyOneWinner() throws Exception { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + List committed = + concurrently( + () -> { + try { + ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(1)); + return true; + } catch (IllegalStateException refused) { + return false; + } + }); + + // then + assertThat(committed).containsExactlyInAnyOrder(true, false); + } + @Test @DisplayName("보존 기간이 지난 COMMITTED·FAILED_TERMINAL 행은 정리된다") void finishedRecordsCompletedBeforeTheCutoffArePurged() { @@ -489,12 +619,12 @@ public abstract class GrpcOperationLedgerContract { // cutoff is compared with. private void failedClaim(GrpcOperationIdentity identity, Instant claimedAt) { ledger().claim(identity, FINGERPRINT, claimedAt); - ledger().markFailed(identity, claimedAt.plusSeconds(1)); + ledger().markFailed(identity, GrpcClaimToken.FIRST, claimedAt.plusSeconds(1)); } private void committedClaim(GrpcOperationIdentity identity, Instant claimedAt) { ledger().claim(identity, FINGERPRINT, claimedAt); - ledger().markCommitted(identity, OUTCOME, claimedAt.plusSeconds(1)); + ledger().markCommitted(identity, GrpcClaimToken.FIRST, OUTCOME, claimedAt.plusSeconds(1)); } private static GrpcOperationIdentity identityWithKeyHash(char hexDigit) { diff --git a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java index 55479149..bc26942d 100644 --- a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java +++ b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java @@ -6,15 +6,18 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicBoolean; /** * A hand-rolled ledger for tests of code that depends on {@link GrpcOperationLedger}. * *

        {@code putIfAbsent} on a concurrent map is the in-memory equivalent of the unique constraint - * the real adapter relies on, and {@code replace(key, expected, next)} of its conditional update, - * so claim, re-claim, stale takeover and purge are atomic here for the same reason they are there. - * The transitions match the JPA adapter's because {@link GrpcOperationLedgerContract} runs against - * both; a fake that allowed more would let the policy tests pass for code the database refuses. + * the real adapter relies on, and {@code replace(key, expected, next)} and {@code computeIfPresent} + * of its conditional updates, so claim, re-claim, stale takeover, commit, failure and purge are + * atomic here for the same reason they are there. A commit or failure is recorded only for the + * attempt whose {@link GrpcClaimToken} still holds the claim. The transitions match the JPA + * adapter's because {@link GrpcOperationLedgerContract} runs against both; a fake that allowed more + * would let the policy tests pass for code the database refuses. */ public final class InMemoryOperationLedger implements GrpcOperationLedger { @@ -46,16 +49,19 @@ public final class InMemoryOperationLedger implements GrpcOperationLedger { } @Override - public void markCommitted(GrpcOperationIdentity identity, String outcomeReference, Instant now) { + public void markCommitted( + GrpcOperationIdentity identity, + GrpcClaimToken claimToken, + String outcomeReference, + Instant now) { GrpcOperationLedgerRecord committed = records.computeIfPresent( identity.storageKey(), - (key, existing) -> - finish( - existing, - GrpcOperationLedgerState.COMMITTED, - Optional.of(outcomeReference), - now)); + (key, existing) -> { + requireHeldBy(existing, claimToken); + return finish( + existing, GrpcOperationLedgerState.COMMITTED, Optional.of(outcomeReference), now); + }); if (committed == null) { throw new IllegalStateException( "cannot commit operation '" + identity.storageKey() + "': no claim exists"); @@ -63,28 +69,36 @@ public final class InMemoryOperationLedger implements GrpcOperationLedger { } @Override - public void markFailed(GrpcOperationIdentity identity, Instant now) { + public boolean markFailed( + GrpcOperationIdentity identity, GrpcClaimToken claimToken, Instant now) { + AtomicBoolean recorded = new AtomicBoolean(); records.computeIfPresent( identity.storageKey(), - (key, existing) -> - finish(existing, GrpcOperationLedgerState.FAILED_TERMINAL, Optional.empty(), now)); + (key, existing) -> { + if (existing.state() != GrpcOperationLedgerState.IN_PROGRESS + || !existing.claimToken().equals(claimToken)) { + return existing; + } + recorded.set(true); + return finish(existing, GrpcOperationLedgerState.FAILED_TERMINAL, Optional.empty(), now); + }); + return recorded.get(); } @Override - public boolean reclaimFailed( + public Optional reclaimFailed( GrpcOperationIdentity identity, String requestFingerprint, Instant now) { GrpcOperationLedgerRecord current = records.get(identity.storageKey()); - return current != null - && current.state() == GrpcOperationLedgerState.FAILED_TERMINAL - && current.sameRequestAs(requestFingerprint) - && records.replace( - identity.storageKey(), - current, - GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now)); + if (current == null + || current.state() != GrpcOperationLedgerState.FAILED_TERMINAL + || !current.sameRequestAs(requestFingerprint)) { + return Optional.empty(); + } + return handOver(identity, requestFingerprint, current, now); } @Override - public boolean reclaimStale( + public Optional reclaimStale( GrpcOperationIdentity identity, String requestFingerprint, Instant claimedBefore, @@ -94,14 +108,28 @@ public final class InMemoryOperationLedger implements GrpcOperationLedger { "a stale-claim cutoff after now would leave the new claim stale as well"); } GrpcOperationLedgerRecord current = records.get(identity.storageKey()); - return current != null - && current.state() == GrpcOperationLedgerState.IN_PROGRESS - && current.claimedAt().isBefore(claimedBefore) - && current.sameRequestAs(requestFingerprint) - && records.replace( + if (current == null + || current.state() != GrpcOperationLedgerState.IN_PROGRESS + || !current.claimedAt().isBefore(claimedBefore) + || !current.sameRequestAs(requestFingerprint)) { + return Optional.empty(); + } + return handOver(identity, requestFingerprint, current, now); + } + + // The conditional replace is the compare-and-set: of two hand-overs of the same record, one wins. + private Optional handOver( + GrpcOperationIdentity identity, + String requestFingerprint, + GrpcOperationLedgerRecord current, + Instant now) { + GrpcClaimToken next = current.claimToken().next(); + return records.replace( identity.storageKey(), current, - GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now)); + GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now, next)) + ? Optional.of(next) + : Optional.empty(); } @Override @@ -132,6 +160,21 @@ public final class InMemoryOperationLedger implements GrpcOperationLedger { records.remove(identity.storageKey()); } + // An attempt that lost the claim must not commit beside the attempt that holds it; checked + // before the state, so a lost owner hears that it lost rather than that the row finished. + private static void requireHeldBy(GrpcOperationLedgerRecord existing, GrpcClaimToken claimToken) { + if (!existing.claimToken().equals(claimToken)) { + throw new IllegalStateException( + "operation '" + + existing.identity().storageKey() + + "' is no longer held by attempt " + + claimToken.attempt() + + "; attempt " + + existing.claimToken().attempt() + + " holds it"); + } + } + // Only an IN_PROGRESS claim finishes; a terminal row is re-opened by reclaimFailed alone. private static GrpcOperationLedgerRecord finish( GrpcOperationLedgerRecord existing, @@ -152,6 +195,7 @@ public final class InMemoryOperationLedger implements GrpcOperationLedger { existing.requestFingerprint(), outcomeReference, existing.claimedAt(), - Optional.of(now)); + Optional.of(now), + existing.claimToken()); } } diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java index 6e28dfa2..d84695d5 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java @@ -16,7 +16,8 @@ final class GrpcOperationLedgerMigrations { private static final List IN_ORDER = List.of( "db/migration/grpc/V001__create_grpc_operation_ledger.sql", - "db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql"); + "db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql", + "db/migration/grpc/V003__add_grpc_operation_ledger_claim_attempt.sql"); private GrpcOperationLedgerMigrations() {} diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java index 7888f7e8..ec357db4 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java @@ -2,6 +2,7 @@ package dev.caskeleton.grpc.ledger; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.grpc.api.ledger.GrpcClaimToken; import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerContract; @@ -102,14 +103,15 @@ class JpaGrpcOperationLedgerContractIT extends GrpcOperationLedgerContract { String fingerprint = "sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"; Instant now = Instant.parse("2026-09-25T10:00:00Z"); ledger.claim(id, fingerprint, now); - ledger.markFailed(id, now.plusSeconds(1)); + ledger.markFailed(id, GrpcClaimToken.FIRST, now.plusSeconds(1)); // when transactions.executeWithoutResult( status -> { adapter.claim(id, fingerprint, now.plusSeconds(2)); - adapter.reclaimFailed(id, fingerprint, now.plusSeconds(2)); - adapter.markCommitted(id, "outcome://document/42", now.plusSeconds(3)); + GrpcClaimToken reclaimed = + adapter.reclaimFailed(id, fingerprint, now.plusSeconds(2)).orElseThrow(); + adapter.markCommitted(id, reclaimed, "outcome://document/42", now.plusSeconds(3)); }); // then @@ -142,8 +144,11 @@ class JpaGrpcOperationLedgerContractIT extends GrpcOperationLedgerContract { transactions.executeWithoutResult( status -> { adapter.claim(id, fingerprint, retryAt); - adapter.reclaimStale(id, fingerprint, retryAt.minusSeconds(300), retryAt); - adapter.markCommitted(id, "outcome://document/42", retryAt.plusSeconds(1)); + GrpcClaimToken takenOver = + adapter + .reclaimStale(id, fingerprint, retryAt.minusSeconds(300), retryAt) + .orElseThrow(); + adapter.markCommitted(id, takenOver, "outcome://document/42", retryAt.plusSeconds(1)); }); // then @@ -188,33 +193,36 @@ class JpaGrpcOperationLedgerContractIT extends GrpcOperationLedgerContract { @Override public void markCommitted( - GrpcOperationIdentity identity, String outcomeReference, Instant now) { + GrpcOperationIdentity identity, + GrpcClaimToken claimToken, + String outcomeReference, + Instant now) { transactions.executeWithoutResult( - status -> delegate.markCommitted(identity, outcomeReference, now)); + status -> delegate.markCommitted(identity, claimToken, outcomeReference, now)); } @Override - public void markFailed(GrpcOperationIdentity identity, Instant now) { - transactions.executeWithoutResult(status -> delegate.markFailed(identity, now)); - } - - @Override - public boolean reclaimFailed( - GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + public boolean markFailed( + GrpcOperationIdentity identity, GrpcClaimToken claimToken, Instant now) { return Boolean.TRUE.equals( - transactions.execute( - status -> delegate.reclaimFailed(identity, requestFingerprint, now))); + transactions.execute(status -> delegate.markFailed(identity, claimToken, now))); } @Override - public boolean reclaimStale( + public Optional reclaimFailed( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + return transactions.execute( + status -> delegate.reclaimFailed(identity, requestFingerprint, now)); + } + + @Override + public Optional reclaimStale( GrpcOperationIdentity identity, String requestFingerprint, Instant claimedBefore, Instant now) { - return Boolean.TRUE.equals( - transactions.execute( - status -> delegate.reclaimStale(identity, requestFingerprint, claimedBefore, now))); + return transactions.execute( + status -> delegate.reclaimStale(identity, requestFingerprint, claimedBefore, now)); } @Override diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerEntity.java b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerEntity.java index 54e26abb..571f36e0 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerEntity.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerEntity.java @@ -1,5 +1,6 @@ package dev.caskeleton.grpc.ledger; +import dev.caskeleton.grpc.api.ledger.GrpcClaimToken; import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerRecord; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerState; @@ -56,6 +57,9 @@ public class GrpcOperationLedgerEntity { @Column(name = "completed_at") private Instant completedAt; + @Column(name = "claim_attempt", nullable = false) + private long claimAttempt; + /** JPA requires a no-argument constructor. */ protected GrpcOperationLedgerEntity() { // for JPA @@ -70,6 +74,7 @@ public class GrpcOperationLedgerEntity { this.requestFingerprint = requestFingerprint; this.state = GrpcOperationLedgerState.IN_PROGRESS; this.claimedAt = claimedAt; + this.claimAttempt = GrpcClaimToken.FIRST.attempt(); } /** A new claim, in progress. */ @@ -114,13 +119,26 @@ public class GrpcOperationLedgerEntity { return Optional.ofNullable(completedAt); } + /** The attempt that holds, or last held, the claim. */ + public GrpcClaimToken getClaimToken() { + return new GrpcClaimToken(claimAttempt); + } + /** - * Records a commit with its replayable outcome. + * Records a commit with its replayable outcome, on a row this code already holds. * - * @throws IllegalStateException when the claim already finished; a second terminal transition - * would overwrite the outcome a retry is entitled to receive + *

        The row-level statement of the rule. {@link JpaGrpcOperationLedger} applies the same rule as + * one conditional {@code UPDATE} ({@link GrpcOperationLedgerRepository#tryMarkCommitted}), so + * that the database, not a value read earlier, decides between concurrent transitions. + * + * @param claimToken the attempt committing + * @throws IllegalStateException when another attempt holds the claim, or the claim already + * finished; a second terminal transition would overwrite the outcome a retry is entitled to + * receive */ - public void markCommitted(String outcomeReference, Instant completedAt) { + public void markCommitted( + GrpcClaimToken claimToken, String outcomeReference, Instant completedAt) { + requireHeldBy(claimToken); requireInProgress(); if (outcomeReference == null || outcomeReference.isBlank()) { throw new IllegalArgumentException( @@ -131,8 +149,16 @@ public class GrpcOperationLedgerEntity { this.completedAt = completedAt; } - /** Records a terminal failure. */ - public void markFailed(Instant completedAt) { + /** + * Records a terminal failure, on a row this code already holds; the row-level statement of {@link + * GrpcOperationLedgerRepository#tryMarkFailed}. + * + * @param claimToken the attempt that failed + * @throws IllegalStateException when another attempt holds the claim, or the claim already + * finished + */ + public void markFailed(GrpcClaimToken claimToken, Instant completedAt) { + requireHeldBy(claimToken); requireInProgress(); this.state = GrpcOperationLedgerState.FAILED_TERMINAL; this.completedAt = completedAt; @@ -146,7 +172,21 @@ public class GrpcOperationLedgerEntity { requestFingerprint, Optional.ofNullable(outcomeReference), claimedAt, - Optional.ofNullable(completedAt)); + Optional.ofNullable(completedAt), + getClaimToken()); + } + + private void requireHeldBy(GrpcClaimToken claimToken) { + if (claimAttempt != claimToken.attempt()) { + throw new IllegalStateException( + "operation '" + + storageKey + + "' is no longer held by attempt " + + claimToken.attempt() + + "; attempt " + + claimAttempt + + " holds it"); + } } private void requireInProgress() { diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java index d48c61c3..9a043670 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java @@ -11,10 +11,12 @@ import org.springframework.transaction.annotation.Transactional; /** * The narrow persistence interface the ledger adapter needs. * - *

        The claim path is deliberately not {@code save}. A claim entity already has a non-null string - * id, so Spring Data JPA treats it as detached and routes {@code save} through {@code merge}; merge - * can overwrite a committed row back to {@code IN_PROGRESS}. Claiming therefore uses one native - * insert with PostgreSQL conflict handling and decides ownership from the affected-row count. + *

        No path here is {@code save}. A claim entity already has a non-null string id, so Spring Data + * JPA treats it as detached and routes {@code save} through {@code merge}; merge can overwrite a + * committed row back to {@code IN_PROGRESS}, and a load-check-save commit lets two attempts that + * both read {@code IN_PROGRESS} both write. Claiming is therefore one native insert with PostgreSQL + * conflict handling, and every transition is one conditional update; ownership and every race are + * decided by the affected-row count. */ public interface GrpcOperationLedgerRepository extends Repository { @@ -31,7 +33,8 @@ public interface GrpcOperationLedgerRepository state, outcome_reference, claimed_at, - completed_at + completed_at, + claim_attempt ) VALUES ( :storageKey, :callerFingerprint, @@ -41,7 +44,8 @@ public interface GrpcOperationLedgerRepository 'IN_PROGRESS', NULL, :claimedAt, - NULL + NULL, + 1 ) ON CONFLICT DO NOTHING """; @@ -71,7 +75,11 @@ public interface GrpcOperationLedgerRepository * claim's read-on-conflict does) would otherwise still read {@code FAILED_TERMINAL} and refuse * the commit. * - * @return one when this caller re-claimed the row, zero otherwise + *

        Conditional on the attempt the caller read as well, and the new attempt is that one plus + * one: the caller then knows its own fencing token without reading the row again. + * + * @return one when this caller re-claimed the row as attempt {@code readAttempt + 1}, zero + * otherwise */ @Modifying(flushAutomatically = true, clearAutomatically = true) @Transactional @@ -81,15 +89,18 @@ public interface GrpcOperationLedgerRepository UPDATE grpc_operation_ledger SET state = 'IN_PROGRESS', claimed_at = :claimedAt, - completed_at = NULL + completed_at = NULL, + claim_attempt = claim_attempt + 1 WHERE storage_key = :storageKey AND state = 'FAILED_TERMINAL' AND request_fingerprint = :requestFingerprint + AND claim_attempt = :readAttempt """, nativeQuery = true) int tryReclaimFailed( @Param("storageKey") String storageKey, @Param("requestFingerprint") String requestFingerprint, + @Param("readAttempt") long readAttempt, @Param("claimedAt") Instant claimedAt); /** @@ -99,9 +110,11 @@ public interface GrpcOperationLedgerRepository *

        Same shape as {@link #tryReclaimFailed}: one conditional update decided by PostgreSQL's row * lock. A concurrent second takeover waits for the winner, re-evaluates the condition against the * winner's row — whose {@code claimed_at} is now {@code :claimedAt}, not before the cutoff — and - * updates nothing. It clears the persistence context for the same reason. + * updates nothing. It clears the persistence context for the same reason. The attempt grows by + * one, as in {@link #tryReclaimFailed}, and that is what fences the owner taken over. * - * @return one when this caller took the row over, zero otherwise + * @return one when this caller took the row over as attempt {@code readAttempt + 1}, zero + * otherwise */ @Modifying(flushAutomatically = true, clearAutomatically = true) @Transactional @@ -109,19 +122,76 @@ public interface GrpcOperationLedgerRepository value = """ UPDATE grpc_operation_ledger - SET claimed_at = :claimedAt + SET claimed_at = :claimedAt, + claim_attempt = claim_attempt + 1 WHERE storage_key = :storageKey AND state = 'IN_PROGRESS' AND request_fingerprint = :requestFingerprint AND claimed_at < :claimedBefore + AND claim_attempt = :readAttempt """, nativeQuery = true) int tryReclaimStale( @Param("storageKey") String storageKey, @Param("requestFingerprint") String requestFingerprint, + @Param("readAttempt") long readAttempt, @Param("claimedBefore") Instant claimedBefore, @Param("claimedAt") Instant claimedAt); + /** + * Commits the claim if attempt {@code claimAttempt} still holds it. + * + *

        One conditional update rather than load-check-save: two commits of the same claim both read + * {@code IN_PROGRESS} under load-check-save and both wrote; here PostgreSQL's row lock makes the + * second re-evaluate the condition against the first's {@code COMMITTED} row and update nothing. + * An attempt whose claim was taken over or re-claimed matches nothing for the same reason. + * + * @return one when the claim was committed, zero otherwise + */ + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Transactional + @Query( + value = + """ + UPDATE grpc_operation_ledger + SET state = 'COMMITTED', + outcome_reference = :outcomeReference, + completed_at = :completedAt + WHERE storage_key = :storageKey + AND state = 'IN_PROGRESS' + AND claim_attempt = :claimAttempt + """, + nativeQuery = true) + int tryMarkCommitted( + @Param("storageKey") String storageKey, + @Param("claimAttempt") long claimAttempt, + @Param("outcomeReference") String outcomeReference, + @Param("completedAt") Instant completedAt); + + /** + * Marks the claim terminally failed if attempt {@code claimAttempt} still holds it; the same + * conditional shape as {@link #tryMarkCommitted}. + * + * @return one when the failure was recorded, zero otherwise + */ + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Transactional + @Query( + value = + """ + UPDATE grpc_operation_ledger + SET state = 'FAILED_TERMINAL', + completed_at = :completedAt + WHERE storage_key = :storageKey + AND state = 'IN_PROGRESS' + AND claim_attempt = :claimAttempt + """, + nativeQuery = true) + int tryMarkFailed( + @Param("storageKey") String storageKey, + @Param("claimAttempt") long claimAttempt, + @Param("completedAt") Instant completedAt); + /** * Deletes up to {@code limit} finished rows that completed before {@code completedBefore}, oldest * first. Never an {@code IN_PROGRESS} row. @@ -155,9 +225,6 @@ public interface GrpcOperationLedgerRepository int deleteFinishedBefore( @Param("completedBefore") Instant completedBefore, @Param("limit") int limit); - /** Updates an existing claim after it has been loaded. */ - GrpcOperationLedgerEntity save(GrpcOperationLedgerEntity entity); - /** Reads a claim by its derived storage key. */ Optional findById(String storageKey); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java index 55d80bcd..9db0c3d8 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java @@ -1,5 +1,6 @@ package dev.caskeleton.grpc.ledger; +import dev.caskeleton.grpc.api.ledger.GrpcClaimToken; import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerRecord; @@ -16,6 +17,11 @@ import java.util.Optional; * {@code save}: this entity has a non-null application-assigned id, so save routes through merge * and can overwrite an existing terminal row. * + *

        Every transition — re-claim, takeover, commit, failure — is one conditional {@code UPDATE} + * that names the claim attempt ({@link GrpcClaimToken}). An attempt whose claim was handed over + * matches nothing: its commit is refused and its failure ignored, which is what keeps a takeover of + * a slow owner from becoming two concurrent runs (re-review 2026-11-03, RR-02-04). + * *

        No transaction annotations here. The commit is meant to happen inside the caller's business * transaction, and a {@code REQUIRES_NEW} on this adapter would put the ledger in its own * transaction — reintroducing the window in which the mutation is durable and the claim is not. @@ -36,6 +42,28 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { public Optional claim( GrpcOperationIdentity identity, String requestFingerprint, Instant now) { requireIdentity(identity); + // Twice at most. Zero rows means another claim holds the key; an empty read after that means + // the row went in between (a purge of an expired record, or a release). Treating that as + // "ours" would run the mutation without a claim row to guard it, so the insert is tried once + // more and decides again. + for (int round = 0; round < 2; round++) { + if (insertClaim(identity, requestFingerprint, now)) { + return Optional.empty(); + } + Optional existing = repository.findById(identity.storageKey()); + if (existing.isPresent()) { + return Optional.of(existing.get().toRecord(identity)); + } + } + throw new IllegalStateException( + "claim for '" + + identity.storageKey() + + "' conflicted twice, but there was no row to read either time; another owner keeps" + + " releasing it. Retry the claim."); + } + + private boolean insertClaim( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { int inserted = repository.tryInsertClaim( identity.storageKey(), @@ -44,25 +72,10 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { identity.idempotencyKeyHash(), requestFingerprint, now); - if (inserted == 1) { - return Optional.empty(); - } - if (inserted != 0) { + if (inserted != 0 && inserted != 1) { throw new IllegalStateException("claim insert affected an unexpected row count: " + inserted); } - // Zero rows means another claim holds the key. An empty read now means that owner released it - // in between; treating that as "ours" would run the mutation without a claim row to guard it. - return Optional.of( - repository - .findById(identity.storageKey()) - .orElseThrow( - () -> - new IllegalStateException( - "claim for '" - + identity.storageKey() - + "' conflicted, but there was no row to read; the other owner released" - + " it in between. Retry the claim.")) - .toRecord(identity)); + return inserted == 1; } @Override @@ -71,10 +84,30 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { return repository.findById(identity.storageKey()).map(entity -> entity.toRecord(identity)); } + /** + * Commits the claim if {@code claimToken} still holds it, as one conditional update. + * + *

        When nothing matched, the row is read only to say why; the refusal itself was the + * database's, and the exception is what rolls back the caller's business transaction. + */ @Override - public void markCommitted(GrpcOperationIdentity identity, String outcomeReference, Instant now) { + public void markCommitted( + GrpcOperationIdentity identity, + GrpcClaimToken claimToken, + String outcomeReference, + Instant now) { requireIdentity(identity); - GrpcOperationLedgerEntity entity = + requireToken(claimToken); + if (outcomeReference == null || outcomeReference.isBlank()) { + throw new IllegalArgumentException( + "a commit records the outcome to replay; without it the row cannot answer a retry"); + } + if (repository.tryMarkCommitted( + identity.storageKey(), claimToken.attempt(), outcomeReference, now) + == 1) { + return; + } + GrpcOperationLedgerEntity current = repository .findById(identity.storageKey()) .orElseThrow( @@ -84,31 +117,54 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { + identity.storageKey() + "': no claim exists. The claim is what a retry reads; committing " + "without one leaves the mutation durable and unguarded.")); - entity.markCommitted(outcomeReference, now); - repository.save(entity); + if (!current.getClaimToken().equals(claimToken)) { + throw new IllegalStateException( + "operation '" + + identity.storageKey() + + "' is no longer held by attempt " + + claimToken.attempt() + + "; attempt " + + current.getClaimToken().attempt() + + " holds it, so this attempt's transaction must roll back"); + } + throw new IllegalStateException( + "operation '" + + identity.storageKey() + + "' is already " + + current.getState() + + " and cannot transition again"); } @Override - public void markFailed(GrpcOperationIdentity identity, Instant now) { + public boolean markFailed( + GrpcOperationIdentity identity, GrpcClaimToken claimToken, Instant now) { requireIdentity(identity); - repository - .findById(identity.storageKey()) - .ifPresent( - entity -> { - entity.markFailed(now); - repository.save(entity); - }); + requireToken(claimToken); + return repository.tryMarkFailed(identity.storageKey(), claimToken.attempt(), now) == 1; } + /** + * Re-claims a failed record. Conditional on the attempt read just before, so the new token is + * known exactly: that attempt plus one. A record that changed in between matches nothing, and + * this caller has lost the race it would have lost anyway. + */ @Override - public boolean reclaimFailed( + public Optional reclaimFailed( GrpcOperationIdentity identity, String requestFingerprint, Instant now) { requireIdentity(identity); - return repository.tryReclaimFailed(identity.storageKey(), requestFingerprint, now) == 1; + Optional read = currentToken(identity); + if (read.isEmpty()) { + return Optional.empty(); + } + return repository.tryReclaimFailed( + identity.storageKey(), requestFingerprint, read.get().attempt(), now) + == 1 + ? Optional.of(read.get().next()) + : Optional.empty(); } @Override - public boolean reclaimStale( + public Optional reclaimStale( GrpcOperationIdentity identity, String requestFingerprint, Instant claimedBefore, @@ -118,8 +174,19 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { throw new IllegalArgumentException( "a stale-claim cutoff after now would leave the new claim stale as well"); } - return repository.tryReclaimStale(identity.storageKey(), requestFingerprint, claimedBefore, now) - == 1; + Optional read = currentToken(identity); + if (read.isEmpty()) { + return Optional.empty(); + } + return repository.tryReclaimStale( + identity.storageKey(), requestFingerprint, read.get().attempt(), claimedBefore, now) + == 1 + ? Optional.of(read.get().next()) + : Optional.empty(); + } + + private Optional currentToken(GrpcOperationIdentity identity) { + return repository.findById(identity.storageKey()).map(GrpcOperationLedgerEntity::getClaimToken); } @Override @@ -139,6 +206,12 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { repository.deleteById(identity.storageKey()); } + private static void requireToken(GrpcClaimToken claimToken) { + if (claimToken == null) { + throw new IllegalArgumentException("a transition names the attempt that holds the claim"); + } + } + private static void requireIdentity(GrpcOperationIdentity identity) { if (identity == null) { throw new IllegalArgumentException("an operation identity is required"); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V003__add_grpc_operation_ledger_claim_attempt.sql b/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V003__add_grpc_operation_ledger_claim_attempt.sql new file mode 100644 index 00000000..23b03687 --- /dev/null +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V003__add_grpc_operation_ledger_claim_attempt.sql @@ -0,0 +1,20 @@ +-- Claim attempts: the fencing token of the operation ledger (re-review 2026-11-03, RR-02-04). +-- +-- A claim changes hands when a stale one is taken over after the claim TTL or a failed one is +-- re-claimed. The owner that lost it may still be running, and when it finishes it records an +-- outcome. Without knowing which attempt holds the claim, that record landed on the new attempt's +-- claim: an old owner's failure turned a running attempt FAILED_TERMINAL, the next retry re-claimed +-- it, and two attempts ran the mutation at once. +-- +-- claim_attempt is 1 for the first claim and grows by one with every hand-over. A commit or a +-- failure is one conditional UPDATE that names the attempt (WHERE state = 'IN_PROGRESS' AND +-- claim_attempt = :attempt), so a lost owner's record changes nothing and two commits of the same +-- attempt have one winner. +-- +-- Existing rows are their first attempt: no row has been handed over under a token yet. The table is +-- small and the platform is not adopted anywhere, so a plain ALTER with a default is enough. +ALTER TABLE grpc_operation_ledger + ADD COLUMN claim_attempt BIGINT NOT NULL DEFAULT 1; + +ALTER TABLE grpc_operation_ledger + ADD CONSTRAINT ck_grpc_operation_ledger_claim_attempt_positive CHECK (claim_attempt > 0); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java b/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java index e3aada69..f2f90758 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.grpc.api.ledger.GrpcClaimToken; import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerRecord; @@ -34,12 +35,12 @@ class GrpcOperationLedgerRepositoryTest { "sha256:aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"; /** - * An in-memory stand-in for Spring Data's non-null-id save semantics. + * An in-memory stand-in for the repository's native statements. * - *

        A newly constructed ledger entity already has its string id, so a real {@code - * SimpleJpaRepository.save} treats it as detached and merges it. The old fake used {@code - * putIfAbsent} and therefore tested the database constraint we wished save() would hit rather - * than the merge behavior it actually uses. + *

        The insert is {@code putIfAbsent}, the stand-in for the unique constraint. The commit and + * failure are the entity's own transition rules, which state the conditions the native {@code + * UPDATE}s carry (state {@code IN_PROGRESS} and the same claim attempt); a refused transition + * updates zero rows. The re-claims and the purge are certified against PostgreSQL only. */ private static class InMemoryRepository implements GrpcOperationLedgerRepository { private final ConcurrentMap rows = new ConcurrentHashMap<>(); @@ -61,14 +62,19 @@ class GrpcOperationLedgerRepositoryTest { } @Override - public int tryReclaimFailed(String storageKey, String requestFingerprint, Instant claimedAt) { + public int tryReclaimFailed( + String storageKey, String requestFingerprint, long readAttempt, Instant claimedAt) { throw new UnsupportedOperationException( "the re-claim is certified against PostgreSQL by JpaGrpcOperationLedgerContractIT"); } @Override public int tryReclaimStale( - String storageKey, String requestFingerprint, Instant claimedBefore, Instant claimedAt) { + String storageKey, + String requestFingerprint, + long readAttempt, + Instant claimedBefore, + Instant claimedAt) { throw new UnsupportedOperationException( "the stale takeover is certified against PostgreSQL by JpaGrpcOperationLedgerContractIT"); } @@ -80,9 +86,32 @@ class GrpcOperationLedgerRepositoryTest { } @Override - public GrpcOperationLedgerEntity save(GrpcOperationLedgerEntity entity) { - rows.put(entity.getStorageKey(), entity); - return entity; + public int tryMarkCommitted( + String storageKey, long claimAttempt, String outcomeReference, Instant completedAt) { + GrpcOperationLedgerEntity row = rows.get(storageKey); + if (row == null) { + return 0; + } + try { + row.markCommitted(new GrpcClaimToken(claimAttempt), outcomeReference, completedAt); + return 1; + } catch (IllegalStateException refused) { + return 0; + } + } + + @Override + public int tryMarkFailed(String storageKey, long claimAttempt, Instant completedAt) { + GrpcOperationLedgerEntity row = rows.get(storageKey); + if (row == null) { + return 0; + } + try { + row.markFailed(new GrpcClaimToken(claimAttempt), completedAt); + return 1; + } catch (IllegalStateException refused) { + return 0; + } } @Override @@ -139,6 +168,7 @@ class GrpcOperationLedgerRepositoryTest { } @Test + @DisplayName("충돌한 행이 다시 시도해도 계속 사라지면 소유로 보지 않고 거부한다") void aConflictWhoseRowVanishedBeforeTheReadIsNotTakenAsOwnership() { // given InMemoryRepository conflictThenReleased = @@ -166,6 +196,54 @@ class GrpcOperationLedgerRepositoryTest { .hasMessageContaining("no row to read"); } + /** + * A purge (or release) can delete the conflicting row between the insert and the read. The read + * then finds nothing, and the claim tries the insert once more instead of failing the call + * (re-review 2026-11-03, RR-02-04). + */ + @Test + @DisplayName("충돌한 행이 읽기 전에 사라지면 claim 은 insert 를 한 번 더 시도해 소유한다") + void aConflictWhoseRowVanishedOnceIsClaimedByTheRetriedInsert() { + // given + InMemoryRepository conflictOnceThenFree = + new InMemoryRepository() { + private boolean conflicted; + + @Override + public int tryInsertClaim( + String storageKey, + String callerFingerprint, + String fullMethodName, + String idempotencyKeyHash, + String requestFingerprint, + Instant claimedAt) { + if (!conflicted) { + conflicted = true; + return 0; // a row held the key and was purged before this read + } + return super.tryInsertClaim( + storageKey, + callerFingerprint, + fullMethodName, + idempotencyKeyHash, + requestFingerprint, + claimedAt); + } + }; + GrpcOperationLedger racing = new JpaGrpcOperationLedger(conflictOnceThenFree); + + // when + Optional existing = + racing.claim(identity("tenant-1.actor-1"), FINGERPRINT, NOW); + + // then + assertThat(existing).isEmpty(); + assertThat(racing.find(identity("tenant-1.actor-1"))) + .get() + .extracting(GrpcOperationLedgerRecord::state, GrpcOperationLedgerRecord::claimToken) + .containsExactly(GrpcOperationLedgerState.IN_PROGRESS, GrpcClaimToken.FIRST); + } + @Test @DisplayName("one caller's key does not collide with another's") void callersDoNotCollide() { @@ -179,7 +257,7 @@ class GrpcOperationLedgerRepositoryTest { GrpcOperationIdentity id = identity("tenant-1.actor-1"); ledger.claim(id, FINGERPRINT, NOW); - ledger.markCommitted(id, "outcome://document/42", NOW.plusSeconds(1)); + ledger.markCommitted(id, GrpcClaimToken.FIRST, "outcome://document/42", NOW.plusSeconds(1)); GrpcOperationLedgerRecord record = ledger.find(id).orElseThrow(); assertThat(record.state()).isEqualTo(GrpcOperationLedgerState.COMMITTED); @@ -192,7 +270,7 @@ class GrpcOperationLedgerRepositoryTest { void retryingACommittedClaimPreservesTheWinner() { GrpcOperationIdentity id = identity("tenant-1.actor-1"); assertThat(ledger.claim(id, FINGERPRINT, NOW)).isEmpty(); - ledger.markCommitted(id, "outcome://document/42", NOW.plusSeconds(1)); + ledger.markCommitted(id, GrpcClaimToken.FIRST, "outcome://document/42", NOW.plusSeconds(1)); GrpcOperationLedgerRecord retry = ledger.claim(id, OTHER_FINGERPRINT, NOW.plusSeconds(2)).orElseThrow(); @@ -206,7 +284,12 @@ class GrpcOperationLedgerRepositoryTest { @DisplayName("a commit without a claim is refused rather than silently inserted") void committingWithoutAClaimIsRefused() { assertThatThrownBy( - () -> ledger.markCommitted(identity("tenant-1.actor-1"), "outcome://document/42", NOW)) + () -> + ledger.markCommitted( + identity("tenant-1.actor-1"), + GrpcClaimToken.FIRST, + "outcome://document/42", + NOW)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("durable and unguarded"); } @@ -216,9 +299,12 @@ class GrpcOperationLedgerRepositoryTest { void aTerminalRowDoesNotTransitionAgain() { GrpcOperationIdentity id = identity("tenant-1.actor-1"); ledger.claim(id, FINGERPRINT, NOW); - ledger.markCommitted(id, "outcome://document/42", NOW.plusSeconds(1)); + ledger.markCommitted(id, GrpcClaimToken.FIRST, "outcome://document/42", NOW.plusSeconds(1)); - assertThatThrownBy(() -> ledger.markCommitted(id, "outcome://document/99", NOW.plusSeconds(2))) + assertThatThrownBy( + () -> + ledger.markCommitted( + id, GrpcClaimToken.FIRST, "outcome://document/99", NOW.plusSeconds(2))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("cannot transition again"); } @@ -240,7 +326,7 @@ class GrpcOperationLedgerRepositoryTest { GrpcOperationIdentity id = identity("tenant-1.actor-1"); ledger.claim(id, FINGERPRINT, NOW); - ledger.markFailed(id, NOW.plusSeconds(1)); + ledger.markFailed(id, GrpcClaimToken.FIRST, NOW.plusSeconds(1)); assertThat(ledger.find(id).orElseThrow().state()) .isEqualTo(GrpcOperationLedgerState.FAILED_TERMINAL); @@ -259,7 +345,8 @@ class GrpcOperationLedgerRepositoryTest { FINGERPRINT, Optional.empty(), NOW, - Optional.of(NOW))) + Optional.of(NOW), + GrpcClaimToken.FIRST)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("cannot be replayed"); } diff --git a/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyDecision.java b/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyDecision.java index ecc9f400..ca7ebef1 100644 --- a/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyDecision.java +++ b/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyDecision.java @@ -1,5 +1,6 @@ package dev.caskeleton.grpc.idempotency; +import dev.caskeleton.grpc.api.ledger.GrpcClaimToken; import java.time.Duration; import java.util.Optional; @@ -10,9 +11,18 @@ import java.util.Optional; * duplicate". A duplicate of a committed operation should be answered with the original result; a * duplicate of a running one is a race that has to wait or be refused; and a key reused for a * different request is a caller bug that must be reported rather than absorbed. + * + *

        A {@code PROCEED} that won a claim carries the claim's {@link GrpcClaimToken}. The caller + * hands it back to {@code recordCommit} or {@code recordFailure}: the ledger records an outcome + * only for the attempt that still holds the claim, so a caller whose claim was taken over cannot + * write over the attempt that took it (re-review 2026-11-03, RR-02-04). */ public record GrpcIdempotencyDecision( - Outcome outcome, Optional outcomeReference, Duration retryAfter, String reason) { + Outcome outcome, + Optional outcomeReference, + Duration retryAfter, + String reason, + Optional claimToken) { /** The five ways an idempotency check can end. */ public enum Outcome { @@ -48,11 +58,31 @@ public record GrpcIdempotencyDecision( if (outcome == Outcome.WAIT_AND_POLL && retryAfter.isZero()) { throw new IllegalArgumentException("a WAIT_AND_POLL decision says how long to wait"); } + if (claimToken == null) { + throw new IllegalArgumentException("the claim token Optional must be present"); + } + if (outcome != Outcome.PROCEED && claimToken.isPresent()) { + throw new IllegalArgumentException("only a PROCEED decision can hold a claim"); + } } - /** Proceed with the operation. */ + /** Proceed with an operation that is not claimed: the method takes no idempotency key. */ public static GrpcIdempotencyDecision proceed(String reason) { - return new GrpcIdempotencyDecision(Outcome.PROCEED, Optional.empty(), Duration.ZERO, reason); + return new GrpcIdempotencyDecision( + Outcome.PROCEED, Optional.empty(), Duration.ZERO, reason, Optional.empty()); + } + + /** + * Proceed as the attempt that holds the claim. + * + * @param claimToken the token to hand back when recording the commit or the failure + */ + public static GrpcIdempotencyDecision proceedHolding(GrpcClaimToken claimToken, String reason) { + if (claimToken == null) { + throw new IllegalArgumentException("a claimed PROCEED carries its claim token"); + } + return new GrpcIdempotencyDecision( + Outcome.PROCEED, Optional.empty(), Duration.ZERO, reason, Optional.of(claimToken)); } /** Replay a stored outcome. */ @@ -61,13 +91,18 @@ public record GrpcIdempotencyDecision( Outcome.REPLAY, Optional.of(outcomeReference), Duration.ZERO, - "an identical request already committed; returning the stored outcome"); + "an identical request already committed; returning the stored outcome", + Optional.empty()); } /** Wait and poll for an in-progress claim. */ public static GrpcIdempotencyDecision waitAndPoll(Duration retryAfter) { return new GrpcIdempotencyDecision( - Outcome.WAIT_AND_POLL, Optional.empty(), retryAfter, "an identical request is in progress"); + Outcome.WAIT_AND_POLL, + Optional.empty(), + retryAfter, + "an identical request is in progress", + Optional.empty()); } /** Refuse a duplicate of an in-progress claim. */ @@ -76,7 +111,8 @@ public record GrpcIdempotencyDecision( Outcome.REJECT_IN_PROGRESS, Optional.empty(), Duration.ZERO, - "an identical request is in progress and this method does not wait for it"); + "an identical request is in progress and this method does not wait for it", + Optional.empty()); } /** Report a key reused for a different request. */ @@ -85,7 +121,8 @@ public record GrpcIdempotencyDecision( Outcome.FINGERPRINT_MISMATCH, Optional.empty(), Duration.ZERO, - "the idempotency key was already used for a different request"); + "the idempotency key was already used for a different request", + Optional.empty()); } /** Whether the use case should run. */ diff --git a/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java b/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java index b48d9a65..5387ffa2 100644 --- a/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java +++ b/src/grpc/grpc-runtime/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java @@ -1,5 +1,6 @@ package dev.caskeleton.grpc.idempotency; +import dev.caskeleton.grpc.api.ledger.GrpcClaimToken; import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerRecord; @@ -21,7 +22,9 @@ import java.util.Optional; * *

        A claim does not block its key forever. One still {@code IN_PROGRESS} after the claim TTL is * treated as abandoned by a dead owner and taken over by the next retry of the same request — one - * winner, like the re-claim of a terminal failure. + * winner, like the re-claim of a terminal failure. The owner taken over may only have been slow; it + * still holds the old {@link GrpcClaimToken}, so its later commit is refused and its later failure + * ignored instead of landing on the attempt that took the claim. * *

        The ordering matters and is easy to get subtly wrong. The claim is attempted first, * atomically; only then is the existing record examined. Reading first and claiming second leaves a @@ -124,7 +127,8 @@ public final class GrpcIdempotencyInterceptor { callerFingerprint, method, GrpcRequestFingerprint.hashIdempotencyKey(idempotencyKey)); Optional existing = ledger.claim(identity, requestFingerprint, now); if (existing.isEmpty()) { - return GrpcIdempotencyDecision.proceed("claimed; this caller owns the operation"); + return GrpcIdempotencyDecision.proceedHolding( + GrpcClaimToken.FIRST, "claimed; this caller owns the operation"); } GrpcOperationLedgerRecord record = existing.get(); @@ -142,24 +146,32 @@ public final class GrpcIdempotencyInterceptor { + identity.storageKey() + "' has no outcome reference to replay"))); } - if (record.state() == GrpcOperationLedgerState.FAILED_TERMINAL - && ledger.reclaimFailed(identity, requestFingerprint, now)) { + if (record.state() == GrpcOperationLedgerState.FAILED_TERMINAL) { // A terminal failure is not replayed: the caller asked for the operation, it did not happen, // and repeating it is exactly what the key makes safe — but only for the one retry that // re-claims the row. Proceeding unclaimed runs concurrent retries twice and leaves the // commit without an owner. - return GrpcIdempotencyDecision.proceed( - "the previous attempt failed terminally; this caller re-claimed it for a new attempt"); + Optional reclaimed = ledger.reclaimFailed(identity, requestFingerprint, now); + if (reclaimed.isPresent()) { + return GrpcIdempotencyDecision.proceedHolding( + reclaimed.get(), + "the previous attempt failed terminally; this caller re-claimed it for a new attempt"); + } } if (record.state() == GrpcOperationLedgerState.IN_PROGRESS) { Instant cutoff = now.minus(claimTtl); - if (record.claimedAt().isBefore(cutoff) - && ledger.reclaimStale(identity, requestFingerprint, cutoff, now)) { - // The owner outlived the TTL without committing or failing, so it is presumed dead. Its - // mutation did not commit if the commit was recorded in the mutation's own transaction, - // which the ledger contract requires; when an adopter commits them separately, the - // abandoned attempt's outcome is unknown and this re-run can duplicate it. - return GrpcIdempotencyDecision.proceed( + // The owner outlived the TTL without committing or failing, so it is presumed dead. Its + // mutation did not commit if the commit was recorded in the mutation's own transaction, + // which the ledger contract requires; when an adopter commits them separately, the + // abandoned attempt's outcome is unknown and this re-run can duplicate it. An owner that was + // only slow is fenced by the new claim token: its commit is refused, its failure ignored. + Optional takenOver = + record.claimedAt().isBefore(cutoff) + ? ledger.reclaimStale(identity, requestFingerprint, cutoff, now) + : Optional.empty(); + if (takenOver.isPresent()) { + return GrpcIdempotencyDecision.proceedHolding( + takenOver.get(), "the previous claim was abandoned (older than the " + claimTtl + " claim TTL); this caller took it over for a new attempt"); @@ -178,26 +190,42 @@ public final class GrpcIdempotencyInterceptor { *

        Called from inside the business transaction wherever the datastore permits it. A ledger * committed after the mutation leaves a window in which the write is durable and the claim is * not. + * + * @param claimToken the token of the {@code PROCEED} decision this attempt ran under + * @throws IllegalStateException when this attempt no longer holds the claim — another attempt + * took it over — so the business transaction rolls back instead of committing a second run */ public void recordCommit( GrpcMethodName method, String callerFingerprint, String idempotencyKey, + GrpcClaimToken claimToken, String outcomeReference, Instant now) { ledger.markCommitted( new GrpcOperationIdentity( callerFingerprint, method, GrpcRequestFingerprint.hashIdempotencyKey(idempotencyKey)), + claimToken, outcomeReference, now); } - /** Records a terminal failure against the claim. */ - public void recordFailure( - GrpcMethodName method, String callerFingerprint, String idempotencyKey, Instant now) { - ledger.markFailed( + /** + * Records a terminal failure against the claim, if this attempt still holds it. + * + * @param claimToken the token of the {@code PROCEED} decision this attempt ran under + * @return false when another attempt holds the claim now; its run is not failed by this one + */ + public boolean recordFailure( + GrpcMethodName method, + String callerFingerprint, + String idempotencyKey, + GrpcClaimToken claimToken, + Instant now) { + return ledger.markFailed( new GrpcOperationIdentity( callerFingerprint, method, GrpcRequestFingerprint.hashIdempotencyKey(idempotencyKey)), + claimToken, now); } } diff --git a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java index 90c34214..dd500825 100644 --- a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java +++ b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.grpc.idempotency; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.grpc.api.ledger.GrpcClaimToken; import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; import dev.caskeleton.grpc.api.ledger.InMemoryOperationLedger; import dev.caskeleton.grpc.core.GrpcMethodName; @@ -42,8 +43,11 @@ class GrpcCompletionReconcilerTest { GrpcCompletionReconciler reconciler = new GrpcCompletionReconciler(query); claim(); reconciler.reconcile(CREATE, CALLER, KEY, null); - ledger.reclaimStale(identity, fingerprint, afterTtl.minus(Duration.ofMinutes(5)), afterTtl); - ledger.markCommitted(identity, "outcome://document/42", afterTtl.plusSeconds(1)); + GrpcClaimToken takenOver = + ledger + .reclaimStale(identity, fingerprint, afterTtl.minus(Duration.ofMinutes(5)), afterTtl) + .orElseThrow(); + ledger.markCommitted(identity, takenOver, "outcome://document/42", afterTtl.plusSeconds(1)); // when GrpcCompletionResolution nextPass = reconciler.reconcile(CREATE, CALLER, KEY, null); @@ -93,6 +97,7 @@ class GrpcCompletionReconcilerTest { ledger.markCommitted( new dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity( CALLER, CREATE, GrpcRequestFingerprint.hashIdempotencyKey(KEY)), + GrpcClaimToken.FIRST, "outcome://document/42", NOW.plusSeconds(1)); @@ -116,6 +121,7 @@ class GrpcCompletionReconcilerTest { ledger.markCommitted( new dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity( CALLER, CREATE, GrpcRequestFingerprint.hashIdempotencyKey(KEY)), + GrpcClaimToken.FIRST, "outcome://from-ledger", NOW.plusSeconds(1)); GrpcCompletionReconciler reconciler = new GrpcCompletionReconciler(query); diff --git a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java index df26ea21..99fa0687 100644 --- a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java +++ b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile; +import dev.caskeleton.grpc.api.ledger.GrpcClaimToken; import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerRecord; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerState; @@ -98,8 +99,10 @@ class GrpcIdempotencyInterceptorTest { void aDuplicateOfACommittedOperationReplays() { GrpcIdempotencyInterceptor interceptor = interceptor(false); String fingerprint = GrpcRequestFingerprint.of("body"); - interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); - interceptor.recordCommit(CREATE, CALLER, KEY, "outcome://document/42", NOW.plusSeconds(1)); + GrpcClaimToken claim = + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW).claimToken().orElseThrow(); + interceptor.recordCommit( + CREATE, CALLER, KEY, claim, "outcome://document/42", NOW.plusSeconds(1)); GrpcIdempotencyDecision replayed = interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW.plusSeconds(2)); @@ -139,8 +142,9 @@ class GrpcIdempotencyInterceptorTest { void aTerminallyFailedOperationMayBeRetried() { GrpcIdempotencyInterceptor interceptor = interceptor(false); String fingerprint = GrpcRequestFingerprint.of("body"); - interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); - interceptor.recordFailure(CREATE, CALLER, KEY, NOW.plusSeconds(1)); + GrpcClaimToken claim = + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW).claimToken().orElseThrow(); + interceptor.recordFailure(CREATE, CALLER, KEY, claim, NOW.plusSeconds(1)); assertThat(interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW.plusSeconds(2)).outcome()) .isEqualTo(GrpcIdempotencyDecision.Outcome.PROCEED); @@ -151,8 +155,9 @@ class GrpcIdempotencyInterceptorTest { // given GrpcIdempotencyInterceptor interceptor = interceptor(false); String fingerprint = GrpcRequestFingerprint.of("body"); - interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); - interceptor.recordFailure(CREATE, CALLER, KEY, NOW.plusSeconds(1)); + GrpcClaimToken claim = + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW).claimToken().orElseThrow(); + interceptor.recordFailure(CREATE, CALLER, KEY, claim, NOW.plusSeconds(1)); // when interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW.plusSeconds(2)); @@ -172,8 +177,9 @@ class GrpcIdempotencyInterceptorTest { // given GrpcIdempotencyInterceptor interceptor = interceptor(false); String fingerprint = GrpcRequestFingerprint.of("body"); - interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); - interceptor.recordFailure(CREATE, CALLER, KEY, NOW.plusSeconds(1)); + GrpcClaimToken claim = + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW).claimToken().orElseThrow(); + interceptor.recordFailure(CREATE, CALLER, KEY, claim, NOW.plusSeconds(1)); CountDownLatch start = new CountDownLatch(1); Callable retry = () -> { @@ -235,6 +241,70 @@ class GrpcIdempotencyInterceptorTest { .contains(AFTER_TTL); } + @Test + @DisplayName("claim 을 이긴 PROCEED 는 그 시도의 claim token 을 들고 있다") + void aProceedThatWonAClaimHoldsItsClaimToken() { + // given + GrpcIdempotencyInterceptor interceptor = interceptor(false); + String fingerprint = GrpcRequestFingerprint.of("body"); + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); + + // when + GrpcIdempotencyDecision takenOver = + interceptor.decide(CREATE, CALLER, KEY, fingerprint, AFTER_TTL); + + // then + assertThat(takenOver.claimToken()).contains(GrpcClaimToken.FIRST.next()); + } + + /** + * The re-review probe's sequence through the interceptor (2026-11-03, RR-02-04): A is slow, B + * takes over after the TTL, A then fails. A's failure must not free the key for C while B runs. + */ + @Test + @DisplayName("TTL 뒤 넘겨받힌 옛 owner 의 실패 기록은 무시되어 다음 재시도는 진행 중으로 거부된다") + void aFailureRecordedByTheOwnerThatLostTheClaimDoesNotLetTheNextRetryRun() { + // given + GrpcIdempotencyInterceptor interceptor = interceptor(false); + String fingerprint = GrpcRequestFingerprint.of("body"); + GrpcClaimToken first = + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW).claimToken().orElseThrow(); + interceptor.decide(CREATE, CALLER, KEY, fingerprint, AFTER_TTL); + boolean recorded = + interceptor.recordFailure(CREATE, CALLER, KEY, first, AFTER_TTL.plusSeconds(1)); + + // when + GrpcIdempotencyDecision third = + interceptor.decide(CREATE, CALLER, KEY, fingerprint, AFTER_TTL.plusSeconds(2)); + + // then + assertThat(recorded).isFalse(); + assertThat(third.outcome()).isEqualTo(GrpcIdempotencyDecision.Outcome.REJECT_IN_PROGRESS); + } + + @Test + @DisplayName("TTL 뒤 넘겨받힌 옛 owner 의 commit 은 거부되어 그 트랜잭션이 롤백된다") + void aCommitRecordedByTheOwnerThatLostTheClaimIsRefused() { + // given + GrpcIdempotencyInterceptor interceptor = interceptor(false); + String fingerprint = GrpcRequestFingerprint.of("body"); + GrpcClaimToken first = + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW).claimToken().orElseThrow(); + interceptor.decide(CREATE, CALLER, KEY, fingerprint, AFTER_TTL); + + // when + Throwable refused = + org.assertj.core.api.Assertions.catchThrowable( + () -> + interceptor.recordCommit( + CREATE, CALLER, KEY, first, "outcome://document/42", AFTER_TTL.plusSeconds(1))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no longer held"); + } + @Test @DisplayName("TTL이 지나기 직전의 중복 요청은 여전히 대기하거나 거부된다") void aDuplicateAtTheTtlBoundaryIsStillTreatedAsRunning() { diff --git a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetentionTest.java b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetentionTest.java index fca364a6..817514af 100644 --- a/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetentionTest.java +++ b/src/grpc/grpc-runtime/src/test/java/dev/caskeleton/grpc/idempotency/GrpcOperationLedgerRetentionTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.grpc.idempotency; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import dev.caskeleton.grpc.api.ledger.GrpcClaimToken; import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; import dev.caskeleton.grpc.api.ledger.InMemoryOperationLedger; import dev.caskeleton.grpc.core.GrpcMethodName; @@ -78,6 +79,7 @@ class GrpcOperationLedgerRetentionTest { // Finished at the claim moment; the completion moment is what the retention measures. private void committed(GrpcOperationIdentity identity, Instant claimedAt) { ledger.claim(identity, BODY, claimedAt); - ledger.markCommitted(identity, "outcome://document/" + identity.storageKey(), claimedAt); + ledger.markCommitted( + identity, GrpcClaimToken.FIRST, "outcome://document/" + identity.storageKey(), claimedAt); } } diff --git a/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java b/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java index a2892787..85a3ed85 100644 --- a/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java +++ b/src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java @@ -24,6 +24,11 @@ import java.util.Set; * reflection in production publishes the schema, and a keyed method without a ledger accepts * idempotency keys it cannot honour. None of them fails a smoke test. * + *

        The keyed-method rule has a limit it states in its own message: with the ledger flag on, the + * starter assembles the decision function, and the server stage that calls it is the adopter's. A + * running process cannot see whether that stage exists, so passing this check with the flag on does + * not mean keys are honoured (re-review 2026-11-03, RR-02-07; ADR-GRPC-004). + * *

        Fails once with every violation, so a deployment learns the whole list in one restart. */ public final class GrpcPlatformStartupValidator { @@ -152,7 +157,10 @@ public final class GrpcPlatformStartupValidator { "method '" + method.canonical() + "' requires an idempotency key but app.grpc.platform.operation-ledger-enabled is" - + " false; the key would be accepted and never honoured"); + + " false; the key would be accepted and never honoured. Turning the flag on" + + " assembles the decision function only: the key is honoured once the server's" + + " IDEMPOTENCY stage interceptor or the service adapter calls decide/recordCommit," + + " which this starter does not wire"); } if (!policy.rpcType().stable()) { violations.add( diff --git a/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java b/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java index a07b65b2..b3fcbd21 100644 --- a/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java +++ b/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformAutoConfigurationContextTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile; +import dev.caskeleton.grpc.api.ledger.GrpcClaimToken; import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; import dev.caskeleton.grpc.api.ledger.InMemoryOperationLedger; @@ -196,7 +197,8 @@ class GrpcPlatformAutoConfigurationContextTest { GrpcOperationIdentity identity = new GrpcOperationIdentity(CALLER, CREATE, GrpcRequestFingerprint.hashIdempotencyKey(KEY)); ledger.claim(identity, GrpcRequestFingerprint.of("body"), NOW); - ledger.markCommitted(identity, "outcome://document/42", NOW.plusSeconds(1)); + ledger.markCommitted( + identity, GrpcClaimToken.FIRST, "outcome://document/42", NOW.plusSeconds(1)); // when int purged = diff --git a/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidatorTest.java b/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidatorTest.java index dcffee91..d7307b1d 100644 --- a/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidatorTest.java +++ b/src/grpc/grpc-spring-boot-starter/src/test/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidatorTest.java @@ -200,6 +200,44 @@ class GrpcPlatformStartupValidatorTest { .anySatisfy(violation -> assertThat(violation).contains("never honoured")); } + /** + * The flag assembles the decision function only; the starter builds no server, so nothing calls + * it until the adopter's IDEMPOTENCY stage or service adapter does. The refusal must not read as + * "turn the flag on and keys are honoured" (re-review 2026-11-03, RR-02-07). + */ + @Test + @DisplayName("키 필수 메서드 거부 문구는 플래그가 결정 함수만 조립하고 서버 단계 연결은 따로라고 말한다") + void theKeyedMethodRefusalSaysTheFlagAssemblesTheDecisionOnly() { + // given + GrpcPlatformProperties properties = productionProperties(); + properties.setOperationLedgerEnabled(false); + GrpcMethodPolicyCatalog catalog = + GrpcMethodPolicyCatalog.builder() + .register( + new GrpcMethodPolicy( + CREATE, + RpcType.UNARY, + RpcIdempotencyProfile.IDEMPOTENCY_KEY_REQUIRED, + GrpcDeadlineProfile.of(Duration.ofSeconds(2)), + WaitForReadyPolicy.DISABLED, + false, + 1024, + 1024)) + .build(); + + // when + var violations = + GrpcPlatformStartupValidator.violations(properties, catalog, oneChannel(), stableServer()); + + // then + assertThat(violations) + .anySatisfy( + violation -> + assertThat(violation) + .contains("assembles the decision function only") + .contains("IDEMPOTENCY stage")); + } + @Test @DisplayName("a client-streaming method is refused as an Advanced capability") void clientStreamingIsRefusedAsAdvanced() { diff --git a/src/grpc/grpc-testkit/build.gradle b/src/grpc/grpc-testkit/build.gradle index 3387707d..7dad3194 100644 --- a/src/grpc/grpc-testkit/build.gradle +++ b/src/grpc/grpc-testkit/build.gradle @@ -5,8 +5,9 @@ plugins { // Certification. The Stable plan splits this across four modules (core / in-process / netty / // fault); this repository already expresses "these two runs are not the same kind of evidence" with // strict test lanes rather than with module boundaries, so the four become four lanes over one -// leaf (adaptation design §2). A lane that discovers nothing fails, and none of them can serve an -// up-to-date result — which is the property the split was protecting. +// leaf (adaptation design §2). A lane that discovers nothing fails, and the three hermetic lanes +// reuse a result only when their classes and their lane policy are unchanged — the performance lane +// never does. That is the property the split was protecting. strictTestLanes { lane('grpcInProcessContractTest') { @@ -33,8 +34,8 @@ strictTestLanes { } // The performance lane is excluded from the default `test` task. It measures a running server -// under load, and a measurement in the release gate is a flaky test on a shared CI runner; it runs -// when somebody asks for it, by name. +// under load, so it is not in the pull-request or release gate; it runs in the optional build's +// `performanceCheck`, which integration-main.yml's performance-check job runs on main and nightly. tasks.named('test') { useJUnitPlatform { excludeTags 'grpc-performance' diff --git a/src/messaging/CLAUDE.md b/src/messaging/CLAUDE.md index 8c8d2acf..931c282e 100644 --- a/src/messaging/CLAUDE.md +++ b/src/messaging/CLAUDE.md @@ -40,6 +40,31 @@ JDBC이고 SQL은 `jsonb` · `FOR UPDATE SKIP LOCKED` · `ON CONFLICT` · `TIMES registry edge를 주면 그 경계가 깨진다. 복사본을 고칠 때(키 길이 검사, constant-time 비교 등)는 `shared-contract`의 정본과 같은 규칙인지 함께 본다. +### Publish retryability of authentication and authorization (review 2026-11-01 06-01) + +이 제품 안에는 같은 category에 대한 재시도 규칙이 둘 있다. 의도다. + +- category 기본값: `FailureDescriptor.defaultRetryable(AUTHENTICATION | AUTHORIZATION) = false`. 소비 쪽 + 재시도 엔진(`DefaultRetryDecisionEngine`)은 policy가 category를 따로 정하지 않으면 이 기본값과 + descriptor의 `retryable`을 둘 다 요구한다. 그래서 인가받지 못한 메시지의 재전달은 지금도 재시도하지 않는다. +- publish 거부의 `retryable`: `KafkaPublishFailureClassifier`는 인증·인가 거부에 `retryable = true`를 붙인다. + broker가 레코드를 저장하지 않았고, credential 교체나 application보다 늦게 배포된 ACL은 몇 분 동안 모든 + publish를 거부한 뒤 멈추기 때문이다. `retryable`을 믿는 publisher가 그 몇 분 동안의 레코드를 영구 보류하지 + 않게 하려는 것이다. + +06-01 수정이 이 제품에서 바꾼 것(모두 publish 경로, 소비 경로 동작은 그대로): + +- `KafkaPublishFailureClassifier`: 인증·인가 거부를 `retryable = true`로. +- `DefaultMessagePublisher`: runtime이 없을 때의 거부(`PUBLISH_RUNTIME_UNAVAILABLE`)를 `retryable = true`로. +- `KafkaMessagingTransport`: 닫힌 transport의 거부(`KAFKA_TRANSPORT_CLOSED`)를 `retryable = true`로. +- `MessagingShutdownLifecycle.PHASE`: platform 밖 relay의 순서 테스트가 참조하도록 public. + +버린 대안: vendored 제품은 그대로 두고 application bridge(ACL)가 category를 보고 "인증·인가면 재시도"로 +번역하는 것. 버린 이유: `retryable`은 이 제품이 "같은 레코드를 나중에 다시 보내면 받아질 수 있나"를 말하는 +자리다. bridge가 category로 그 판단을 다시 하면 같은 사실을 제품과 bridge가 따로 정하고, 이 제품의 +`PublishResult`를 읽는 다른 호출자는 bridge와 다른 답을 본다. 대신 이 제품 주석은 소비자 이름(application +relay, `composition:outbox-relay`)을 부르지 않는다 — "flag를 믿는 publisher"로 쓴다(재리뷰 2026-11-03 RR-05-07). + ## Public surface 정책 - **vendor 타입을 public signature에 노출하면 그 의존성은 `api`로 선언한다.** 숨긴다고 타입이 diff --git a/src/messaging/messaging-core-api/src/main/java/dev/caskeleton/messaging/api/error/FailureDescriptor.java b/src/messaging/messaging-core-api/src/main/java/dev/caskeleton/messaging/api/error/FailureDescriptor.java index 5c00b102..ff8dd47a 100644 --- a/src/messaging/messaging-core-api/src/main/java/dev/caskeleton/messaging/api/error/FailureDescriptor.java +++ b/src/messaging/messaging-core-api/src/main/java/dev/caskeleton/messaging/api/error/FailureDescriptor.java @@ -61,6 +61,14 @@ public record FailureDescriptor( * automatically: each of them fails identically on every redelivery, so retrying only multiplies * the load while the message is still poison. * + *

        A default, not a rule every descriptor follows. A publish rejection may carry {@code + * retryable = true} with an authentication or authorization category: the broker did not store + * the record, and a credential being rotated or an ACL deployed after the application refuses + * every publish for a few minutes and then stops (the Kafka publish classifier). The + * consumer-side retry engine requires this default as well as the flag unless its policy names + * the category, so redelivery of an unauthorised message is still not retried; only a publisher + * that reads {@link #retryable()} sees the difference. + * * @param category the classification * @return true when automatic retry is allowed by default */ diff --git a/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaConsumerRegistrar.java b/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaConsumerRegistrar.java index 4b85f2fc..4e96018c 100644 --- a/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaConsumerRegistrar.java +++ b/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaConsumerRegistrar.java @@ -344,10 +344,17 @@ public final class KafkaConsumerRegistrar implements TransportConsumerRegistrati // A decode failure is not a handler failure and must not be retried forever. The // offset may only advance once the record exists somewhere else, so an unavailable // quarantine leaves it uncommitted rather than dropping the message. - if (quarantine.quarantine(record, undecodable)) { + // It will never decode, however often it is redriven: DESERIALIZATION, not the + // POISON_MESSAGE of a handler that ran out of attempts (review 2026-11-01 06-14). + if (quarantine.quarantine( + record, + dev.caskeleton.messaging.api.error.FailureCategory.DESERIALIZATION, + undecodable)) { settlement.acknowledgeAfterQuarantine(); } else { - settlement.requeueAfterFailure(undecodable); + settlement.requeueAfterFailure( + undecodable, + dev.caskeleton.messaging.api.error.FailureCategory.DESERIALIZATION); } coordinator.release(partition); shutdown.endWork(); @@ -682,6 +689,7 @@ public final class KafkaConsumerRegistrar implements TransportConsumerRegistrati retryOrQuarantine( new IllegalStateException( "the handler asked for another attempt and the retry budget is spent"), + dev.caskeleton.messaging.api.error.FailureCategory.POISON_MESSAGE, delay)); } @@ -715,11 +723,21 @@ public final class KafkaConsumerRegistrar implements TransportConsumerRegistrati * that exists nowhere else — which is why a production destination must have one. */ private void requeueAfterFailure(Throwable reason) { + requeueAfterFailure(reason, exhaustedCategory(reason)); + } + + /** + * {@link #requeueAfterFailure(Throwable)} under a category the caller already knows: a record + * that could not be decoded stays {@code DESERIALIZATION} when its first quarantine write was + * not confirmed and it reaches quarantine again through the retry path. + */ + private void requeueAfterFailure( + Throwable reason, dev.caskeleton.messaging.api.error.FailureCategory category) { if (!terminal.compareAndSet(null, "requeue")) { // The handler settled before it failed or before its late completion; that answer stands. return; } - retryOrQuarantine(reason, Duration.ZERO); + retryOrQuarantine(reason, category, Duration.ZERO); } /** @@ -730,11 +748,13 @@ public final class KafkaConsumerRegistrar implements TransportConsumerRegistrati * being retried — the offset may not advance past a message that exists nowhere else. */ private dev.caskeleton.messaging.api.settlement.SettlementResult retryOrQuarantine( - Throwable reason, Duration requested) { + Throwable reason, + dev.caskeleton.messaging.api.error.FailureCategory category, + Duration requested) { FailedOffset key = new FailedOffset(partition, offset); int attempt = failures.merge(key, 1, Integer::sum); dev.caskeleton.messaging.policy.RetryPolicy retry = spec.profile().retry(); - if (attempt >= retry.maxAttempts() && quarantine.quarantine(record, reason)) { + if (attempt >= retry.maxAttempts() && quarantine.quarantine(record, category, reason)) { failures.remove(key); settlements.enqueue( new KafkaSettlementCommand( @@ -751,6 +771,19 @@ public final class KafkaConsumerRegistrar implements TransportConsumerRegistrati return enqueueRequeue(backoff); } + /** + * The category a record that ran out of attempts is quarantined under: its last failure's own, + * when that failure is a platform one and so carries a classification — a transient one tells a + * redrive the record may pass now — and {@code POISON_MESSAGE}, the platform's name for "keeps + * failing its consumer", when it is not. + */ + private static dev.caskeleton.messaging.api.error.FailureCategory exhaustedCategory( + Throwable reason) { + return reason instanceof dev.caskeleton.messaging.api.error.MessagingException classified + ? classified.category() + : dev.caskeleton.messaging.api.error.FailureCategory.POISON_MESSAGE; + } + private dev.caskeleton.messaging.api.settlement.SettlementResult enqueueRequeue( Duration delay) { retries.pauseUntil(partition, offset, delay, clock.instant()); diff --git a/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifier.java b/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifier.java index 0eea955a..d6569fdc 100644 --- a/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifier.java +++ b/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaPublishFailureClassifier.java @@ -67,10 +67,14 @@ public final class KafkaPublishFailureClassifier { *

        Authentication and authorization prove the broker did not store the record, but not that it * will refuse it again: a credential being rotated, or an ACL deployed after the application, * fails every publish this way for a few minutes and then stops. Marked not retryable, a - * publisher that trusts the flag — the application's outbox relay does — parks every record sent - * in those minutes. A credential that is simply wrong is retried too, and the outbox then holds - * its rows FAILED with an alert every retry — recoverable once the credential is fixed, where - * DEAD rows needed a manual reset each. + * publisher that trusts the flag parks every record sent in those minutes. A credential that is + * simply wrong is retried too, for as long as it stays wrong; the descriptor's code names it, so + * a caller can tell that retry from a rotation and stop it. + * + *

        This flag departs from {@link FailureDescriptor#defaultRetryable} on purpose, for publish + * only: that default says an authentication or authorization failure is not retried, and it still + * governs consumption, where the retry engine requires both. See {@code src/messaging/CLAUDE.md} + * "Publish retryability of authentication and authorization". */ private static boolean mayPassOnRetry(Throwable cause) { return cause instanceof AuthenticationException || cause instanceof AuthorizationException; diff --git a/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaQuarantinePublisher.java b/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaQuarantinePublisher.java index 20489c95..af09f0e8 100644 --- a/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaQuarantinePublisher.java +++ b/src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaQuarantinePublisher.java @@ -1,5 +1,6 @@ package dev.caskeleton.messaging.kafka; +import dev.caskeleton.messaging.api.error.FailureCategory; import org.apache.kafka.clients.consumer.ConsumerRecord; /** @@ -18,11 +19,22 @@ import org.apache.kafka.clients.consumer.ConsumerRecord; public interface KafkaQuarantinePublisher { /** - * Writes an undecodable record somewhere durable. + * Writes a record the consumer will not deliver somewhere durable, under the reason it gives. * + *

        The category is the caller's, because only the caller knows which of two very different + * things happened: the record could not be rebuilt at all ({@link + * FailureCategory#DESERIALIZATION}), or its handler failed until the attempt budget ran out — + * under the failure's own category when it carries one, {@link FailureCategory#POISON_MESSAGE} + * when it does not. Both were written as {@code POISON_MESSAGE}, so a redrive could not tell a + * message that will never decode from one an outage kept failing (review 2026-11-01 06-14). + * + * @param record the record as it arrived + * @param category why it is quarantined, written as the failure-category header + * @param reason the failure; its type is written as the failure-code header * @return true when the write is confirmed, so the source offset may be committed */ - boolean quarantine(ConsumerRecord record, Throwable reason); + boolean quarantine( + ConsumerRecord record, FailureCategory category, Throwable reason); /** * The default: nothing is configured, so nothing may be committed past. @@ -37,7 +49,7 @@ public interface KafkaQuarantinePublisher { /** Holds the single "not configured" quarantine. */ final class Unavailable { - private static final KafkaQuarantinePublisher INSTANCE = (record, reason) -> false; + private static final KafkaQuarantinePublisher INSTANCE = (record, category, reason) -> false; private Unavailable() {} } diff --git a/src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaConsumerRegistrarTest.java b/src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaConsumerRegistrarTest.java index f5580a52..edd77699 100644 --- a/src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaConsumerRegistrarTest.java +++ b/src/messaging/messaging-kafka/src/test/java/dev/caskeleton/messaging/kafka/KafkaConsumerRegistrarTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.messaging.kafka; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.messaging.api.MessageId; +import dev.caskeleton.messaging.api.error.FailureCategory; import dev.caskeleton.messaging.api.header.ReservedHeaders; import dev.caskeleton.messaging.policy.OrderingImpact; import dev.caskeleton.messaging.policy.RetryMode; @@ -258,7 +259,7 @@ class KafkaConsumerRegistrarTest { registrar( KafkaContractHarness.profile(), this::fail, - (record, reason) -> quarantined.add(record.offset()), + (record, category, reason) -> quarantined.add(record.offset()), () -> NOW); assign(); addRecord(10); @@ -274,6 +275,29 @@ class KafkaConsumerRegistrarTest { .hasValue(11L); } + @Test + @DisplayName("handler가 시도 예산을 다 쓴 레코드는 그 실패의 분류로 격리하고 분류가 없으면 POISON_MESSAGE로 적는다") + void aDeliveryThatSpentItsBudgetIsQuarantinedUnderItsFailuresCategory() { + // given: a handler that fails with a plain exception every time + List categories = new ArrayList<>(); + KafkaConsumerRegistrar registrar = + registrar( + KafkaContractHarness.profile(), + this::fail, + (record, category, reason) -> categories.add(category), + () -> NOW); + assign(); + addRecord(10); + registrar.pollOnce(NOW); + handlers.runAll(); + + // when + registrar.pollOnce(NOW); + + // then + assertThat(categories).containsExactly(FailureCategory.POISON_MESSAGE); + } + @Test @DisplayName("handler가 요청한 requeue도 시도 횟수를 세어 예산을 쓰면 quarantine 후 commit된다") void aDeliveryItsHandlerKeepsRequeueingSpendsTheBudgetAndIsQuarantined() { @@ -283,7 +307,7 @@ class KafkaConsumerRegistrarTest { registrar( KafkaContractHarness.profile(), this::requeue, - (record, reason) -> quarantined.add(record.offset()), + (record, category, reason) -> quarantined.add(record.offset()), () -> NOW); assign(); addRecord(10); @@ -470,7 +494,7 @@ class KafkaConsumerRegistrarTest { handlers, new GracefulShutdownCoordinator(Duration.ofSeconds(30)), Duration.ofMillis(1), - (record, reason) -> { + (record, category, reason) -> { quarantined.add(record.offset()); return true; })) { @@ -486,6 +510,65 @@ class KafkaConsumerRegistrarTest { } } + /** + * A record that cannot be rebuilt into an envelope will never decode, however often it is + * redriven; the one whose handler ran out of attempts may pass once the outage is over. They were + * both written as {@code POISON_MESSAGE} (review 2026-11-01 06-14). + */ + @Test + @DisplayName("envelope로 되살릴 수 없는 레코드는 시도 예산 소진과 다른 DESERIALIZATION으로 격리한다") + void anUndecodableRecordIsQuarantinedAsDeserializationNotAsPoison() { + // given + List categories = new ArrayList<>(); + try (KafkaConsumerRegistrar registrar = + new KafkaConsumerRegistrar( + new TransportConsumerSpec(KafkaContractHarness.profile(), this::settleImmediately), + consumer, + handlers, + new GracefulShutdownCoordinator(Duration.ofSeconds(30)), + Duration.ofMillis(1), + (record, category, reason) -> categories.add(category))) { + assign(); + addRecordWithoutIdentityHeaders(10); + registrar.pollOnce(NOW); + + // when + handlers.runAll(); + + // then + assertThat(categories).containsExactly(FailureCategory.DESERIALIZATION); + } + } + + @Test + @DisplayName("격리 쓰기가 한 번 실패해 재시도로 넘어간 읽을 수 없는 레코드도 DESERIALIZATION으로 격리한다") + void anUndecodableRecordStaysDeserializationWhenItsQuarantineIsRetried() { + // given: the first quarantine write is not confirmed, so the record goes round the retry path + List categories = new ArrayList<>(); + try (KafkaConsumerRegistrar registrar = + new KafkaConsumerRegistrar( + new TransportConsumerSpec(KafkaContractHarness.profile(), this::settleImmediately), + consumer, + handlers, + new GracefulShutdownCoordinator(Duration.ofSeconds(30)), + Duration.ofMillis(1), + (record, category, reason) -> { + categories.add(category); + return categories.size() > 1; + })) { + assign(); + addRecordWithoutIdentityHeaders(10); + registrar.pollOnce(NOW); + + // when + handlers.runAll(); + + // then + assertThat(categories) + .containsExactly(FailureCategory.DESERIALIZATION, FailureCategory.DESERIALIZATION); + } + } + @Test @DisplayName("one partition hitting its ceiling does not abandon the other's records") void oneSaturatedPartitionDoesNotAbandonAnother() { diff --git a/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java b/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java index a51f9fef..5c4341e3 100644 --- a/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java +++ b/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java @@ -265,7 +265,7 @@ public final class DefaultMessagePublisher implements MessagePublisher, EncodedM admission.complete(destination.name().value()); // No runtime to send through — the registry closed during shutdown, or none is installed // yet. Nothing about the message was wrong, so the refusal is marked retryable: a caller that - // trusts the flag, as the application's outbox relay does, retries it instead of parking it. + // trusts the flag retries it instead of parking it. return refused( new FailureDescriptor( FailureCategory.TRANSIENT_INFRASTRUCTURE, diff --git a/src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaDeadLetterQuarantine.java b/src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaDeadLetterQuarantine.java index 8185ef6c..85ad9c2e 100644 --- a/src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaDeadLetterQuarantine.java +++ b/src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaDeadLetterQuarantine.java @@ -1,5 +1,6 @@ package dev.caskeleton.messaging.autoconfigure; +import dev.caskeleton.messaging.api.error.FailureCategory; import dev.caskeleton.messaging.api.header.ReservedHeaders; import dev.caskeleton.messaging.kafka.KafkaQuarantinePublisher; import java.nio.charset.StandardCharsets; @@ -38,11 +39,14 @@ final class KafkaDeadLetterQuarantine implements KafkaQuarantinePublisher { } @Override - public boolean quarantine(ConsumerRecord record, Throwable reason) { + public boolean quarantine( + ConsumerRecord record, FailureCategory category, Throwable reason) { RecordHeaders headers = new RecordHeaders(record.headers().toArray()); headers.remove(ReservedHeaders.FAILURE_CATEGORY); headers.remove(ReservedHeaders.FAILURE_CODE); - headers.add(ReservedHeaders.FAILURE_CATEGORY, bytes("POISON_MESSAGE")); + headers.add( + ReservedHeaders.FAILURE_CATEGORY, + bytes(category == null ? FailureCategory.POISON_MESSAGE.name() : category.name())); headers.add( ReservedHeaders.FAILURE_CODE, bytes(reason == null ? "UNKNOWN" : reason.getClass().getSimpleName())); diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingShutdownLifecycle.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingShutdownLifecycle.java index 7efaa471..147c2661 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingShutdownLifecycle.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingShutdownLifecycle.java @@ -29,14 +29,14 @@ import org.springframework.context.SmartLifecycle; */ public final class MessagingShutdownLifecycle implements SmartLifecycle { - /** How often the drain is re-checked. Short enough that a fast drain is not padded. */ /** - * The phase this drain stops in: {@link #getPhase()}. Public so a relay outside the platform — - * the application's own outbox relay, which may not name this type in production code — can be - * held above it by a test that does name it. + * The phase this drain stops in: {@link #getPhase()}. Public so a relay outside the platform — a + * publisher whose production code may not name this type — can be held above it by a test that + * does name it. */ public static final int PHASE = Integer.MAX_VALUE - 1024; + /** How often the drain is re-checked. Short enough that a fast drain is not padded. */ private static final Duration POLL = Duration.ofMillis(50); private final MessagingAdmissionController admission; @@ -120,11 +120,10 @@ public final class MessagingShutdownLifecycle implements SmartLifecycle { * drain ahead of the transports it is draining, because closing a connection first would strand * the settlements the drain exists to flush. It sits below the outbox relays' phase for the * mirror-image reason: refusing admission while a relay pass is mid-publish turns that pass's - * rows into refusals. Two relays stand above it: the platform's own ({@code - * MessagingOutboxRelayLifecycle}, built only when a platform outbox repository exists) and the - * application's ({@code composition:outbox-relay} {@code OutboxRelayScheduler}, phase {@code - * Integer.MAX_VALUE}), which finishes the publish it is in and releases its other claims before - * this phase runs. + * rows into refusals. The platform's own relay ({@code MessagingOutboxRelayLifecycle}, built only + * when a platform outbox repository exists) stands above it, and so must any relay outside the + * platform that publishes through it: a phase above {@link #PHASE}, finishing the publish it is + * in before this phase runs. * * @return the lifecycle phase, {@link #PHASE} */ diff --git a/src/optional-platforms/build.gradle b/src/optional-platforms/build.gradle index 59808a93..1c5ff1b0 100644 --- a/src/optional-platforms/build.gradle +++ b/src/optional-platforms/build.gradle @@ -1,5 +1,9 @@ plugins { id 'ca.architecture' + // Every strict lane of this build belongs to a stage a workflow executes, checked here exactly + // as in the main build: the main build's check cannot see this build's lanes, and while only it + // applied the plugin, grpcPerformanceTest ran nowhere (review 2026-11-03 RR-06-03). + id 'ca.strict-lane-stages' } // No `ca.release-provenance` any more: each gRPC leaf's `ca.java-conventions` derives its version @@ -47,3 +51,33 @@ tasks.register('integrationCheck') { description = 'Runs every optional-platform leaf integration test lane. Needs a container runtime.' dependsOn subprojects.findAll { it.childProjects.isEmpty() }.collect { "${it.path}:integrationTestLaneCheck" } } + +// The performance stage of this build: grpcPerformanceTest. It asserts the shape of a measurement +// (ordered percentiles, a gate that reads them) with a generous budget, not a number, so it can run +// on a shared runner. integration-main.yml's performance-check job runs it next to the main build's +// `:performanceCheck`; before this aggregate it ran when somebody asked for it by name, which was +// nobody (review 2026-11-03 RR-06-03). +tasks.register('performanceCheck') { + group = 'verification' + description = 'Runs every optional-platform leaf performance test lane.' + dependsOn subprojects.findAll { it.childProjects.isEmpty() }.collect { "${it.path}:performanceTestLaneCheck" } +} + +// The tag-only stage of this build: the hermetic strict lanes (the three gRPC certification lanes). +// Their tests already run inside each leaf's `test`; the lanes add the one thing `test` cannot say — +// that a tag still selects something — which is worth asserting once per release tag. release.yml +// runs this aggregate instead of naming the lanes, so a lane added here is in the release gate +// without a workflow edit. +tasks.register('releaseCheck') { + group = 'verification' + description = 'Runs every optional-platform leaf hermetic strict test lane (the release gate).' + dependsOn subprojects.findAll { it.childProjects.isEmpty() }.collect { "${it.path}:testLaneCheck" } +} + +// The stages this build's strict lanes may belong to, executed by workflows as +// `./gradlew -p optional-platforms ` from `src`. +strictLaneStages { + stage ':ci', ':integrationCheck', ':performanceCheck', ':releaseCheck' + workflowDirectory = layout.projectDirectory.dir('../../.github/workflows') + workflowProjectDirectory = 'optional-platforms' +} diff --git a/src/sample-portfolio/README.md b/src/sample-portfolio/README.md index fd427c76..eb63c231 100644 --- a/src/sample-portfolio/README.md +++ b/src/sample-portfolio/README.md @@ -48,8 +48,13 @@ 비밀번호가 문서에 적혀 있는 공개 데모 계정입니다. 비밀이 아니며, 실제 서비스는 이 방식을 쓰지 않고 `adapter:inbound:web`의 JWT 체인으로 인증합니다. -그래서 `prod` 프로필로 띄우면 기동을 거부합니다(`SampleDemoAccountsProductionGuard`, 종료 코드 71). -샘플을 복제해 운영에 올릴 때 이 계정이 남아 있으면 누구나 관리자로 들어올 수 있기 때문입니다. 운영으로 +그래서 데모 프로필(`local`·`test`·`demo`)이 명시적으로 켜져 있고 그 밖의 프로필이 하나도 없을 때만 +기동합니다. 프로필 없음, `prod`, `production`, `staging` 등은 기동을 거부합니다 +(`SampleDemoAccountsProductionGuard`, 종료 코드 71). 샘플을 복제해 운영에 올릴 때 이 계정이 남아 있으면 +누구나 관리자로 들어올 수 있기 때문입니다. 거부 목록(`prod`)이 아니라 허용 목록인 이유는 프로필 이름이 +하나만 달라도 계정이 열리지 않게 하려는 것입니다. `./gradlew :sample-portfolio:bootRun`은 +`SPRING_PROFILES_ACTIVE`가 비어 있으면 `local`을 넘기고, jar·이미지로 띄울 때는 +`SPRING_PROFILES_ACTIVE=local`(또는 `test`·`demo`)을 직접 줍니다. 운영으로 가져가려면 `SampleDemoSecurityConfig`·`SampleDemoAccounts`를 지우고 `SamplePortfolioApplication`에서 `WebSecurityAutoConfiguration` 제외를 풉니다. 이 규칙은 데모 설정 옆에 선언되어 있어 함께 지워집니다. diff --git a/src/sample-portfolio/build.gradle b/src/sample-portfolio/build.gradle index d1b079e4..a494b00e 100644 --- a/src/sample-portfolio/build.gradle +++ b/src/sample-portfolio/build.gradle @@ -196,7 +196,6 @@ strictTestLanes { requires('dev.caskeleton.sample.portfolio.adapter.inbound.web.contract.OpenApiDriftContractTest') systemProperty 'openapi.snapshot.write', project.hasProperty('approveOpenApiChange') ? 'true' : 'false' - // Pin UTC like the main test task for host-locale independence. } } @@ -228,7 +227,8 @@ strictTestLanes { lane('messagingSampleContractQualificationTest') { sourceSet = 'test' description = 'Runs exact Messaging sample contract qualification tests.' - requires('dev.caskeleton.sample.portfolio.application.worklog.WorkLogReservedContractContributionTest') + requires('dev.caskeleton.sample.portfolio.application.worklog.WorkLogReservedContractContributionTest', + 'dev.caskeleton.sample.portfolio.application.event.SamplePayloadSchemaReleaseTest') rejectSkipped = true } } @@ -245,6 +245,11 @@ tasks.register('stageDockerJar', Sync) { } // Run from the repo's src/ root so src/.env is picked up (same as app-bootstrap). +// bootRun is the local developer command, so it says `local` explicitly unless SPRING_PROFILES_ACTIVE +// names a profile: the demo accounts refuse to start without a demo profile, and application.yml no +// longer defaults one (RR-07-02). The jar and the image get no such default. bootRun { workingDir = rootProject.projectDir + systemProperty 'spring.profiles.active', + providers.environmentVariable('SPRING_PROFILES_ACTIVE').filter { !it.isBlank() }.orElse('local').get() } diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterContractTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterContractTest.java new file mode 100644 index 00000000..efda28c1 --- /dev/null +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterContractTest.java @@ -0,0 +1,71 @@ +package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; + +import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.config.JpaConfig; +import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; +import dev.caskeleton.sample.portfolio.domain.poster.testkit.PosterRepositoryContract; +import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.TestPropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * The shipped {@link PosterRepositoryAdapter} against real PostgreSQL, held to the same {@link + * PosterRepositoryContract} as the in-memory fake. The test-managed transaction is switched off so + * every contract call commits on its own: the title rule is the unique index's, and it answers at + * the statement the adapter flushes. + */ +@DataJpaTest +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +@Testcontainers(disabledWithoutDocker = true) +@Transactional(propagation = Propagation.NOT_SUPPORTED) +@Import({ + JpaConfig.class, + PosterRepositoryAdapter.class, + PosterRepositoryAdapterIntegrationTest.TestAuditConfig.class +}) +@TestPropertySource( + properties = { + "spring.flyway.enabled=true", + "spring.flyway.locations=classpath:db/migration/postgresql,classpath:db/sample-migration", + "spring.jpa.hibernate.ddl-auto=validate" + }) +class PosterRepositoryAdapterContractTest extends PosterRepositoryContract { + + @Container @ServiceConnection + static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); + + @Autowired private PosterRepositoryAdapter adapter; + @Autowired private PosterJpaRepository jpa; + @Autowired private PlatformTransactionManager transactionManager; + + @BeforeEach + void empty() { + inTransaction( + () -> { + jpa.deleteAll(); + return null; + }); + } + + @Override + protected PosterRepository repository() { + return adapter; + } + + @Override + protected T inTransaction(Supplier work) { + return new TransactionTemplate(transactionManager).execute(status -> work.get()); + } +} 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 fae67951..9f7f9628 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 @@ -5,13 +5,13 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.persistence.audit.AuditContextPort; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.config.JpaConfig; -import dev.caskeleton.sample.portfolio.application.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.domain.poster.Poster; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterImageReference; import dev.caskeleton.sample.portfolio.domain.poster.PosterPage; import dev.caskeleton.sample.portfolio.domain.poster.PosterSortField; import dev.caskeleton.sample.portfolio.domain.poster.PosterStatus; +import dev.caskeleton.sample.portfolio.domain.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.domain.poster.PublishedPosterImageAttachment; import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; import java.time.Clock; diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java index d31647f0..26fd857e 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterConcurrencyIntegrationTest.java @@ -7,10 +7,12 @@ import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxAggregateSequences; import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; +import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.UuidOutboxEventIdFactory; import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.UuidPosterIdFactory; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.config.JpaConfig; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository.PosterRepositoryAdapter; import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; +import dev.caskeleton.sample.portfolio.domain.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; import java.time.Clock; import java.util.ArrayList; @@ -150,7 +152,7 @@ class CreatePosterConcurrencyIntegrationTest { return encoder.encode(draft); } }, - () -> UUID.randomUUID().toString(), + new UuidOutboxEventIdFactory(), Optional::empty, Clock.systemUTC(), new InMemoryOutboxAggregateSequences()); diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandler.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandler.java index ffb4f4ce..42dc6adf 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandler.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandler.java @@ -2,12 +2,12 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.error; import dev.caskeleton.adapter.inbound.web.error.ErrorResponseFactory; import dev.caskeleton.sample.portfolio.application.poster.PosterNotFoundException; -import dev.caskeleton.sample.portfolio.application.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageAlreadyPublishedException; import dev.caskeleton.sample.portfolio.application.worklog.WorkLogNotFoundException; import dev.caskeleton.sample.portfolio.application.worklog.WorkLogNotOwnedException; import dev.caskeleton.sample.portfolio.application.worklog.WorkLogVersionMismatchException; import dev.caskeleton.sample.portfolio.domain.poster.PosterInvariantException; +import dev.caskeleton.sample.portfolio.domain.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.response.Envelope; 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 2b42d19c..4f62d964 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 @@ -3,13 +3,13 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; import dev.caskeleton.adapter.outbound.persistence.audit.AuditContextPort; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.entity.PosterEntity; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.mapper.PosterPersistenceMapper; -import dev.caskeleton.sample.portfolio.application.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.domain.poster.Poster; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterPage; import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; import dev.caskeleton.sample.portfolio.domain.poster.PosterSortField; import dev.caskeleton.sample.portfolio.domain.poster.PosterStatus; +import dev.caskeleton.sample.portfolio.domain.poster.PosterTitleAlreadyExistsException; import java.time.Clock; import java.time.Instant; import java.util.List; @@ -66,8 +66,8 @@ public class PosterRepositoryAdapter implements PosterRepository { * The unique index {@value #TITLE_UNIQUE_INDEX} (sample migration V8.1) is what keeps poster * titles unique; the use case's {@code existsByTitle} check only gives the common case an early * answer and loses races. Flushing here makes a violation surface inside this call, where it is - * turned into the same {@link PosterTitleAlreadyExistsException} the check throws, instead of at - * commit as a generic unique-violation failure. + * turned into the domain's {@link PosterTitleAlreadyExistsException} that the port declares, + * instead of at commit as a generic unique-violation failure. */ private PosterEntity saveHoldingTheTitleRule(PosterEntity entity, String title) { try { diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterUseCase.java index 9fd982cb..53650119 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterUseCase.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/CreatePosterUseCase.java @@ -11,6 +11,7 @@ import dev.caskeleton.sample.portfolio.domain.poster.Poster; import dev.caskeleton.sample.portfolio.domain.poster.PosterCreated; import dev.caskeleton.sample.portfolio.domain.poster.PosterIdFactory; import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; +import dev.caskeleton.sample.portfolio.domain.poster.PosterTitleAlreadyExistsException; /** * Creates a new {@link Poster} (server-assigned id via {@link PosterIdFactory}) and appends a diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PosterTitleAlreadyExistsException.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PosterTitleAlreadyExistsException.java deleted file mode 100644 index d697beec..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PosterTitleAlreadyExistsException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.poster; - -/** Raised when creating a poster whose title is already taken. Web handler maps it to 409. */ -public class PosterTitleAlreadyExistsException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public PosterTitleAlreadyExistsException(String title) { - super("Poster title already in use: " + title); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/UpdatePosterUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/UpdatePosterUseCase.java index d2bf7cba..2e001d50 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/UpdatePosterUseCase.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/UpdatePosterUseCase.java @@ -9,6 +9,7 @@ import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.CommandUseCase; import dev.caskeleton.sample.portfolio.domain.poster.Poster; import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; +import dev.caskeleton.sample.portfolio.domain.poster.PosterTitleAlreadyExistsException; /** * Partial update of a poster's title/caption using {@code Patch} 3-state semantics. Mirrors {@code diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedPayload.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedPayload.java index e02c25e7..b3bd0f26 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedPayload.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedPayload.java @@ -1,17 +1,18 @@ package dev.caskeleton.sample.portfolio.application.worklog; import dev.caskeleton.application.messaging.contract.IntegrationPayload; +import dev.caskeleton.application.messaging.event.IntegrationIdentity; -/** Immutable sample payload for the {@code portfolio.worklog.reserved} v1 contract. */ +/** + * Immutable sample payload for the {@code portfolio.worklog.reserved} v1 contract. + * + *

        The work log id is the event's aggregate id, so it takes the aggregate id grammar and bound + * from {@link IntegrationIdentity} rather than a copy of them (review 2026-11-03 RR-01-08). + */ public record WorkLogReservedPayload(String workLogId) implements IntegrationPayload { - private static final int MAXIMUM_WORK_LOG_ID_LENGTH = 160; - private static final String WORK_LOG_ID_GRAMMAR = "[A-Za-z0-9][A-Za-z0-9._:-]*"; - public WorkLogReservedPayload { - if (workLogId == null - || workLogId.length() > MAXIMUM_WORK_LOG_ID_LENGTH - || !workLogId.matches(WORK_LOG_ID_GRAMMAR)) { + if (!IntegrationIdentity.isCanonical(workLogId, IntegrationIdentity.AGGREGATE_ID_MAX_LENGTH)) { throw new IllegalArgumentException( "workLogId must be a 1-160 character canonical US-ASCII identifier"); } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/management/SampleManagementSecurityConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/management/SampleManagementSecurityConfig.java index 2905046e..9a0c29f7 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/management/SampleManagementSecurityConfig.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/management/SampleManagementSecurityConfig.java @@ -21,7 +21,12 @@ import org.springframework.security.web.SecurityFilterChain; @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) public class SampleManagementSecurityConfig { - /** Actuator security chain ordered at {@code 0} to run BEFORE the main app chain. */ + /** + * The actuator chain. Its order ({@code 0}) does not put it in front of the demo chain, which is + * {@code @Order(-100)} and matches {@code /**}: requests to the management port reach the demo + * chain first, which permits every read. The bean exists for its name, which replaces the + * template's restricted chain from {@code composition:service-runtime}. + */ @Bean @Order(0) public SecurityFilterChain actuatorSecurityFilterChain(HttpSecurity http) throws Exception { diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java index 5d64db3b..943e2542 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java @@ -1,28 +1,34 @@ package dev.caskeleton.sample.portfolio.bootstrap.security; -import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; import dev.caskeleton.adapter.outbound.support.startup.StartupRule; +import java.util.Arrays; import java.util.List; +import java.util.Set; import org.springframework.core.env.Environment; /** - * Refuses the {@code prod} profile while the {@link SampleDemoAccounts} authenticate requests. + * Lets the {@link SampleDemoAccounts} authenticate requests only under a profile that names a demo: + * {@code local}, {@code test} or {@code demo}, switched on explicitly and alone. * *

        The demo accounts are published on purpose: each password is the account name and the sample * README prints both, so a reader can watch {@code @RequiresPermission} allow one caller and refuse * another. That is harmless in a demo and an open admin account anywhere else. The sample is also - * the code adopters copy first, so the copy that matters is the one that reaches a production - * deployment with this configuration still in it. The README says not to; this rule makes the - * deployment say so too, before any datasource, migration or listener is created. + * the code adopters copy first, so the copy that matters is the one that reaches a deployment with + * this configuration still in it. The README says not to; this rule makes the deployment say so + * too, before any datasource, migration or listener is created. * - *

        "Production" is the template's own answer ({@link RuntimeProfileSnapshot#isProduction()}), not - * a profile name compared here, so the sample and every module agree on what it means. The rule is - * declared beside the accounts in {@link SampleDemoSecurityConfig}: replacing the demo chain with a - * real one removes the refusal with it. + *

        An allow list, not a deny list (review 2026-11-03 RR-07-02, owner decision). Refusing exactly + * {@code prod} left the accounts open under no profile, {@code production}, {@code staging} or any + * other name a deployment happened to use: one differently spelled profile opened an admin account. + * Here a deployment is refused unless every active profile is a demo profile, so no profile at all + * — the sample's image sets none — is refused too. */ final class SampleDemoAccountsProductionGuard implements StartupRule { + /** The profiles that say "this is a demo", and nothing else may be active beside them. */ + static final Set DEMO_PROFILES = Set.of("local", "test", "demo"); + @Override public StartupPhase phase() { return StartupPhase.PROFILE_CHECK; @@ -30,23 +36,31 @@ final class SampleDemoAccountsProductionGuard implements StartupRule { @Override public String summary() { - return "the sample's demo accounts must not authenticate under the prod profile"; + return "the sample's demo accounts authenticate only under the local, test or demo profile"; } @Override public String remedy() { - return "run the sample under local or dev; a production service authenticates through the JWT" - + " chain — delete SampleDemoSecurityConfig and SampleDemoAccounts and stop excluding" - + " WebSecurityAutoConfiguration in SamplePortfolioApplication"; + return "run the sample with SPRING_PROFILES_ACTIVE=local (or test or demo); a real service" + + " authenticates through the JWT chain — delete SampleDemoSecurityConfig and" + + " SampleDemoAccounts and stop excluding WebSecurityAutoConfiguration in" + + " SamplePortfolioApplication"; } @Override public List violations(Environment environment) { - if (!RuntimeProfileSnapshot.from(environment).isProduction()) { + List active = Arrays.asList(environment.getActiveProfiles()); + String risk = + "demo-user and demo-admin sign in over HTTP Basic, each password is the account name, and" + + " the sample README prints both — anyone could act as an admin"; + if (active.isEmpty()) { + return List.of("no profile is active, which a deployment cannot be told apart from: " + risk); + } + List outside = + active.stream().filter(profile -> !DEMO_PROFILES.contains(profile)).toList(); + if (outside.isEmpty()) { return List.of(); } - return List.of( - "demo-user and demo-admin sign in over HTTP Basic, each password is the account name, and" - + " the sample README prints both — anyone could act as an admin"); + return List.of("active profile(s) " + outside + " are not a demo profile: " + risk); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java index 0fad9aab..15d15e80 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfig.java @@ -3,6 +3,7 @@ package dev.caskeleton.sample.portfolio.bootstrap.security; import dev.caskeleton.adapter.inbound.web.auth.EnvelopeAuthenticationEntryPoint; import dev.caskeleton.adapter.inbound.web.auth.SecurityErrorClassifier; import dev.caskeleton.adapter.outbound.support.startup.StartupRule; +import jakarta.servlet.DispatcherType; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -25,7 +26,8 @@ import tools.jackson.databind.ObjectMapper; * {@code @RequiresPermission} is checked against {@code app.authz} exactly as it is for a JWT * caller. This chain only answers who the caller is. * - *

        The accounts are public, so they refuse the prod profile at startup ({@link + *

        The accounts are public, so the sample refuses to start unless a demo profile ({@code local}, + * {@code test} or {@code demo}) is explicitly active and no other is ({@link * SampleDemoAccountsProductionGuard}). */ @Configuration @@ -48,10 +50,10 @@ public class SampleDemoSecurityConfig { } /** - * Refuses to start under the prod profile while these accounts are the way in. + * Refuses to start outside a demo profile while these accounts are the way in. * *

        Static and argument-free, as every startup rule is: the support module's runner creates it - * before any other singleton, so a production start is refused before a datasource opens or a + * before any other singleton, so a non-demo start is refused before a datasource opens or a * migration runs. Declared here, beside the accounts, so the refusal leaves with them. * * @return the rule @@ -74,7 +76,13 @@ public class SampleDemoSecurityConfig { .exceptionHandling(ex -> ex.authenticationEntryPoint(unauthenticated)) .authorizeHttpRequests( auth -> - auth.requestMatchers(HttpMethod.GET) + // The container's error dispatch for a request that already failed, as the web + // leaf's chain allows it: authorising it again would answer a rejected anonymous + // write with a 401 that blames authentication. Only the dispatch type is opened; a + // request that names /error itself is still a request (re-review RR-02-02). + auth.dispatcherTypeMatchers(DispatcherType.ERROR) + .permitAll() + .requestMatchers(HttpMethod.GET) .permitAll() .requestMatchers(HttpMethod.HEAD) .permitAll() diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterRepository.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterRepository.java index 420f08f5..e3ba130f 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterRepository.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterRepository.java @@ -2,13 +2,23 @@ package dev.caskeleton.sample.portfolio.domain.poster; import java.util.Optional; -/** Outbound port for Poster persistence. Implemented in adapter-persistence. */ +/** + * Outbound port for Poster persistence. Implemented in adapter-persistence; {@code + * PosterRepositoryContract} (test fixtures) holds the adapter and the in-memory fake to the same + * promises. + */ public interface PosterRepository { /** - * Stores the poster. Titles are unique ignoring case, and the store enforces it: a save that - * would duplicate a stored title fails with the application's {@code - * PosterTitleAlreadyExistsException}, even when {@link #existsByTitle} said the title was free. + * Stores the poster. Titles are unique ignoring case, and the store enforces it, even when {@link + * #existsByTitle} said the title was free. + * + *

        A business-rule conflict is a domain exception the port declares and the adapter raises, so + * every implementation answers it the same way. A technical conflict — a stale {@code @Version}, + * as in {@code WorkLogRepository} — stays the framework's exception, which the transaction port + * classifies as {@code DB_OPTIMISTIC_CONFLICT}. + * + * @throws PosterTitleAlreadyExistsException when another poster already has this title */ Poster save(Poster poster); diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTitleAlreadyExistsException.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTitleAlreadyExistsException.java new file mode 100644 index 00000000..0d90e3fd --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTitleAlreadyExistsException.java @@ -0,0 +1,20 @@ +package dev.caskeleton.sample.portfolio.domain.poster; + +/** + * A poster title is already taken, ignoring case — the rule {@link PosterRepository#save} enforces + * and the create use case asks about first. The web adapter answers it 409 {@code + * POSTER_ALREADY_EXISTS}. + * + *

        A domain type, beside the port that raises it, because the port's contract has to name it in + * code (review 2026-11-03 RR-06-12): it used to be an application exception that the domain port + * could only mention in Javadoc. One type for both paths — the use case's early answer and the + * store's unique index — so the two cannot drift into different answers. + */ +public class PosterTitleAlreadyExistsException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public PosterTitleAlreadyExistsException(String title) { + super("Poster title already in use: " + title); + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogRepository.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogRepository.java index 4ae6dbfb..17cc9c1e 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogRepository.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogRepository.java @@ -8,6 +8,13 @@ import java.util.Optional; * this port. See README. */ public interface WorkLogRepository { + /** + * Stores the work log. Saving one read at an older version than the stored row is a technical + * conflict, not a business rule: the adapter raises the framework's optimistic-locking failure — + * the same one Hibernate raises when the version check fails at flush — and the transaction port + * classifies both as {@code DB_OPTIMISTIC_CONFLICT}. A business-rule conflict is a domain + * exception the port declares instead ({@code PosterRepository#save}). + */ WorkLog save(WorkLog workLog); Optional findById(WorkLogId id); diff --git a/src/sample-portfolio/src/main/resources/application.yml b/src/sample-portfolio/src/main/resources/application.yml index 7c5ec9fe..4ce4bf16 100644 --- a/src/sample-portfolio/src/main/resources/application.yml +++ b/src/sample-portfolio/src/main/resources/application.yml @@ -26,8 +26,10 @@ spring: error: include-stacktrace: ${APP_SERVER_ERROR_INCLUDE_STACKTRACE:never} include-message: ${APP_SERVER_ERROR_INCLUDE_MESSAGE:never} - profiles: - active: ${SPRING_PROFILES_ACTIVE:local} + # No spring.profiles.active default. The demo accounts open only under an explicitly active + # local, test or demo profile (SampleDemoAccountsProductionGuard), and a default here would turn + # "no profile" — what the image and a copied deployment start with — into `local` (RR-07-02). + # SPRING_PROFILES_ACTIVE still sets it; `./gradlew :sample-portfolio:bootRun` passes `local`. datasource: url: ${APP_DATASOURCE_URL:jdbc:postgresql://localhost:5432/ca_skeleton} username: ${APP_DATASOURCE_USERNAME:ca_skeleton} @@ -153,8 +155,10 @@ logging: org.hibernate.SQL: ${APP_LOG_LEVEL_SQL:WARN} # --------------------------------------------------------------------------- -# Application-owned settings (app.*). -# These are bound by @ConfigurationProperties in the respective modules. +# Application-owned settings (app.*), each read by a module on this sample's classpath. +# SampleRuntimeDefaultsContractTest (app-bootstrap repository-contract lane) fails on a group nothing +# here reads: the messaging, notification and HTTP-client blocks that used to sit below configured +# modules the sample does not have (review 2026-11-03 RR-06-06). # --------------------------------------------------------------------------- app: capabilities: @@ -197,7 +201,7 @@ app: published-retention: P7D # ------------------------------------------------------------------------- - # Optional integration adapter toggles (all disabled for lean demo). + # The poster image workflow, off for the lean demo. # ------------------------------------------------------------------------- poster-image: api: @@ -207,32 +211,6 @@ app: enabled: false publication: enabled: false - messaging: - broker: ${APP_MESSAGING_BROKER:} - notification: - slack-webhook: - enabled: ${APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED:false} - google-email: - enabled: ${APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED:false} - outbound: - http: - connect-timeout: ${APP_OUTBOUND_HTTP_CONNECT_TIMEOUT:2s} - read-timeout: ${APP_OUTBOUND_HTTP_READ_TIMEOUT:5s} - global-call-timeout: ${APP_OUTBOUND_HTTP_GLOBAL_CALL_TIMEOUT:10s} - maximum-in-flight-calls: ${APP_OUTBOUND_HTTP_MAXIMUM_IN_FLIGHT_CALLS:128} - retry-enabled: ${APP_OUTBOUND_HTTP_RETRY_ENABLED:false} - retry: - max-attempts: ${APP_OUTBOUND_HTTP_RETRY_MAX_ATTEMPTS:3} - initial-backoff: ${APP_OUTBOUND_HTTP_RETRY_INITIAL_BACKOFF:100ms} - backoff-multiplier: ${APP_OUTBOUND_HTTP_RETRY_BACKOFF_MULTIPLIER:2.0} - circuit-breaker-enabled: ${APP_OUTBOUND_HTTP_CIRCUIT_BREAKER_ENABLED:false} - circuit-breaker: - failure-rate-threshold: ${APP_OUTBOUND_HTTP_CIRCUIT_BREAKER_FAILURE_RATE_THRESHOLD:50} - sliding-window-size: ${APP_OUTBOUND_HTTP_CIRCUIT_BREAKER_SLIDING_WINDOW_SIZE:100} - minimum-number-of-calls: ${APP_OUTBOUND_HTTP_CIRCUIT_BREAKER_MINIMUM_NUMBER_OF_CALLS:100} - wait-duration-in-open-state: ${APP_OUTBOUND_HTTP_CIRCUIT_BREAKER_WAIT_DURATION_IN_OPEN_STATE:60s} - permitted-calls-in-half-open: ${APP_OUTBOUND_HTTP_CIRCUIT_BREAKER_PERMITTED_CALLS_IN_HALF_OPEN:10} - response-size-limit: ${APP_OUTBOUND_HTTP_RESPONSE_SIZE_LIMIT:10MB} --- spring: diff --git a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java index d5f6c7d7..69c015b9 100644 --- a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java +++ b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleWorkLogAuthorizationSystemTest.java @@ -21,6 +21,7 @@ import java.time.LocalDate; import java.util.Base64; import java.util.List; import java.util.UUID; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -144,6 +145,43 @@ class SampleWorkLogAuthorizationSystemTest { assertThat(List.of(response.statusCode(), title(id))).containsExactly(403, "stored"); } + /** + * A write the firewall rejects (a {@code ;} in the path) never reaches authentication, so the + * container's error dispatch to {@code /error} carries no caller. The demo chain lets that + * dispatch through, as the web leaf's chain does; otherwise the rejection reached the client as a + * 401 that blamed authentication for a malformed request (re-review RR-02-02). + */ + @Test + @DisplayName("방화벽이 거절한 익명 쓰기 요청은 오류 디스패치에서 401로 바뀌지 않고 원래 400으로 나간다") + void aRejectedAnonymousWriteKeepsItsOwnStatusThroughTheErrorDispatch() throws Exception { + // given + HttpRequest.Builder rejected = + HttpRequest.newBuilder(uri("/api/worklogs;x=1")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(CREATE_BODY)); + + // when + HttpResponse response = send(rejected, null); + + // then + assertThat(response.statusCode()).as(response.body()).isEqualTo(400); + } + + @Test + @DisplayName("오류 디스패치만 열린다 — /error에 직접 보낸 익명 쓰기는 여전히 401이다") + void anAnonymousWriteNamingTheErrorPathStillNeedsADemoAccount() throws Exception { + // when + HttpResponse response = + send( + HttpRequest.newBuilder(uri("/error")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(CREATE_BODY)), + null); + + // then + assertThat(response.statusCode()).isEqualTo(401); + } + private WorkLogId storedWorkLog() { return storedWorkLog("sample-owner"); } 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 cc319c83..1e64bbf4 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 @@ -21,7 +21,6 @@ import dev.caskeleton.sample.portfolio.application.poster.GetPosterQuery; import dev.caskeleton.sample.portfolio.application.poster.GetPosterUseCase; import dev.caskeleton.sample.portfolio.application.poster.ListPostersUseCase; import dev.caskeleton.sample.portfolio.application.poster.PosterNotFoundException; -import dev.caskeleton.sample.portfolio.application.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.application.poster.PublishPosterUseCase; import dev.caskeleton.sample.portfolio.application.poster.UpdatePosterUseCase; import dev.caskeleton.sample.portfolio.domain.poster.Poster; @@ -29,6 +28,7 @@ import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterInvariantException; import dev.caskeleton.sample.portfolio.domain.poster.PosterPage; import dev.caskeleton.sample.portfolio.domain.poster.PosterStatus; +import dev.caskeleton.sample.portfolio.domain.poster.PosterTitleAlreadyExistsException; import java.util.List; import java.util.Locale; import org.junit.jupiter.api.Nested; diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java index 718181fc..4c19e0e0 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java @@ -3,11 +3,11 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.error; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.sample.portfolio.application.poster.PosterNotFoundException; -import dev.caskeleton.sample.portfolio.application.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageAlreadyPublishedException; import dev.caskeleton.sample.portfolio.application.worklog.WorkLogNotFoundException; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterInvariantException; +import dev.caskeleton.sample.portfolio.domain.poster.PosterTitleAlreadyExistsException; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException; import dev.caskeleton.shared.error.Category; diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/SamplePayloadSchemaReleaseTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/SamplePayloadSchemaReleaseTest.java new file mode 100644 index 00000000..36ce65ca --- /dev/null +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/SamplePayloadSchemaReleaseTest.java @@ -0,0 +1,18 @@ +package dev.caskeleton.sample.portfolio.application.event; + +import dev.caskeleton.application.messaging.contract.testkit.ReleasedPayloadSchemaContract; +import java.nio.file.Path; + +/** The payload schemas the sample publishes (poster and work-log events). */ +class SamplePayloadSchemaReleaseTest extends ReleasedPayloadSchemaContract { + + @Override + protected Path schemaRoot() { + return Path.of("src/main/resources/contracts/messaging"); + } + + @Override + protected Path manifest() { + return Path.of("src/test/resources/contracts/released-payload-schemas.sha256"); + } +} diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java index 42e9167e..8c2b645e 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java @@ -56,7 +56,7 @@ class WorkLogUseCasesTest { new PortfolioEventOutbox( NO_OP_OUTBOX, new FakeIntegrationEventEncoder(new WorkLogReservedContractContribution()), - () -> "01FAKEEVENTIDTSV4RRFFQ6900", + () -> "0190c9a2-1b3c-7def-8abc-1234567890ac", NO_CORRELATION, Clock.systemUTC(), new InMemoryOutboxAggregateSequences()), diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuardTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuardTest.java index c56ed6d1..c570821b 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuardTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuardTest.java @@ -53,8 +53,9 @@ class SampleDemoAccountsProductionGuardTest { } @ParameterizedTest - @ValueSource(strings = {"local", "dev", "test"}) - void theDemoAccountsAreAllowedOutsideProduction(String profile) { + @ValueSource(strings = {"local", "test", "demo"}) + @DisplayName("local·test·demo 프로필이 명시적으로 켜졌을 때만 데모 계정을 허용한다") + void theDemoAccountsAreAllowedOnlyUnderAnExplicitDemoProfile(String profile) { // given MockEnvironment environment = new MockEnvironment(); environment.setActiveProfiles(profile); @@ -66,13 +67,29 @@ class SampleDemoAccountsProductionGuardTest { assertThat(violations).isEmpty(); } + @ParameterizedTest + @ValueSource(strings = {"production", "staging", "prd", "dev", "local,prod", "test,staging"}) + @DisplayName("허용 목록 밖의 프로필이 하나라도 켜져 있으면 데모 계정을 거부한다") + void theDemoAccountsAreRefusedUnderAnyProfileOutsideTheAllowList(String profiles) { + // given + MockEnvironment environment = new MockEnvironment(); + environment.setActiveProfiles(profiles.split(",")); + + // when + List violations = new SampleDemoAccountsProductionGuard().violations(environment); + + // then + assertThat(violations).singleElement().asString().contains("demo-admin"); + } + @Test - void theDemoAccountsAreAllowedWithNoProfileAtAll() { + @DisplayName("프로필이 하나도 없으면 운영 배포와 구별할 수 없으므로 데모 계정을 거부한다") + void theDemoAccountsAreRefusedWithNoProfileAtAll() { // when List violations = new SampleDemoAccountsProductionGuard().violations(new MockEnvironment()); // then - assertThat(violations).isEmpty(); + assertThat(violations).singleElement().asString().contains("no profile"); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfigTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfigTest.java index 98067db3..e5b8f976 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfigTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfigTest.java @@ -43,6 +43,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; @@ -53,9 +54,14 @@ import org.springframework.test.web.servlet.ResultActions; properties = { "app.persistence-jpa.enabled=false", // The PostgreSQL idempotency store needs the relational module this test leaves off. - "app.capabilities.idempotency.provider=disabled" + "app.capabilities.idempotency.provider=disabled", + // Object storage is on while present and has no destination here; the `local` profile used to + // switch it off by default, and this test runs under `test` (RR-07-02). + "app.object-storage.enabled=false" }) @AutoConfigureMockMvc +// The demo accounts start only under a demo profile (SampleDemoAccountsProductionGuard). +@ActiveProfiles("test") class SampleDemoSecurityConfigTest { private static final String ID = "0190bd6e-7c3e-7abc-8def-0123456789ab"; diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/InMemoryPosterRepositoryContractTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/InMemoryPosterRepositoryContractTest.java new file mode 100644 index 00000000..ff29433e --- /dev/null +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/InMemoryPosterRepositoryContractTest.java @@ -0,0 +1,19 @@ +package dev.caskeleton.sample.portfolio.domain.poster.testkit; + +import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; +import java.util.function.Supplier; + +class InMemoryPosterRepositoryContractTest extends PosterRepositoryContract { + + private final InMemoryPosterRepository repository = new InMemoryPosterRepository(); + + @Override + protected PosterRepository repository() { + return repository; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/sample-portfolio/src/test/resources/contracts/released-payload-schemas.sha256 b/src/sample-portfolio/src/test/resources/contracts/released-payload-schemas.sha256 new file mode 100644 index 00000000..bb3f2a39 --- /dev/null +++ b/src/sample-portfolio/src/test/resources/contracts/released-payload-schemas.sha256 @@ -0,0 +1,10 @@ +# SHA-256 (LF-normalized) of every released payload schema version in src/main/resources/contracts/messaging. +# A released version is never edited: a change goes into a new version (application-core README). +# Add a line when a version is released; change a line only for a version no one can have consumed. +7264efd4e2531e6fd00010bb3deca96af2f1d0408d0021d014feaf90190f2eac portfolio.worklog.reserved/v1.schema.json +c71019a727f351aa26afbf6c9246b6cf1a7abcfd2b6bb3ee1185dfce6be504d8 poster.archived/v1.schema.json +8be3a72b7b469d894d06bd30f79f565feb23fbf698674d5caee094de5a2300fb poster.created/v1.schema.json +c5310821c338be5aa916d126008a0a0f4be6c6999775018ce29cbefc44c8a942 poster.deleted/v1.schema.json +179160ec458b710535c7846a47a1abceab1a743a3a5f11633c47c2115e82e2c4 poster.image-attachment-prepared/v1.schema.json +1a256fa47c382a4900ed8f852da9256a01ef1ddb2dc5b0b75047f827ae81644e poster.image-attachment-ready/v2.schema.json +d89954e3074fc015a20d616bf0ec1cb46c088fa417d78e006163f1c2dc61170c poster.published/v1.schema.json diff --git a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/InMemoryPosterRepository.java b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/InMemoryPosterRepository.java new file mode 100644 index 00000000..15cf66be --- /dev/null +++ b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/InMemoryPosterRepository.java @@ -0,0 +1,114 @@ +package dev.caskeleton.sample.portfolio.domain.poster.testkit; + +import dev.caskeleton.sample.portfolio.domain.poster.Poster; +import dev.caskeleton.sample.portfolio.domain.poster.PosterId; +import dev.caskeleton.sample.portfolio.domain.poster.PosterPage; +import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; +import dev.caskeleton.sample.portfolio.domain.poster.PosterSortField; +import dev.caskeleton.sample.portfolio.domain.poster.PosterStatus; +import dev.caskeleton.sample.portfolio.domain.poster.PosterTitleAlreadyExistsException; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; + +/** + * In-memory {@link PosterRepository} with the semantics of {@code PosterRepositoryAdapter}, held to + * them by {@link PosterRepositoryContract}: snapshots (a caller's later mutation is not saved), a + * new poster at version 0 and an update incrementing it, and the title rule — a save that would + * duplicate another poster's title, ignoring case, raises {@link PosterTitleAlreadyExistsException} + * as the unique index does. + * + *

        It does not model optimistic-lock conflicts on a stale version. + */ +public final class InMemoryPosterRepository implements PosterRepository { + + private final Map rows = new LinkedHashMap<>(); + + @Override + public Poster save(Poster poster) { + long version; + if (poster.version() == null) { + version = 0L; + } else { + Poster existing = rows.get(poster.id()); + if (existing == null) { + throw new IllegalStateException( + "no persisted poster row to carry audit creation from: " + poster.id()); + } + version = existing.version() + 1; + } + String key = titleKey(poster.title()); + boolean taken = + rows.values().stream() + .anyMatch( + other -> !other.id().equals(poster.id()) && titleKey(other.title()).equals(key)); + if (taken) { + throw new PosterTitleAlreadyExistsException(poster.title()); + } + Poster stored = copy(poster, version); + rows.put(stored.id(), stored); + return copy(stored, version); + } + + @Override + public Optional findById(PosterId id) { + return Optional.ofNullable(rows.get(id)).map(p -> copy(p, p.version())); + } + + @Override + public PosterPage findPage( + int page, int size, PosterSortField sortField, boolean ascending, PosterStatus status) { + int safeSize = size <= 0 ? 20 : size; + int safePage = Math.max(0, page); + List matching = + rows.values().stream().filter(p -> status == null || p.status() == status).toList(); + if (sortField != null) { + Comparator order = + sortField == PosterSortField.TITLE + ? Comparator.comparing(Poster::title) + : Comparator.comparing(Poster::status); + matching = matching.stream().sorted(ascending ? order : order.reversed()).toList(); + } + List items = + matching.stream() + .skip((long) safePage * safeSize) + .limit(safeSize) + .map(p -> copy(p, p.version())) + .toList(); + return new PosterPage(items, matching.size()); + } + + @Override + public boolean existsById(PosterId id) { + return rows.containsKey(id); + } + + @Override + public boolean existsByTitle(String title) { + String key = titleKey(title); + return rows.values().stream().anyMatch(p -> titleKey(p.title()).equals(key)); + } + + @Override + public void deleteById(PosterId id) { + rows.remove(id); + } + + /** The unique index's key: {@code lower(title)} (sample migration V8.1). */ + private static String titleKey(String title) { + return title.toLowerCase(Locale.ROOT); + } + + private static Poster copy(Poster poster, long version) { + return Poster.rehydrate( + poster.id(), + poster.title(), + poster.caption(), + poster.imageReference(), + poster.status(), + version); + } +} diff --git a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/PosterRepositoryContract.java b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/PosterRepositoryContract.java new file mode 100644 index 00000000..2835061e --- /dev/null +++ b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/poster/testkit/PosterRepositoryContract.java @@ -0,0 +1,119 @@ +package dev.caskeleton.sample.portfolio.domain.poster.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.sample.portfolio.domain.poster.Poster; +import dev.caskeleton.sample.portfolio.domain.poster.PosterId; +import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; +import dev.caskeleton.sample.portfolio.domain.poster.PosterTitleAlreadyExistsException; +import java.util.Optional; +import java.util.function.Supplier; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link PosterRepository} promises, run against {@link InMemoryPosterRepository} and + * the PostgreSQL {@code PosterRepositoryAdapter} alike (review 2026-11-03 RR-06-12). + * + *

        The promise that matters is the title rule: titles are unique ignoring case, and {@link + * PosterRepository#save} enforces it by raising the domain's {@link + * PosterTitleAlreadyExistsException}. It used to be a sentence in the port's Javadoc that pointed + * at an application type, so only the PostgreSQL adapter kept it and a unit test's mock could not. + * + *

        Every call goes through {@link #inTransaction}, so each one commits before the next reads it. + */ +public abstract class PosterRepositoryContract { + + private static final PosterId FIRST = PosterId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); + private static final PosterId SECOND = PosterId.of("0190bd6e-7c3e-7abc-8def-0123456789ac"); + + /** The repository under test, empty at the start of each test. */ + protected abstract PosterRepository repository(); + + /** Runs {@code work} in one committed transaction of the repository under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + @DisplayName("저장한 포스터는 id로 다시 읽으면 같은 제목과 버전 0으로 나온다") + void aSavedPosterIsReadBackByIdAtVersionZero() { + // given + save(Poster.create(FIRST, "여름 세일 배너", "7월 한정")); + + // when + Optional found = inTransaction(() -> repository().findById(FIRST)); + + // then + assertThat(found) + .get() + .extracting(Poster::title, Poster::version) + .containsExactly("여름 세일 배너", 0L); + } + + @Test + @DisplayName("대소문자만 다른 같은 제목의 두 번째 포스터 저장은 domain 제목 충돌 예외로 거절된다") + void aSecondPosterWithTheSameTitleInAnotherCaseIsRejected() { + // given + save(Poster.create(FIRST, "Summer Sale Banner", null)); + + // when + Throwable failure = + catchThrowable(() -> save(Poster.create(SECOND, "SUMMER SALE banner", null))); + + // then + assertThat(failure) + .isInstanceOf(PosterTitleAlreadyExistsException.class) + .hasMessage("Poster title already in use: SUMMER SALE banner"); + } + + @Test + @DisplayName("다른 포스터의 제목으로 바꾸는 저장도 같은 제목 충돌 예외로 거절된다") + void renamingAPosterToAnotherPostersTitleIsRejected() { + // given + save(Poster.create(FIRST, "Summer Sale Banner", null)); + save(Poster.create(SECOND, "Autumn Banner", null)); + Poster second = inTransaction(() -> repository().findById(SECOND)).orElseThrow(); + second.rename("summer sale banner"); + + // when + Throwable failure = catchThrowable(() -> save(second)); + + // then + assertThat(failure).isInstanceOf(PosterTitleAlreadyExistsException.class); + } + + @Test + @DisplayName("자기 제목을 대소문자만 바꿔 저장하는 것은 허용된다") + void renamingAPosterToItsOwnTitleInAnotherCaseIsAccepted() { + // given + save(Poster.create(FIRST, "Summer Sale Banner", null)); + Poster loaded = inTransaction(() -> repository().findById(FIRST)).orElseThrow(); + loaded.rename("SUMMER SALE BANNER"); + + // when + save(loaded); + + // then + assertThat(inTransaction(() -> repository().findById(FIRST))) + .get() + .extracting(Poster::title) + .isEqualTo("SUMMER SALE BANNER"); + } + + @Test + @DisplayName("existsByTitle은 대소문자를 무시하고 저장된 제목을 찾는다") + void existsByTitleIgnoresCase() { + // given + save(Poster.create(FIRST, "Summer Sale Banner", null)); + + // when + boolean exists = inTransaction(() -> repository().existsByTitle("SUMMER sale BANNER")); + + // then + assertThat(exists).isTrue(); + } + + private Poster save(Poster poster) { + return inTransaction(() -> repository().save(poster)); + } +} 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 993d1921..550dba62 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 @@ -40,6 +40,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Import; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.bean.override.mockito.MockitoBean; /** @@ -58,6 +59,9 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean; * ./gradlew openapiCheckSnapshot -PapproveOpenApiChange} (sets {@code * -Dopenapi.snapshot.write=true}). */ +// The sample's local composition (object storage off), which application.yml used to select by +// default before the demo-profile allow list removed the default (RR-07-02). +@ActiveProfiles("local") @SpringBootTest( classes = OpenApiDriftContractTest.OpenApiDriftTestApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, 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 b6367ddb..92355b96 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 @@ -21,6 +21,7 @@ import org.springframework.boot.security.oauth2.server.resource.autoconfigure.se import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -30,6 +31,9 @@ import org.springframework.web.bind.annotation.RestController; * container and checks the header across a success (200) and an error (404) response — the * status-matrix that a mock MVC test cannot exercise (MockMvc never goes through Tomcat). */ +// The sample's local composition (object storage off), which application.yml used to select by +// default before the demo-profile allow list removed the default (RR-07-02). +@ActiveProfiles("local") @SpringBootTest( classes = DateHeaderContractTest.DateProbeApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, 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 8440a8c1..0e2d519a 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 @@ -35,6 +35,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -56,6 +57,9 @@ import org.springframework.web.bind.annotation.RestController; *

        Auto-configuration is narrowed to skip security so the demo endpoint is reachable without a * JWT — security is owned by a sibling branch and is not the contract under test here. */ +// The sample's local composition (object storage off), which application.yml used to select by +// default before the demo-profile allow list removed the default (RR-07-02). +@ActiveProfiles("local") @SpringBootTest( classes = VirtualThreadMdcE2ETest.TestBootstrap.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, 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 7ea15eba..2cd61b73 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 @@ -30,6 +30,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Import; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.bean.override.mockito.MockitoBean; import tools.jackson.databind.ObjectMapper; @@ -40,6 +41,9 @@ import tools.jackson.databind.ObjectMapper; * schema cannot pass). The release-blocking drift gate against a committed snapshot is * owned by feature-contract-verification-test-suite (planned). */ +// The sample's local composition (object storage off), which application.yml used to select by +// default before the demo-profile allow list removed the default (RR-07-02). +@ActiveProfiles("local") @SpringBootTest( classes = OpenApiSnapshotTest.OpenApiTestApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, diff --git a/src/shared-contract/README.md b/src/shared-contract/README.md index d3b2e6bb..e825d9e2 100644 --- a/src/shared-contract/README.md +++ b/src/shared-contract/README.md @@ -366,7 +366,8 @@ Spring/Lettuce 타입을 노출하지 않는다. - **`ERROR_CODE`=100 은 `error-codes.yaml` 의 행 수 상한과 동기화한다.** 레지스트리가 100행을 넘으면 이 상수와 레지스트리 메모를 함께 갱신해야 한다. - **`TENANT_ID`=1000:** 메트릭 라벨은 bounded mapping-table ID 나 cohort bucket 을 써야 한다 — - raw UUID tenant 식별자는 라벨로 금지. 1001번째 tenant 부터는 bucket folding 이 자동 적용된다. + raw UUID tenant 식별자는 라벨로 금지. 이 상수는 상한 값일 뿐이다: 1000개를 넘는 tenant 값을 접어 + 주는(bucket folding) 코드는 없으므로, 상한을 지키는 매핑은 메트릭을 등록하는 쪽이 만든다. - **tag-key 매핑 quirk 2가지**(`limitFor` 에서 명시 처리): (1) HTTP 메트릭 레지스트리 행의 tag 이름은 `status_code` 가 아니라 `status` 다 — 혼동을 막으려 `status`/`status_code` 둘 다 `STATUS_CODE`(7)로 매핑. (2) Resilience4j bound 는 `outcome` tag(5값)에 적용 — 상수명은 명료성을 위해 diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java index 5bd8e8c6..db6e1d52 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java @@ -47,6 +47,8 @@ public enum OperationalError implements ApiErrorCode { IDEMPOTENT_IN_FLIGHT(Category.CONFLICT, 409, true), IDEMPOTENT_REQUEST_MISMATCH(Category.VALIDATION, 422, false), IDEMPOTENCY_UNAVAILABLE(Category.TRANSIENT_DEPENDENCY, 503, true), + // the action ran and recording its result failed; a resend with the same key is safe + IDEMPOTENCY_COMPLETION_UNKNOWN(Category.TRANSIENT_DEPENDENCY, 503, true), IDEMPOTENCY_RECOVERY_REQUIRED(Category.DATA_INTEGRITY, 500, false), // adapter runtime lifecycle ADAPTER_DISABLED(Category.INTERNAL, 500, false), diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/runtime/RuntimeEnvironment.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/runtime/RuntimeEnvironment.java index cd3bcd08..5ad8aed2 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/runtime/RuntimeEnvironment.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/runtime/RuntimeEnvironment.java @@ -29,11 +29,11 @@ import java.util.Optional; *

        Three module families ask this question — the composition root, the Fileserver and HTTP client * platform configurations, and the object-storage adapter. {@code shared-contract} is the one leaf * all of them may depend on. It is also Java-stdlib-only, so this type cannot accept Spring's - * {@code Environment}. Spring-aware composition code captures active profiles through - * app-bootstrap's {@code RuntimeProfileSnapshot} bridge and passes the resulting plain collection - * here. That keeps the vocabulary testable without a container and usable from the {@code - * EnvironmentPostProcessor} phase, where no application context exists yet, while preventing ad-hoc - * profile reads from reappearing throughout bootstrap code. + * {@code Environment}. Spring-aware composition code captures active profiles through the {@code + * RuntimeProfileSnapshot} bridge in {@code adapter:outbound:support} and passes the resulting plain + * collection here. That keeps the vocabulary testable without a container and usable from the + * {@code EnvironmentPostProcessor} phase, where no application context exists yet, while preventing + * ad-hoc profile reads from reappearing throughout bootstrap code. * *

        The vendored {@code messaging:*} platform deliberately does not use this type. It depends on * no {@code shared-contract} type by design, and its own profile vocabulary is its own contract. diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/error/OperationalErrorTest.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/error/OperationalErrorTest.java index 3de1a863..af634e14 100644 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/error/OperationalErrorTest.java +++ b/src/shared-contract/src/test/java/dev/caskeleton/shared/error/OperationalErrorTest.java @@ -239,6 +239,21 @@ class OperationalErrorTest { assertThat(OperationalError.IDEMPOTENT_IN_FLIGHT.retryable()).isTrue(); } + @Test + @DisplayName("action 뒤 결과를 기록하지 못한 결과 불명은 같은 키로 다시 보내면 되므로 retryable 503이다") + void idempotencyCompletionUnknownIs503TransientRetryableWithTheSameKey() { + // docs/web/http-contract.md §2 (re-review 2026-11-03, RR-02-03) — the action ran and its result + // was not recorded. Distinct from IDEMPOTENCY_UNAVAILABLE (refused before the action) by code; + // a + // resend with the same key is judged by the server (replay / in-flight / recovery required). + assertThat(OperationalError.IDEMPOTENCY_COMPLETION_UNKNOWN.code()) + .isEqualTo("IDEMPOTENCY_COMPLETION_UNKNOWN"); + assertThat(OperationalError.IDEMPOTENCY_COMPLETION_UNKNOWN.httpStatus()).isEqualTo(503); + assertThat(OperationalError.IDEMPOTENCY_COMPLETION_UNKNOWN.category()) + .isEqualTo(Category.TRANSIENT_DEPENDENCY); + assertThat(OperationalError.IDEMPOTENCY_COMPLETION_UNKNOWN.retryable()).isTrue(); + } + @Test void idempotentRequestMismatchIs422ValidationNotRetryable() { // D8 / error-codes.yaml#IDEMPOTENT_REQUEST_MISMATCH — same key + different body is a client From ecc74b7df724eb373c4af1b5b654764e89620660 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 00:21:51 +0900 Subject: [PATCH 06/17] =?UTF-8?q?docs(review):=202=EC=B0=A8=20=EC=9E=AC?= =?UTF-8?q?=EB=A6=AC=EB=B7=B0=20=EA=B2=B0=EA=B3=BC=EC=99=80=20=ED=8C=8C?= =?UTF-8?q?=EC=83=9D=20=EC=84=9C=EB=B9=84=EC=8A=A4=20=EC=97=85=EA=B7=B8?= =?UTF-8?q?=EB=A0=88=EC=9D=B4=EB=93=9C=20=EC=95=88=EB=82=B4=EB=A5=BC=20?= =?UTF-8?q?=EB=8D=94=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 1차 재리뷰 수정(bbe944bd)도 앞 라운드처럼 새 결함을 만들었는지 아무도 다시 읽지 않았다. 이 브랜치는 파생 서비스가 깨지는 변경이 많은데 따라올 안내가 없었다. 방법: 수정 커밋만 대상으로 리뷰어 4명이 1차와 같은 템플릿·스킬 방식으로 봤다(round2/). Critical·회귀 0, Important 7(이번 라운드가 새로 만든 것 4), Minor 22. 3차 수정에 쓸 결정을 README 9.1절에 적었다. 파생 서비스용 docs/upgrade/2026-11-maturity-review.md에 깨지는 변경 38건, 마이그레이션 영향, 따라오는 순서를 diff 근거와 함께 정리했다. 위험·한계: 이 커밋은 기록만 담는다. Important 7건은 다음 수정에서 고친다. 업그레이드 안내는 tech-log-backend에 실제로 적용해 보지 않았다. 검증: 문서만. 리뷰어별 실행 명령은 각 문서 "범위" 절. Refs: docs/reviews/2026-11-03-rereview/README.md 9절 --- docs/reviews/2026-11-03-rereview/README.md | 33 ++ .../round2/01-core-app-inbound.md | 314 ++++++++++++++++++ .../round2/02-persistence-messaging.md | 246 ++++++++++++++ .../2026-11-03-rereview/round2/03-outbound.md | 268 +++++++++++++++ .../round2/04-bootstrap-build-sample.md | 306 +++++++++++++++++ docs/upgrade/2026-11-maturity-review.md | 271 +++++++++++++++ 6 files changed, 1438 insertions(+) create mode 100644 docs/reviews/2026-11-03-rereview/round2/01-core-app-inbound.md create mode 100644 docs/reviews/2026-11-03-rereview/round2/02-persistence-messaging.md create mode 100644 docs/reviews/2026-11-03-rereview/round2/03-outbound.md create mode 100644 docs/reviews/2026-11-03-rereview/round2/04-bootstrap-build-sample.md create mode 100644 docs/upgrade/2026-11-maturity-review.md diff --git a/docs/reviews/2026-11-03-rereview/README.md b/docs/reviews/2026-11-03-rereview/README.md index 484d3913..5fbe2cb2 100644 --- a/docs/reviews/2026-11-03-rereview/README.md +++ b/docs/reviews/2026-11-03-rereview/README.md @@ -110,3 +110,36 @@ Minor 41건은 각 문서에 있다. - **짝 프론트**: `IDEMPOTENCY_COMPLETION_UNKNOWN`(503, 결과 불명)을 인계 문서에 더했다. - **이 환경에서 확인할 수 없는 것**: 실제 CI runner 실행. + +## 9. 2차 재리뷰 (수정 커밋 `bbe944bd`만, 2026-11-04) + +1차 재리뷰 수정(`bbe944bd`, 406파일)을 리뷰어 4명이 같은 템플릿·스킬 방식으로 다시 봤다(`round2/01~04-*.md`). 저장소 전체가 아니라 이 커밋만 본 이유: 원래 리뷰와 1차 재리뷰가 전 영역을 이미 봤고, 위험은 "수정이 새 결함을 만든다"는 반복 패턴이다. + +| 문서 | Important | Minor | 이번 라운드가 새로 만든 Important | 회귀 | +|---|---|---|---|---| +| [round2/01 core·inbound](round2/01-core-app-inbound.md) | 2 | 5 | RR-01-12 | 0 | +| [round2/02 persistence·messaging](round2/02-persistence-messaging.md) | 1 | 7 | RR-02-09 | 0 | +| [round2/03 outbound](round2/03-outbound.md) | 1 | 7 | 없음 | 0 | +| [round2/04 bootstrap·build·sample](round2/04-bootstrap-build-sample.md) | 3 | 3 | RR2-04-01, RR2-04-02 | 0 | + +Important 7건: +- RR-01-11 — `http-contract.md`는 결과 불명 503 뒤 같은 키 재전송이 lease 뒤 500으로 막힌다고 적었지만, Redis store는 lease가 지난 EXECUTING을 넘겨받아 작업을 다시 실행한다(실 Redis 확인). RR-02-03 부분. +- RR-01-12 — 새 `@SystemInvoked` 규칙 두 개가 매뉴얼 09장의 이벤트 소비 handler → 쓰기 use case 경로를 막는다. +- RR-03-11 — Redis claim이 key TTL을 replay TTL로 둬서, replay TTL < processing lease인 배포에서 lease 도중 key가 사라져 같은 키가 두 번 실행된다(실 Redis Lua 확인). RR-04-08 부분. +- RR-02-09 — V22가 `outbox_event`에 가장 강한 잠금을 걸면서 `lock_timeout`이 없다(실 PG16: 19초 대기, 그동안 읽기·쓰기 막힘). +- RR2-04-01 — prod `fixture-` 거부가 비밀이 아닌 값(`HOSTNAME` 등)까지 막는다. +- RR2-04-02 — 데모 허용 목록의 `test`·`demo` 프로필로 sample이 뜨지 않는다(이미지 실행 문서대로 하면 기동 거부). +- RR2-04-03 — 기동 rule runner에 검사 없는 면제 경로가 남아 `@Value` 필드·JavaBean 설정이 조용히 null(RR-06-01 부분). + +### 9.1 결정 (3차 수정용, 2026-11-04) + +| 항목 | 결정 | 이유 | +|---|---|---| +| RR-01-11 결과 불명 뒤 재전송 | 두 멱등성 store(PostgreSQL·Redis)가 같은 공유 계약을 따른다: lease가 지난 실행 중 기록은 작업을 다시 돌리지 않고 "회복 필요"로 답한다. 계약 문서와 코드를 맞춘다 | 결과 불명인 작업을 서버가 몰래 다시 실행하면 이번 계약의 목적(중복 효과 방지)이 무너진다 | +| RR-03-11 Redis key TTL | claim·renew 모두 key TTL ≥ max(replay TTL, processing lease). 설정 검사도 둔다 | lease가 남아 있는 동안 key가 사라지면 안 된다 | +| RR-01-12 소비 경로 | 사용자가 닿는 전송(web·GraphQL·gRPC·WebSocket)만 `@SystemInvoked` use case에 닿지 못한다. 시스템이 부르는 inbound(메시지 소비자·스케줄러)는 명시적 표시로 허용하고, 매뉴얼 09장 경로를 실제 테스트로 고정한다 | 규칙의 목적은 "사용자 요청이 권한 검사 없이 쓰기에 닿지 않게"다. 시스템 경로까지 막으면 매뉴얼이 거짓이 된다 | +| RR2-04-01 fixture 값 거부 범위 | 비밀로 분류된 키(`docs/registries/secrets-classification.yaml`)만 검사한다 | 운영 hostname·이름은 비밀이 아니다 | +| RR2-04-02 데모 프로필 | 허용 목록의 각 프로필은 sample이 실제로 뜨는 프로필이어야 한다. 뜨게 고치거나, 독립 실행용이 아니면 목록에서 뺀다. 문서·Dockerfile과 맞춘다 | 허용한 프로필로 뜨지 않으면 허용 목록이 거짓이다 | +| RR-02-09 V22 잠금 | V21과 같은 `SET LOCAL lock_timeout`과 같은 모양의 lane 테스트 | 같은 커밋 안의 두 마이그레이션이 다른 규칙을 따르면 안 된다 | + +멈추는 기준: 3차 수정 뒤 그 diff만 보는 확인 리뷰에서 새 Important가 0이면 멈춘다. diff --git a/docs/reviews/2026-11-03-rereview/round2/01-core-app-inbound.md b/docs/reviews/2026-11-03-rereview/round2/01-core-app-inbound.md new file mode 100644 index 00000000..9864771f --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round2/01-core-app-inbound.md @@ -0,0 +1,314 @@ +# 01 core·application·inbound 재리뷰 (2026-11-03, 2차) + +경로는 저장소 루트 기준이다. 코드 경로는 `src/`가 앞에 붙는다. + +## 범위 — 본 pathspec, 불러온 스킬과 적용한 기준, 실행한 명령과 결과, 못 본 것 + +### 본 pathspec + +- 리뷰 범위: Base `7ef8d0b4` → Head `bbe944bd`(커밋 1개) 중 아래 pathspec. 152파일, +5,757 −692. + ```text + src/domain-core src/shared-contract src/application-core src/application-fileserver + src/application-objectstorage src/composition src/adapter/inbound src/grpc src/grpc-advanced + scripts docs/manual docs/web + ``` +- 맡은 1차 재리뷰 발견: RR-01-01~10, RR-02-01~08, RR-07-01, RR-07-06, RR-04-04(=RR-01-05). +- 이 문서의 새 발견 ID는 `RR-01-11`부터다. 1차의 `RR-01-01~10`과 겹치지 않게 이어 붙였다. +- 읽은 방식: diff가 커서 여러 번에 나눠 직접 읽었다(하위 에이전트 없음). + 1. application-core main diff 전부(멱등성 executor·예외, `IntegrationEventDraft`·`IntegrationIdentity`, + `SubmitDurableOperationUseCase`, outbox 포트·relay·`OutboxPublishAttempt`, `SystemInvoked`). + 2. application-core testFixtures 중 멱등성 저장소 계약, outbox 순서 계약·fake, `OverlappingWrites`, + `DirectTransactionPort`, 캐시 계약 추가분. + 3. composition: service-runtime(`PermissionEnforcementGuard`), outbox-relay(조립·지표·설정), + idempotency(`IdempotencySettings`), fileserver-platform(move 조립). + 4. web main diff 전부(`EnvelopeErrorController`, `HttpStatusErrorCodes`, `EnvelopeBodyAdvice`, + `SecurityConfig`, `WebMvcPlatformAutoConfiguration`, `RetryAfterAdvisor`)와 새 시스템 테스트·testkit. + 5. GraphQL scorer diff와 새 union·interface 테스트. 같은 leaf의 page 크기 계산 복사본을 grep으로 전수 확인. + 6. gRPC: `GrpcClaimToken`, 포트, JPA adapter·repository·entity·V003, in-memory fake, 공유 계약 diff, + interceptor·decision, 기동 검증기. + 7. application-fileserver: move use case, `FileAccessSubject.owns`, 새 계약 6개의 케이스 목록과 상속 관계, + 쿼터 fake. + 8. 생성 명령 템플릿·탐침·`verify-feature-scaffold.sh` diff, 매뉴얼 04·05·06·07·09 diff, `docs/web/http-contract.md` diff. +- 범위 밖에서 확인용으로 읽은 것: `ApplicationBoundaryArchitectureTest`(D4·새 ArchUnit 2개), + `RequiresPermissionAuthorizationManager`, `adapter/inbound/messaging/README.md`·통합 테스트의 handler 모양, + Redis 멱등성 Lua(`IdempotencyScripts.java`)와 adapter, `PostgreSqlIdempotencyStore`와 그 PG 테스트, + `JpaFileQuota`·`JpaQuotaReclaim`(호출자 트랜잭션 요구 여부), `docs/registries/error-codes.yaml` diff, + ADR-GRPC-004 diff. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +| --- | --- | --- | +| `superpowers:requesting-code-review` | 리뷰어 템플릿(Strengths → Critical/Important/Minor → Declined → Assessment), 실제 심각도로 분류, 읽지 않은 코드에 판정 금지 | 문서 양식 전체. 발견마다 "고치는 법"과 4절 결정을 코드로 대조 | +| `clean-architecture` | 의존은 안쪽으로, 포트는 안쪽이 소유, composition root(Main)가 조립, 경계에서 framework 격리 | `@SystemInvoked` 조립 규칙이 시스템 호출자(relay·이벤트 소비자)를 composition에서 조립할 수 있게 두는지, web leaf가 application-core 상수를 읽는 방향, 계약 키트 위치 | +| `api-and-interface-design` | 일관된 오류 의미, Hyrum's Law(관찰되는 동작이 계약), 멱등 키의 세 결과(성공·실패·불명)와 in-flight 중복 처리, 계약과 구현의 일치 | `IDEMPOTENCY_COMPLETION_UNKNOWN`이 약속한 재전송 판정을 저장소 구현이 지키는지, `/error` 응답 status·모양, gRPC·GraphQL wire 변경 표시 | +| `security-and-hardening` | 인가는 모든 요청에서, 오류 본문에 내부 정보 금지, 자원 상한(DoS), 숨은 우회 경로 | ERROR 디스패치 허용이 새 노출을 만드는지, `@SystemInvoked` 우회 경로, GraphQL union 아래 page 상한, 파일 move 쿼터 우회 | + +### 실행한 명령과 결과 + +| 명령 | 결과 | +| --- | --- | +| `git diff --stat / --shortstat 7ef8d0b4..bbe944bd -- ` | 152파일 +5,757 −692 | +| `git grep`으로 `@SystemInvoked` 사용처, `new PublishPendingOutboxEventsUseCase`, `effectivePageSize`, `sendError(`, `SecurityFilterChain`, `extends <각 fileserver 계약>` 전수 확인 | 아래 표·발견의 근거 | +| `git worktree add --detach /rr2-01 bbe944bd` 후 `IdempotencyStoreContract`에 탐침 메서드 1개 추가, `flock … ./gradlew :adapter:outbound:cache-redis:redisContainerContractTest --console=plain -i` | 첫 실행은 탐침의 Error Prone `ReturnValueIgnored`로 컴파일 실패(탐침 코드 문제). 고친 뒤 `BUILD SUCCESSFUL in 44s`, 출력 `RR2-PROBE … duringLease=InProgress afterLease=TakenOverClaimed`(RR-01-11) | +| `git worktree remove --force /rr2-01` | 탐침과 함께 삭제 | + +### 못 본 것 + +- 전체 게이트는 다시 돌리지 않았다. 재리뷰 README 7절 결과를 읽기만 했다. +- gRPC ledger의 PG lane(`JpaGrpcOperationLedgerContractIT`)은 다시 돌리지 않았다. 동시 commit 경쟁은 그 lane이 + 7절 게이트(`-p optional-platforms … integrationCheck`)에서 통과했다는 기록과 SQL을 읽은 것에 기댄다. +- Jetty의 오류 디스패치, 관리 포트를 따로 둔 배포의 오류 처리는 보지 않았다. +- application-core의 outbox·messaging 변경(RR-05-xx, 06-10~14)은 diff를 읽었지만 판정은 05 영역 리뷰어 몫으로 두었다 + (「Declined to judge」). +- sample-portfolio(데모 체인의 ERROR 디스패치 허용, `WorkLogReservedPayload`)는 pathspec 밖이라 grep으로 수정 여부만 봤다. + +## Strengths + +- `@SystemInvoked` 빈은 advisor가 있어도 기동을 멈춘다. 검사가 advisor 검사보다 먼저다 + (`src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java:57-70`). 테스트가 "advisor가 있어도 + 실패"를 고정한다(`PermissionEnforcementGuardTest.aSystemInvokedUseCaseRegisteredAsABeanFailsStartupEvenWithAnAdvisor`). +- relay는 여전히 `new`로 조립돼 scheduler에만 들어간다(`src/composition/outbox-relay/.../OutboxRelayAutoConfiguration.java:80`). + 새 기동 차단이 relay를 막지 않는다. +- gRPC ledger의 모든 전이가 `claim_attempt`를 조건에 넣은 UPDATE 한 문장이다 + (`GrpcOperationLedgerRepository.java` `tryReclaimFailed`·`tryReclaimStale`·`tryMarkCommitted`·`tryMarkFailed`). + load-check-save가 사라졌다. 공유 계약에 "옛 owner의 실패 무시"(`GrpcOperationLedgerContract.java:439`)와 + "동시 commit은 하나만"(`:515`)이 들어가 fake와 PG adapter가 같이 받는다. +- claim이 "충돌인데 행이 없음"을 보면 insert를 한 번 더 한다(`JpaGrpcOperationLedger.java:49-62`). 1차의 purge 경쟁이 닫혔다. +- GraphQL scorer가 `GraphQLCompositeType`으로 내려간다(`GraphQlDocumentComplexityScorer.java:154,232,265`). union과 + interface 각각 "중첩 list 곱셈"과 "page 상한 거부"를 테스트한다(`GraphQlDocumentComplexityScorerTest.java:299` 등). +- `/error` 응답이 요청에서 아무것도 싣지 않는다(`EnvelopeErrorController.java:60-71`). 실제 Tomcat에서 방화벽 거부 + 경로를 단언하고, 기본 JWT 체인에서 "오류 디스패치는 원래 400, `/error` 직접 호출은 401"을 둘 다 확인한다 + (`JwtChainErrorDispatchIT`). +- status → code 표가 한 곳이다(`HttpStatusErrorCodes.java:18`). 예외 처리기와 오류 컨트롤러가 같은 표를 쓴다. +- move의 쿼터 이동이 relocate와 같은 트랜잭션이다(`MoveFileApplicationUseCase.java:92-109`). JPA 쪽 세 포트가 모두 + 호출자 트랜잭션을 요구하므로(`JpaFileQuota.java:39,58,71`, `JpaQuotaReclaim.java:42`) 버전 충돌이면 쿼터도 롤백된다. +- 생성 계약에 `inTransaction` hook이 생겼고(`__Feature__RepositoryContract.java.tmpl:41`), 왕복 검사가 "호출자 + 트랜잭션 밖이면 거부하는 저장소"로 계약을 한 번 더 돌린다(`scripts/verify-feature-scaffold.sh:140-161`). 확인할 + 결과 XML 목록도 템플릿에서 만든다(`:102`). +- Retry-After 2초가 상수 하나이고(`IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER`), lease가 그 이하면 기동이 실패한다 + (`IdempotencySettings.java:57`). +- 파일 소유자 규칙이 `FileAccessSubject.owns` 하나다(`FileAccessSubject.java:63`). fake와 `RoleBasedFileAccessPolicy`가 + 둘 다 부르고, `FileAccessPolicyPortContract`를 둘 다 상속한다. + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +| --- | --- | --- | +| RR-01-01 | 닫힘 | 템플릿 계약의 모든 호출이 `inTransaction`을 거친다(`__Feature__RepositoryContract.java.tmpl:41` 이하). 탐침 `CallerTransaction__Feature__RepositoryContractTest.java.tmpl`이 트랜잭션 요구 저장소로 계약을 통과시키고, `verify-feature-scaffold.sh:140-161`이 그 결과 XML을 확인한다. 매뉴얼 04장 4단계에 hook 사용을 적었다 | +| RR-01-02 = RR-07-01 | 닫힘(결정대로) | 4절 결정 두 가지가 다 들어갔다: 빈이면 기동 실패(`PermissionEnforcementGuard.java:57-70`), inbound adapter 의존 금지 ArchUnit(`ApplicationBoundaryArchitectureTest.java:455-467`). 결정이 만든 새 위험 → RR-01-12 | +| RR-01-03 | 닫힘 | 07장(`docs/manual/07-authorization.md:65-89`), 09장(`docs/manual/09-outbox-events.md:56-87`), 06장(`:44-46`) 문장이 코드와 맞다. `INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`(`ApplicationBoundaryArchitectureTest.java:475`), `application-core/CLAUDE.md` 표에 두 타입 | +| RR-01-04 (+RR-07-06) | 닫힘 | 저장 포트 9개 모두 계약이 있고 fake와 PG 테스트가 각각 상속한다(`extends` grep: ContentReferenceLedger·FileQuotaLedger·RecoveryQueue·StagingUploadLocator·UploadSession·FileMetadata·CleanupQueue). `FileQuotaLedgerContract`가 만료·해제 뒤 확정·연장 거부를 같은 표로 본다. build.gradle 주석도 사실대로 고쳤다 | +| RR-01-05 = RR-04-04 | 닫힘 | `MoveFileApplicationUseCase.java:100-109`가 대상 `requireRoom` → 예약·확정 → 출발 회수를 relocate와 한 트랜잭션에서 한다. 테스트 두 개(`FileLifecycleUseCasesTest.java:467,485`). 남은 작은 틈 → RR-01-17 | +| RR-01-06 | 닫힘 | 2^53 경우(`CacheRegionContract`), 트랜잭션 밖 거부·롤백 번호 재사용(`OutboxAggregateSequenceContract`), 시간 경우는 시계 없으면 abort(`IdempotencyStoreContract.java:94`). 새로 넣은 겹침 경우의 fake 실행 방식 → RR-01-16 | +| RR-01-07 | 닫힘 | `__Feature__Config.java.tmpl:36` `afterName = PersistenceJpaAutoConfiguration` | +| RR-01-08 | 닫힘(범위 밖 grep) | `sample-portfolio/.../WorkLogReservedPayload.java:15`가 `IntegrationIdentity.isCanonical`을 부른다 | +| RR-01-09 | 닫힘 | `shared-contract/README.md:369-370`, `RuntimeEnvironment.java:32-33`, application-core README 알림 절 정리 | +| RR-01-10 | 닫힘 | `verify-feature-scaffold.sh:102-127`이 템플릿의 `*Test.java.tmpl` 전부에서 결과 XML 경로를 만들고 `tests="0"`도 거부한다 | +| RR-02-01 | 닫힘 | 위 Strengths. union·interface 아래 곱셈·page 상한 테스트 4개 | +| RR-02-02 | 닫힘 | `EnvelopeErrorController` + `SecurityConfig.java:91` ERROR 디스패치만 허용 + `EnvelopeBodyAdvice`가 4xx·5xx를 감싸지 않음. 실 Tomcat·JWT 체인 테스트. 문서와 다른 작은 점 → RR-01-13 | +| RR-02-03 | 부분 | 코드 분기(`IdempotencyExecutor.java:251,286`)와 테스트는 들어갔다. 그러나 이 코드를 실제로 내는 저장소는 Redis뿐이고, Redis는 lease가 지난 EXECUTING 기록을 넘겨받아 작업을 다시 돌린다. 계약 문서가 약속한 "lease 뒤 500 RECOVERY_REQUIRED"가 지켜지지 않는다 → RR-01-11 | +| RR-02-04 | 닫힘 | 토큰·V003·조건부 UPDATE·계약 케이스(Strengths). `release`만 토큰 밖에 남았다 → RR-01-15 | +| RR-02-05 | 닫힘 | `IdempotencySettings.java:57`, `RetryAfterAdvisor`가 같은 상수를 읽는다 | +| RR-02-06 | 닫힘 | `GrpcStatusMapperTest`·`GraphQlWireErrorMapperTest` 케이스, 두 README, registry `compatibility_impact: behavior-change` | +| RR-02-07 | 닫힘 | 검증기 문구(`GrpcPlatformStartupValidator.java` keyed-method 메시지), ADR-GRPC-004 "(b)" 기록, `src/grpc/CLAUDE.md:168` | +| RR-02-08 | 부분 | ② Javadoc은 고쳤다(`GraphQlDeadline.java:17-19`). ① calculator의 복사본은 지웠지만 같은 규칙의 세 번째 복사본이 `GraphQlClientPolicy.java:101`에 남았다 → RR-01-14 | +| RR-07-01 | 닫힘(결정대로) | = RR-01-02 | +| RR-07-06 | 닫힘 | `FileAccessSubject.owns` 한 곳, `FileAccessPolicyPortContract`를 `FakeFileAccessPolicyContractTest`와 `RoleBasedFileAccessPolicyContractTest`가 상속 | +| RR-04-04 | 닫힘 | = RR-01-05 | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +#### RR-01-11 · `IDEMPOTENCY_COMPLETION_UNKNOWN` 뒤 "같은 키 재전송은 안전" 약속을 Redis 저장소가 지키지 않는다 — lease가 지나면 작업을 다시 돌린다 + +- **위치**: `docs/web/http-contract.md:108-114`, `src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompletionUnknownException.java:16-17`, + `src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java:50`(주석), `docs/registries/error-codes.yaml:448-450`(주석), + `src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java:71-79`, + `src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java:136-137` +- **무엇이 틀렸나**: + - 새 계약은 "결과 불명 503을 받으면 같은 키로 다시 보내라. 서버가 판정한다 — 기록됐으면 재생, lease 안이면 409, + lease가 지났으면 500 `IDEMPOTENCY_RECOVERY_REQUIRED`"라고 적는다(`http-contract.md:111-113`, 예외 Javadoc `:16-17`). + - 이 예외는 `complete`가 `UNAVAILABLE`을 돌려줄 때만 난다. `UNAVAILABLE`을 돌려주는 저장소는 Redis뿐이다 + (`RedisIdempotencyStoreAdapter.java:248,251` — lane이 보내기 전에 거절). PostgreSQL 저장소에는 `UNAVAILABLE` 결과가 + 아예 없다(`PostgreSqlIdempotencyStore`에서 grep 0건). 즉 결과 불명은 실제로 Redis 배포에서만 생긴다. + - 그때 Redis 기록은 `EXECUTING`으로 남는다(complete가 보내지지 않았다). 그런데 Redis CLAIM 스크립트는 상태를 가리지 + 않고 lease가 끝난 기록을 넘겨준다: `if state == 'FAILED_RETRYABLE' or (leaseUntil ~= nil and leaseUntil <= nowMillis)` + → `TAKEN_OVER`(`IdempotencyScripts.java:71-79`). executor는 `TakenOverClaimed`를 받으면 `startAndRun`으로 작업을 다시 + 돌린다(`IdempotencyExecutor.java:136-137`). + - PostgreSQL은 반대다. lease가 지난 `EXECUTING`은 `ABANDONED`로 바꾸고 `RecoveryRequired`를 준다 + (`PostgreSqlIdempotencyStore.java:153-155`, 테스트 이름 `expiredExecutingRecordRequiresReconciliationAndIsNeverBlindlyTakenOver`). + 공유 `IdempotencyStoreContract`는 이 경우를 묶지 않는다("expiry and take-over … stay with each store's own tests", `:34-35`). + 그래서 두 저장소가 갈라진 채 게이트를 통과한다. +- **왜 중요한가**: + - 4절 결정이 막으려던 것은 "결과 불명을 '안 됨'으로 믿고 다시 실행"이다. 새 코드는 클라이언트에게 "같은 키면 안전"이라고 + 말하는데, 이 코드가 나는 유일한 저장소에서 같은 키 재전송이 lease(기본 30초) 뒤 작업을 다시 실행한다. + - 발생 조건: `provider=redis` + complete 단계에서 lane이 포화·종료 중 + action이 트랜잭션 밖 효과(외부 호출·메일)를 가짐 + + 클라이언트가 계약대로 30초 넘게 재시도. 결과: 외부 효과가 두 번 일어난다. 클라이언트는 "같은 키라 안전"이라고 믿었으므로 + 이상을 알아챌 근거가 없다. + - DB만 쓰는 action이고 `execute`가 `tx.inWrite` 안이면(sample `PublishPosterImageUseCase.java:109-118`) DB 효과는 롤백되므로 + 다시 돌리는 것이 오히려 맞다. 하지만 그것도 계약 문장("500 RECOVERY_REQUIRED")과 다르다. 어느 쪽이든 문서가 틀렸다. + - 사용자 원칙: 위험이 코드에 드러나야 한다. 지금은 두 저장소의 차이가 각자의 테스트에만 있고, 계약 문서는 PG 쪽만 말한다. +- **고치는 법**: 4절 결정 문장("lease 뒤 회복 필요")을 기준으로 맞춘다. + 1. Redis CLAIM 스크립트: `state == 'EXECUTING'`이고 lease가 끝났으면 `ABANDONED`로 바꾸고 `RECOVERY_REQUIRED`를 돌려준다. + lease 만료 넘겨받기는 `CLAIMED`(실행 전)와 `FAILED_RETRYABLE`만 한다. PG와 같은 규칙이다. + 2. `IdempotencyStoreContract`에 시간 경우 하나: "실행 시작 뒤 lease가 지나면 다른 claim은 `RecoveryRequired`". + in-memory는 abort되고 Live Redis·PG lane이 실제로 돈다(아래 탐침이 그 모양이다). + 3. 예외 Javadoc의 "Effects inside the action's own transaction roll back"을 "`execute`를 쓰기 트랜잭션 안에서 부른 경우"로 + 좁힌다. action이 자기 트랜잭션을 따로 커밋하면 DB 효과도 남는다. + - Redis 스크립트 변경은 04 영역 파일이다. 계약 문서·계약 테스트·Javadoc은 이 영역이다. +- **가이드 심각도·우선순위**: Medium · P2 (Redis 배포·complete 단계 lane 거절·외부 효과가 겹칠 때만. 기본 조립은 멱등성 비활성) +- **증거**: E3 — 아래 탐침. 코드 경로는 E1. + - 탐침: worktree에서 `IdempotencyStoreContract`에 메서드 하나를 넣었다. claim(lease 1s) → `markExecutionStarted` → + 다른 attempt로 claim(lease 안) → `elapse(2s)` → 다른 attempt로 claim. `LiveRedisIdempotencyStoreContractTest`(Testcontainers + Redis, 실제 서버 시계)로 `redisContainerContractTest` lane을 돌렸다. + - 출력: `RR2-PROBE LiveRedisIdempotencyStoreContractTest duringLease=InProgress afterLease=TakenOverClaimed`, + `BUILD SUCCESSFUL in 44s`. lease 안에서는 409가 되고, lease 뒤에는 계약이 말한 `RecoveryRequired`가 아니라 + `TakenOverClaimed`다 — executor는 이것을 받으면 작업을 다시 돌린다. + - PG 쪽 반대 동작은 기존 테스트 `PostgreSqlIdempotencyIntegrationTest.java:164`가 고정한다(E2, 다시 돌리지 않음). + +#### RR-01-12 · 새 `@SystemInvoked` 규칙 둘이 매뉴얼 09장의 이벤트 소비 경로(쓰기 use case 호출)를 막는다 — 규칙을 지키는 방법이 문서에 없다 + +- **위치**: `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java:455-467`, + `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java:57-70`, + `docs/manual/09-outbox-events.md:115-117`, `docs/manual/07-authorization.md:65-89`, `src/adapter/inbound/messaging/README.md:32,95` +- **무엇이 틀렸나**: + - 매뉴얼 09장 4단계는 소비 handler(`MessageHandler`)를 `adapter:inbound:messaging`에 두고 "delivery 하나를 use case 호출 + 하나로 바꾸라, use case는 평소처럼 `tx.inWrite`로 쓴다"고 가르친다. 소유자 결정 10(Kafka 소비)의 정식 경로다. + - 그 use case는 쓰기다(`WRITE_REPOSITORY`). 지금 쓰기 use case가 고를 수 있는 길은 셋인데, 소비 handler에서는 셋 다 막힌다. + 1. `@RequiresPermission` + bean: 소비 스레드에는 `Authentication`이 없다. `RequiresPermissionAuthorizationManager.java:56`이 + `auth == null`이면 거부한다. 메시지는 재시도 후 DLQ로 간다. + 2. `@SystemInvoked`(07장이 말하는 "시스템이 부르는 쓰기"): bean이면 이번 라운드의 가드가 기동을 막는다. handler가 그 + 클래스에 의존하면 이번 라운드의 ArchUnit이 막는다 — 규칙이 `..adapter.inbound..` 전체를 대상으로 하므로 + `dev.caskeleton.adapter.inbound.messaging`도 들어간다(`:458`). + 3. 표시 없음: D4(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)가 빌드를 막는다. + - 남는 길은 "handler가 구체 클래스 대신 `CommandUseCase` 같은 인터페이스에 의존하고, composition이 `new`로 만든 + `@SystemInvoked` use case를 handler bean에 넣는다"뿐이다. 이 방법은 07장·09장·messaging README·ArchUnit 메시지 어디에도 + 없다. ArchUnit 메시지는 "scheduler에 넘긴다"고만 한다. 게다가 messaging README는 handler를 app-bootstrap에서 등록하는 + 안을 버렸다(`:95`). + - 이번 라운드 전에는 `@SystemInvoked` use case를 bean으로 만들어 handler에 넣는 길이 있었다(그래서 RR-01-02가 위험했다). + 그 문을 닫으면서 정당한 시스템 호출자 하나(소비자)의 길을 문서 없이 함께 닫았다. +- **왜 중요한가**: + - 첫 소비자를 붙이는 파생 서비스는 매뉴얼대로 하면 기동·빌드·런타임 중 하나에서 반드시 실패한다. + - 실패를 끄는 가장 쉬운 우회가 위험하다. `repositoryAccess`를 낮춰 D4를 피하면 권한 표시 없는 쓰기 use case가 bean으로 + 생기고, 컨트롤러도 그것을 주입받을 수 있다. RR-01-02가 막으려던 "검사 없는 쓰기"가 다른 문으로 돌아온다. + - 사용자 원칙: 선택지가 여럿이면 고른 방법·버린 대안·이유가 남아야 하고, 개발자가 따로 기억해야 하는 규칙은 결함이다. +- **고치는 법**: 둘 중 하나를 고르고 기록한다. + - (a) 경로를 문서로 고정: 09장 4단계와 07장 「시스템이 부르는 쓰기」에 "소비 handler는 use case를 인터페이스(또는 + application-core가 소유한 함수형 포트)로 받고, `@SystemInvoked` use case는 소비 조립(composition)이 `new`로 만들어 + handler bean에 넣는다"를 적는다. 예시 조립 하나(`InboxRedeliveryIntegrationTest`의 handler 모양을 그 방식으로)와 + ArchUnit 메시지에 "scheduler 또는 소비 handler"를 넣는다. + - (b) 규칙을 좁힘: ArchUnit 대상에서 `..adapter.inbound.messaging..`을 빼고, 대신 "messaging inbound는 HTTP·gRPC·GraphQL· + WebSocket 패키지에 의존하지 않는다"로 노출 경로를 막는다. 가드는 그대로 둔다(소비 handler가 use case를 `new`로 만들면 bean이 + 아니다). + - 어느 쪽이든 07장 "지금 이해하면 되는 것"의 "시스템만 부르는 쓰기" 줄에 소비자를 넣는다. +- **가이드 심각도·우선순위**: Medium · P2 (런타임 결함이 아니라 매뉴얼이 가르치는 경로와 새 규칙의 충돌. 템플릿에 소비자는 아직 없다) +- **증거**: E1 — 규칙 대상 패키지(`:458`), 가드 조건(`:57`), 인가 관리자의 무인증 거부(`:56`), 매뉴얼 4단계(`:115-117`)를 대조했다. + ArchUnit을 fixture로 돌려 보지는 않았다. + +### Minor (Nice to Have) + +#### RR-01-13 · `/error` 응답이 표에 없는 status를 400·500으로 바꾸는데, 정본은 "원래 status가 그대로 나간다"고 적는다 + +- **위치**: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorController.java:65-70`, + `HttpStatusErrorCodes.java:32-35`, `EnvelopeResponseWriter.java:37`, `docs/web/http-contract.md:59` +- **무엇이 틀렸나**: 오류 컨트롤러는 디스패치 status를 `HttpStatusErrorCodes`로 코드에 바꾼 뒤 그 코드의 status를 다시 쓴다. + 표에 없는 4xx(408·409·410·422 등)는 `BAD_PARAMETER` 400, 표에 없는 5xx(501·502·504)는 `INTERNAL_ERROR` 500이 된다. + Boot 기본 컨트롤러는 원래 status를 그대로 냈다. 지금 main 코드에 `sendError`는 없어서(grep 0건) 나오는 경우는 컨테이너· + 라이브러리가 낸 오류뿐이다. +- **왜 중요한가**: 정본 1절의 "원래 status가 그대로"는 표에 있는 status에서만 참이다. 필터를 더하는 서비스가 `sendError(409)`를 + 쓰면 400으로 바뀌어 클라이언트 분기가 틀어진다. +- **고치는 법**: 문장을 "표에 있는 status는 그대로, 그 밖은 400·500으로 접힌다"로 고치거나, 오류 컨트롤러가 status는 원래 값을 + 두고 code만 표로 고르게 한다(`EnvelopeResponseWriter`에 status를 따로 받는 overload). +- **가이드 심각도·우선순위**: Low · P3 · **증거**: E1 + +#### RR-01-14 · page 크기 규칙의 세 번째 복사본이 남았다(RR-02-08 ① 부분) + +- **위치**: `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java:101-107` +- **무엇이 틀렸나**: 지운 `GraphQlComplexityCalculator.effectivePageSize`와 같은 "둘 다 있으면 `first`" 규칙이 public 메서드로 + `GraphQlClientPolicy`에 있다. 상한 검사도 없다. main 호출자는 없고 테스트(`GraphQlClientPolicyTest.java:45-47`)만 부른다. + 실제 점수는 `connectionCost`(큰 쪽), 실제 resolver 쪽은 `GraphQlConnectionPolicy.effectivePageSize`(방향 섞임 거부)다. +- **왜 중요한가**: 갈라진 복사본이다. adopter가 이름만 보고 이것을 resolver에서 부르면 상한 없는 page를 받는다. +- **고치는 법**: 지우고 테스트를 `GraphQlConnectionPolicy` 쪽으로 옮긴다. +- **가이드 심각도·우선순위**: Low · P3 · **증거**: E1(grep) + +#### RR-01-15 · gRPC ledger `release`는 토큰 밖에 있고, 행이 지워지면 시도 번호가 1로 돌아간다 + +- **위치**: `src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java:143`, + `src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java:204-207`, + `GrpcOperationLedgerRepository.java:48`, `GrpcClaimToken.java:14-15` +- **무엇이 틀렸나**: 다른 전이는 모두 토큰을 받는데 `release(identity)`는 토큰 없이 `deleteById`한다. 지운 뒤 새 claim은 + `claim_attempt = 1`로 시작한다. 그래서 `GrpcClaimToken` Javadoc의 "두 시도는 같은 값을 나눠 갖지 않는다"는 release·purge 뒤에는 + 거짓이다. 옛 attempt 1 owner가 그때 살아 있으면 새 attempt 1의 claim에 commit·실패를 기록할 수 있다(ABA). +- **왜 중요한가**: 지금 main에 `release` 호출자는 없고, purge는 24h 지난 완료 행만 지우므로 실제 창은 아주 좁다. 다만 포트에 + "토큰 없는 파괴 연산"이 남아 있고 Javadoc이 반대로 말한다. +- **고치는 법**: `release(identity, claimToken)`으로 바꿔 `DELETE … WHERE claim_attempt = :token AND state = 'IN_PROGRESS'`로 하거나, + 포트에서 지운다. Javadoc 문장을 "같은 행이 살아 있는 동안"으로 좁힌다. +- **가이드 심각도·우선순위**: Low · P3 · **증거**: E1 + +#### RR-01-16 · 새 "첫 쓰기 두 개가 겹침" 계약 케이스가 fake에서는 겹치지 않는다 + +- **위치**: `src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxAggregateSequenceContract.java:71-83`, + `src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java:47,115-118` +- **무엇이 틀렸나**: `OverlappingWrites`는 두 스레드에서 트랜잭션을 연다. in-memory 계약 테스트의 `DirectTransactionPort`는 + 스레드를 구분하지 않는 필드 하나(`current`)로 "열린 트랜잭션"을 기억한다. 둘째 스레드는 첫 스레드의 트랜잭션이 열려 있는 것을 + 보고 거기에 join한다(`:117`). fake에서는 "겹친 두 트랜잭션"이 아니라 "한 트랜잭션 안의 두 호출"을 검사한다. `ArrayList`도 + 두 스레드가 같이 고친다. +- **왜 중요한가**: 실제 대상인 PG에서는 의미대로 돈다. fake에서는 녹색이 아무것도 말하지 않고, 경쟁 상태가 있는 테스트 코드라 + 드물게 흔들릴 수 있다. +- **고치는 법**: `DirectTransactionPort`의 `current`를 `ThreadLocal`로 바꾸거나, fake 계약 테스트에서 이 케이스를 순차 실행으로 + 바꾸고 그렇게 적는다. +- **가이드 심각도·우선순위**: Low · P3 · **증거**: E1 + +#### RR-01-17 · move의 "거절되면 아무것도 바뀌지 않는다"는 쓰기 전 거절에서만 테스트된다 + +- **위치**: `src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java:38-40,92-109`, + `FileLifecycleUseCasesTest.java:485` +- **무엇이 틀렸나**: 테스트는 `requireRoom`에서 거절되는 경우(아직 아무것도 안 씀)만 본다. 쿼터를 옮긴 뒤 `relocate`가 버전 충돌로 + 실패하는 경우의 롤백은 JPA 포트들이 호출자 트랜잭션에 합류한다는 사실에만 기댄다. 쿼터 fake는 롤백을 모르므로 use case 테스트로는 + 볼 수 없고, PG lane에도 move 케이스가 없다. 또 이번 수정 전에 move된 파일은 여전히 출발 namespace에 잡혀 있고, 그 파일을 지우면 + 지금 namespace에서 회수한다. 이 과거 데이터의 처리 방법이 어디에도 없다. +- **왜 중요한가**: 지금 코드는 맞다(E1). 나중에 누가 quota 포트 하나를 `inNew`로 바꾸면 잡을 테스트가 없다. +- **고치는 법**: persistence-fileserver PG lane에 "move 중 버전 충돌 → 양쪽 사용량 그대로" 하나. `NamespaceQuota` 또는 fileserver + runbook에 "수정 전 move된 파일은 장부가 틀릴 수 있다, 재계산 SQL"을 한 줄. +- **가이드 심각도·우선순위**: Low · P3 · **증거**: E1 + +## Declined to judge + +- application-core outbox 변경(`OutboxPublishAttempt`, `last_failure_code`, `PARKED`, `longRetries`, 포트 시그니처 변경): diff는 읽었고 + 눈에 띄는 결함은 없었다. RR-05-xx·06-10~14의 닫힘 판정은 05 영역 리뷰어 몫이다. +- `SubmitDurableOperationUseCase`의 파생 UUIDv7 event id: 클라이언트가 고른 operation id가 남의 파생 id와 같으면 inbox가 두 이벤트를 + 같은 것으로 본다. 옛 `operation-` 방식에도 같은 성질이 있었고 남의 operation id를 알아야 하므로 이번 라운드 결함으로 보지 않았다. +- `PermissionEnforcementGuard`가 못 보는 경우(lazy·prototype bean의 선언 타입이 인터페이스, `registerSingleton`, 람다 wrapper): + 일부러 우회해야 생기는 경우라 판정하지 않았다. +- ERROR 디스패치 허용의 새 노출: 컨테이너 오류 페이지가 `/error` 하나이고 컨트롤러가 요청 값을 쓰지 않으며, 다른 체인 + (actuator·알림 콜백)은 `/error`와 맞지 않는다. 새 노출은 찾지 못했다. Jetty와 관리 포트 분리 배포는 보지 않았다. +- V003의 `CHECK` 제약은 `NOT VALID` 없이 붙어 테이블 전체를 검사한다. 마이그레이션 주석대로 플랫폼이 아직 어디에도 채택되지 않아 + 판정하지 않았다. +- 필터가 던진 예외의 오류 디스패치가 span 오류 기록을 남기지 않는 것(예외 처리기는 남긴다): 1차 이전부터 같았다. + +## 수렴 판단 + +**이 라운드가 만든 새 Important가 있다: 2건.** + +- RR-01-11: 이번 라운드가 새로 쓴 계약 문장(같은 키 재전송 판정)이 그 코드를 실제로 내는 유일한 저장소(Redis)와 반대다. 원인인 + Redis 동작은 이전부터 있었지만, 그 위에 "안전"이라는 약속을 이번에 얹었다. +- RR-01-12: 이번 라운드의 `@SystemInvoked` 규칙 둘이 매뉴얼의 이벤트 소비 경로를 문서 없이 막는다. + +둘 다 기본 조립(멱등성 비활성, 소비자 없음)에서는 동작하지 않는 경로라 Critical·High는 아니다. 고치는 범위도 작다(Redis 스크립트 한 +분기 + 계약 케이스 하나 + 문서, 그리고 매뉴얼 두 장과 ArchUnit 메시지). 그래도 둘 다 "계약·매뉴얼대로 한 사람이 틀린 결과를 받는다"는 +종류라 다음 수정 라운드가 필요하다. Minor 5건은 같은 라운드에 묶을 수 있다. + +## Assessment + +**Ready to merge? With fixes** + +맡은 1차 발견은 중복(RR-07-01=RR-01-02, RR-04-04=RR-01-05)을 빼면 19건이다. 17건이 닫혔고 2건이 부분이며 회귀는 없다. RR-02-03은 결과 불명 계약이 Redis 저장소와 맞지 않아 부분이고(RR-01-11), +`@SystemInvoked` 규칙은 결정대로 들어갔지만 소비자 경로를 막는 새 Important를 만들었다(RR-01-12). diff --git a/docs/reviews/2026-11-03-rereview/round2/02-persistence-messaging.md b/docs/reviews/2026-11-03-rereview/round2/02-persistence-messaging.md new file mode 100644 index 00000000..487fe9da --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round2/02-persistence-messaging.md @@ -0,0 +1,246 @@ +# 02 persistence·messaging 재리뷰 (2026-11-03, 2차) + +경로는 저장소 루트 기준이다. 코드 경로는 `src/`가 앞에 붙는다. + +## 범위 — 본 pathspec, 불러온 스킬과 적용한 기준, 실행한 명령과 결과, 못 본 것 + +### 본 pathspec + +- 리뷰 범위: Base `7ef8d0b4` → Head `bbe944bd`(커밋 1개) 중 아래 pathspec. 90파일, +2,924 −454. + ```text + src/adapter/outbound/persistence-jpa src/adapter/outbound/persistence-mongo + src/adapter/outbound/persistence-fileserver src/adapter/outbound/persistence-notification + src/messaging src/adapter/outbound/messaging src/adapter/outbound/messaging-kafka + src/adapter/inbound/messaging src/application-notification docs/runbooks docs/messaging docs/jpa + docs/reviews/2026-11-01-maturity-review/06-messaging.md + ``` + `persistence-mongo`와 `adapter/inbound/messaging`은 이 커밋에 바뀐 파일이 없다. +- 맡은 1차 재리뷰 발견: RR-03-01~10, RR-05-01~10, 06-10~06-14. +- 새 발견 ID는 `RR-02-09`부터다. 1차의 `RR-02-01~08`은 inbound 영역의 발견이라 겹치지 않게 이어 붙였다. +- 읽은 방식: 하위 에이전트 없이 여러 번에 나눠 직접 읽었다. + 1. persistence-jpa main 전부(`JpaOutboxStore`, `OutboxEventJpaRepository`, floor entity, `OutboxEventEntity`, + `SpringTransaction`, `PersistenceExceptionTranslator`, V21·V22)와 build.gradle. + 2. persistence-jpa 테스트: `PostgreSqlOutboxOrderKeyRunbookIntegrationTest`, `PostgreSqlOutboxDispositionRunbookIntegrationTest`, + `OutboxRunbookSql`, `PostgreSqlOutboxAggregateSequenceIntegrationTest`, `SpringTransactionDeadlineTest`, + `PostgreSqlTransactionIntegrationTest` 추가분, `JpaOutboxStoreTest`, 아키텍처 규칙·fixture. + 3. runbook 두 개(`outbox-dead-letter.md`, `outbox-publish-failed.md`) 전문과 나머지 runbook diff. + 4. messaging bridge·relay 포트 diff, vendored messaging diff 전부(`KafkaConsumerRegistrar`, + `KafkaQuarantinePublisher`, `KafkaDeadLetterQuarantine`, `FailureDescriptor`, `MessagingShutdownLifecycle`), + `KafkaConsumerRegistrarTest` 추가분. + 5. notification·fileserver persistence diff, `ReconciliationJobWorker`(시도 한도가 실제로 걸리는지). +- 판단에 필요해서 pathspec 밖에서 읽은 것(전체 diff 리뷰는 아님): application-core의 `OutboxPublishAttempt`, + `PublishPendingOutboxEventsUseCase`, `OutboxEventStatus`, `OutboxAggregateSequencePort`, `IntegrationEventDraft`, + `IntegrationIdentity`, `SubmitDurableOperationUseCase`, `ReleasedPayloadSchemaContract`, `OutboxAggregateSequenceContract`, + `OverlappingWrites`; composition의 `OutboxSettings`, `OutboxRelayAutoConfiguration`, `OutboxMetrics`; + `DefaultMessagePublisher`의 기한 처리, `KafkaMessagingAutoConfiguration`의 producer 설정, `docs/registries/metrics.yaml` + outbox 항목, `docs/manual/09-outbox-events.md`. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +|---|---|---| +| `superpowers:requesting-code-review` | 리뷰어 템플릿: 요구사항 정합, mock이 아닌 실제 동작 테스트, 마이그레이션 전략·하위 호환, Declined to judge, 심각도 보정, 읽지 않은 코드를 칭찬하지 않기 | 발견마다 "고치는 법"·4절 결정 대조, 테스트가 실제 DB·실제 문서를 쓰는지, V21·V22의 배포 경로 | +| `jpa-patterns` | Flyway 마이그레이션은 additive·재실행 가능, Hibernate는 validate만, 짧은 트랜잭션, 연관관계 규칙(사용자 원칙 "양방향 금지"를 스킬의 `mappedBy` 예시보다 우선) | V21·V22, `insertable/updatable=false` 필드의 실제 SELECT 동작(RR-02-13), `SingleSidedAssociationCondition`의 그래프 판정(RR-02-15), 트랜잭션 마감 분류 | +| `supabase-postgres-best-practices` | `lock-short-transactions`(DDL은 `lock_timeout`으로 잠금 대기를 묶는다), `data-upsert`(`ON CONFLICT`로 경쟁을 DB가 판정), `lock-skip-locked`, `schema-constraints`(제약·상태 값의 재실행 안전성) | V21 `lock_timeout`·무효 인덱스 거부·floor, V22의 잠금 대기(RR-02-09, 실 PG), counter `ON CONFLICT DO NOTHING` 경쟁, PARKED를 DDL 없이 둔 결정의 영향(RR-02-11) | +| `doubt-driven-development` | 주장(CLAIM)을 적고 반증을 시도한다 | 아래 7개 주장. 브리프가 하위 에이전트를 금지해 새 맥락 리뷰어 대신 자기 반증(축소 적용)으로 했다. 비대화 실행이라 교차 모델 검토는 건너뛰었다 | + +반증을 시도한 주장과 결과: + +1. "V21은 실패해도 다시 돌리면 된다" → 반증 못 함. 한 트랜잭션이라 lock_timeout·중복·무효 인덱스 실패 모두 V20에 남고, floor는 다시 돌 때의 시각으로 다시 기록된다. 해당 lane 테스트 3개가 확인한다. +2. "rolling 배포 중 옛 인스턴스의 벽시계 번호 뒤에 새 번호가 온다" → **일부 반증**. 같은 identity면 맞다. tenant scope가 바뀌는 배포에서는 옛 scope 행을 보지 못해 새 번호가 더 작다(RR-02-10, 실 PG). +3. "counter 첫 생성 경쟁에서 두 쓰기 모두 성공한다" → 반증 못 함. PG(공용 계약의 겹침 테스트)와 H2 PostgreSQL 모드(직접 실험) 둘 다 맞다. +4. "이번 라운드의 마이그레이션은 잠금 대기가 묶여 있다" → **반증**. V21은 5초로 묶었지만 같은 커밋의 V22는 ACCESS EXCLUSIVE를 상한 없이 기다리고, 그동안 outbox 읽기·쓰기가 모두 멈춘다(RR-02-09, 실 PG). +5. "runbook SQL은 lane이 문서에서 읽어 실 PG로 돌린다" → 반증 못 함. 두 lane이 system property로 문서 경로를 받고 문서를 Gradle 입력으로 선언한다. 표지 없는 SQL은 돌지 않는다(Declined 참고). +6. "draft의 UUIDv7 거부는 기존 데이터·재시도를 막지 않는다" → 반증 못 함. draft는 새 이벤트에만 쓰이고, 저장된 행 복원은 draft를 거치지 않는다. durable operation 재시도는 같은 UUIDv7을 다시 만든다. +7. "PARKED는 DDL 없이 안전하다" → **일부 반증**. 새 버전에서는 맞다. 옛 버전(배포 중·롤백 후)은 상태 이름을 몰라 `outbox.pending.size` 게이지 전체가 꺼진다(RR-02-11, 코드). + +### 실행한 명령과 결과 + +메인 작업 트리·index·HEAD는 바꾸지 않았다. Gradle은 돌리지 않았다. 실험은 scratchpad에 마이그레이션 파일을 복사해서 했다. + +| 명령 | 실행 직전 부하 | 결과 | +|---|---|---| +| `git diff --stat 7ef8d0b4..bbe944bd -- `, `git diff ...` | — | 90파일. 나눠서 전부 읽었다 | +| `java -cp h2-2.4.240.jar H2Check.java` (scratchpad, `nextSequence`의 세 문장을 그대로 H2 `MODE=PostgreSQL`에서 실행) | — | `first=1 second=2 third=3`, 이미 있는 counter에 생성 문장 → `0`. 두 연결 겹침: 첫째가 생성 후 커밋 보류, 둘째 `next=2`, 최종 `2`. 커밋에 적힌 "H2가 `ON CONFLICT DO NOTHING`을 받는다"를 확인 | +| `flock heavy.lock scratchpad/rr2-02/exp.sh` (postgres:16-alpine, 컨테이너 안 psql로 HEAD의 V1~V21 적용 후 실험) | load 16.65 | rc=0. 첫 시도는 다른 작업이 잠금을 잡고 있어 대기 중 시간 초과(rc=124)였고 재실행했다 | +| └ EXP1: 세션 A가 `outbox_event`를 읽은 트랜잭션을 20초 열어 둠 → 세션 B가 V22 실행 → 세션 C·D가 3초 제한으로 읽기·쓰기 | | `pg_locks`: A `AccessShareLock` granted, V22 `AccessExclusiveLock` 대기. C 읽기 `canceling statement due to statement timeout`(3.09초), D 쓰기 같은 오류(3.20초). **V22는 19.1초 기다린 뒤 rc=0** | +| └ EXP2: floor 뒤 30초에 옛 버전이 `portfolio` scope로 쓴 행(번호 floor+30,000,000) → 새 버전이 같은 aggregate를 `global` scope로 `nextSequence` 문장 실행 | | floor=1793718324464623, 옛 행=1793718354464623, **새 번호=1793718324464624(옛 행보다 작음)** | + +### 못 본 것 + +- Gradle lane을 직접 돌리지 않았다. `postgresqlOutboxDispositionRunbookIntegrationTest`·`postgresqlOutboxOrderKeyRunbookIntegrationTest`· + `postgresqlOutboxAggregateSequenceIntegrationTest`·Kafka relay lane·`KafkaConsumerRegistrarTest`의 통과는 재리뷰 README 7절 게이트 기록을 따랐다. +- persistence-jpa에 새로 들어온 fileserver PG 계약 테스트(`FileserverPostgreSqlStack`, `PostgreSqlFileQuotaLedgerContractTest` 등)는 + RR-01-04 몫이라 stack만 읽었다. 계약 케이스 목록은 01 영역 리뷰가 본다. +- 실제 Kafka·SIGTERM·다중 인스턴스 동시 기동은 실행하지 않았다. +- idempotency·redis·grpc·job-timeout runbook diff는 다른 영역 발견의 문서라 이 영역 코드와 모순이 없는지만 봤다. + +## Strengths + +- **counter 첫 생성 경쟁을 DB가 판정한다.** `JpaOutboxStore.java:125-139`는 `UPDATE` → `INSERT … ON CONFLICT DO NOTHING` → 다시 `UPDATE`다. 두 번째 쓰기는 첫째의 커밋을 기다렸다가 증가만 한다. 공용 계약 `OutboxAggregateSequenceContract.java:71`이 `OverlappingWrites`로 겹침을 운에 맡기지 않고 만들고, PG 테스트가 상속한다. H2 개발 경로도 직접 실험으로 같은 결과였다. +- **번호가 뒤로 가지 않게 두 겹으로 막았다.** 새 counter는 floor와 남은 행 최대값 중 큰 값 다음에서 시작한다(`OutboxEventJpaRepository.java:164`). 기존 counter의 증가도 그 aggregate의 가장 큰 행 아래로 내려가지 않는다(`:140`). 롤백 후 재배포처럼 옛 번호가 다시 섞여도 다음 번호가 그 뒤에 온다. +- **V21의 실패 경로를 실 PG로 고정했다.** 잠금 대기 초과(`PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java:227`), 실패한 CONCURRENTLY가 남긴 무효 인덱스 거부(`:263`), runbook대로 미리 만든 인덱스 재사용(`:298`), counter 선생성(`:185`)이 있다. 각 테스트가 "DB가 V20에 남는다"를 함께 단언한다. +- **runbook SQL이 문서 그대로 실행된다.** `OutboxRunbookSql`이 `` 블록을 문서에서 읽고, 두 lane이 문서를 Gradle 입력으로 선언한다(`persistence-jpa/build.gradle:252-260`). 재발행 테스트(`PostgreSqlOutboxDispositionRunbookIntegrationTest.java:63`)는 옛 SQL이면 실패하는 RED가 성립한다. "다음 claim이 그 행을 가져가는가"로 결과를 본다. +- **PARKED가 순서를 지키는지 실제로 본다.** 보류 행 뒤의 행이 claim되지 않음을 단언한다(`PostgreSqlOutboxDispositionRunbookIntegrationTest.java:149`). +- **마감 초과 분류를 자기가 연 트랜잭션으로 좁혔다.** `SpringTransaction.java:201-232`는 이 호출이 시작한 트랜잭션이고 마감이 지났고 다른 분류가 없을 때만 `translateAfterDeadline`을 부른다. 운영 조합(`JpaTransactionManager`)의 실 PG 테스트(`PostgreSqlTransactionIntegrationTest.java:305`)와 "업무 예외는 그대로" 테스트(`SpringTransactionDeadlineTest.java:113`)가 있다. +- **ACL이 원인 코드를 잃지 않는다.** bridge가 platform 코드를 그대로 옮기고, 문법 밖이면 platform의 category 이름으로 바꾼다(`PlatformIntegrationEventPublishAdapter.java:205-233`). 메시지가 아니라 이름만 옮긴다. +- **06-12 검사가 값이 만나는 곳에 있다.** 발행 포트만 아는 최악 시간과 설정이 relay 조립에서 만난다(`OutboxRelayAutoConfiguration.java:76`, `OutboxSettings.java:80`). Kafka `max.block.ms`를 같은 기본 기한으로 묶은 설정과 계산이 맞다. +- **정산 job의 버려진 claim이 시도로 셈된다.** `JdbcReconciliationJobStore.java:74`, 그리고 worker가 provider를 부르기 전에 한도를 본다(`ReconciliationJobWorker.java:111`). 매번 죽는 job도 끝난다. +- **격리 분류가 재시도 경로에서도 유지된다.** 읽을 수 없는 레코드는 첫 격리 쓰기가 실패해도 DESERIALIZATION으로 남는다(`KafkaConsumerRegistrar.java:351,357`, 테스트 `anUndecodableRecordStaysDeserializationWhenItsQuarantineIsRetried`). + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +|---|---|---| +| RR-03-01 | 닫힘 | `JpaOutboxStore.java:132-137`, `OutboxEventJpaRepository.java:169`. PG 겹침 계약 `OutboxAggregateSequenceContract.java:71`. H2 경로는 이 리뷰의 직접 실험으로 확인(E3) | +| RR-03-02 = RR-05-02 | 결정으로 닫힘(잔여 RR-02-10) | V21 floor(`V21:54-56`)·counter 선생성(`:58-65`), 생성 `GREATEST(MAX, floor)`, 증가 `GREATEST(last, MAX)`. PG 테스트 reaper·scope 변경·rolling(`PostgreSqlOutboxAggregateSequenceIntegrationTest.java:108,126`). manual 09에 첫 번호 안내. scope가 바뀌는 배포의 rolling 구간은 막지 못한다(RR-02-10, E3) | +| RR-03-03 | 닫힘 | `SpringTransaction.java:209,220`, `PersistenceExceptionTranslator.java:159-179`. H2 본문 flush·커밋 flush, 실 PG `JpaTransactionManager` 테스트 | +| RR-03-04 | 닫힘(잔여 RR-02-15) | `SingleSidedAssociationCondition.java:84-117` 그래프 판정, fixture `JoinColumnParentEntity`·`JoinColumnChildEntity`, 가이드 `entity-mapping-guide.md:75-91`. 서로 다른 두 FK를 양방향으로 오판한다(Minor) | +| RR-03-05 | 닫힘 | `V21:28-34` `lock_timeout 5s`, `:73-93` 고른 이유·무효 인덱스 거부, runbook §8 Step 0, lane 테스트 3개. 같은 커밋의 V22가 같은 종류의 빈틈을 새로 만들었다(RR-02-09) | +| RR-03-06 | 닫힘 | 두 `positional` helper와 그 테스트 삭제, Javadoc 정정(`CleanupClaimSql.java:17-19`) | +| RR-03-07 | 닫힘 | `WorkerCrashRecoveryContractTest` 이름·`as()`를 단언 범위로 줄이고 한국어 DisplayName, `CleanupClaimSqlTest` 이름을 "문장 텍스트"로 | +| RR-03-08 | 닫힘 | `JdbcReconciliationJobStore.java:74`, 한도 판정 `ReconciliationJobWorker.java:111`, 계약 `ReconciliationJobStoreContract` 추가분 | +| RR-03-09 | 닫힘 | `JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf`, `JpaProductionArchitectureTest`가 notification·fileserver에 적용, red/green fixture(`OrderEntityReader`) | +| RR-03-10 | 결정으로 닫힘 | `FailureCategory.java` Javadoc 첫 문장 "Not a transaction timeout", 이름 변경은 다음 호환성 깨짐 때로 기록 | +| RR-05-01 | 닫힘 | runbook §4 두 SQL에 `deferred_attempt_count = 0`, `runbook-sql` 표지와 실 PG lane, claim의 WARN이 `ATTEMPT_COUNTERS_INCONSISTENT`로 원인을 말함(`JpaOutboxStore.java:166-177`). CHECK 제약은 결정으로 넣지 않음 | +| RR-05-03 | 결정으로 닫힘(잔여 RR-02-11·12·14) | `OutboxPublishAttempt`, V22 `last_failure_code`, 실패 로그 `error.reason`, `outbox.retry.long.size/age` 게이지·registry·경보, PARKED와 runbook §4.1 SQL 4개(실 PG lane) | +| RR-05-04 | 닫힘 | `IntegrationEventDraft`가 비UUIDv7 event id·causation id 거부, durable operation은 결정적 UUIDv7 파생(`SubmitDurableOperationUseCase.java:177-193`), bridge 주석·README의 "until it does" 제거 | +| RR-05-05 | 닫힘 | 게이지가 자기 스레드(`OutboxMetrics` SmartLifecycle, `outbox-gauges`)에서 poll 주기로 갱신 | +| RR-05-06 | 닫힘 | registry `outcome` 허용 값에 RELEASED, IN_FLIGHT 제거, `OutboxStatusRegistryContractTest`가 outcome label도 비교 | +| RR-05-07 | 닫힘 | `FailureDescriptor` Javadoc, vendored 주석에서 소비자 이름 제거, `src/messaging/CLAUDE.md`에 수정 목록과 버린 대안 | +| RR-05-08 | 닫힘 | `MessagingShutdownLifecycle.java` POLL Javadoc 위치 복구. 같은 모양의 떨어진 Javadoc이 `OutboxEventEntity`에 새로 생겼다(RR-02-13) | +| RR-05-09 | 닫힘 | V21 주석의 클래스명, manual 09 문단, leader election 토큰 삭제, runbook `last_updated` | +| RR-05-10 | 닫힘 | 2026-11-01 README 12절 색인에 06-10~06-14와 정정 문단 | +| 06-10 | 닫힘(다른 방법, 이유 기록) | 출시한 schema 버전 해시 고정(`ReleasedPayloadSchemaContract`, application-core·sample 적용), manual 09 6단계. 버전 간 diff를 하지 않는 이유를 Javadoc에 적었다 | +| 06-11 | 닫힘 | `outbox-inbox.md` 머리말과 두 모델 상태 대응표, `configuration-reference.md` 문장 정정 | +| 06-12 | 닫힘 | `batch-size × longestAttempt ≥ in-flight-timeout`이면 기동 실패. 최악 시간 = 기본 기한 5초 × 2(Kafka `max.block.ms`) | +| 06-13 | 닫힘 | 낡은 문장 정정, `OutboxLeaderElectionToken` 삭제, `composition:outbox-relay`·`messaging-kafka` CLAUDE.md 신설 | +| 06-14 | 닫힘(잔여 RR-02-16) | 읽을 수 없는 레코드 DESERIALIZATION, 예산 소진은 실패의 category 또는 POISON_MESSAGE. 테스트는 SPI 인자를 단언하고 header 쓰기는 테스트가 없다 | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +#### RR-02-09 — V22가 `outbox_event`의 ACCESS EXCLUSIVE 잠금을 상한 없이 기다려, 그동안 outbox 읽기·쓰기가 모두 멈춘다 + +- **위치**: `src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V22__outbox_event_last_failure_code.sql:20-21`. 비교: 같은 커밋의 `V21__outbox_aggregate_sequence.sql:28-34`, `docs/runbooks/outbox-dead-letter.md:119-122`. +- **무엇이 틀렸나**: + - V22는 `ALTER TABLE outbox_event ADD COLUMN`이다. 이 문장은 ACCESS EXCLUSIVE 잠금을 잡는다. + - 열려 있는 트랜잭션 하나가 `outbox_event`를 읽기만 했어도 V22는 그 트랜잭션이 끝날 때까지 기다린다. + - 기다리는 동안 뒤에 오는 모든 읽기·쓰기가 V22 뒤에 줄을 선다. ACCESS EXCLUSIVE는 읽기와도 충돌한다. + - V22에는 `lock_timeout`이 없다. 같은 커밋이 RR-03-05를 고치며 V21에 "Without a bound, the migration queues behind any open outbox write and every outbox write after it queues behind the migration"이라고 적고 5초 상한을 넣었다. 그 규칙이 바로 다음 마이그레이션에 빠졌다. +- **증거(E3, 실 PG 16)**: 세션 A가 `outbox_event`를 읽은 트랜잭션을 20초 열어 두었다. V22는 19.1초 기다린 뒤 적용됐다. 그동안 `pg_locks`에 V22의 `AccessExclusiveLock`이 granted=false로 있었다. 3초 제한을 건 일반 읽기(`SELECT count(*)`)와 일반 쓰기(`UPDATE`)가 둘 다 `canceling statement due to statement timeout`으로 끝났다. +- **왜 중요한가**: + - 발생 조건: V21 이하 DB를 올리는 첫 배포. Flyway는 기본으로 기동 때 돈다(`persistence-jpa.yml` `flyway.enabled: ${APP_FLYWAY_ENABLED:true}`). 옛 버전이 트래픽을 받는 rolling 배포 중이다. + - 영향: 기다리는 시간만큼 outbox를 쓰는 모든 업무 쓰기, relay claim, 모든 인스턴스의 게이지 갱신이 멈춘다. 멈춘 요청은 Hikari 연결을 쥔 채 기다리므로 outbox와 무관한 요청도 연결을 못 받을 수 있다. + - 기다리는 시간은 그 순간 가장 오래 열린, `outbox_event`를 건드린 트랜잭션의 남은 시간이다. 앱 트랜잭션은 30초 마감이 있다. 운영자가 runbook 조회를 `BEGIN` 안에서 하고 둔 psql 세션, 백업·분석 질의처럼 앱 밖의 세션에는 상한이 없다. + - 1차의 RR-03-05(같은 종류, V21)는 Low였다. 이것을 Medium으로 올린 이유: (1) ACCESS EXCLUSIVE는 SHARE와 달리 읽기까지 막아 relay와 게이지도 선다. (2) 이 라운드가 규칙과 이유를 V21·runbook에 적고 바로 옆 파일에서 어겼다 — 사용자 원칙 "위험은 코드에 드러나야 한다"에 걸리고, 같은 정책의 갈라진 복사본이다. +- **고치는 법**: + 1. V22 맨 앞에 `SET LOCAL lock_timeout = '5s';`와 이유 한 줄을 둔다. V22도 아직 어디에도 적용되지 않았으니 V21처럼 직접 고치고 `applied-migrations.sha256`을 갱신한다. + 2. `PostgreSqlOutboxOrderKeyRunbookIntegrationTest.v21GivesUpOnALock…`와 같은 테스트를 V22에 둔다. "읽기 트랜잭션이 잡고 있으면 V22는 실패하고 DB는 V21에 남는다". + 3. 다음 마이그레이션이 같은 빈틈을 다시 만들지 않게 `docs/jpa/migration-guide.md`에 "운영 중인 테이블에 잠금을 거는 DDL은 `SET LOCAL lock_timeout`을 둔다"를 적는다. 가능하면 마이그레이션 테스트가 `ALTER TABLE`/`CREATE INDEX`(비동시)가 있는 파일에 `lock_timeout`이 있는지 검사한다. + 4. runbook §8에 V22 실패 시 동작(롤백, V21에 남음, 새 버전 기동 실패)을 한 줄 더한다. +- **가이드 심각도·우선순위**: Medium · P2. **증거**: E3. **통제**: V22에 대해 M0(V21은 M3). + +### Minor (Nice to Have) + +#### RR-02-10 — tenant scope가 바뀌는 배포의 rolling 구간에서는 새 번호가 옛 버전이 막 쓴 번호보다 작다 + +- **위치**: `docs/runbooks/outbox-dead-letter.md:124-131`, `src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java:29-31`, `OutboxEventJpaRepository.java:140-169`. +- **무엇이 틀렸나**: + - floor는 V21이 돈 순간의 값이다. rolling 중 옛 버전은 그 뒤에도 벽시계 번호(초당 10⁶씩 커짐)를 쓴다. + - 새 버전의 `GREATEST(…, MAX(행))`는 같은 identity의 행만 본다. + - 샘플처럼 scope를 바꾸면 옛 버전은 `portfolio`로, 새 버전은 `global`로 쓴다. 새 번호는 floor+1부터라 옛 버전이 방금 쓴 번호보다 작다. + - runbook 124행은 rolling 중 새 번호가 "그 행 뒤에" 온다고 말한다. 포트 계약은 "written under an identity that has since changed" 행보다도 크다고 약속한다. 두 문장이 이 경우에 틀린다. + - runbook 128행의 대응은 "배포 전에 옛 scope 미발행 행 확인"뿐이다. 배포 중에 옛 버전이 새로 쓰는 행은 다루지 않는다. +- **증거(E3)**: 실 PG에서 floor+30초 번호의 `portfolio` 행 뒤에 `global` scope로 `nextSequence` 문장을 돌리자 floor+1이 나왔다. +- **왜 중요한가**: scope를 무시하고 aggregate id로 "마지막 번호보다 작으면 버린다"를 구현한 소비자는 rolling 구간의 새 이벤트를 버린다. 발생은 scope를 바꾸는 배포(현재는 샘플)에 한정된다. +- **고치는 법**: runbook §8에 "scope를 바꾸는 배포는 옛 writer를 모두 멈춘 뒤(혼합 버전 금지) 한다"를 적는다. 포트 Javadoc의 그 구절을 "배포 전에 쓰인 행"으로 좁힌다. 또는 샘플만 옛 scope를 유지한다. +- Low · P3 · E3. + +#### RR-02-11 — PARKED 행이 하나라도 있으면 옛 버전 인스턴스의 `outbox.pending.size` 게이지가 통째로 꺼진다 + +- **위치**: `JpaOutboxStore.java:264`(`OutboxEventStatus.valueOf`), 옛 버전 같은 줄(`7ef8d0b4`·`origin/main`의 `countByStatus`), `V22__outbox_event_last_failure_code.sql:16-19`(PARKED는 DDL 없음). +- **무엇이 틀렸나**: `countByStatus`는 DB의 상태 문자열을 enum `valueOf`로 바꾼다. PARKED를 모르는 옛 버전은 `IllegalArgumentException`을 던지고, 게이지 갱신은 그 상태 하나가 아니라 전체가 실패한다(WARN). rolling 배포 중의 옛 인스턴스와, 운영자가 행을 보류한 뒤 롤백한 버전이 해당한다. DB CHECK가 없으니(결정) 수동 SQL 오타 상태값도 같은 일을 일으킨다. +- **왜 중요한가**: 보류는 장애 중에 하는 일이고, 장애 중 롤백은 흔하다. 그때 `PENDING size growing` 경보의 입력이 사라진다. 결정(DDL 없음·CHECK 없음)을 뒤집자는 것이 아니라 그 결정이 만든 호환성 위험이다. +- **고치는 법**: `countByStatus`가 모르는 상태를 건너뛰거나 `UNKNOWN`으로 모아 세게 한다(새 버전부터라도 이후 상태 추가에 대비). runbook §4.1 Step 2에 "롤백한 버전은 PARKED를 모른다 — 게이지가 꺼지므로 롤백 전에 resume 또는 skip"을 적는다. +- Low · P3 · E1. + +#### RR-02-12 — claim이 DEAD로 옮긴 행은 `last_failure_code`가 낡은 값으로 남고 DEAD 경보도 울리지 않는다 + +- **위치**: `JpaOutboxStore.java:166-189`, `OutboxEventEntity.java:70`(`updatable = false`), `docs/runbooks/outbox-dead-letter.md` §1·§2 Step 1. +- **무엇이 틀렸나**: + - claim 때의 DEAD 전이(`ATTEMPT_COUNTERS_INCONSISTENT`, `UNREADABLE_ROW`)는 entity flush로 쓴다. `lastFailureCode`는 읽기 전용이라 이 경로는 원인 코드를 행에 쓰지 못한다. 행에는 이전 재시도의 코드(예: `KAFKA_AUTHENTICATIONEXCEPTION`)가 그대로 남는다. + - 이 경로는 relay 결과를 거치지 않아 `outbox.publisher.published.total{outcome=DEAD}`가 오르지 않는다. runbook §1의 경보 조건이 이 카운터다. `outbox.pending.size{status=DEAD}`에는 경보가 없다. +- **왜 중요한가**: 운영자가 `SELECT … WHERE status='DEAD'`로 보면 원인을 잘못 읽는다. 경보도 없어 WARN 로그를 찾지 않으면 모른다. 카운터 공백은 1차 RR-05-01이 적은 기존 문제이고, 낡은 원인 코드는 V22가 새로 만든 부분이다. +- **고치는 법**: claim의 DEAD 전이를 조건부 UPDATE로 바꿔 `last_failure_code`에 `error.reason`과 같은 값을 쓴다. `outbox.pending.size{status=DEAD} > 0`을 경보 조건에 더하거나 claim DEAD도 카운터에 센다. +- Low · P3 · E1. + +#### RR-02-13 — `OutboxEventEntity`에 주인 없는 Javadoc이 생겼고, 새 필드 주석이 사실과 다르다 + +- **위치**: `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java:60-74`. +- **무엇이 틀렸나**: + - `nextAttemptAt`의 Javadoc("Dual-purpose per status …", 60행)이 새 필드의 Javadoc 바로 위로 떨어졌다. `nextAttemptAt`(74행)에는 설명이 없어졌다. 이 커밋이 RR-05-08로 고친 것과 같은 모양이다. + - 새 필드 주석은 append·claim이 "need the column on a database that has not run V22 yet"가 아니라고 말한다. `insertable/updatable = false`는 INSERT·UPDATE에서만 빠진다. Hibernate는 SELECT에 이 열을 넣으므로 claim은 V22 없는 DB에서 실패한다. +- **고치는 법**: 60행 주석을 `nextAttemptAt` 위로 옮긴다. 새 필드 주석의 V22 문장을 "INSERT와 flush는 이 열을 쓰지 않는다"로 줄인다. +- Low · P3 · E1. + +#### RR-02-14 — "오래 재시도" 기준 10이 세 곳에 따로 적혀 있고 서로 묶여 있지 않다 + +- **위치**: `src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxMetrics.java:52`, `docs/runbooks/outbox-publish-failed.md:97`, `src/composition/outbox-relay/README.md:118`. +- **무엇이 틀렸나**: 게이지는 상수를, runbook SQL은 리터럴 `10`을 쓴다. runbook은 "같은 기준(`OutboxMetrics.LONG_RETRY_DEFERRED_CLAIMS`)으로 센다"고 말하지만 이를 확인하는 테스트가 없다. runbook lane의 테스트 데이터(12와 1)는 상수가 2~12 사이로 바뀌어도 통과한다. +- **왜 중요한가**: 상수만 바꾸면 경보가 센 행과 runbook 조회가 보여 주는 행이 달라진다. 사용자 원칙의 "갈라진 복사본"이다. +- **고치는 법**: 문서 계약 테스트(`document-contract`)가 runbook 블록의 숫자와 상수를 비교한다. 또는 disposition lane이 경계값(기준-1, 기준)으로 runbook 조회와 `longRetries`를 같이 단언한다. +- Low · P3 · E1. + +#### RR-02-15 — 서로 다른 두 FK로 서로를 가리키는 두 엔티티를 양방향 쌍으로 오판한다 + +- **위치**: `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java:84-117`, `docs/jpa/entity-mapping-guide.md:84-91`. +- **무엇이 틀렸나**: 규칙은 A의 연관이 B를, B의 연관이 A를 가리키면 위반으로 본다. `Order.@OneToOne latestInvoice`와 `Invoice.@ManyToOne order`처럼 FK가 둘인 두 단방향 링크도 걸린다. 메시지는 "two fields map one link"라고 하지만 링크가 둘이다. 같은 클래스 안의 두 링크(manager·mentor)는 예외로 두면서 두 클래스 사이의 같은 모양은 예외가 없다. +- **왜 중요한가**: 금지 쪽으로 틀린 것이라 데이터 위험은 없다. 개발자가 정당한 모델을 바꾸거나 규칙을 끄는 쪽으로 밀린다. 이유를 말하는 메시지가 틀리면 규칙을 믿지 않게 된다. +- **고치는 법**: 같은 join column을 두 쪽이 매핑하는지(`@JoinColumn` 이름 비교, 또는 `@OneToMany`↔`@ManyToOne`·`@ManyToMany`↔`@ManyToMany` 짝)로 좁힌다. 아니면 가이드와 메시지를 "서로 가리키는 연관은 FK가 달라도 금지"로 고쳐 의도를 적는다. 어느 쪽이든 그 모양의 fixture를 둔다. +- Low · P3 · E1. + +#### RR-02-16 — 06-14의 header 쓰기는 테스트가 없고, 공개 SPI 시그니처 변경이 깨지는 변경 목록에 없다 + +- **위치**: `src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaDeadLetterQuarantine.java:42-52`, `src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaQuarantinePublisher.java:36`, 재리뷰 README 8절. +- **무엇이 틀렸나**: + - 06-14 완료 기준은 "두 경로가 다른 header 값을 남긴다"다. 새 테스트는 registrar가 SPI에 넘기는 category만 본다. category를 `msg.failure-category` header로 쓰는 `KafkaDeadLetterQuarantine`에는 테스트가 없다. + - `KafkaQuarantinePublisher.quarantine`에 인자가 하나 늘었다. 파생 서비스가 이 public SPI를 구현했다면 컴파일이 깨진다. README 8절의 "소유자 확인이 필요한 결정"은 발행·저장소 포트 변경만 적는다. +- **고치는 법**: `KafkaDeadLetterQuarantine` 단위 테스트에서 두 category의 header 바이트를 단언한다. 깨지는 변경 목록에 SPI 변경을 더한다. +- Low · P3 · E1. + +## Declined to judge + +- `ValidatedIntegrationEvent`는 public record라 draft를 거치지 않고 만들면 UUIDv7 검사를 건너뛴다 — 운영 코드의 생성처는 encoder와 저장 행 복원 둘뿐이고, 테스트의 v4 id는 의도된 것이다. +- 06-12의 최악 시간에 platform admission 대기(최대 남은 기한)가 들어 있지 않다 — relay는 한 번에 하나씩 보내고, 템플릿에는 같은 destination에 직접 발행하는 다른 publisher가 없다. +- 06-12 검사는 `<`라 행마다의 DB 쓰기 시간을 위한 여유가 없다 — 기본값(200초 대 300초)에서는 여유가 크다. +- `translateAfterDeadline`은 원인 사슬 전체를 본다. 마감이 지난 뒤 `DataAccessException`을 cause로 감싼 업무 예외는 `DB_QUERY_CANCELED`로 바뀐다 — 그렇게 감싸는 코드를 찾지 못했다(`PosterRepositoryAdapter`는 cause를 넘기지 않는다). +- 두 aggregate를 서로 다른 순서로 쓰는 두 트랜잭션의 counter 행 교착 — 1400dc15부터 있던 성질이고 이번 수정이 바꾸지 않았다. +- REPEATABLE READ에서 `ON CONFLICT DO NOTHING`은 직렬화 실패를 낸다 — 템플릿은 풀에서 READ COMMITTED를 강제하고 기동 검사가 있다(09-05). +- 옛 인스턴스의 시계가 DB보다 느려 floor 아래 번호를 쓰는 경우 — 옛 벽시계 방식이 보장하지 않던 것이고 runbook이 그렇게 적는다. +- V21의 `IF NOT EXISTS`는 같은 이름의 "다른 열" 유효 유일 인덱스를 받아들인다 — runbook 문장을 그대로 쓰면 생기지 않는다. +- runbook의 표지 없는 SQL(§2 차단 범위 조회, §8 scope 확인, `DROP INDEX CONCURRENTLY`)은 lane이 돌리지 않는다 — runbook 문장이 시험되는 범위를 정확히 적는다. 모든 `runbook-sql` 표지가 어느 테스트에서 쓰이는지 검사하는 장치는 없다. +- runbook lane이 문서 절대 경로를 `systemProperty`로 받아 build cache가 다른 경로에서 재사용되지 않는다 — 기존 lane과 같은 방식이고 정확성 문제는 아니다. +- idempotency runbook의 "action 자신의 트랜잭션 안 효과는 롤백된다" — 호출자가 executor를 트랜잭션으로 감쌀 때 참이다(샘플은 감싼다). inbound 영역 몫이다. +- 06-10이 버전 간 schema diff 대신 출시 버전 불변을 고른 것 — 이유가 Javadoc에 있고, 새 버전은 소비자가 먼저 읽는 절차(application-core README)를 따른다. + +## 수렴 판단 — 이 라운드가 만든 새 Important 이상이 있는가 + +**있다. 1건(RR-02-09).** 이 라운드에서 새로 들어온 V22가 V21에 넣은 잠금 대기 상한을 빠뜨렸다. 실 PG에서 읽기·쓰기가 모두 막히는 것을 확인했다. + +고치는 범위는 좁다. V22 한 줄, 같은 모양의 lane 테스트 하나, migration-guide 규칙 한 줄이다. 맡은 1차 발견 25건(RR-03 10건, RR-05 10건, 06-10~14)은 모두 닫혔거나 결정으로 닫혔고 회귀는 없다. 새 Minor 7건 중 6건은 이번 수정이 만든 잔여·문서 불일치이고, 데이터 손상으로 이어지는 것은 없다. + +그래서 이 영역은 전체 재리뷰 라운드가 아니라 RR-02-09만 고치고 그 lane을 돌리는 좁은 수정으로 수렴할 수 있다고 본다. + +## Assessment + +**Ready to merge? With fixes.** + +순서 번호·runbook SQL·원인 코드·PARKED·마감 분류는 결정대로 구현됐고 실제 PG·문서 원문으로 검증된다. 다만 같은 커밋의 V22가 outbox 테이블 잠금을 상한 없이 기다려 배포 중 outbox 읽기·쓰기를 멈출 수 있으므로(RR-02-09, E3), V22에 `lock_timeout`과 그 테스트를 넣은 뒤 병합한다. diff --git a/docs/reviews/2026-11-03-rereview/round2/03-outbound.md b/docs/reviews/2026-11-03-rereview/round2/03-outbound.md new file mode 100644 index 00000000..904573f6 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round2/03-outbound.md @@ -0,0 +1,268 @@ +# 03 outbound 재리뷰 (2026-11-03) + +> 2차 재리뷰. 대상은 재리뷰 수정 커밋 `bbe944bd`(Base `7ef8d0b4`)의 outbound capability 영역이다. +> 경로는 따로 적지 않으면 `src/adapter/outbound/`를 생략한다. + +## 범위 — 본 pathspec, 불러온 스킬과 적용한 기준, 실행한 명령과 결과, 못 본 것 + +### 본 pathspec + +- `src/adapter/outbound/{support, identifier, redis-runtime, redis-sdk, cache-redis, httpclient, objectstorage, notification, fileserver}`, + `docs/httpclient`, `docs/notification`, `docs/registries/metrics.yaml`, `infra/redis-sdk`. + `git diff --stat 7ef8d0b4..bbe944bd -- ` 기준 78파일, +2,750 −364. diff 전체를 읽었다. +- 재확인한 1차 발견: RR-04-01·02·03·05~11(RR-04-04 제외), RR-07-03, RR-07-04, RR-07-07. +- pathspec 밖 파일은 판정에 필요한 줄만 읽었다: `application-core` `IdempotencyExecutor`·`IdempotencyClaimRequest`, + `composition/idempotency` `IdempotencySettings`·`idempotency.yml`, `persistence-notification` `JpaProviderEventLedger`, + `persistence-jpa` 멱등성 claim SQL·reaper, `app-bootstrap` `SecretSourceValidator`, `docs/runbooks/redis-capability-incident.md`, + `docker-compose.infra.yml`, `.github/workflows/object-storage-qualification.yml`. +- 이 문서의 새 발견 ID는 `RR-03-11`부터다. 1차의 `RR-03-01~10`(그때 03 영역은 persistence)과 겹치지 않게 이어서 매겼다. + 01 영역 2차 리뷰어(`RR-01-11~`)와 같은 방식이다. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +| --- | --- | --- | +| `superpowers:requesting-code-review` | 리뷰어 템플릿: 요구사항(1차 "고치는 법"·4절 결정) 대비 정렬, Critical/Important/Minor, 읽은 코드에만 판정 | 출력 양식 전체, 발견 재확인 표 | +| `performance-optimization` | "추정 말고 잰다", 바꾼 뒤 다시 잰다, 측정이 잡음 안이면 문제로 올리지 않는다 | JDK read-idle 타이머의 read당 비용과 JVM 전체 상한(측정해 Minor로), lane 대기 Timer의 borrow당 등록 비용(측정 결과 무시할 수준이라 기각), 캐시 전용 lane의 연결 예산 | +| `observability-and-instrumentation` | 태그는 닫힌 작은 집합, 지표가 on-call 질문에 답하는가, 계측 실패가 결과를 바꾸지 않되 보이는가, runbook이 실제 신호를 가리키는가 | `redis.lane.*` 태그·histogram 버킷, listener 실패 격리·로그 수준, opened 지표의 뜻, 레지스트리·runbook과 코드의 일치 | +| `security-and-hardening` | trust boundary마다 "누가 이 값을 썼나", STRIDE의 R(감사)·D(자원), 공개 비밀값, 서명 범위 | SNS 인증서 4xx를 위조로 보는 근거, `MessageId`가 서명 문자열 안인지, `fixture-` 비밀 거부, ACL fixture 표기 | + +### 실행한 명령과 결과 + +checkout은 바꾸지 않았다. Gradle과 worktree는 쓰지 않았다. 탐침은 `git show bbe944bd:`로 꺼낸 사본을 scratchpad에서 +컴파일했고, Redis는 버리는 컨테이너 하나로 돌렸다. + +| 명령 | 결과 | +| --- | --- | +| `git diff --stat` / `git diff 7ef8d0b4..bbe944bd -- ` | 78파일 | +| `javap java.io.FilterInputStream`, `javap java.io.InputStream`, `javap --module java.net.http 'jdk.internal.net.http.ResponseSubscribers$HttpResponseInputStream'` | `FilterInputStream`은 `transferTo`·`readAllBytes`를 재정의하지 않는다 → 감시되는 `read(byte[],int,int)`를 지난다. JDK 응답 stream은 `skip`을 재정의하지 않는다 → `InputStream.skip`이 `read`를 여러 번 부른다 | +| `javap -c` Spring 7.0.9 `JdkClientHttpRequest`(Gradle cache) | `disallowedHeaders()`가 `jdk.httpclient.allowRestrictedHeaders`를 읽는다 | +| `SkipProbe` — `bbe944bd`의 `ReadIdleInputStream`, 100ms마다 1바이트 주는 stream 30바이트, read-idle 1s | `readAllBytes`: 30바이트 3,018ms 성공. **`skip(30)`: 1,001ms에 `SocketTimeoutException`**(공백은 모두 100ms) | +| `Bench` — `guarded()`와 같은 `completeOnTimeout` 걸기 + `cancel` 반복 | 1스레드 3.9~4.6µs/회. 8·32스레드에서 JVM 전체 0.35~0.51M회/초에서 멈춘다. 측정 당시 load average 14~22(22코어) | +| `TimerBench` — Micrometer 1.16.7 `SimpleMeterRegistry` | borrow마다 `Timer.builder(..).register(..).record(..)` 152~241ns, 미리 만든 Timer `record` 64ns. Redis 왕복(100µs 이상)에 비해 무시할 수준 → 발견으로 올리지 않음 | +| `docker run redis:7.4`(로컬 이미지 `b6b6e3dc0c09`, 고정 digest와 같은 id) + `bbe944bd`의 CLAIM Lua를 `redis-cli EVAL` | owner A claim(lease 3000ms, replay TTL 1000ms) → `ACQUIRED`, `PTTL 996`. 1.3s 뒤 `EXISTS 0`. owner B claim → **`ACQUIRED`**. A의 lease는 1.7s 남아 있었다 | + +### 못 본 것 + +- Gradle 테스트와 게이트는 다시 돌리지 않았다(재리뷰 README 7절을 읽기만 했다). +- Redis 컨테이너 lane·topology lane, MinIO·Toxiproxy lane은 돌리지 않았다. 캐시 전용 배포의 ACL probe가 실제 Redis의 + 거절 메시지(`NOPERM …`)를 맞게 분류하는지는 합성 메시지 테스트로만 확인됐다. +- 실제 AWS SNS 인증서 호스트가 없는 인증서에 주는 status, VPC endpoint 경유 동작은 확인하지 못했다. +- JDK HTTP/2 스트리밍, TLS 소켓을 JVM 공용 delay 스레드에서 닫을 때의 지연은 보지 않았다. +- PostgreSQL 멱등성 저장소(claim SQL, reaper)는 RR-03-11의 범위를 가늠하려고 읽기만 했다. +- `app-bootstrap` `SecretSourceValidator`는 RR-07-04 판정에 필요한 diff만 읽었다. + +## Strengths + +- breaker가 deadline 출처를 구분한다. `Deadline.Source`(`httpclient/.../resilience/Deadline.java:28`)를 계산기가 정하고, 같으면 + profile 쪽으로 기운다(`DeadlineCalculator.java:24-26`). 호출자 deadline으로 끝난 시도는 `releasePermission()`으로 permit만 + 돌려준다(`AttemptResiliencePipeline.java:136-137`). 회귀 테스트가 두 transport × 두 출처를 실제 서버로 본다 + (`CircuitBreakerStatusAccountingTest.java:178,221`). +- JDK 스트리밍이 setup 전용 scope를 따로 연다(`AttemptDeadline.openStreamSetup`, `BlockingStreamingGateway.java:86`). 그래서 + setup 상한과 본문 gap 상한이 섞이지 않는다. 테스트는 헤더 timeout·전체 예산보다 긴 본문과 read-idle보다 긴 공백을 두 + transport에서 모두 본다(`StreamingBodyLifetimeTest`). +- 캐시 전용 lane의 결정이 코드에 남아 있다. 버린 대안 둘과 이유가 `CacheScriptLane.java:20-24`와 README + 「Why the cache has its own script lane」(`cache-redis/README.md:192`)에 있다. lane 분리를 SCRIPT 1개를 잡은 상태로 + 증명하는 테스트가 있다(`RedisCacheRegionAdapterTest.java:442`). +- lane 지표가 닫힌 이름만 태그로 쓴다. 거절·폐기 counter는 기동 때 0으로 미리 만든다(`RedisLaneMetrics.java:89-108`). + listener는 lock 밖에서 부르고, 실패해도 borrow를 깨지 않는다(`RedisRuntimeOwner.java:350-356`, 테스트 + `RedisLaneMetricsTest.java:277`). +- renew의 TTL 연장이 같은 Lua 안에 있어 원자적이다(`IdempotencyScripts.java:186-189`). 공유 계약에 실제 시간이 흐르는 경우가 + 생겼고(`IdempotencyStoreContract.java:373`), 시계를 못 움직이는 저장소는 통과 대신 abort로 보고된다. +- ACL probe가 "거절"을 허용 목록으로 판정한다(`RedisSemanticScriptAclProbe.java:124-145`). 끊김·`LOADING`·`BUSY`는 기동을 + 막지 않고, 읽은 값이 틀린 경우는 막는다. 둘 다 테스트가 있다. +- `MessageId`는 서명 검증을 통과한 envelope에서만 읽는다(`SesCallbackAdapter.java:126-129`). ledger가 두 유일 인덱스를 모두 + 먼저 조회하고 `ON CONFLICT DO NOTHING`을 대상 없이 쓴다(`JpaProviderEventLedger.java:237`). 그래서 event id가 새로 생겨도 + 제약 위반 예외가 아니라 중복으로 답한다. +- SNS 인증서 4xx 중 408·429를 장애 쪽에 남겼다(`NotificationCallbackProviderConfig.java:93`). 검증기는 + `IllegalArgumentException`을 서명 실패로 바꾼다(`SnsSignatureVerifier.java:89`). +- 기동 rule이 앞당긴 bean을 이름으로 보고한다(`StartupRuleRunner.java:66-81`). 정적·무인자 `RequiredProductionSecrets`만 + 예외로 두고, 그 이유가 Javadoc에 있다. +- 파일 소유자 규칙이 한 벌이 됐다(`RoleBasedFileAccessPolicy.java:78`의 `subject.owns`). 운영 policy가 fake와 같은 계약을 + 상속한다(`RoleBasedFileAccessPolicyContractTest`). + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +| --- | --- | --- | +| RR-04-01 | 닫힘 | `BlockingAttemptExecutor.java:156` `deadline.setByCaller() && scope.expired()` → `AttemptResiliencePipeline.java:136-137` `releasePermission()`. total-call로 끊긴 시도는 계속 센다(결정). 두 transport 회귀 테스트. 남은 문서 공백은 RR-03-16 | +| RR-04-02 | 닫힘(4절 결정대로) | 캐시 조건부 쓰기가 `CacheScriptLane.CACHE_SCRIPT`(기본 4)로(`RedisCacheRegionAdapter.java:138`, `RedisCacheConfig.java:74-79`). 기여 조건이 캐시 region bean과 같다(`:37`, `:74`). lane별 대기·거절·재연결 지표(`RedisLaneMetrics`). 문서 표류는 RR-03-17 | +| RR-04-03 | 닫힘 | `DeadlineAwareJdkRequestFactory.java:49` → `JdkStreamingClientHttpRequest`, 본문은 `ReadIdleInputStream`, 실패는 `ClassifiedBodyInputStream`. 두 transport 테스트. 새 Minor 넷: RR-03-12(skip), RR-03-13(read당 타이머 비용), RR-03-14(unchecked 예외), RR-03-15(헤더 목록 사본) | +| RR-04-05 | 닫힘 | `cache-redis/build.gradle:89` `requires`에 `LiveRedisIdempotencyStoreContractTest`. CLAUDE.md 목록도 맞췄다. 결과적으로 lane은 `integrationCheck`에서만 돈다(mainCheck 중복 제거). README 목록 누락은 RR-03-18 | +| RR-04-06 | 닫힘 | `package-info.java`, `identifier/CLAUDE.md` Allowed 4개, README가 `build.gradle`과 `modules.json`(`domain-core, application-core, shared-contract`)에 맞는다 | +| RR-04-07 | 닫힘 | `RedisSemanticScriptAclProbe.java:124-145` 허용 목록 판정, `LOADING`·끊김·`BUSY` 테스트. 실제 서버 메시지로는 미확인(못 본 것) | +| RR-04-08 | **부분** | renew는 고쳤다(`IdempotencyScripts.java:186-189`, 계약 `:373`). claim·takeover는 여전히 key TTL을 replay TTL로 둔다(`:44,77`). replay TTL < processing lease면 lease 중에 key가 사라진다 → RR-03-11(E3) | +| RR-04-09 | 닫힘 | `StartupRuleRunner.java:66-81,103-131`(RR-06-01과 같은 수정), 테스트 3건(non-static 규칙, 비정적 secrets, 정적 secrets 허용) | +| RR-04-10 | 닫힘 | 순서 키가 `redis-runtime/.../module-defaults/redis-runtime.yml`로 옮겨졌고 cache-redis에서는 빠졌다(중복 키면 기동 실패라 한 곳뿐). `RedisRuntimeHealthStatusOrderTest` | +| RR-04-11 | 닫힘 | `JavaMailSenderSmtpDispatch.java:120` `400 <= code < 600`, 테스트 | +| RR-07-03 | 닫힘 | 4xx(408·429 제외) → `IllegalArgumentException` → 서명 실패 → 거절·감사. 5xx·408·429·IO → 503. `SnsCertificateFetchTest`. 4xx가 SNS 자신의 답이라는 가정은 Declined to judge | +| RR-07-04 | 닫힘 | 파일 이름 `lane-fixture-accounts.acl`, `acl/README.md`가 "배포 파일 아님"과 계정 구성을 실제대로 적는다, compose 4개·`docker-compose.infra.yml` 주석, `SecretSourceValidator`가 prod에서 `fixture-` 값 거부. 프로필 범위는 Declined to judge | +| RR-07-07 | 닫힘 | SES 이벤트의 `provider_event_id` = SNS `MessageId`(`SesEventNormalizer.normalize(payload, id)`), Javadoc이 실제 인덱스를 적는다. fingerprint는 event id를 입력으로 쓰지 않아 배포 경계의 재전송도 중복으로 잡힌다(`AesGcmCallbackPayloadProtection.java:112-124`) | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +#### RR-03-11 · replay TTL이 processing lease보다 짧으면 Redis 멱등성 key가 lease 도중 사라져, 같은 키의 두 번째 요청이 작업을 다시 돌린다 (RR-04-08 부분) + +- **위치**: `cache-redis/.../idempotency/IdempotencyScripts.java:44`(claim `PEXPIRE ARGV[7]` = replay TTL), `:77`(takeover도 같음), + `:186-189`(renew만 늘림). 설정: `src/composition/idempotency/.../IdempotencySettings.java:57,65`(lease와 replay TTL을 따로만 검사), + `src/application-core/.../IdempotencyClaimRequest.java:23-24`(관계 검사 없음), `idempotency.yml`의 `replay-ttl: ${APP_IDEMPOTENCY_TTL:24h}`. +- **무엇이 틀렸나**: + - 이번 수정은 "key TTL이 lease보다 먼저 끝나면 실행 중에 key가 사라져 같은 부작용이 다시 돈다"를 renew 경로에서만 막았다. + 수정 Javadoc 자신이 원인을 "Claim sets it to the replay TTL, which may be shorter than a lease"라고 적는다. + - claim은 여전히 key TTL을 replay TTL로 둔다. replay TTL이 processing lease보다 짧은 설정은 거부되지 않는다. + `processing-lease`는 `IN_FLIGHT_RETRY_AFTER`보다 길어야 한다는 검사만 있고, `replay-ttl`은 72h 상한만 있다. + - 그 설정에서 action이 replay TTL보다 오래 걸리면 key가 lease 도중 사라진다. 다음 claim은 `ACQUIRED`를 받고 executor는 + 작업을 처음부터 돌린다(`IdempotencyExecutor.java:132-133`). 첫 실행은 아직 진행 중이다. +- **왜 중요한가**: + - 멱등성이 막으려는 바로 그 피해다. 외부 호출·메일 같은 트랜잭션 밖 효과가 두 번 일어난다. 두 실행이 동시에 돈다. + - 발생 조건: `provider=redis` + `APP_IDEMPOTENCY_TTL` < `APP_IDEMPOTENCY_PROCESSING_LEASE`(기본 30s) + action이 replay TTL보다 + 오래 걸림 + 그동안 같은 키 재전송. 변수 이름이 `..._TTL`이고 env 레지스트리 설명도 "완료 응답을 재생하는 시간"뿐이라, + "짧은 재생 창"을 원해 10s를 넣는 설정은 그럴듯하다. 두 값의 관계는 어디에도 적혀 있지 않다. 사용자 원칙의 "숨은 위험"이다. + - 탐지가 어렵다. 두 번째 요청은 정상 `ACQUIRED` 경로라 로그·지표에 이상이 없다. + - RR-01-11(만료된 `EXECUTING`을 `RECOVERY_REQUIRED`로)을 고쳐도 이 경로는 남는다. 기록이 lease가 끝나기 전에, 또는 renew 뒤 + lease와 같은 순간에 사라지므로 "만료된 EXECUTING"을 볼 기록이 없다. renew가 TTL을 lease와 정확히 같게 두기 때문이다(`:187-188`). + - PostgreSQL 저장소도 claim에서 `expires_at = now + replay TTL`을 쓰고 reaper가 상태와 lease를 보지 않고 지운다 + (`IdempotencyClaimGateway.java:44`, `IdempotencyRecordJpaRepository.java:22-24`, E1). reaper 주기만큼 늦을 뿐 같은 원인으로 보인다. +- **고치는 법**: + 1. 설정에서 막는다(두 저장소를 한 번에): `IdempotencySettings`가 `replay-ttl < processing-lease`이면 기동 실패. env 레지스트리와 + `idempotency.yml` 주석에 관계를 적는다. 고른 방법·버린 대안을 Javadoc에 남긴다. + 2. 저장소도 스스로 지킨다: Redis claim·takeover·renew가 key TTL을 `max(replay TTL, lease + 여유)`로 둔다. 여유는 RR-01-11의 + 만료 처리가 기록을 볼 수 있을 만큼(예: replay TTL)이다. "lease와 정확히 같은 TTL"은 피한다. + 3. 계약에 시간 경우 하나: "replay TTL보다 긴 lease로 claim하면 lease 안의 다른 claim은 `InProgress`". Live Redis·PG lane이 실제로 돈다. +- **가이드 심각도·우선순위**: Medium · P2. 피해는 High급(업무 중복 실행)이지만 비기본 설정에서만 도달한다. 기본 조립은 멱등성 비활성. +- **증거**: E3 — `redis:7.4` 컨테이너에서 `bbe944bd`의 CLAIM Lua를 직접 실행. lease 3000ms·replay TTL 1000ms claim → 1.3s 뒤 + key 없음 → 다른 owner claim `ACQUIRED`(A의 lease 1.7s 남음). 설정 경로(`IdempotencySettings`→executor→claim)는 E1. + 이번 라운드가 만든 결함은 아니다. 1차 RR-04-08이 renew만 짚었고, 같은 원인의 claim 경로가 남았다. + +### Minor (Nice to Have) + +#### RR-03-12 · JDK `ReadIdleInputStream.skip`이 gap이 아니라 skip 전체 시간을 read-idle로 묶는다 + +- **위치**: `httpclient/.../jdk/ReadIdleInputStream.java:49-51`(`skip`을 `guarded` 한 번으로), `:53-57`. +- **무엇**: JDK 응답 stream은 `skip`을 재정의하지 않는다. 그래서 `InputStream.skip`이 안에서 `read`를 여러 번 부른다. 타이머는 + 그 묶음 전체에 한 번 걸린다. 데이터가 꾸준히 와도 큰 `skip`이 read-idle보다 오래 걸리면 거짓 `SocketTimeoutException`이 나고 + stream이 닫힌다. 문서는 "본문은 gap마다 read-idle로만 묶인다"고 적는다. `skipNBytes`도 `skip`을 쓴다. +- **고치는 법**: `skip`을 직접 구현한다. 작은 버퍼로 `read`를 반복하고, 각 `read`만 `guarded`로 감싼다. 위 탐침을 단위 테스트로 둔다. +- **심각도·우선순위**: Low · P3(JDK transport + 스트리밍 + skip 사용에서만). **증거**: E3 — `SkipProbe`: 공백 100ms, read-idle 1s에서 + `readAllBytes`는 30바이트 성공, `skip(30)`은 1,001ms에 `SocketTimeoutException`. + +#### RR-03-13 · JDK 스트리밍의 read마다 JVM 공용 delay 스케줄러에 타이머를 걸고 지운다 + +- **위치**: `httpclient/.../jdk/ReadIdleInputStream.java:53-69`. +- **무엇**: `read` 한 번마다 `CompletableFuture.completeOnTimeout`으로 JVM에 하나뿐인 delay 스케줄러 큐에 작업을 넣고 지운다. + 지울 때 큐의 맨 앞이 바뀌면 그 스레드를 깨운다. 측정: 1스레드 read당 3.9~4.6µs, 여러 스레드에서는 JVM 전체 약 0.5M회/초에서 + 멈춘다. 같은 큐를 `AttemptDeadline`과 Spring JDK 요청 timeout도 쓴다. 16KB read라면 영향이 작다(1GB에 약 0.2초 CPU). 1바이트씩 + 읽는 소비자(`DataInputStream` 등)는 JVM 전체 약 0.5MB/초가 상한이 된다. Apache는 소켓 timeout이라 이 비용이 없다. +- **고치는 법**: stream마다 "마지막 진행 시각"(volatile `nanoTime`)만 read에서 갱신한다. 타이머는 read-idle 주기로 한 번 걸고, + 깨어났을 때 진행이 없으면 닫고 있으면 다시 건다. 전용 `ScheduledExecutorService`를 transport가 하나 갖는 방법도 있다. 고른 방법을 + 주석에 남기고, 위 측정을 전후로 다시 잰다. +- **심각도·우선순위**: Low · P3(기본 transport는 Apache). **증거**: E3 — `Bench`(load average 14~22에서 측정, 수치는 크기 정도로만 읽는다). + +#### RR-03-14 · 스트리밍 본문 `InputStream.read`가 이제 unchecked `HttpClientException`을 던지는데, 공개 타입에 적혀 있지 않다 + +- **위치**: `httpclient/.../restclient/ClassifiedBodyInputStream.java:34,43,52,61`, `api/result/BlockingStreamingResponse.java`(`body()` Javadoc), + `api/error/HttpClientException.java:12`(`extends RuntimeException`). +- **무엇**: 이전에는 본문 실패가 `IOException`이었다. 이제는 `HttpResponseTimeoutException`·`HttpResponseTruncatedException` + (RuntimeException)이다. 두 transport 모두다(Apache도 바뀌었다). `catch (IOException)`으로 부분 파일을 지우거나 재시도하는 소비자 + 코드는 이 예외를 놓친다. `InputStream` 계약상 `read`가 던지는 것은 `IOException`이다. README와 configuration-reference에는 + 적혔지만 소비자가 보는 `BlockingStreamingResponse.body()`에는 없다. +- **고치는 법**: (a) `IOException`을 상속한 본문 예외(예: `HttpBodyReadException`)를 두고 분류된 `HttpClientException`을 cause·accessor로 + 싣는다. 또는 (b) 지금 방식을 유지하되 `body()` Javadoc과 README에 "read는 unchecked `HttpClientException`을 던진다, + `IOException` catch로는 잡히지 않는다"를 적는다. 고른 쪽과 이유를 남긴다. +- **심각도·우선순위**: Low · P3(템플릿 안 운영 소비자 없음, 파생 서비스의 기존 catch가 영향). **증거**: E1. + +#### RR-03-15 · JDK 스트리밍 요청이 Spring의 금지 헤더 목록을 사본으로 갖고, 원본과 갈라졌다 + +- **위치**: `httpclient/.../jdk/JdkStreamingClientHttpRequest.java:44,89,123-127`. +- **무엇**: 사본은 다섯 이름을 고정으로 둔다. Spring 7.0.9 `JdkClientHttpRequest.disallowedHeaders()`는 + `jdk.httpclient.allowRestrictedHeaders` 시스템 속성을 읽어 허용된 이름을 뺀다. 그 속성을 켠 배포에서 같은 profile의 일반 호출은 + `Host` 등을 보내고 스트리밍 호출은 조용히 버린다. 사용자 원칙의 "갈라진 중복 복사본"이다. +- **고치는 법**: 같은 시스템 속성을 읽는다. 또는 사본을 둔 이유와 원본 위치를 주석에 적고, 두 목록이 같은지 보는 테스트를 둔다. +- **심각도·우선순위**: Low · P3. **증거**: E1(`javap -c`로 Spring 쪽 확인). + +#### RR-03-16 · 호출자 예산이 stage timeout보다 짧은 profile에서는 죽은 상대를 breaker가 보지 못한다 — 문서에 없다 + +- **위치**: `httpclient/.../restclient/BlockingAttemptExecutor.java:156`, `resilience/AttemptResiliencePipeline.java:26-29`(Javadoc), + `docs/httpclient/configuration-reference.md` "Two deadlines" 표. +- **무엇**: + - 코드는 "호출자 deadline이 profile보다 이르고, 실패 시점에 scope가 만료됐으면" 기록하지 않는다. + - Javadoc은 "상대가 profile 한도 안에서 답하던 중"인 시도라고 적는다. 코드는 그 조건을 보지 않는다. + - 결과: 모든 호출자가 connect·response-header timeout(기본 2s)보다 짧은 예산을 넘기면, 블랙홀이 된 상대(패킷 버림)의 시도는 하나도 + breaker에 기록되지 않는다. circuit이 열리지 않아 모든 호출이 자기 예산을 끝까지 기다린다. + - connect 거절 같은 즉시 실패는 계속 센다. +- **고치는 법**: 이 맹점을 configuration-reference 표와 Javadoc에 적는다("호출자 예산이 stage timeout보다 짧으면 hang하는 상대는 + breaker가 못 본다. 그런 profile은 stage timeout을 호출자 예산보다 짧게 둔다"). Javadoc의 조건 문장을 코드에 맞춘다. +- **심각도·우선순위**: Low · P3(결정의 부작용 기록). **증거**: E1. + +#### RR-03-17 · Redis 관측 문서가 지금 나오는 신호와 어긋난다 + +- **위치**: `docs/runbooks/redis-capability-incident.md:50,60-63,64-67,74`, `cache-redis/README.md:218`, + `docs/registries/metrics.yaml`의 `redis.lane.acquire.wait.seconds` 행, `redis-runtime/.../RedisRuntimeOwner.java:354`. +- **무엇**: + - runbook의 Detection 절은 "`redis.capability.*`는 내보내지 않는다"로 고쳤다. 그런데 같은 문서의 다른 줄은 그 지표가 있는 것처럼 + 남았다. "semantic operation 계측은 … 결과를 기록한다", "앞선 success 표본과 이 실패를 두 operation으로 합산하지 않는다", + "이 meter와 단일-process lifecycle test는…", "reconnect, cache source-load, session repository error 지표의 변화를 함께 본다" + (cache source-load·session 지표를 내는 코드가 없다). 레지스트리에서 뺀 `redis.capability.*`의 이름을 직접 부르는 곳은 없다 + (`git grep` 결과 README 「아직 내보내지 않는 지표」와 runbook 해명 줄뿐). + - README는 `opened`를 "warm-up 뒤에는 모두 재연결"이라고 적는다. routed lease(Cluster `TRANSACTION`)는 borrow마다 새로 열고 + pool에 돌려주지 않으며 `discarded`로도 세지 않는다(`RedisRuntimeOwner.java:265-267`, 반환 시 `discarded == null`). 그 lane에서는 + 정상 동작이 재연결 급증처럼 보인다. + - 레지스트리는 대기 timer를 `percentiles: [0.5,0.9,0.95,0.99]`, `histogram_buckets: slo_driven`으로 적는다. 코드는 SLO 경계 없이 + `publishPercentileHistogram()`만 쓴다(`RedisLaneMetrics.java:117`). p99 경보는 histogram으로 계산되니 동작은 맞고, 표기만 다르다. + - listener 실패는 DEBUG로만 남는다(`RedisRuntimeOwner.java:354`). 결과를 바꾸지 않는 것은 맞다. 다만 registry 충돌 등으로 + 지표가 통째로 사라져도 운영 로그에는 흔적이 없다. +- **고치는 법**: runbook의 남은 줄을 "설계(미구현)"로 옮기거나 지운다. README에 "routed lease는 매번 연다"를 적거나 routed 열기를 + 다른 reason으로 센다. 레지스트리 행을 코드에 맞춘다. listener 실패는 처음 한 번 WARN으로 남긴다. +- **심각도·우선순위**: Low · P3. **증거**: E1. + +#### RR-03-18 · lane의 자리·구성을 바꾼 뒤 옛 문장이 남은 문서 + +- **위치**: `objectstorage/README.md:108`("(in `mainCheck`)"), `.github/workflows/object-storage-qualification.yml:4` + ("they run in its `mainCheck` on main and here"), `cache-redis/README.md:337-338`. 원인 변경: `objectstorage/build.gradle:158-162` + (mainCheck 의존 삭제), `cache-redis/build.gradle:89`(멱등성 계약 추가). +- **무엇**: + - build는 MinIO lane을 `integrationCheck`에만 둔다. 두 문서는 leaf `mainCheck`가 돌린다고 적는다. cache-redis의 같은 변경은 + README·CLAUDE.md를 함께 고쳤다(`cache-redis/README.md:339-340`). + - cache-redis README는 컨테이너 lane이 "cache-region and lease port contracts"를 돈다고 적는다. RR-04-05로 멱등성 계약이 + 더해졌는데 README에는 없다. CLAUDE.md(`:131-139`)는 맞다. + - 같은 종류의 사소한 것: `SesEventNormalizer.java:58-59` 주석이 "is keyed / by / the active"로 잘못 줄바꿈됐다. +- **고치는 법**: MinIO 두 문장을 "`integrationCheck`(main push·nightly)와 이 workflow"로 고친다. cache-redis README의 계약 목록에 + 멱등성 계약을 넣는다. +- **심각도·우선순위**: Low · P3. **증거**: E1. + +## Declined to judge + +- SNS 인증서 URL의 4xx를 "SNS가 없다고 답했다 = 위조"로 보는 가정. 호스트 검사를 통과해도 TLS를 가로채는 egress 장비나 + private DNS를 켠 SNS VPC endpoint가 답할 수 있다. 그 경로에서 정상 콜백이 400으로 영구 거절되고(SNS는 4xx에 재전송을 멈춘다) + 감사 로그가 위조로 찬다. 명시 proxy의 CONNECT 실패는 JDK가 `IOException`으로 주므로 503 쪽이다. AWS가 없는 인증서·VPC endpoint + 경유에 어떤 status를 주는지 확인하지 못해 판단을 미룬다. 확인할 것: 운영과 같은 네트워크에서 존재하지 않는 `.pem`을 받아 보기. +- `SecretSourceValidator`의 `fixture-` 거부가 `isProduction()`(prod 프로필)에서만 돈다. 프로필 없음·`staging`은 그대로 기동한다. + 기존 sentinel 검사와 같은 범위이고, RR-07-02가 문제 삼은 "거부 목록이 prod 하나" 구조와 닮았다. pathspec 밖(app-bootstrap)이라 07 영역에 넘긴다. +- PostgreSQL 멱등성 reaper가 `expires_at`만 보고 진행 중 기록도 지우는 것(RR-03-11 근거로 읽음). persistence 영역의 판단이 필요하다. +- 캐시 전용 배포에서 advanced 계정 비밀번호가 틀리면(`WRONGPASS`) 연결 단계 실패라 "장애"로 WARN 후 기동한다. 이번 diff 전부터의 + 동작이다. 설정 오류로 볼지는 판단하지 않았다. +- `CACHE_SCRIPT`가 pod당 advanced 계정 연결을 최대 4개 늘린다(SCRIPT 8 + 4). Redis `maxclients`와 ACL 계정별 연결 예산에 주는 영향은 판단하지 않았다. +- read-idle 타이머가 만료되면 JDK 공용 delay 스레드에서 `in.close()`를 부른다. JDK 응답 stream의 close는 구독 취소라 막히지 않는다고 + 보지만, HTTP/2·TLS에서 재 보지 않았다(1차 Declined와 같은 질문). +- lane 대기 Timer를 borrow마다 builder로 등록하는 비용. 측정 결과 152~241ns로 Redis 왕복 대비 무시할 수준이라 발견으로 올리지 않았다. + +## 수렴 판단 + +- **이 라운드가 만든 새 Important 이상: 없음.** 수정 diff가 새로 만든 결함은 모두 Minor다(RR-03-12~18). 그중 실행으로 확인한 것은 + RR-03-12(E3)와 RR-03-13(E3)이고, 둘 다 기본이 아닌 JDK transport의 스트리밍에만 닿는다. +- **남은 Important 1건은 덜 닫힌 1차 발견이다.** RR-03-11은 RR-04-08과 같은 원인의 claim 경로다. 이번 라운드가 만든 것이 아니라 + 1차가 renew만 짚어 남은 것이다. 고치는 비용은 설정 검사 몇 줄이다. RR-01-11의 수정과 TTL 규칙을 함께 정해야 한다. +- 따라서 이 영역만 보면 수정 라운드는 수렴했다. 다음 라운드가 필요하다면 RR-03-11(및 RR-01-11과의 묶음) 때문이다. + +## Assessment + +**Ready to merge: With fixes.** 1차 발견 13건 중 12건이 코드와 실제 서버 테스트로 닫혔고, 회귀와 이 라운드가 만든 새 Important는 없다. +다만 RR-04-08의 claim 경로가 남아 있어(RR-03-11, E3) replay TTL을 processing lease보다 짧게 둔 Redis 배포에서 멱등 작업이 두 번 돈다. diff --git a/docs/reviews/2026-11-03-rereview/round2/04-bootstrap-build-sample.md b/docs/reviews/2026-11-03-rereview/round2/04-bootstrap-build-sample.md new file mode 100644 index 00000000..8389a4f5 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round2/04-bootstrap-build-sample.md @@ -0,0 +1,306 @@ +# 04 bootstrap·build·sample 재리뷰 (2026-11-03) + +리뷰 대상: Base `7ef8d0b4` → Head `bbe944bd`(재리뷰 수정 커밋), 영역 번호 04(slug `bootstrap-build-sample`). +1차 재리뷰 발견 중 이 영역이 맡은 것: RR-06-01~12, RR-07-02, RR-07-05, RR-04-09. 경로는 저장소 루트 기준이다. + +## 범위 — 본 pathspec, 불러온 스킬과 적용한 기준, 실행한 명령과 결과, 못 본 것 + +### 본 pathspec + +```text +src/app-bootstrap src/sample-portfolio src/build-logic src/build.gradle src/settings.gradle src/gradle +src/gradle.properties src/optional-platforms src/config src/.env.example .github docker-compose*.yml +infra/postgres infra/fileserver AGENTS.md CLAUDE.md docs/registries docs/capability-status.md docs/testing +``` + +`git diff --stat` 기준 83파일 +2,159 −413. 하위 에이전트 없이 여러 번에 나눠 직접 읽었다. + +- 전부 읽은 것: build-logic main diff 전체(`StrictLaneStagesPlugin`, `WorkflowGradleInvocations`, + `StrictTestLanePlugin`, `ConfigContractPlugin`, `ConfigurationMetadataClasspath`, `EnvContractVerifier`, + `VerifyEnvKeysTask`)와 그 테스트 diff, workflow diff 3개, `src/optional-platforms/build.gradle`, + `src/config/spotbugs/exclude.xml` diff, app-bootstrap main·test·architectureTest diff, sample main diff 전체와 + `application.yml` 전문, sample 보안 테스트 diff, AGENTS.md·CLAUDE.md·`docs/capability-status.md`· + `src/build-logic/README.md`·`src/app-bootstrap/README.md`·`CLAUDE.md` diff, `.env.example` diff. +- 표본으로 읽은 것: `docs/registries/env-keys.yaml`·`error-codes.yaml`·`secrets-classification.yaml` diff, + `metrics.yaml` diff(키 이름만), `docs/testing/TESTING_STRATEGY.md` diff, `OutboxStatusRegistryContractTest` diff. +- pathspec 밖에서 확인용으로 읽은 것: `src/adapter/outbound/support/.../startup/StartupRuleRunner.java`· + `StartupRule.java`·`RequiredProductionSecrets.java`와 그 테스트 diff(RR-06-01 수정 본체), + `src/Dockerfile.sample`, `src/adapter/inbound/web/.../error/EnvelopeErrorController.java`, + `src/adapter/outbound/objectstorage/build.gradle`·`ObjectStorageAutoConfiguration.java`, + `src/grpc/grpc-testkit/build.gradle`·`GrpcPerformanceLaneTest.java`, `docs/runbooks/job-timeout.md` diff, + `scripts/run-compose-runtime-smoke.sh`, `infra/redis-sdk/acl/*.acl`. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +| --- | --- | --- | +| `superpowers:requesting-code-review` | 리뷰어 템플릿(Strengths → severity별 Issues → Declined → Assessment), "spec이 말하지 않은 동작은 합리적인 사용자의 기대로 판단", 읽기 전용, 의심 결함은 별도 worktree에서 확인 | 수정이 1차 발견의 "고치는 법"을 채웠는지, 수정이 만든 새 결함. 의심 5건을 worktree 실험으로 확인 | +| `ci-cd-and-automation` | "No gate can be skipped", Red flag "CI failures ignored or silenced", 캐시 최적화가 결과를 바꾸면 안 된다 | `verifyStrictLaneStages`의 workflow 해석(`-x`·`continue-on-error`·`if:`·`-p`)이 실제 Gradle 계획과 같은지, lane 정책 입력이 캐시 재사용을 불필요하게 깨는지, optional 빌드 단계 연결 | +| `security-and-hardening` | 비밀값은 환경에서, 기본값은 닫힘, 오류 메시지는 내부를 드러내지 않음, CSRF는 ambient 자격이 있을 때 의미가 있다 | 데모 계정 허용 목록·기본 프로필 제거, prod `fixture-` 거부 범위, SpotBugs CSRF 제외 축소와 `EnvelopeErrorController` 제외의 근거 | + +### 실행한 명령과 결과 + +worktree `scratchpad/rr2-04`(HEAD `bbe944bd`)에서 Gradle을 `flock heavy.lock`으로 감싸 실행했다. 시작 부하 6~40. +probe 파일은 worktree에만 만들었고, 끝난 뒤 `git worktree remove --force`로 지웠다. 메인 체크아웃은 건드리지 않았다. + +| # | 명령 | 결과 | +| --- | --- | --- | +| 1 | build-logic에 reader probe 추가 → `./gradlew -p build-logic test --tests '*RR2WorkflowProbeTest*' --tests '*StrictLaneStagesFunctionalTest.rr2*'` | rc=0. `on: workflow_dispatch`만 있는 workflow의 `:integrationCheck`는 실행으로 셈(`reason=null`). `working-directory: src/optional-platforms` + `../gradlew ci`는 main 빌드 `ci` 실행으로 셈. job `if: ${{ !cancelled() && !failure() }}`는 안 셈. `with: run:`(action 입력)은 실행으로 셈. TestKit: `:integrationCheck -x databaseL --dry-run` 계획에서 Gradle은 `:leaf:databaseLane`을 뺐는데, 같은 줄을 가진 workflow로 `verifyStrictLaneStages`는 **"every strict lane is in an executed stage"로 통과** | +| 2 | support·app-bootstrap·sample에 probe 추가 → `./gradlew :adapter:outbound:support:test --tests '*RR2ProbeTest*' :app-bootstrap:test --tests '*RR2FixturePrefixProbeTest*' :sample-portfolio:test --tests '*RR2DemoProfile*' --continue` | rc=1(의도한 실패 14건). 아래 2-a~2-e | +| 2-a | support: JavaBean `@ConfigurationProperties("probe2")`가 `RequiredProductionSecrets`를 구현, static 규칙이 `ObjectProvider.orderedStream()`으로 읽음, `probe2.name=bound` | runner 없음: `name=bound`. runner 있음: **기동 성공, `name=null`**, 경고 없음 | +| 2-b | support: `@Import`한 `StartupRule` 클래스에 `@Value("${probe3.mode}")` 필드, `probe3.mode=strict` | **기동 성공, 규칙이 본 값 `null`, 기동 뒤 bean 필드도 `null`** | +| 2-c | support: raw `FactoryBean` 컴포넌트(생성자 의존 1개) + 같은 static 규칙 | 기동 성공(오탐 없음). 규칙 없는 대조군도 성공 | +| 2-d | app-bootstrap: prod 프로필, `HOSTNAME=fixture-api-6d5f7c9b8-x2k4q`(시스템 환경 소스), `spring.application.name=fixture-service`, `app.messaging.topic=fixture-updates` | 세 이름 모두 위반: `'fixture-' repository fixture password (public, infra/redis-sdk/acl) is configured for HOSTNAME` 등 | +| 2-e | sample: `SampleDemoSecurityConfigTest`를 복사해 `app.object-storage.enabled=false`만 빼고 프로필을 `demo`·`test`·`local`로 | `local` 7건 통과. `demo`·`test` 각 7건 **전부 실패**: `Error creating bean with name 'objectStorageCapability' ... object-storage binding is incomplete or invalid` | +| 3 | `./gradlew :sample-portfolio:qualityCheck` | rc=0 (PR sample job이 새로 부르는 태스크) | +| 4 | `./gradlew -p optional-platforms :verifyStrictLaneStages --dry-run`, `./gradlew :verifyStrictLaneStages --dry-run` | 둘 다 rc=0 | +| 4-b | worktree의 `integration-main.yml` optional performance 줄에 `-x grpcPerformanceT` 추가 → 같은 optional 검사, 그리고 `./gradlew -p optional-platforms performanceCheck -x grpcPerformanceT --dry-run` | 검사는 **통과**. 실제 계획에는 `:grpc:grpc-testkit:grpcPerformanceTest`가 없고 `performanceTestLaneCheck`만 있다 — RR-06-03이 닫은 lane이 다시 어디서도 돌지 않는데 검사가 모른다 | + +돌리지 않은 것: `ci`·`mainCheck`·`integrationCheck` 전체(README 7절 오케스트레이터 실행을 근거로 삼았다), `docker build`· +`docker run`(Dockerfile.sample은 정적 확인), compose 실제 기동, GitHub Actions 실행. + +### 못 본 것 + +- 실제 CI runner에서의 workflow 실행, `gradle/actions/setup-gradle`의 캐시 복원 범위. +- `docs/registries/metrics.yaml`의 새 `redis.lane.*` 행과 코드가 내보내는 이름의 대조(03·04 outbound 영역 소관). +- `env-keys.yaml`에 새로 넣은 행 중 `APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS` 외 다른 영역 행의 의미. +- architectureTest의 새 ArchUnit 규칙 2개의 적용 범위(01 core 영역 소관). 실패 fixture가 있다는 것까지만 봤다. + +## Strengths + +- **기동 규칙이 앞당긴 bean을 이제 실제로 잡는다.** `src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java:64-83,100-131`. + 1차 probe와 같은 모양(설정 bean을 받는 non-static `@Bean` 규칙)이 `probeRule`·`probe-dev.caskeleton`을 대며 기동 실패한다 + (`StartupRuleRunnerTest.java` 새 테스트 3건). 같은 수정 때문에 기존 테스트 설정 2곳이 static으로 바뀌었다 + (`ErrorDetailExposureSafetyValidatorTest.java:71`, `RuntimeNumericBoundsValidatorTest.java:81`). 검사가 장식이 아니라는 증거다. +- **정상 구성에서 오탐하지 않는다.** 실험 2-c에서 생성자 의존이 있는 raw `FactoryBean`이 있어도 규칙이 `RequiredProductionSecrets`를 + 읽는 동안 다른 singleton이 생기지 않았다. 템플릿의 모든 조립(app-bootstrap·sample·qualification)은 README 7절 게이트에서 기동했다. +- **lane 정책이 캐시 입력이 됐고, 바뀌지 않은 lane의 캐시는 그대로 쓴다.** `StrictTestLanePlugin.java:227-240`. + 정책만 바꾼 두 번째 실행이 "forbids skipped tests"로 실패하는 TestKit(`StrictTestLaneConventionTest.java:549-583`)과, + 정책을 그대로 둔 hermetic lane이 여전히 `FROM_CACHE`인 기존 TestKit(`:505-547`)이 둘 다 HEAD에서 통과한다. 입력은 모두 + 상수 값(Boolean·String·List)이라 머신 간 캐시 키가 갈라지지 않는다. +- **optional 빌드가 자기 lane 도달성을 스스로 검사한다.** `src/optional-platforms/build.gradle:1-7,55-83`, + `StrictLaneStagesExtension.java:19-25`. 실험 4에서 `grpcPerformanceTest`가 `-p optional-platforms performanceCheck`로 덮인다. + `performanceCheck`·`releaseCheck` 집계로 바뀌어 lane을 더해도 workflow를 고칠 필요가 없다(`release.yml:135`). +- **`-x` 경로 지정·`continue-on-error`·비상태 `if:`를 Gradle 계획 위에서 판정한다.** `StrictLaneStagesPlugin.java:120-183`. + 전체 경로 `-x`는 lane과 그 아래 의존을 계획에서 잘라 낸다. TestKit 4건(`StrictLaneStagesFunctionalTest.java:189-316`). +- **env 계약이 leaf 이름을 모른다.** `ConfigContractPlugin.java:21-66`, `VerifyEnvKeysTask.java:50-118`, + `src/app-bootstrap/build.gradle:483-488`. metadata classpath가 비면 실패한다(`VerifyEnvKeysTask.java:67-71`). +- **CSRF 제외가 클래스 이름으로 좁혀졌고 sample이 처음으로 분석된다.** `src/config/spotbugs/exclude.xml:19-50`, + `.github/workflows/ci-quality-gates.yml:73`. 실험 3에서 `:sample-portfolio:qualityCheck`가 통과한다. +- **데모 계정 허용 목록이 섞인 프로필도 거부한다.** `SampleDemoAccountsProductionGuard.java:51-65`. + `local,prod`·`test,staging`·프로필 없음이 거부되는 테스트가 있다(`SampleDemoAccountsProductionGuardTest.java:70-94`). +- **Poster 포트의 충돌 규칙이 코드로 묶였다.** domain 예외(`domain/poster/PosterTitleAlreadyExistsException.java`)와 + `PosterRepositoryContract`를 in-memory fake와 실 PostgreSQL adapter(`integrationTest` source set)가 함께 상속한다. +- **종료 예산의 web drain을 compose가 실제로 주는 값에서 읽는다.** `DeveloperExperienceContractTest.java:412-418,632-639`. + runbook도 49초 기준으로 고쳤다(`docs/runbooks/job-timeout.md:51-54`). + +## 발견 재확인 표 + +상태: 닫힘 / 부분 / 회귀 / 결정으로 닫힘. `>`는 다른 영역 소관. + +| ID | 상태 | 근거 | +| --- | --- | --- | +| RR-06-01 | 부분 | 1차 probe 모양(non-static `@Bean` 규칙이 설정 bean을 받음)은 기동 실패로 잡힌다(`StartupRuleRunner.java:100-131`). 그러나 새로 생긴 singleton이 `StartupRule`·`RequiredProductionSecrets` 타입이면 묻지 않고 허용한다(`:108-109`). 그 bean 자신이 BPP 없이 만들어지는 경우 — 필드 주입 컴포넌트 규칙, JavaBean 설정 클래스가 비밀 목록을 겸함 — 는 여전히 조용히 바인딩되지 않는다(실험 2-a·2-b) → RR2-04-03 | +| RR-06-02 | 닫힘 | `StrictTestLanePlugin.java:227-240` 정책 5개를 입력으로. TestKit `:549-583`. release job `--rerun-tasks`는 결정으로 넣지 않음(README 6절 r4-f) | +| RR-06-03 | 닫힘(잔여 RR2-04-04) | `src/optional-platforms/build.gradle:1-7,55-83`, `ci-quality-gates.yml:83-87`, `integration-main.yml:206-211`. 실험 4 통과. 다만 축약 `-x`로 같은 lane을 빼도 검사는 모른다(실험 4-b) | +| RR-06-04 | 부분 → RR2-04-04 | 지목한 세 가지(`-x` 전체 경로, `continue-on-error`, 비상태 `if:`)는 닫힘(`WorkflowGradleInvocations.java:236-307`). 축약 `-x`, `on:` 트리거, `working-directory`는 여전히 안 본다(실험 1·4-b) | +| RR-06-05 | 닫힘 | sample PR job에 `:sample-portfolio:qualityCheck`(`ci-quality-gates.yml:73`), CSRF Match FQCN화(`exclude.xml:19-50`). 실험 3 통과 | +| RR-06-06 | 닫힘 | 죽은 블록 3개 삭제(`sample application.yml`), `SampleRuntimeDefaultsContractTest.java:83-176`이 `app.*` 최상위 묶음마다 sample classpath의 읽는 코드를 요구. 하위 키까지는 보지 않는다(고치는 법이 요구한 수준) | +| RR-06-07 | 부분 → RR2-04-05 | lane json·smoke 래퍼의 `APP_*` 키는 이제 등록·읽힘 검사 대상(`ConfigContractPlugin.java:45-62`, `EnvContractVerifier.java:44,216-224`). 1차 발견을 낳은 `CASKELETON_GRPC_ENABLED` 같은 비-`APP_` 키는 여전히 아무 검사도 받지 않는다 | +| RR-06-08 | 닫힘 | `DeveloperExperienceContractTest.java:412-418`, `docs/runbooks/job-timeout.md:51-54` | +| RR-06-09 | 닫힘 | `src/adapter/outbound/objectstorage/build.gradle:158-162` mainCheck 의존 삭제 | +| RR-06-10 | 닫힘 | `ConfigContractPlugin.java`에서 redis-runtime 경로·`dependsOn` 삭제, `ConfigurationMetadataClasspath`, `app-bootstrap/build.gradle:483-488` | +| RR-06-11 | 닫힘(새 drift RR2-04-06) | 지목한 7곳 모두 고침(build-logic README:64, grpc-testkit 주석, CLAUDE.md·AGENTS.md mainCheck, runtime.yml·observability.yml, SampleManagementSecurityConfig:24-29, capability-status idempotency 행, sample build.gradle). 이번 수정이 같은 종류의 새 drift를 만들었다 | +| RR-06-12 | 닫힘 | domain 예외 + `PosterRepositoryContract`(fake·PG adapter 상속), `PosterRepository.java:12-23`, `WorkLogRepository.java:11-17`이 두 갈래의 이유를 적음 | +| RR-07-02 | 결정으로 닫힘(새 결함 RR2-04-02) | 허용 목록 `local`·`test`·`demo`(`SampleDemoAccountsProductionGuard.java:30,51-65`), yml 기본 프로필 삭제(`application.yml:29-32`), bootRun만 `local`을 넘김(`sample-portfolio/build.gradle:248-254`). 결정대로 구현됐다. 그런데 허용한 `test`·`demo`로는 sample이 기동하지 않고, 이미지 실행 문서가 깨졌다 | +| RR-07-05 | 닫힘 | `exclude.xml:19-50`. sample 데모 체인은 별도 Match와 이유 | +| RR-04-09 | 닫힘 | non-static `@Bean` 규칙은 그 설정 클래스를 만들므로 이름을 대며 실패한다(`StartupRuleRunnerTest` 새 테스트 1·2). 남은 경로는 RR2-04-03 | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +#### RR2-04-01 · prod의 `fixture-` 거부가 모든 설정값을 보아서, 비밀이 아닌 정당한 값으로 운영 기동이 막힌다 (이번 라운드가 만든 결함) + +- **위치**: `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java:48,51-54,113-140`. + 문서: `src/app-bootstrap/README.md:132-136`, `docs/registries/secrets-classification.yaml:13-15`. +- **무엇이 틀렸나**: prod 프로필이면 모든 property source의 모든 값을 훑어 `fixture-`로 시작하면 기동을 거부한다. + OS 환경 변수도 포함한다. `fixture-`는 이 저장소의 lane 비밀번호 접두사이기 전에 평범한 영어 단어다. + 거부 대상은 비밀번호가 아니라 "그 접두사로 시작하는 모든 문자열"이다. +- **증거 (E3)**: 실험 2-d. prod에서 `HOSTNAME=fixture-api-6d5f7c9b8-x2k4q`, `spring.application.name=fixture-service`, + `app.messaging.topic=fixture-updates`가 모두 위반이 됐다. 메시지는 셋 다 "repository fixture password (public, + infra/redis-sdk/acl)"라고 말한다. +- **왜 중요한가**: + - 발생 조건: Kubernetes는 pod 이름을 `HOSTNAME`으로 넣는다. Deployment 이름이 `fixture-`로 시작하면(경기 일정 + "fixture" 도메인, 테스트 데이터 서비스 등) 모든 pod가 이 값을 가진다. 앱 이름·topic·bucket·key prefix도 같다. + - 발견 시점: 검사는 prod 프로필에서만 돈다. dev·staging은 통과하고 첫 운영 배포가 crash loop가 된다. + - 우회 수단: 없다. 이름을 바꾸거나 이 클래스를 고쳐야 한다. README는 "설정값이면 이름을 바꾼다"고 적지만, + 운영자가 `HOSTNAME`을 설정값으로 떠올릴 이유가 없다. + - 막으려던 것은 공개된 lane 비밀번호 7개다(`infra/redis-sdk/acl/lane-fixture-accounts.acl`의 `fixture-admin`· + `fixture-advanced`·`fixture-application`·`fixture-bootstrap`·`fixture-raw`·`fixture-replication`·`fixture-sentinel`). + 정확한 값 목록으로도 같은 사고를 막을 수 있어서, 넓은 접두사 일치가 얻는 것은 없다. +- **고치는 법**: 결정(prod에서 lane fixture 비밀번호 거부)은 그대로 두고 범위만 좁힌다. + 1. 접두사가 아니라 저장소가 공개한 값 집합과 정확히 같을 때만 거부한다. 값 목록은 ACL fixture 파일에서 한 번만 + 정의하고, 그 파일과 목록이 같은지 테스트로 묶는다. + 2. 또는 검사 대상을 비밀값으로 좁힌다: 레지스트리에서 `secret`으로 분류된 키와, `secret://…@environment/` + 참조가 가리키는 변수. + 3. 메시지는 "lane fixture 비밀번호와 같은 값"이라고 말하고, `HOSTNAME`·`spring.application.name` 같은 값이 통과하는 + 테스트를 둔다. +- **가이드 심각도·우선순위**: Medium · P2. 운영에서만 드러나는 기동 실패이고, 원인이 된 값이 정당하다. +- **증거 등급**: E3(실험 2-d), prod 전용 경로는 E1(`SecretSourceValidator.java:98`). + +#### RR2-04-02 · 허용 목록의 `test`·`demo`로는 sample이 기동하지 않고, sample 이미지의 실행 문서가 깨졌다 (이번 라운드가 만든 결함) + +- **위치**: `src/sample-portfolio/src/main/resources/application.yml:215-227`(object storage를 끄는 것은 `local` 문서뿐), + `SampleDemoAccountsProductionGuard.java:30,44`(remedy가 "local (or test or demo)"를 권함), + `src/sample-portfolio/README.md:54-57`(jar·이미지는 "`local`(또는 `test`·`demo`)"), `src/Dockerfile.sample:7-9,14-17` + (pathspec 밖), `src/sample-portfolio/src/systemTest/resources/application-test.yml:176-177`(테스트만 object storage를 끔). +- **무엇이 틀렸나**: + 1. object storage 모듈은 classpath에 있으면 켜진다. sample main 설정은 `local` 프로필에서만 끈다. + `test`·`demo`로 jar나 이미지를 띄우면 목적지 없는 object storage가 기동을 막는다. `demo` 프로필 문서는 아예 없다. + 2. `Dockerfile.sample`의 실행 예시는 프로필을 주지 않는다. 이제 그 명령은 종료 코드 71로 끝난다. 머리말의 + "필요한 외부 의존은 PostgreSQL 하나"도 틀렸다. + 3. 게이트가 이를 못 본 이유: sample의 모든 Spring 테스트는 `local`이거나, `test` 프로필에 테스트 리소스 + `application-test.yml`이 object storage를 끈다. 실제 jar의 `test`·`demo`를 띄우는 테스트는 없다. +- **증거 (E3)**: 실험 2-e. 같은 slice를 `demo`·`test`로 띄우면 14건 모두 `objectStorageCapability ... object-storage binding + is incomplete or invalid`로 실패했고, `local`은 7건 통과했다. 이번 diff의 `SampleDemoSecurityConfigTest.java:57-59`도 + 같은 이유로 `app.object-storage.enabled=false`를 손으로 더했다(주석이 그렇게 말한다). +- **왜 중요한가**: sample은 도입자가 가장 먼저 띄우고 복제하는 실행 경로다(가이드 35.3: 템플릿에서는 개발자 경험의 + 실행 경로가 도입 차단 항목이 될 수 있다). 결정이 `demo` 프로필을 새로 허용했지만 그 프로필로는 아무것도 뜨지 + 않는다. 이미지 사용자는 문서대로 하면 거부되고, 거부 메시지가 권하는 두 번째·세 번째 선택지에서 다시 + 프로필과 무관해 보이는 object storage 오류를 만난다. 보안 결함은 아니다(실패는 닫힌 쪽이다). +- **고치는 법**: + 1. sample의 lean demo 기본값(object storage off 등)을 `local` 문서가 아니라 기본 문서에 두거나, 세 데모 프로필 + 모두에 같은 문서를 둔다(`on-profile: local | test | demo`). + 2. `Dockerfile.sample` 실행 예시에 `-e SPRING_PROFILES_ACTIVE=demo`(또는 `local`)를 넣고, 머리말을 고친다. + 이미지에 기본 프로필을 굽지 않는 것은 결정대로 둔다. + 3. 회귀 방지: 허용 목록의 각 프로필로 `SamplePortfolioApplication`을 테스트 리소스 없이 띄우는 테스트 하나 + (`DEMO_PROFILES`를 파라미터로). +- **가이드 심각도·우선순위**: Medium · P2. +- **증거 등급**: E3(실험 2-e), Dockerfile 부분은 E1. + +#### RR2-04-03 · 기동 규칙 검사가 `StartupRule`·`RequiredProductionSecrets` 타입이면 묻지 않고 통과시켜, RR-06-01과 같은 "조용히 바인딩 안 됨"이 남는다 (RR-06-01 부분) + +- **위치**: `src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java:104-110` + (타입 면제), `:44-49`(Javadoc "the two kinds that are declared static and argument-free"), `src/app-bootstrap/CLAUDE.md:88-92`, + prod 전용 경로 `SecretSourceValidator.java:98,142-147`·`SecretSourceConfig.java:31-35`. +- **무엇이 틀렸나**: 검사는 "규칙을 만들거나 돌리는 동안 새로 생긴 singleton"을 본다. 그 singleton이 규칙이나 비밀 목록 + 자신이면 무조건 허용한다. Javadoc은 이 두 종류가 static·인자 없음으로 선언된다고 말하지만, 그 사실은 검사하지 않는다. + 그래서 bean 자신이 BPP 없이 만들어지는 모양은 빠져나간다. + - JavaBean `@ConfigurationProperties` 클래스가 `RequiredProductionSecrets`를 겸하면 바인딩되지 않는다. + - `@Component` 규칙의 `@Value` 필드·`@Autowired` 필드는 주입되지 않는다(생성자 `@Value`는 된다). + 둘 다 다른 singleton을 만들지 않으므로 검사가 볼 것이 없다. +- **증거 (E3)**: 실험 2-a. runner가 없으면 `name=bound`, runner가 있으면 기동 성공·`name=null`·경고 없음. + 실험 2-b. 규칙이 본 값과 기동 뒤 bean의 필드가 모두 `null`, 기동 성공. +- **왜 중요한가**: + - `RequiredProductionSecrets`는 `SecretSourceValidator`가 prod에서만 꺼낸다(`SecretSourceValidator.java:98`). 그래서 2-a + 모양은 dev·test·staging에서는 정상 바인딩되고 prod에서만 기본값으로 돈다. 그 설정 bean을 쓰는 런타임 코드도 + prod에서만 기본값을 본다. + - 2-b 모양은 Spring에서 가장 흔한 컴포넌트 작성법이다. 규칙이 항상 `null`을 보면 그 안전 검사가 조용히 꺼진다. + - 1차 발견의 핵심은 "개발자가 기억해야 하는 숨은 제약"이었다. 수정 뒤 문서(`StartupRuleRunner` Javadoc, app-bootstrap + CLAUDE.md)는 "runner가 막아 준다"고 읽히지만, 이 두 모양은 막지 못한다. 지금 템플릿의 규칙·비밀 목록 선언은 + 모두 static `@Bean`이라 터지는 곳은 없다. +- **고치는 법**: 1차 리뷰의 첫째 안을 면제 대상에만 적용한다. 새로 생긴 singleton이 규칙·비밀 목록 타입이면 + `beanFactory.getBeanDefinition(name)`이 `AnnotatedBeanDefinition`이고 `getFactoryMethodMetadata()`가 static이며 매개변수가 + `Environment`·`ListableBeanFactory`·`ObjectProvider`뿐일 때만 허용한다. 그 밖(컴포넌트 스캔·`@Import`· + `@EnableConfigurationProperties`로 등록된 클래스)은 이름을 대며 실패시킨다. 실험 2-a·2-b를 RED 테스트로 쓴다. +- **가이드 심각도·우선순위**: Medium · P2(1차 RR-06-01과 같은 근거·같은 등급). +- **증거 등급**: E3(실험 2-a·2-b), prod 전용 경로는 E1. + +### Minor (Nice to Have) + +#### RR2-04-04 · `verifyStrictLaneStages`의 workflow 해석에 남은 틈 — 축약 `-x`, `on:` 트리거, `working-directory` + +- **위치**: `src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java:102-110` + (`excludes`: 전체 이름만 비교), `:197-230`(트리거·`working-directory`를 읽지 않음), `:236-278`. +- **무엇이 틀렸나**: + 1. Gradle은 `-x`에 축약 이름(camel-case)을 받는다. reader는 이름이 정확히 같을 때만 제외로 본다. + 2. `if: github.event_name == 'workflow_dispatch'`는 "실행 아님"으로 거부하면서, 같은 뜻의 `on: workflow_dispatch`만 있는 + workflow는 실행으로 센다. + 3. `working-directory: src/optional-platforms` + `../gradlew ci`를 main 빌드의 `ci` 실행으로 센다. optional 빌드에는 안 센다. + 4. `uses:` 단계의 `with: run:` 입력을 실행으로 센다(이전부터). +- **증거 (E3)**: 실험 1과 4-b. 실제 `integration-main.yml`에 `-x grpcPerformanceT`를 넣으면 Gradle 계획에서 + `grpcPerformanceTest`가 빠지는데 optional 검사는 통과한다. 지금 workflow에는 이런 줄이 없다. +- **왜 중요한가**: 검사는 "lane이 실제로 돈다"를 증명한다고 문서(AGENTS.md:79-86, CLAUDE.md:40-44)에 적혀 있다. + 축약 `-x`는 사람이 터미널에서 흔히 쓰는 형태라 workflow로 그대로 옮겨질 수 있다. 그러면 RR-06-03이 막은 상태가 + 조용히 돌아온다. +- **고치는 법**: `-x` 판정을 문자열 비교가 아니라 Gradle에 맡긴다. 각 실행 명령의 `-x` 값을 `--dry-run` 계획을 + 다시 만들 때 `StartParameter.excludedTaskNames`로 넘기거나, 계획의 태스크 이름에 Gradle과 같은 camel-case 일치를 + 적용한다. 트리거가 `workflow_dispatch`뿐인 workflow는 `if:`와 같은 이유로 세지 않는다. `working-directory`가 + 있으면 그 경로를 `-p`처럼 읽는다. 각각 reader 단위 테스트 1건. +- **심각도·우선순위·증거**: Low · P3 · E3. + +#### RR2-04-05 · lane 활성화 키 검사가 `APP_` 키만 봐서, RR-06-07을 낳은 비-`APP_` 키는 여전히 아무도 안 본다 (RR-06-07 부분) + +- **위치**: `src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java:44`(`JSON_KEY`는 + `"APP_…"`만), `:225-233`(레지스트리 행에 `property:`가 있으면 "읽힘"), `ConfigContractPlugin.java:45-49`(주석), + `EnvContractVerifierTest.java:236-253`. +- **무엇이 틀렸나**: 1차 발견의 실제 사례는 `CASKELETON_GRPC_ENABLED`, 즉 `APP_`가 아닌 아무도 읽지 않는 키였다. + 새 검사는 그 키를 패턴에서부터 건너뛴다. 새 테스트 fixture에 이 키가 들어 있지만 단언하지 않는다. plugin 주석은 + "이 태스크가 아니라 손으로 찾았다"를 들어 이제는 잡힌다고 읽힌다. 또 레지스트리 행에 `property:`만 있으면 그 property가 + 실제로 있는지(`app.redis.` 밖) 보지 않고 "읽힘"으로 친다. +- **왜 중요한가**: compose lane에 오타 난 비-`APP_` 스위치를 넣어도 lane은 다른 이유로 녹색일 수 있다. 1차 결함과 같은 모양이다. +- **고치는 법**: lane json의 `activationEnv` 키 중 `APP_`·`SPRING_`·`MANAGEMENT_`·`SERVER_`·`REDIS_LANE_`(문서화된 비밀번호 + 변수) 같은 허용 접두사 밖의 키를 거부한다. fixture의 `CASKELETON_GRPC_ENABLED`를 실패로 단언한다. `property:` 행은 + qualification classpath metadata에서 그 이름을 찾는다. +- **심각도·우선순위·증거**: Low · P3 · E1(테스트 본문으로 확인). + +#### RR2-04-06 · 이번 수정이 새로 만든 문서·주석 불일치 + +- **무엇이 틀렸나** (모두 E1): + - `docs/capability-status.md:42` gRPC transport 행: "`ca-skeleton.grpc.server.enabled` (no `APP_*` row)". 이번 diff가 + `APP_GRPC_SERVER_ENABLED`(property `app.grpc.server.enabled`, `GrpcServerSettings.java:27`)를 등록했다. object storage 행만 고쳤다. + - `src/.env.example:297-299`: "Explicit offs for two more capabilities"라고 쓰고 값은 `true`다. + - `src/config/spotbugs/exclude.xml:474-478`: "Only DispatcherType.ERROR reaches it ... meets the normal chain (and its CSRF + rules)". 인증된 직접 요청도 이 메서드에 닿고(`EnvelopeErrorController.java:35-37`가 그렇게 말한다), JWT 체인은 CSRF를 끈다. + 제외가 성립하는 진짜 이유는 "상태를 바꾸지 않고 고정된 실패 envelope만 쓴다"이다. 결론은 맞고 근거 문장이 틀렸다. + - `src/Dockerfile.sample:7-9,14-17`: RR2-04-02 참조. + - `StartupRuleRunner.java:44-49`, `src/app-bootstrap/CLAUDE.md:88-92`: RR2-04-03 참조. +- **고치는 법**: 위 줄을 코드에 맞춘다. exclude 이유는 "부작용 없음, 직접 요청은 인증 체인을 거친다"로 바꾼다. +- **심각도·우선순위·증거**: Low · P3 · E1. + +## Declined to judge + +- 데모 허용 목록에 `test`가 있는 것 — 회사마다 외부에 열린 공유 "test" 환경이 있을 수 있다. 4절 결정이라 뒤집지 않는다. +- release job이 `--rerun-tasks` 없이 캐시 결과를 증거로 올리는 것 — README 6절 r4-f 결정. 이유는 문서에 없지만, tag 필터가 + task 입력이라 "tag가 무언가를 고른다"는 증거 의미는 캐시로도 유지된다. +- job·단계의 비상태 `if:`(`github.event_name == 'push'`, `!cancelled() && !failure()`)를 실행으로 세지 않는 것 — 정상 + workflow를 거부할 수 있지만 닫힌 쪽 실패이고 메시지가 이유를 말한다. 결함으로 세지 않았다. +- `verifyEnvKeys`가 이제 모든 capability jar를 만든다(qualification classpath) — mainCheck 비용 증가를 측정하지 않았다. +- lane 입력 중 `tag`·`mainStage`는 판정에 쓰이지 않거나 이미 다른 입력에 들어 있다 — 캐시를 불필요하게 깨는 경우는 + 그 값을 바꿀 때뿐이라 해가 없다. +- IDE에서 `SamplePortfolioApplication`을 프로필 없이 바로 실행하면 거부된다 — 결정의 직접 결과이고 메시지가 해결책을 말한다. +- sample 관리 포트에서 데모 체인이 모든 GET을 허용 — 이전부터의 상태(1차 06 Declined). +- 새 ArchUnit 규칙 2개(`INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES`, `INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`)의 + 범위 — 01 영역 소관. +- `metrics.yaml`의 `redis.lane.*`·`outbox.retry.long.*` 행과 코드의 일치 — 03·04·05 영역 소관. +- `SampleRuntimeDefaultsContractTest`가 `app.*` 최상위 묶음만 보는 것 — RR-06-06 고치는 법이 요구한 수준이다. + +## 수렴 판단 — 이 라운드가 만든 새 Important 이상이 있는가 + +**있다. 2건이다.** + +- RR2-04-01: RR-07-04 수정(prod `fixture-` 거부)이 모든 설정값을 보아서, 정당한 값(예: Kubernetes pod 이름 `HOSTNAME`)으로 + 운영 기동만 막힌다. +- RR2-04-02: RR-07-02 결정 구현(허용 목록·기본 프로필 삭제)이 허용한 `test`·`demo`로는 sample이 뜨지 않고, sample 이미지 + 실행 문서가 깨졌다. + +그 밖에 1차 Important 하나가 덜 닫혔다. RR-06-01(RR2-04-03)은 1차 probe 모양은 막았지만, 규칙·비밀 목록 bean 자신이 +바인딩되지 않는 모양은 여전히 조용하다. + +세 건 모두 고치는 범위가 작다. 정확한 값 목록 하나, yml 문서 하나와 Dockerfile 주석, runner의 면제 조건 하나다. +다음 수정 라운드는 필요하다. 다만 이 영역에서 구조를 다시 바꿀 일은 아니다. + +## Assessment + +**Ready to merge? With fixes.** + +RR-06-02·03·05~12, RR-07-05, RR-04-09는 코드와 실행으로 닫혔고 회귀는 없다. 다만 이번 라운드의 보안·데모 수정이 새 +Medium 2건(운영에서만 터지는 `fixture-` 오거부, 허용한 데모 프로필로 sample이 뜨지 않음)을 만들었다. RR-06-01도 면제 +경로가 남았다. 셋 다 merge 전에 고치는 것이 맞다. diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md new file mode 100644 index 00000000..6a96a80a --- /dev/null +++ b/docs/upgrade/2026-11-maturity-review.md @@ -0,0 +1,271 @@ +# 업그레이드 안내 — 2026-11 성숙도 리뷰 수정 + +- 범위: `01a8a2a70..bbe944bd` (main → `refactor/maturity-review-2026-11`, 커밋 5개) +- 커밋: `34565130` High·P1 19건 · `1400dc15` 남은 발견·매뉴얼·생성 명령 · `5786126c` 남은 항목과 합친 뒤 결함 · + `7ef8d0b4` 재리뷰 기록(문서만) · `bbe944bd` 재리뷰 결함 +- 근거 문서: `docs/reviews/2026-11-01-maturity-review/README.md` 13~16절, `docs/reviews/2026-11-03-rereview/README.md` + 4·6·8절, 각 커밋의 `BREAKING CHANGE:` 꼬리말 +- 아래 표의 각 줄은 위 범위의 diff와 코드로 확인했다. 확인하지 못한 것은 그 자리에 "확인 못 함"으로 적었고 9절에 + 모았다. + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 변경을 merge해 받는 파생 서비스(예: `tech-log-backend` — `origin`=서비스, +`upstream`=이 템플릿)의 개발자가 읽는다. 이 브랜치가 main에 합쳐진 뒤 `git merge upstream/main`을 하기 전에 본다. + +## 2. 한눈에 + +### 반드시 할 일 + +| # | 할 일 | 안 하면 | 해당 서비스 | +|---|---|---|---| +| 1 | JWT 모드면 `APP_SECURITY_JWT_AUDIENCE`에 이 서비스의 client id를 쉼표로 넣는다 | 기동 실패 `APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required` | JWT 모드(기본값) 전부 | +| 2 | dev·prod 환경 변수의 `APP_FLYWAY_ENABLED` 값을 확인한다 | `false`가 남아 있으면 이제 정말로 마이그레이션이 안 돈다 | persistence-jpa 선택 | +| 3 | prod 설정 어디에도 `fixture-`로 시작하는 값이 없게 한다 | prod 기동 실패(exit 78) | prod 배포 전부 | +| 4 | 직접 만든 `StartupRule`·`RequiredProductionSecrets` bean을 `static @Bean`, 의존성 없이 바꾼다 | 기동 실패 `startup rule '<이름>' created [...]`(exit 78) | 자기 rule이 있는 서비스 | +| 5 | 직접 구현한 outbox·발행·알림·파일 서버 포트를 새 시그니처로 고친다(3.1절) | 컴파일 오류 | 해당 포트를 구현·호출하는 서비스 | +| 6 | `dev.caskeleton.application.outbound.*` import를 `application.secret.*`·`application.objectstorage.content.CallBudget`으로 바꾼다 | 컴파일 오류 | 해당 타입을 쓰는 서비스 | +| 7 | 이벤트 id를 소문자 UUIDv7로 만들고 `IntegrationEventDraft`는 `IntegrationEventDrafts.draft(...)`로만 만든다 | 쓰기 요청이 `IllegalArgumentException`으로 실패, architectureTest 실패 | 통합 이벤트를 내는 서비스 | +| 8 | V21 배포 전에 `docs/runbooks/outbox-dead-letter.md` §8 Step 1 쿼리를 운영 DB에 돌린다 | 중복 순서 키가 있으면 기동 실패(exit 70, V20에 남음) | persistence-jpa + outbox | +| 9 | 이 브랜치의 이전 V21을 적용한 개발 DB를 다시 만든다(4.2절) | Flyway checksum 불일치로 기동 실패(exit 70) | 이 브랜치를 미리 받아 돌린 개발 DB | +| 10 | 자기 SecurityFilterChain이 있으면 `DispatcherType.ERROR`를 허용한다 | 핸들러 밖 오류가 401로 바뀌어 나간다 | 자기 보안 체인을 둔 서비스 | +| 11 | 짝 프론트(또는 다른 클라이언트)에 7절 계약을 맞추게 한다 | 409를 재시도 불가로 읽거나, `null` 키를 기대하다 깨진다 | HTTP 클라이언트가 있는 서비스 | +| 12 | 자기 Flyway 마이그레이션 번호가 템플릿의 새 번호와 겹치지 않는지 본다(4절) | 같은 버전 두 개로 Flyway 실패 | 같은 stream에 자기 마이그레이션을 둔 서비스 | +| 13 | `.env`에 옛 `.env.example` 값을 복사해 두었다면 5.6절 키를 다시 맞춘다 | 새 기본값이 안 먹거나(JDBC batch), 기동 실패(알림 콜백 상한) | `.env`를 복사해 쓰는 서비스 | + +### 되돌릴 수 없는 것 + +- 이 repo에는 down 마이그레이션이 없다(`U*__*.sql` 파일 0개). 되돌리려면 배포 전 백업을 복원한다(4.4절). +- notification V12는 중복 수신 거부(suppression) 행을 **지운다**. 알림을 쓰는 서비스는 배포 전 백업이 필수다. + +## 3. 호환성을 깨는 변경 + +증상 칸의 exit 코드는 `StartupErrorCode`(`src/adapter/outbound/support/.../startup/StartupErrorCode.java`)를 따른다: +70 `MIGRATION_FAILED`, 71 `PROFILE_MISMATCH`, 72 `REQUIRED_ADAPTER_DISABLED`, 78 `STARTUP_VALIDATION_FAILED`. + +### 3.1 Java API — 컴파일이 깨진다 + +| # | 무엇이 바뀌었나 | 파생 서비스 증상 | 할 일 | 근거 | +|---|---|---|---|---| +| B-01 | `OutboxStorePort`: `markFailed(OutboxLease, Instant)` → `markFailed(OutboxLease, Instant, String failureCode)`, `markDead(OutboxLease)` → `markDead(OutboxLease, String failureCode)`. 추상 메서드 추가: `markDeferred(OutboxLease, Instant, String)`, `releaseLease(OutboxLease, Instant)`, `longRetries(int, Instant)`(반환 `OutboxLongRetries`) | 직접 만든 store·fake가 `does not override abstract method` 컴파일 오류, 호출부 인자 수 오류 | 템플릿 `JpaOutboxStore`만 쓰면 할 일 없음. 직접 구현했다면 다섯 메서드를 구현한다. `failureCode`는 메시지가 아닌 코드다(`OutboxPublishAttempt.isFailureCode`) | `1400dc15`(markDeferred·releaseLease), `bbe944bd`(failureCode·longRetries) · `src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java` | +| B-02 | 발행 포트 반환형: `IntegrationEventPublishPort.publish(ValidatedIntegrationEvent)`가 `CompletionStage` → `CompletionStage`. `OutboxMessagePublishPort.publishForOutcome(ClaimedOutboxEvent)`가 `OutboxPublishOutcome` → `OutboxPublishAttempt`. 둘 다 default `longestAttempt()` 추가 | 구현체 반환형 불일치 컴파일 오류 | 결과를 `OutboxPublishAttempt.confirmed()`, `OutboxPublishAttempt.of(outcome)`, `OutboxPublishAttempt.failed(outcome, code)`로 감싼다 | `bbe944bd` · `.../messaging/event/IntegrationEventPublishPort.java`, `.../outbox/OutboxMessagePublishPort.java` | +| B-03 | enum 값 추가: `OutboxPublishOutcome.REJECTED_RETRYABLE`(`retryable()`=true), `OutboxRelayResult.Outcome.RELEASED`, `OutboxEventStatus.PARKED` | `default` 없는 switch 식이 "does not cover all possible input values" 컴파일 오류 | 새 값 분기를 더한다 | `34565130`(REJECTED_RETRYABLE), `1400dc15`(RELEASED), `bbe944bd`(PARKED) | +| B-04 | `OutboxRelayFailureReport`에 `failureCode` 필드 추가, `retryableFailure(...)`·`deadLetter(...)`에 `String failureCode` 인자 추가. `PublishPendingOutboxEventsCommand()` → `PublishPendingOutboxEventsCommand(BooleanSupplier stopRequested)` | 직접 생성하는 코드 컴파일 오류 | 보고서는 code를 넘긴다. command는 `PublishPendingOutboxEventsCommand.INSTANCE`를 쓰거나 supplier를 넘긴다 | `bbe944bd`(report), `1400dc15`(command) | +| B-05 | 알림: `ReconciliationJobStorePort.claimDue(int, Instant)` → `claimDue(int limit, Instant now, Duration lease)`. `ReconciliationJob`에 `long claimFence` 필드 추가. `reschedule`·`complete`는 fence가 다르면 아무것도 안 바꾼다 | 직접 구현한 store·job 생성 코드 컴파일 오류 | lease 인자를 받고, claim마다 fence를 올리고, 쓰기에 fence 조건을 건다. 계약은 `application-notification` testFixtures의 공유 계약 테스트로 확인 | `34565130`, `bbe944bd` · `src/application-notification/.../dispatch/ReconciliationJobStorePort.java` | +| B-06 | 파일 서버: `CleanupQueuePort.claimDue(Instant, int)` → `claimDue(Instant, int, Duration lease)`, `markAbandoned(CleanupItem, String reasonCode)` 추가. `CleanupItem`에 `UUID claimToken` 필드 추가. `FileQuotaPort.usedBytes(QuotaScope)` 추가. `UploadContentPort.releaseLease(UploadSession, RequestContext)` 삭제 | 직접 구현한 포트·`CleanupItem` 생성 코드 컴파일 오류 | 새 메서드 구현, `releaseLease` 호출 제거 | `1400dc15`(cleanup), `5786126c`(quota·upload) · `src/application-fileserver/.../cleanup/CleanupQueuePort.java`, `.../api/metadata/FileQuotaPort.java`, `.../upload/UploadContentPort.java` | +| B-07 | 패키지 이동: `dev.caskeleton.application.outbound.SecretSourcePort`·`SecretReference` → `dev.caskeleton.application.secret.*`. `dev.caskeleton.application.outbound.CallBudget` → `dev.caskeleton.application.objectstorage.content.CallBudget`(leaf `application-objectstorage`). `application.outbound` 패키지 삭제 | `package dev.caskeleton.application.outbound does not exist` | import를 바꾼다. `CallBudget`을 쓰는 leaf가 `application-objectstorage`에 의존해도 되는지 `modules.json` 간선을 확인 | `5786126c` · `src/application-core/.../secret/`, `src/application-objectstorage/.../content/CallBudget.java` | +| B-08 | `shared-contract`에서 `dev.caskeleton.shared.operation.Operation`·`OperationStatus` 삭제. sample-portfolio(`...sample.portfolio.adapter.inbound.web.operation`)로 옮겨졌다 | import 실패 | 쓰고 있었다면 자기 inbound adapter로 복사한다 | `1400dc15` · `src/shared-contract/src/main/java/dev/caskeleton/shared/operation/`(삭제) | +| B-09 | `SecuritySettings`(adapter:inbound:web): `audience`가 `String` → `List`. `@ConfigurationProperties` 제거, `SecuritySettings.bind(Environment)`로 strict 바인딩. 생성자 `(String, String, List)` → `(String, List, List)`. `bootstrap.security.AuthenticationModeSettings` 삭제 | `audience()`를 문자열로 쓰는 코드, 직접 생성하는 테스트 컴파일 오류 | `List`으로 바꾼다. 인증 모드는 `SecuritySettings.authMode()`에서 읽는다 | `34565130`(List), `5786126c`(strict·삭제) · `src/adapter/inbound/web/.../settings/SecuritySettings.java` | +| B-10 | adapter 공개 타입 삭제·이동: graphql `execution.GraphQlTimeoutPolicy`·`dataloader.GraphQlDataLoaderRequestRegistry` 삭제(`runtime.GraphQlDeadlineInstrumentation`·`GraphQlPerParentFetchInstrumentation` 추가). jpa `experimental.tenant.TenantId` 삭제 → `dev.caskeleton.application.tenant.TenantId`. persistence-notification의 엔티티는 `...platform.entity`, 저장소는 `...platform.repository`로 이동, `inbox` 하위 클래스는 `platform`으로 올라옴, `PreferenceJpaRepository`·`SuppressionJpaRepository` 삭제, `JpaNotificationSideEffect` → application-notification `dispatch.SuppressionSideEffect` | import 실패. leaf `check`의 API surface 비교가 스냅샷과 달라 실패(자기 공개 타입을 더했다면 merge 충돌) | import를 바꾼다. 스냅샷 파일은 upstream 것을 받고 자기 추가분을 다시 승인한다 | `1400dc15`·`5786126c` · `docs/architecture/graphql-api-surface.txt`, `docs/architecture/jpa-api-surface.txt`(166→165), `docs/notification/api-surface-snapshot.txt`(362→364) | +| B-11 | 조립·지원 타입: `bootstrap.autoconfigure.operation.DurableOperationConfig` → `composition:durable-operation`의 `composition.operation.DurableOperationAutoConfiguration`. `bootstrap.settings.LoggingSettings` 삭제. `composition.outbox.OutboxLeaderElectionToken` 삭제. `TracingSamplingEnvironmentPostProcessor` → `TracingEnvironmentPostProcessor`, `StartupOrder.TRACING_SAMPLING` → `TRACING_PROPERTIES`. `StartupRuleRunner(Environment, List)` → `StartupRuleRunner(Environment)`. `SecretSourceValidator(ConfigurableEnvironment, SecretSourcePort, List)` → `SecretSourceValidator(Supplier>)` | 이 타입을 참조하는 코드·테스트 컴파일 오류 | 새 이름으로 바꾼다 | `1400dc15`, `34565130`, `bbe944bd` · `src/composition/durable-operation/`, `src/adapter/outbound/support/.../startup/` | + +### 3.2 설정·기동 — 기동이 실패하거나 런타임 예외가 난다 + +| # | 무엇이 바뀌었나 | 파생 서비스 증상 | 할 일 | 근거 | +|---|---|---|---|---| +| B-12 | JWT 모드에서 `APP_SECURITY_JWT_AUDIENCE` 필수(빈 값 거부, `${...}`가 안 풀린 값도 없는 값으로 봄). 토큰 `aud`가 목록 중 하나를 담아야 통과. `resource_access` role은 audience에 적은 client 것만 읽는다(realm role은 그대로) | 기동 실패 `APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required`(exit 코드 확인 못 함). `.env.example`이 `APP_SECURITY_JWT_AUDIENCE=`(빈 값)를 싣고 있다. 다른 client의 role에 기대던 권한이 사라짐 | client id를 쉼표로 넣는다. 다른 client role로 권한을 받던 사용자가 있는지 IdP에서 확인 | `34565130`(필수·role), `1400dc15`(안 풀린 `${...}`) · `src/adapter/inbound/web/.../auth/JwtDecoderConfig.java`, `.../JwtToAuthenticatedPrincipalConverter.java`, `.../settings/SecuritySettings.java` | +| B-13 | `app.security.*` strict 바인딩: 접두어 아래 오타 키, 또는 설정·placeholder 어디에도 쓰이지 않는 `APP_SECURITY_*` 환경 변수가 기동을 막는다 | 기동 실패(메시지는 `StrictSettingsBinder`가 키 이름을 담아 냄, 정확한 문구 확인 못 함) | 쓰지 않는 `APP_SECURITY_*` 변수를 지운다 | `5786126c` · `SecuritySettings.bind`, `src/adapter/outbound/support/.../StrictSettingsBinder.java` | +| B-14 | prod 프로필에서 `fixture-`로 시작하는 설정 값(변수 이름 무관)을 거부. Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로 | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` | +| B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다 | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule '<이름>' created [] while creating it ... Declare the rule with a static @Bean method ...`(exit 78) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` | +| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES` 추가 | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). inbound adapter가 그 유스케이스를 부르면 architectureTest 실패 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 호출자(scheduler 등)에 넘긴다. `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd` · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java` | +| B-17 | `IntegrationEventDraft`: `eventId`·`causationId`는 소문자 UUIDv7만. ArchUnit `INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`: `new IntegrationEventDraft<>(...)` 금지, `IntegrationEventDrafts.draft(...)`만 | 이벤트를 만드는 쓰기 요청이 `IllegalArgumentException: eventId must be a canonical lower-case UUIDv7...`로 실패. architectureTest 실패 | event id를 UUIDv7로 만든다(예: sample `UuidOutboxEventIdFactory`가 `UuidCreator.getTimeOrderedEpochPlus1()`). draft는 헬퍼로 만든다. tenant가 없는 이벤트는 `IntegrationEventDrafts.SINGLE_TENANT_SCOPE`(`global`) | `1400dc15`, `bbe944bd` · `src/application-core/.../messaging/event/IntegrationEventDraft.java`, `IntegrationEventDrafts.java` | +| B-18 | `MessageHandler.schemaVersions()`(vendored `messaging-core-api`, default `{v1}`): 소비자 decode 목록을 handler 선언으로 만든다. 같은 (메시지 타입, 버전)에 다른 payload class를 선언하면 실패 | 컴파일은 된다. v1이 아닌 메시지는 `SCHEMA_VERSION_NOT_REGISTERED`로 거부. 발행 등록(`MessageContracts`)과 class가 다르면 기동 실패 `MESSAGING_CONTRACT_CONFLICT` | v2 이상을 읽는 handler는 `schemaVersions()`를 override한다. 소비 타입을 `MessageContracts`에 따로 등록하던 코드는 지운다 | `5786126c` · `src/messaging/messaging-core-api/.../delivery/MessageHandler.java`, `messaging-spring-boot-starter/.../MessageContracts.java` | +| B-19 | `APP_FLYWAY_ENABLED`가 모든 프로필에서 읽힌다. dev·prod 프로필 파일의 `spring.flyway.enabled: true`·`app.persistence.vendor` 고정값을 지우고 persistence-jpa `config/module-defaults`가 `${APP_FLYWAY_ENABLED:true}`를 싣는다 | dev·prod 환경에 `APP_FLYWAY_ENABLED=false`가 있으면 전에는 무시됐지만 이제 기동 때 마이그레이션이 안 돈다 | dev·prod 환경 값을 확인한다. 자기 `application-dev.yml`·`application-prod.yml`에 같은 고정값을 다시 넣지 않는다 | `5786126c` · `src/app-bootstrap/src/main/resources/application-{dev,prod}.yml`, `src/adapter/outbound/persistence-jpa/.../module-defaults/persistence-jpa.yml` | +| B-20 | JDBC batch 기본 켜짐: `APP_JPA_HIBERNATE_BATCH_SIZE` 0→50, `APP_JPA_HIBERNATE_ORDER_INSERTS`·`ORDER_UPDATES` false→true(registry `compatibility_impact: behavior-change`) | 컴파일·기동은 그대로. SQL이 묶여 나가고 insert·update 순서가 바뀐다. IDENTITY 키 엔티티는 batch가 조용히 꺼진다. `.env`에 옛 값(0·false)이 있으면 새 기본값이 안 먹는다 | 문장 순서에 기대는 코드가 있는지 본다. 끄려면 0·false를 명시 | `1400dc15` · `persistence-jpa.yml`, `docs/registries/env-keys.yaml` | +| B-21 | 트랜잭션 제한: `TransactionPort` 쓰기·읽기 트랜잭션 30초(`app.persistence-jpa.transaction.write-timeout`·`read-timeout`, env 키 아님) | 30초를 넘는 트랜잭션은 문장이 취소되고 `DB_QUERY_CANCELED`로 실패 | 긴 일괄 작업은 쪼갠다. 꼭 필요하면 프로필 yml에서 값을 올린다 | `1400dc15` · `persistence-jpa.yml` | +| B-22 | 격리 수준을 Hikari에서 고정: `spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED`. 다른 값이면 거부. `TransactionPort`는 트랜잭션마다 격리 수준을 정하지 않는다 | 다른 격리 수준을 설정했다면 기동 실패(`HikariPoolConstraintValidator`) | 값을 지운다. 더 높은 격리가 필요한 곳은 따로 설계한다 | `1400dc15` · `src/adapter/outbound/persistence-jpa/.../startup/HikariPoolConstraintValidator.java` | +| B-23 | H2 드라이버가 운영 jar에서 빠짐(persistence-jpa `runtimeOnly` → `testRuntimeOnly`). `bootRunH2` 작업만 따로 넣는다 | `APP_PERSISTENCE_VENDOR=h2`로 `bootRunH2` 밖에서 띄우면 드라이버가 없다(정확한 오류 확인 못 함) | 로컬은 Compose PostgreSQL 또는 `bootRunH2`를 쓴다 | `1400dc15` · `src/adapter/outbound/persistence-jpa/build.gradle` | +| B-24 | `APP_IDEMPOTENCY_PROCESSING_LEASE`는 2초(`IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER`)보다 길어야 한다 | 2초 이하면 기동 실패 | 값을 2초보다 길게(기본 30s) | `5786126c`, `bbe944bd` · `src/composition/idempotency/.../IdempotencySettings.java` | +| B-25 | 알림 콜백 본문 상한 65508 → 65251(바인딩에서 상한 검사) | `.env`에 옛 예제 값 `APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES=65508`이 있으면 기동 실패 `max-body-bytes must be 1..65251` | 값을 지우거나 65251 이하로 | `5786126c` · `src/adapter/outbound/notification/.../autoconfigure/NotificationPlatformSettings.java` | +| B-26 | `config/module-defaults/`에 같은 이름 파일이 둘이거나, 두 파일이 같은 키를 실으면 기동 실패 | 기동 실패 `two capability modules ship config/module-defaults/` 또는 `... both ship `(exit 78) | 자기 leaf의 module-defaults 파일 이름·키가 템플릿 모듈과 겹치지 않게 한다 | `1400dc15` · `src/adapter/outbound/support/.../startup/ModuleDefaultsEnvironmentPostProcessor.java` | +| B-27 | (sample-portfolio를 남겨 둔 경우) 데모 계정은 활성 프로필이 모두 `local`·`test`·`demo` 중 하나일 때만. 프로필이 없어도 거부 | 기동 실패 `the sample's demo accounts authenticate only under the local, test or demo profile` | `SPRING_PROFILES_ACTIVE=local` 등으로 띄우거나 sample 보안 설정을 지운다 | `5786126c`, `bbe944bd` · `src/sample-portfolio/.../security/SampleDemoAccountsProductionGuard.java` | + +### 3.3 HTTP wire — 응답이 달라진다 + +정본은 `docs/web/http-contract.md`다. 클라이언트는 `success`와 `error.code`로 가른다. + +| # | 무엇이 바뀌었나 | 파생 서비스 증상 | 할 일 | 근거 | +|---|---|---|---|---| +| B-28 | 처리 중 409 `IDEMPOTENT_IN_FLIGHT`: `retryable` false→true, `Retry-After: 2` 추가. gRPC trailer `error-retryable`과 GraphQL extension `retryable`도 true | 409를 "재시도 금지"로 처리하던 클라이언트가 틀린다 | **같은 `Idempotency-Key`로** `Retry-After` 뒤 재전송하게 한다. 새 키 금지 | `34565130` · `src/shared-contract/.../error/OperationalError.java`, `docs/registries/error-codes.yaml` | +| B-29 | Envelope의 `null` 필드를 키째 생략: 성공은 `error` 키 없음, 실패는 `data` 키 없음, `meta.page`·`meta.correlationId`·`error.details`도 값이 없으면 키 없음. 빈 목록은 그대로 | `"error": null`·`"data": null`을 기대하던 클라이언트·계약 테스트가 깨진다 | `success`로 가르고 키 존재로 판단하지 않는다 | `34565130` · `src/adapter/inbound/web/.../envelope/EnvelopeWireFormatConfig.java` | +| B-30 | 새 코드 `IDEMPOTENCY_COMPLETION_UNKNOWN`(503, `TRANSIENT_DEPENDENCY`, retryable=true): 작업 실행 **뒤** complete 단계에서 멱등성 저장소가 응답하지 않음. 전에는 `IDEMPOTENCY_UNAVAILABLE` | 503을 "적용 안 됨"으로 읽던 클라이언트가 새 키로 다시 보내 중복이 생길 수 있다 | `error.code`로 가른다. 결과 불명이므로 같은 키로만 재전송 | `bbe944bd` · `src/application-core/.../idempotency/IdempotencyCompletionUnknownException.java`, `IdempotencyExecutor.java` | +| B-31 | 핸들러 밖 오류(`/error` 디스패치)를 `EnvelopeErrorController`가 실패 Envelope로 답한다. 전에는 Boot `/error` 맵이 `success:true`로 감싸져 요청 경로까지 실려 나갔다. 기본 JWT 체인에서 익명 400이 401로 바뀌지 않는다. 4xx·5xx 본문은 `success:true`로 감싸지 않는다. 보안 체인이 `DispatcherType.ERROR`를 허용한다 | 오류 본문 모양이 바뀐다. 자기 SecurityFilterChain이 ERROR 디스패치를 막으면 400이 401로 나간다 | 자기 체인에 `auth.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()`을 넣는다(템플릿 `SecurityConfig`와 같게) | `bbe944bd` · `src/adapter/inbound/web/.../error/EnvelopeErrorController.java`, `.../auth/SecurityConfig.java` | +| B-32 | 새·바뀐 오류 코드: 비동기 요청 timeout 500 `INTERNAL_ERROR` → 503 `REQUEST_TIMEOUT`(retryable). `IDEMPOTENCY_KEY_INVALID` 400(`details.reason`=`MISSING`·`MALFORMED`, `IdempotencyKeyHeader.parse`를 쓰는 엔드포인트, sample은 `BAD_PARAMETER`에서 바뀜). web-advanced 예외 10종이 모두 500 `INTERNAL_ERROR`였다가 각자 코드(`ADMISSION_REFUSED` 503 등) | 코드로 분기하던 클라이언트가 새 코드를 모른다 | 클라이언트 분기표에 더한다. web-advanced 표는 `src/adapter/inbound/web-advanced/README.md` 「오류 응답」 | `1400dc15` · `src/adapter/inbound/web/.../error/WebTransportError.java`, `HttpStatusErrorCodes.java`, `src/adapter/inbound/web-advanced/.../error/WebAdvancedError.java` | +| B-33 | DB 실패 분류: 낙관적 잠금 충돌 500 → 409 `DB_OPTIMISTIC_CONFLICT`. 커밋 단계 연결 끊김(08xxx, 40003 등)을 재시도 가능으로 답하던 것 → 500 `DB_COMPLETION_UNKNOWN`(retryable=false) | 응답 status·code가 바뀐다 | 409는 다시 읽고 재시도, `DB_COMPLETION_UNKNOWN`은 업무 데이터로 결과를 확인 | `34565130`, `1400dc15` · `src/adapter/outbound/persistence-jpa/.../failure/PersistenceExceptionTranslator.java` | + +### 3.4 빌드 게이트·아키텍처 규칙 — `ci`가 빨개진다 + +| # | 무엇이 바뀌었나 | 파생 서비스 증상 | 할 일 | 근거 | +|---|---|---|---|---| +| B-34 | 템플릿 패키지 규칙(ArchUnit): `FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`, `TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`. 템플릿 이름: application `usecase command query capability transaction security tenant observability secret messaging outbox idempotency operation lease lock cache realtime notification fileserver objectstorage`, domain `identifier stereotype` | 기능 패키지 이름이 이 목록과 겹치거나(예: `domain.lock`), 업무 코드를 템플릿 패키지(예: `application.usecase.*`)에 두고 기능 패키지를 import하면 `:app-bootstrap:architectureTest` 실패 | 기능 패키지 이름을 바꾸고, 업무 코드를 `dev.caskeleton.application.`로 옮긴다. 규칙 정본은 `src/application-core/CLAUDE.md` "Package ownership" | `5786126c` · `src/app-bootstrap/src/architectureTest/.../TemplatePackageOwnership.java` | +| B-35 | JPA 규칙: 양방향 연관은 한쪽에서만 매핑(`mappedBy`), notification·fileserver 저장소 엔티티는 그 leaf 안에서만, `@Version` 엔티티의 bulk update는 version을 올려야 함 | 위반 엔티티·쿼리가 있으면 architectureTest 실패 | 매핑·쿼리를 고친다 | `34565130`, `1400dc15`, `bbe944bd` · `src/app-bootstrap/src/architectureTest/.../JpaProductionArchitectureTest.java` | +| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c` · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` | +| B-37 | app-bootstrap 테스트 lane 분리: 저장소 파일을 읽는 테스트는 태그 `document-contract`(main 단계) 또는 `repository-contract`(`check`)여야 하고, 일반 `test` lane에는 `ca.repository.root`가 없다 | app-bootstrap에 둔 자기 테스트가 저장소 파일을 읽으면 `test`에서 실패 | 태그를 단다 | `1400dc15` · `src/app-bootstrap/build.gradle` | + +### 3.5 모듈 registry·새 leaf + +| # | 무엇이 바뀌었나 | 파생 서비스 증상 | 할 일 | 근거 | +|---|---|---|---|---| +| B-38 | 새 leaf: `adapter-inbound-messaging`(`:adapter:inbound:messaging`, 이벤트 소비+inbox, 기본 조립에 없음), `composition-durable-operation`(`:composition:durable-operation`, `/operations`). 새 간선: `application-objectstorage`·`adapter-outbound-persistence-mongo`·`adapter-outbound-identifier`·`adapter-outbound-redis-sdk` → `shared-contract`, `adapter-inbound-web` → `adapter-outbound-support`, `sample-portfolio` → `adapter-outbound-support`, `app-bootstrap` → 두 새 leaf. 지운 간선: `composition-fileserver-platform` → `adapter-outbound-identifier`. `app-bootstrap/build.gradle`에 `runtimeOnly project(':composition:durable-operation')` 추가 | 자기 leaf를 더한 서비스는 `modules.json`·`app-bootstrap/build.gradle`에서 merge 충돌. 충돌을 풀다 durable-operation 줄을 빠뜨리면 `/operations` 조립이 없다(`DurableOperationConfig`가 app-bootstrap에서 빠졌기 때문) | 두 파일을 손으로 합친다. 합친 뒤 `architectureCheck`로 간선을 확인 | `1400dc15`, `5786126c` · `src/config/architecture/modules.json`, `src/app-bootstrap/build.gradle` | + +## 4. DB 마이그레이션 + +### 4.1 새 버전과 영향 + +| stream (history 표) | 버전 | 하는 일 | 기존 데이터 영향 | 실패 조건 | 근거 | +|---|---|---|---|---|---| +| postgresql (`flyway_schema_history`, persistence-jpa 선택 시) | V20 | `outbox_event.deferred_attempt_count INTEGER NOT NULL DEFAULT 0` + CHECK ≥ 0 | 기존 행 0. 지난 claim은 전부 시도 예산에 센다 | 확인된 것 없음 | `1400dc15` | +| 〃 | V21 | `outbox_aggregate_sequence`(aggregate별 counter), `outbox_aggregate_sequence_floor`(V21 적용 시각 마이크로초 한 행), 남은 행 최대 번호로 counter 미리 생성, 유일 인덱스 `ux_outbox_event_aggregate_order (tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index)` | 새로 생기는 aggregate의 첫 번호가 floor+1(약 1.7×10¹⁵)부터. 순서 열이 NULL인 옛 행은 비교 안 함 | ① 같은 순서 키 행이 이미 둘 이상 → 실패, V21 전체 롤백, V20에 남음(exit 70). ② `SET LOCAL lock_timeout = '5s'` 안에 `outbox_event` 잠금을 못 잡으면 실패·롤백. ③ 같은 이름 인덱스가 유효한 유일 인덱스가 아니면(실패한 CONCURRENTLY) `RAISE EXCEPTION` | `1400dc15`, `bbe944bd` · `docs/runbooks/outbox-dead-letter.md` §8 | +| 〃 | V22 | `outbox_event.last_failure_code VARCHAR(120)` NULL, 기본값 없음. 새 상태 `PARKED`는 DDL 없음 | 행 재작성 없음. 기존 행은 다음 실패 때까지 NULL | 확인된 것 없음 | `bbe944bd` | +| notification (`flyway_jpa_notification_history`, notification-platform 선택 시) | V11 | `notification_reconciliation_job.claimed_until timestamptz`, `claim_fence bigint NOT NULL DEFAULT 0` + CHECK | 기존 job은 fence 0, lease 없음 | 확인된 것 없음 | `34565130` | +| 〃 | V12 | `notification_suppression`의 `(tenant_id, normalized_target_hmac, reason)` 중복 행을 **삭제**(만료 없는 것 > 늦은 만료 > 이른 `effective_at` > 이른 `created_at` > 작은 id 순으로 하나 남김) 후 UNIQUE `uk_notification_suppression_target` | 지운 행의 `SuppressionId`는 더 이상 조회되지 않는다. 되돌리려면 백업 필요 | 확인된 것 없음(잠금 대기 제한 없음) | `1400dc15` | +| 〃 | V13 | `notification_request.acceptance varchar(40) NOT NULL DEFAULT 'ACCEPTED'` + CHECK(`ACCEPTED`, `DROPPED_AS_DUPLICATE`) | 기존 요청은 모두 `ACCEPTED` | 확인된 것 없음 | `5786126c` | +| sample (`flyway_sample_schema_history`, sample-portfolio를 남긴 경우) | V8_1 | 유일 인덱스 `uq_poster_title_ci ON poster (upper(title))` | 없음 | 대소문자만 다른 제목이 있으면 `poster has titles that differ only by case or repeat: ...`로 실패 | `34565130` | +| grpc-ledger (optional-platforms, history 표 확인 못 함) | V002 | 부분 인덱스 `ix_grpc_operation_ledger_finished_completed_at` (일반 `CREATE INDEX`) | 없음 | 큰 ledger면 만드는 동안 쓰기가 멈춘다. 파일 주석은 손으로 `CONCURRENTLY`를 먼저 돌리라고 한다 | `1400dc15` | +| 〃 | V003 | `grpc_operation_ledger.claim_attempt BIGINT NOT NULL DEFAULT 1` + CHECK > 0 | 기존 행은 첫 시도(1) | 확인된 것 없음 | `bbe944bd` | + +- **새로 연결된 stream**: `adapter:inbound:messaging`을 `runtimeOnly`로 넣으면 platform의 `V1101__messaging_inbox.sql`을 + `MessagingInboxSchemaStream`이 `flyway_messaging_inbox_history`에 적용한다(baseline 1100). 넣지 않으면 영향 없음 + (`src/adapter/inbound/messaging/README.md`). +- **번호 충돌**: 템플릿이 이제 postgresql V20~V22, notification V11~V13, sample V8_1, grpc V002·V003을 쓴다. 파생 서비스가 같은 + 위치에 같은 번호를 두었다면 Flyway가 같은 버전 두 개로 실패한다. 자기 마이그레이션은 템플릿과 떨어진 번호대로 옮긴다 + (이미 적용된 파일 이름을 바꾸면 checksum·history가 어긋나므로 운영 DB에 적용된 것이면 DB 담당과 정한다). +- **migration-on-startup=false로 운영하는 서비스**: `infra/postgres/apply-capability-streams.sh`가 바뀌었다(stream을 + `/flyway/streams/`에서 먼저 찾음). 운영자가 직접 적용한다. + +### 4.2 이 브랜치의 이전 V21을 적용한 DB + +V21은 `bbe944bd`에서 V22를 따로 두지 않고 직접 고쳤다(floor 표와 counter 미리 만들기를 넣음). `1400dc15`·`5786126c` 시점의 +V21(sha256 `f830cda5…`)을 적용한 DB는 새 V21(sha256 `21744ea1…`, `src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256`)과 +checksum이 달라 Flyway 검증에서 기동이 실패한다(exit 70 `MIGRATION_FAILED`). + +- 해당 여부 확인: V21이 history에 있는데 floor 표가 없으면 이전 V21이다. + + ```sql + SELECT version, success FROM flyway_schema_history WHERE version = '21'; + SELECT to_regclass('outbox_aggregate_sequence_floor'); -- NULL이면 이전 V21 + ``` + +- 할 일: 그 개발 DB를 다시 만든다(예: Compose PostgreSQL 볼륨 삭제 후 재기동). `flyway repair`로 checksum만 맞추지 않는다. + 이전 V21에는 floor 표와 counter 미리 만들기가 없어서 스키마가 새 코드와 맞지 않는다. +- 운영 DB: 이 브랜치는 main에 합쳐지기 전이라 어느 배포에도 V21이 없다는 것이 커밋 메시지의 전제다(`bbe944bd`). 파생 서비스가 + 이 브랜치를 운영에 미리 배포했다면 이 전제가 깨진다. 그 경우는 DB 담당과 정한다. + +### 4.3 V21 배포 전 절차 + +`docs/runbooks/outbox-dead-letter.md` §8을 따른다. 요약: + +1. **Step 1 — 중복 확인(읽기 전용)**: §8의 `v21-duplicate-order-keys` 쿼리. 0행이면 배포한다. +2. **Step 2**: 미발행 행이 있는 키는 relay가 비울 때까지 기다린다. `DEAD` 행은 §4 처분을 먼저 한다. +3. **Step 3**: 모두 `PUBLISHED`인 키의 중복을 `outbox_event_v21_duplicates`로 복사한 뒤 지운다(`v21-remove-published-duplicates`). +4. **Step 0 — outbox가 커서 V21이 거는 SHARE 잠금을 견딜 수 없으면**: 중복을 없앤 뒤 같은 이름 인덱스를 transaction 밖에서 + `CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS ux_outbox_event_aggregate_order ...`로 먼저 만든다. V21의 `IF NOT EXISTS`가 그것을 쓴다. + CONCURRENTLY가 실패해 INVALID 인덱스가 남으면 `DROP INDEX CONCURRENTLY` 후 Step 1부터. +5. tenant scope를 바꾼 서비스는 옛 scope의 미발행 행이 없는지 §8의 `GROUP BY tenant_scope` 쿼리로 본다. + +이 절의 SQL 블록은 `:adapter:outbound:persistence-jpa:postgresqlOutboxOrderKeyRunbookIntegrationTest` lane이 실제 PostgreSQL에서 돌린다. +V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failure"에 추가됐다. + +### 4.4 되돌리기 + +- **down 마이그레이션 없음.** 이 repo에 `U*__*.sql`(Flyway undo) 파일이 없다. `migration-failed.md`는 앞으로 고치는 마이그레이션을 + 먼저 쓰고, 적용된 파일 수정·history 고쳐 쓰기·`clean`을 금지한다. +- **배포 전 백업**: 마이그레이션을 돌리기 전에 DB 백업(또는 PITR 지점)을 남긴다. 특히 notification V12는 행을 지운다. + 스키마를 되돌려야 하면 백업 복원이 유일한 길이고, `migration-failed.md` Escalation에 따라 DB 담당이 결정한다. +- **V21 실패 시**: V21은 transaction 하나라 실패하면 V20에 그대로 남는다. 원인(중복·잠금)을 없애고 다시 배포한다. +- **앱만 옛 버전으로 되돌릴 때**: 이번 범위의 마이그레이션은 열·표·인덱스·제약을 더하기만 하고(V12의 중복 행 삭제 제외) 열을 지우거나 + 이름을 바꾸지 않는다. 새 열은 기본값이 있거나 NULL을 허용해서 옛 코드의 insert가 막히지 않는다. 다만 V21 유일 인덱스와 V12·V8_1 + 유일 제약은 옛 코드가 같은 키를 두 번 쓰면 이제 DB가 거부한다. 옛 앱의 Flyway가 자기가 모르는 최신 버전(V20~V22 등)이 적용된 + DB에서 기동하는지는 **확인 못 함**(이 repo는 해당 Flyway 옵션을 설정하지 않음). 스테이징에서 먼저 확인한다. + +## 5. 동작 변경 — 코드는 안 깨지지만 결과가 달라진다 + +| 영역 | 바뀐 것 | 영향 | 근거 | +|---|---|---|---| +| outbox relay | 일시 거부(`REJECTED_RETRYABLE`)·무응답(`AMBIGUOUS`)은 시도 예산을 쓰지 않고 최대 5분 간격(`OutboxBackoffPolicy.MAX_DELAY`)으로 끝없이 재시도. 실패 원인 코드를 `last_failure_code`에 남김. 수동 보류 상태 `PARKED`. 지표 `outbox.retry.long.size`·`outbox.retry.long.age` | 진짜 인증 오류도 DEAD가 아니라 계속 재시도한다. 경보는 새 지표로 잡는다. 처분 SQL은 `docs/runbooks/outbox-dead-letter.md`·`outbox-publish-failed.md` | `34565130`, `1400dc15`, `bbe944bd` | +| outbox append | 읽기 전용 트랜잭션 안의 `append`도 거부(`CallerTransaction.requireReadWrite`). 전에는 트랜잭션 밖만 거부했고 읽기 전용에서는 이벤트가 조용히 사라졌다 | `inRead` 안에서 이벤트를 쓰던 코드가 이제 예외로 드러난다 | `5786126c` · `JpaOutboxStore.java` | +| 순서 번호 | aggregate 순서 번호를 DB counter가 매긴다(`OutboxAggregateSequencePort.nextSequence`). 한 aggregate에 이벤트가 하나면 `AggregateOrder.first()`. 같은 순서 키 두 번째 append는 유일 인덱스가 거부(정확한 오류 코드 확인 못 함) | 소비자가 보는 번호가 새 aggregate에서 floor+1부터 시작해 크게 뛴다. 벽시계로 번호를 만들던 코드는 바꾼다 | `1400dc15`, `bbe944bd` | +| durable operation | operation id가 UUIDv7(`UuidV7DurableOperationIdFactory`). 제출 이벤트의 event id·aggregate id가 UUIDv7이고 tenant scope는 `global` | 전에는 이 이벤트가 messaging bridge에서 전부 DEAD가 됐다(커밋 `1400dc15` 본문). 소비자가 보는 id 모양이 바뀐다 | `1400dc15`, `bbe944bd` · `SubmitDurableOperationUseCase.java` | +| tracing | 자체 tracer를 지우고 Boot tracing·OTLP로. `OTEL_EXPORTER_OTLP_ENDPOINT`는 base 주소로 보고 `<값>/v1/traces`(OTLP/HTTP)로 보낸다. 빈 값이면 exporter 없음. `meta.traceId`가 tracer의 trace id와 같다 | span이 실제로 나가기 시작한다. gRPC 포트(4317)를 넣었다면 HTTP 수신 주소로 바꾼다 | `34565130`, `1400dc15` · `docs/registries/env-keys.yaml` | +| correlation id | `X-Correlation-Id`가 `[A-Za-z0-9._-]{1,128}`(앞뒤 공백 제거 후) 밖이면 서버가 새 값으로 바꾼다 | 규칙 밖 값을 쓰던 호출자는 로그에서 자기 값을 못 찾는다 | `1400dc15` · `docs/web/http-contract.md` §3 | +| String 응답 | `String`을 반환하는 컨트롤러에 JSON을 요청하면 Envelope(`"data": "<문자열>"`)로 나간다. 전에는 500이었다. `byte[]`는 감싸지 않는다(`/v3/api-docs`) | JSON 클라이언트가 이제 200을 받는다 | `1400dc15` · `EnvelopeBodyAdvice.java` | +| GraphQL | 크기를 선언하지 않은 list를 원소 20개로 계산, `first`·`last` 둘 다면 큰 쪽. per-parent 경고 임계 10(`APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD`). deadline instrumentation이 `REQUEST_TIMEOUT` | 전에 통과하던 깊은 목록 쿼리가 복잡도로 거부될 수 있다. 필요한 필드에 `estimatedListSize`를 선언 | `34565130`, `1400dc15`, `bbe944bd` | +| WebSocket | 노드당 STOMP 세션 1000개(`APP_WEBSOCKET_MAX_CONNECTIONS`), 초과 시 연결 후 1013으로 닫음. 메시지 64KB, 송신 버퍼 512KB, 송신 시간 10s, 첫 메시지 60s를 명시 | 동시 연결이 많은 서비스는 상한을 올린다 | `1400dc15` · `env-keys.yaml` | +| gRPC 서버(inbound adapter) | 수신 메시지 1 MiB(io.grpc 기본 4 MiB에서 줄어듦), 메타데이터 8 KiB, 연결당 동시 호출 100, 실행 스레드 32·대기열 256, 기본 deadline 10s, keepalive 30s/10s, 최대 연결 수명 30분, drain 2s | 1 MiB를 넘는 메시지는 거부된다 | `1400dc15` · `src/adapter/inbound/grpc/.../GrpcServerSettings.java` | +| 파일 서버 | 정리 worker 기본 켜짐(`APP_FILESERVER_PLATFORM_CLEANUP_ENABLED` false→true, 끄면 기동 경고). copy·move 대상은 기본 namespace만(`APP_FILESERVER_PLATFORM_TARGET_NAMESPACES`, 그 밖은 `ACCESS_DENIED`). namespace 쿼터 상한(`APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT`, 비우면 무제한, 넘으면 413 `QUOTA_EXCEEDED`). move가 쿼터를 옮긴다 | 다른 namespace로 copy·move하던 서비스는 허용 목록을 설정해야 한다. 정리 worker가 물리 객체를 지운다 | `5786126c`, `bbe944bd` · `CopyFileApplicationUseCase.java`, `env-keys.yaml` | +| 알림 | SES 콜백 replay 허용 차이 5m→1h. 중복 제거 창에서 버린 제출을 `CANCELED`·`DROPPED_AS_DUPLICATE`로 저장해 같은 멱등성 키에 같은 영수증. reconciliation job은 DB lease로 소유. INGEST_ONLY도 accept 때 route 이름 기록 | 콜백·영수증 결과가 바뀐다 | `34565130`, `5786126c` | +| Redis | 캐시 조건부 쓰기가 자기 SCRIPT lane(`APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS`, 기본 4)을 쓴다. registry에서 `redis.capability.*` 지표 6개를 빼고 `redis.lane.*` 6개를 더했다 | Redis 연결이 캐시 lane만큼 늘어난다. 옛 지표 이름으로 만든 대시보드·경보는 바꾼다 | `bbe944bd` · `docs/registries/metrics.yaml` | +| 설정 바인딩 | strict 설정에서 선택 숫자·크기·기간 키의 빈 값은 "미설정". 목록 원소 아래 오타 키도 거부(`StrictSettingsBinder`) | `.env.example`의 빈 값으로 기동 가능. 목록 원소 아래 오타는 이제 기동 실패 | `5786126c` · `StrictSettingsBinder.java` | +| 권한 매핑 | `app.authz.role-permissions` 기본 항목이 app-bootstrap `config/security.yml`에서 각 capability의 module-defaults(notification·fileserver·durable-operation)로 옮겨짐. 여러 출처의 항목이 합쳐진다 | 모듈을 빼면 그 권한 매핑도 빠진다 | `1400dc15` · `src/app-bootstrap/src/main/resources/config/security.yml` | +| 로그 설정 | logback이 `APP_LOG_*` 대신 `app.logging.*`을 읽는다(환경 변수 이름은 그대로 매핑) | 프로필 yml의 `app.logging.*`이 이제 먹힌다 | `1400dc15` · `logback-spring.xml` | +| local 프로필 | `server.port`가 `${APP_SERVER_PORT:8080}`을 읽는다. Flyway·`ddl-auto validate`·PostgreSQL vendor를 module-defaults에서 받는다 | local에서 `APP_SERVER_PORT`가 다른 값이면 포트가 바뀐다 | `1400dc15`, `5786126c` · `application-local.yml` | +| deprecated | `APP_CACHE_REDIS_TTL_JITTER`는 아무것도 바인딩하지 않음(`removal_deadline: 2027-02-28`) | 값이 아무 효과 없다 | `1400dc15` · `env-keys.yaml` | +| sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` | + +## 6. 따라오는 순서 + +모든 명령은 `src/`에서 `--console=plain`으로 돌린다. 한 단계가 빨개지면 다음으로 가지 않는다. + +| 단계 | 할 일 | 게이트 | +|---|---|---| +| 0. 준비 | 운영·스테이징 DB 백업. 작업 브랜치를 따로 만든다. 자기 마이그레이션 번호가 4.1절 번호와 겹치는지 본다. 운영 DB 사본에 4.3절 Step 1 쿼리(필요하면 V8_1 중복 제목 확인)를 돌려 둔다 | — | +| 1. merge·의존성 | `git fetch upstream` 후 merge. 충돌 예상 파일: `config/architecture/modules.json`, `app-bootstrap/build.gradle`, `docs/registries/env-keys.yaml`, `.env.example`, `application*.yml`, API surface 스냅샷, `gradle.lockfile`. 자기 의존성을 바꿨으면 `./gradlew ::resolveAndLockAll --write-locks` | `./gradlew verifyDependencyLocks` | +| 2. 컴파일·아키텍처 | 3.1절(B-01~B-11) 고치기. 3.4절 규칙 위반 고치기 | `./gradlew architectureCheck`, `./gradlew :app-bootstrap:architectureTest`, 고친 leaf마다 `./gradlew :check` | +| 3. PR 게이트 전체 | 자기 strict lane을 단계에 건다. SpotBugs MEDIUM 발견 처리 | `./gradlew ci`, `./gradlew verifyStrictLaneStages --dry-run` | +| 4. 설정 | 2절 체크리스트 1~4·10·13. 3.2절(B-12~B-27) 확인 | `./gradlew :app-bootstrap:verifyEnvKeys`, `./gradlew configContractCheck` | +| 5. DB | 이전 V21을 적용한 개발 DB 재생성(4.2절). 스테이징에 4.3절 절차 후 마이그레이션 | `./gradlew :adapter:outbound:persistence-jpa:integrationTestLaneCheck`(Docker 필요), 알림을 쓰면 `./gradlew integrationCheck` | +| 6. 기동 | prod와 같은 프로필·환경으로 스테이징 기동. exit 코드 70·71·72·78이면 3.2절·4절 해당 줄로 | `./gradlew :app-bootstrap:systemTest`, `./gradlew mainCheck` | +| 7. 계약 | HTTP 응답 모양·코드(3.3절)를 클라이언트와 맞춘다. 공개 경로가 바뀌었는지 확인 | `./gradlew verifyPublicPathSnapshot`, `./gradlew mainCheck`(문서 계약 lane 포함), 짝 프론트 계약 테스트 | + +## 7. 짝 프론트 + +프론트가 맞출 계약의 정본은 `docs/web/http-contract.md`다. 요약: + +**Envelope** + +| 응답 | 있는 키 | 없는 키 | +|---|---|---| +| 성공 | `success`(true), `data`, `meta` | `error` | +| 실패 | `success`(false), `error`, `meta` | `data` | +| bulk 전체 성공 | `success`(true), `results`, `meta` | `error` | +| bulk 부분 실패 | `success`(false), `error`(`BATCH_PARTIAL_FAILURE`, `details`), `meta` | `results` | + +- `success`로 가른다. 키 존재로 판단하지 않는다. `null`이면 키가 없고, 빈 목록은 `[]`로 온다. +- `error`는 `code`·`category`·`message`·`retryable`이 항상 있고 `details`는 있을 때만. +- `meta`의 모르는 키는 무시한다. 요청 id 필터 전에 끊긴 응답은 id 키가 빠질 수 있다. + +**멱등성** (같은 `Idempotency-Key` 재전송에 대한 서버 판정) + +| 경우 | status | `error.code` | `retryable` | `Retry-After` | 클라이언트 행동 | +|---|---|---|---|---|---| +| 재생 | 첫 요청의 성공 status | — | — | — | 첫 결과로 받는다 | +| 처리 중 | 409 | `IDEMPOTENT_IN_FLIGHT` | true | 2 | 같은 키로 `Retry-After` 뒤 재전송. 새 키 금지 | +| 본문 불일치 | 422 | `IDEMPOTENT_REQUEST_MISMATCH` | false | — | 다시 보내지 않는다 | +| 키 누락·형식 오류 | 400 | `IDEMPOTENCY_KEY_INVALID`(`details.reason`) | false | — | 보이는 ASCII 1~256자 키로 다시 | +| 실행 전 저장소 응답 없음 | 503 | `IDEMPOTENCY_UNAVAILABLE` | true | — | 실행 안 됨. 같은 키로 나중에 | +| 실행 뒤 기록 실패(결과 불명) | 503 | `IDEMPOTENCY_COMPLETION_UNKNOWN` | true | — | 같은 키로 나중에. 새 키 금지 | +| 이전 효과 증명 불가 | 500 | `IDEMPOTENCY_RECOVERY_REQUIRED` | false | — | 업무 데이터로 확인 | + +- CORS가 켜져 있으면 `Retry-After`·`X-Request-Id`·`X-Correlation-Id`·`traceparent` 등이 `Access-Control-Expose-Headers`에 있다(§3). +- 새 코드: `REQUEST_TIMEOUT`(503, retryable), web-advanced를 쓰는 서비스는 10종(3.3절 B-32). +- 프론트 계약 문서(`clean-architecture-frontend-template` `docs/architecture/backend-api-and-server-state-contract.md` §4.1·§6)는 + `docs/web/http-contract.md`를 가리켜야 한다. +- 프론트 세션에 넘긴 인계 문서(세션 scratchpad라 지워질 수 있음): + `/tmp/claude-1000/-home-donghyeon-workspace-desktop-server-git-clean-architecture-frontend-template/4cfb2000-88f4-4501-87c2-64e07e1575a5/scratchpad/backend-contract-handoff.md` + +## 8. 소유자 확인이 남은 결정 + +재리뷰 README 8절은 아래를 "소유자 확인이 필요한 결정"으로 남겼다. main에 합쳐지기 전에 바뀔 수 있다. + +- 서블릿 오류 디스패치 허용(B-31), 데모 계정 허용 목록(B-27), V21을 V22 없이 직접 수정(4.2절), 발행·저장소 포트 시그니처 변경 + (B-01·B-02), `IDEMPOTENCY_COMPLETION_UNKNOWN` 신설(B-30), prod `fixture-` 값 거부(B-14). + +## 9. 확인 못 한 것 + +- 실제 파생 서비스(예: `tech-log-backend`) 코드에 이 안내를 적용해 보지 않았다. 각 줄이 그 서비스에 해당하는지는 서비스 쪽에서 확인한다. +- `APP_SECURITY_JWT_AUDIENCE` 누락·`app.security` 오타의 정확한 exit 코드와 메시지 전문(바인딩 예외로 감싸지는 경로). +- H2를 `bootRunH2` 밖에서 쓸 때의 정확한 오류(B-23). +- 같은 순서 키를 두 번 append할 때 나가는 오류 코드(5절 "순서 번호"). +- 옛 버전 앱이 V20~V22가 적용된 DB에서 기동하는지(4.4절). +- gRPC ledger stream의 history 표 이름과 누가 적용하는지. +- 실제 CI runner에서의 workflow 실행(재리뷰 README 8절과 같음). From 1885bf8da7b142eac56cdbd30b376be350a17528 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 01:47:50 +0900 Subject: [PATCH 07/17] =?UTF-8?q?fix!:=202=EC=B0=A8=20=EC=9E=AC=EB=A6=AC?= =?UTF-8?q?=EB=B7=B0=EA=B0=80=20=EC=B0=BE=EC=9D=80=20=EA=B2=B0=ED=95=A8=20?= =?UTF-8?q?29=EA=B1=B4=EC=9D=84=20=EA=B3=A0=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 재리뷰 수정 커밋(bbe944bd)만 다시 본 2차 재리뷰가 Important 7건, Minor 22건을 찾았다. 결과 불명 503 뒤 같은 키를 다시 보내면 Redis store가 lease 지난 실행을 넘겨받아 작업을 다시 돌렸다. replay TTL이 lease보다 짧으면 lease 도중 key가 사라져 같은 키가 두 번 실행됐다. @SystemInvoked 규칙이 매뉴얼 09장의 이벤트 소비 경로까지 막았다. V22가 outbox_event에 가장 강한 잠금을 lock_timeout 없이 걸었다. prod의 fixture- 거부가 HOSTNAME 같은 비밀 아닌 값까지 막았다. 데모 허용 목록의 test·demo 프로필로 sample이 뜨지 않았다. 기동 rule bean의 @Value 필드가 조용히 null이 됐다. 방법: 영역별 4묶음이 test-driven-development 절차로 실패 테스트를 먼저 쓰고 고쳤다. 결정은 재리뷰 README 9.1절이다. - 두 멱등성 store가 같은 계약을 따른다. lease가 지난 실행 기록은 다시 돌리지 않고 포기로 표시해 500 RECOVERY_REQUIRED로 답한다. 기록 수명은 lease + replay TTL이고, replay-ttl < processing-lease면 기동이 실패한다. - 사용자 transport만 @SystemInvoked use case에 닿지 못한다. 메시지 handler·scheduler는 새 표시 @SystemCaller(reason)를 달고 use case를 생성자에서 new로 만든다. 매뉴얼 경로를 테스트로 고정했다. - 아직 어디에도 적용되지 않은 마이그레이션(V20·V22·알림 V11~V13·sample V8_1·grpc V002·V003)에 lock_timeout 5s를 넣고, 텍스트 검사기와 실 PG lane을 더했다. 이미 배포된 24개는 동결 목록으로 둔다. - fixture- 검사는 비밀로 분류된 값만 본다. sample은 local·test·demo에서 object storage를 끈다. 기동 rule bean에 주입 멤버가 있으면 모든 프로필에서 기동이 실패한다. 리뷰어가 제안한 "static @Bean 선언 강제"는 문제없는 등록을 막고 @Value 필드는 통과시켜서 버렸다. - 이 수정 전에 move된 파일의 쿼터 차이를 찾는 쿼리와 재계산 SQL을 docs/fileserver/operations.md에 적었다. 위험·한계: lease 뒤 늦게 끝난 첫 시도의 결과는 기록되지 않는다(그 요청도 500). @SystemCaller가 없는 메시지 handler, 주입 멤버가 있는 기동 rule, working-directory 없이 ./gradlew를 부르는 workflow 명령은 파생 서비스에서 새로 실패하거나 세지지 않는다(업그레이드 안내 B-14~16·B-36·B-39). spotbugsTestFixtures는 게이트 밖이고 기준 커밋에서도 실패하며, 새 검사기의 정규식 경고 8건이 더해졌다. 실제 CI runner 실행은 확인하지 못했다(Gitea repo의 Actions가 꺼져 있다). 검증: ci, 두 빌드의 verifyStrictLaneStages --dry-run, mainCheck, :integrationCheck, -p optional-platforms ci integrationCheck performanceCheck, :performanceCheck, :releaseCheck(-PgitRevision), verify-compose-profile-contracts(18 lane) 첫 실행 통과. 쿼터 재계산 SQL은 실 PostgreSQL 16에서 차이 2행 → 0행을 확인했다. Refs: docs/reviews/2026-11-03-rereview/README.md 9·9.1·10절 BREAKING CHANGE: replay-ttl < processing-lease 설정은 기동 실패, ledger release가 claim token을 받는다, HttpBodyReadException(IOException 하위)이 본문 실패를 싣는다, 기동 rule·비밀 목록 bean의 주입 멤버 금지, verifyStrictLaneStages가 workflow 명령의 working-directory로 빌드를 정한다. --- .../object-storage-qualification.yml | 3 +- AGENTS.md | 5 +- CLAUDE.md | 6 +- ...retry-ownership-and-durable-idempotency.md | 11 + docs/capability-status.md | 2 +- docs/fileserver/operations.md | 69 +++++ docs/httpclient/configuration-reference.md | 18 +- docs/httpclient/operations.md | 5 + docs/jpa/entity-mapping-guide.md | 11 +- docs/jpa/migration-guide.md | 28 ++ docs/manual/04-persistence.md | 6 + docs/manual/05-idempotency.md | 5 + docs/manual/07-authorization.md | 35 ++- docs/manual/09-outbox-events.md | 47 ++- docs/messaging/outbox-inbox.md | 4 +- docs/registries/env-keys.yaml | 10 +- docs/registries/metrics.yaml | 10 +- docs/registries/secrets-classification.yaml | 8 +- docs/reviews/2026-11-03-rereview/README.md | 41 +++ docs/runbooks/migration-failed.md | 10 +- docs/runbooks/outbox-dead-letter.md | 27 +- docs/runbooks/outbox-publish-failed.md | 11 +- docs/runbooks/redis-capability-incident.md | 18 +- docs/upgrade/2026-11-maturity-review.md | 56 ++-- docs/web/http-contract.md | 31 +- infra/redis-sdk/acl/README.md | 9 +- src/.env.example | 4 +- src/Dockerfile.sample | 10 +- src/README.md | 3 +- .../graphql/policy/GraphQlClientPolicy.java | 19 +- .../GraphQlConnectionAssemblerTest.java | 12 + .../policy/GraphQlClientPolicyTest.java | 9 - src/adapter/inbound/messaging/CLAUDE.md | 3 + src/adapter/inbound/messaging/README.md | 25 +- src/adapter/inbound/messaging/build.gradle | 7 +- src/adapter/inbound/messaging/gradle.lockfile | 46 ++- .../InboxRedeliveryIntegrationTest.java | 44 ++- .../SystemInvokedConsumePathTest.java | 286 +++++++++++++++++ .../web/error/EnvelopeErrorController.java | 8 + .../error/EnvelopeErrorControllerTest.java | 58 ++++ src/adapter/outbound/cache-redis/README.md | 19 +- .../redis/idempotency/IdempotencyScripts.java | 61 +++- .../RedisIdempotencyStoreAdapter.java | 1 + .../RedisIdempotencyStoreAdapterTest.java | 25 +- .../RedisServerTimeScriptContractTest.java | 5 +- src/adapter/outbound/httpclient/README.md | 7 +- .../api/error/HttpBodyReadException.java | 42 +++ .../api/result/BlockingStreamingResponse.java | 10 + .../jdk/JdkStreamingClientHttpRequest.java | 21 +- .../httpclient/jdk/ReadIdleInputStream.java | 99 +++++- .../resilience/AttemptResiliencePipeline.java | 12 +- .../restclient/ClassifiedBodyInputStream.java | 13 +- .../JdkStreamingRestrictedHeadersTest.java | 69 +++++ .../jdk/ReadIdleInputStreamTest.java | 152 ++++++++++ .../restclient/StreamingBodyLifetimeTest.java | 12 +- .../provider/ses/SesEventNormalizer.java | 5 +- src/adapter/outbound/objectstorage/README.md | 6 +- ...itional-spring-configuration-metadata.json | 10 + .../outbound/persistence-jpa/CLAUDE.md | 5 +- .../outbound/persistence-jpa/README.md | 27 +- .../outbound/persistence-jpa/build.gradle | 1 + .../postgresql/IdempotencyClaimGateway.java | 21 +- .../IdempotencyTransitionGateway.java | 12 + .../outbox/jpa/JpaOutboxStore.java | 63 +++- .../outbox/jpa/entity/OutboxEventEntity.java | 22 +- ...0__outbox_event_deferred_attempt_count.sql | 14 + .../V22__outbox_event_last_failure_code.sql | 14 + ...ostgreSqlIdempotencyStoreContractTest.java | 49 ++- ...reSqlMigrationLockWaitIntegrationTest.java | 205 +++++++++++++ ...tboxDispositionRunbookIntegrationTest.java | 29 ++ .../AppliedMigrationImmutabilityTest.java | 45 +-- .../migration/MigrationLockWaitTest.java | 105 +++++++ .../persistence/migration/MigrationTrees.java | 70 +++++ .../outbox/jpa/JpaOutboxStoreTest.java | 75 +++++ .../arch/JpaArchitectureRulesTest.java | 25 ++ .../entity/MutualForeignKeyInvoiceEntity.java | 30 ++ .../entity/MutualForeignKeyOrderEntity.java | 37 +++ .../LockWaitMigrationInspectorTest.java | 89 ++++++ .../resources/db/applied-migrations.sha256 | 10 +- .../arch/SingleSidedAssociationCondition.java | 26 +- .../migration/LockWaitMigrationInspector.java | 164 ++++++++++ .../persistence-notification/CLAUDE.md | 5 +- ...otification_reconciliation_claim_lease.sql | 13 + ...notification_suppression_target_unique.sql | 13 + .../V13__notification_request_acceptance.sql | 13 + .../runtime/connection/RedisRuntimeOwner.java | 16 +- .../runtime/config/RedisLaneMetricsTest.java | 38 +++ .../InMemorySemanticRedisCommands.java | 10 +- .../outbound/support/startup/StartupRule.java | 6 +- .../support/startup/StartupRuleRunner.java | 111 ++++++- .../startup/StartupRuleRunnerTest.java | 138 +++++++++ src/app-bootstrap/CLAUDE.md | 5 +- src/app-bootstrap/README.md | 9 +- .../ApplicationBoundaryArchitectureTest.java | 101 +++++- .../ArchRuleDiscoveryContractTest.java | 3 +- .../ArchitectureViolationFixtureTest.java | 75 ++++- .../messaging/SystemCallerHandlerFixture.java | 18 ++ .../inbound/messaging/package-info.java | 9 + .../SystemCallerRestControllerFixture.java | 23 ++ .../UnmarkedSystemInvokedHandlerFixture.java | 17 ++ .../SystemCallerControllerFixture.java | 19 ++ ...SystemInvokedCallingControllerFixture.java | 6 +- .../SystemInvokedFixtureUseCase.java | 7 +- .../runtime/SecretSourceValidator.java | 188 ++++++++---- .../SecretsClassificationRegistryTest.java | 25 ++ .../runtime/SecretSourceValidatorTest.java | 63 +++- src/application-core/CLAUDE.md | 22 +- src/application-core/README.md | 9 +- .../idempotency/IdempotencyClaimOutcome.java | 12 + ...IdempotencyCompletionUnknownException.java | 17 +- .../idempotency/IdempotencyExecutor.java | 3 + .../outbox/OutboxAggregateSequencePort.java | 12 +- .../application/outbox/OutboxStorePort.java | 7 +- .../application/security/SystemCaller.java | 34 +++ .../application/security/SystemInvoked.java | 27 +- .../testkit/IdempotencyStoreContract.java | 145 ++++++++- .../testkit/DirectTransactionPort.java | 62 ++-- .../testkit/TransactionPortContract.java | 54 ++++ .../InMemoryQuotaLedgerContractTest.java | 6 + .../testkit/FakeFileQuotaService.java | 29 ++ .../testkit/FileQuotaLedgerContract.java | 41 ++- src/build-logic/README.md | 2 +- .../config/ConfigContractPlugin.java | 6 +- .../config/EnvContractVerifier.java | 90 +++++- .../buildlogic/config/VerifyEnvKeysTask.java | 3 +- .../SpringConfigConventionPlugin.java | 31 ++ .../strictlane/StrictLaneStagesExtension.java | 14 +- .../strictlane/StrictLaneStagesPlugin.java | 60 ++-- .../buildlogic/strictlane/TaskSelectors.java | 214 +++++++++++++ .../strictlane/WorkflowGradleInvocations.java | 287 ++++++++++++++---- .../config/EnvContractVerifierTest.java | 52 ++++ .../StrictLaneStagesFunctionalTest.java | 142 ++++++++- .../strictlane/TaskSelectorsTest.java | 71 +++++ .../WorkflowGradleInvocationsTest.java | 151 ++++++++- src/composition/idempotency/README.md | 10 +- .../idempotency/IdempotencySettings.java | 17 +- .../config/module-defaults/idempotency.yml | 3 + .../idempotency/IdempotencySettingsTest.java | 43 +++ src/composition/outbox-relay/README.md | 4 +- src/composition/outbox-relay/build.gradle | 18 ++ .../OutboxLongRetryRunbookContractTest.java | 61 ++++ src/composition/service-runtime/README.md | 4 +- .../PermissionEnforcementGuard.java | 20 +- .../PermissionEnforcementGuardTest.java | 40 ++- src/config/spotbugs/exclude.xml | 8 +- .../grpc/api/ledger/GrpcClaimToken.java | 7 +- .../grpc/api/ledger/GrpcOperationLedger.java | 18 +- .../ledger/GrpcOperationLedgerContract.java | 54 ++++ .../api/ledger/InMemoryOperationLedger.java | 8 +- ...rpcOperationLedgerMigrationLockWaitIT.java | 155 ++++++++++ .../ledger/GrpcOperationLedgerMigrations.java | 34 ++- .../JpaGrpcOperationLedgerContractIT.java | 5 +- .../ledger/GrpcOperationLedgerRepository.java | 21 +- .../grpc/ledger/JpaGrpcOperationLedger.java | 5 +- ...ex_grpc_operation_ledger_finished_rows.sql | 13 + ...dd_grpc_operation_ledger_claim_attempt.sql | 13 + .../GrpcOperationLedgerRepositoryTest.java | 30 +- .../KafkaDeadLetterQuarantineTest.java | 82 +++++ src/optional-platforms/build.gradle | 4 +- src/sample-portfolio/README.md | 4 +- .../SampleDemoAccountsProductionGuard.java | 8 +- .../src/main/resources/application.yml | 12 +- .../V8_1__poster_title_unique.sql | 12 + .../SampleDemoProfilesStartupSystemTest.java | 65 ++++ .../systemTest/resources/application-test.yml | 4 +- .../SampleMigrationLockWaitTest.java | 63 ++++ .../SampleDemoSecurityConfigTest.java | 5 +- .../shared/error/OperationalError.java | 2 +- 168 files changed, 5511 insertions(+), 602 deletions(-) create mode 100644 src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/SystemInvokedConsumePathTest.java create mode 100644 src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/api/error/HttpBodyReadException.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingRestrictedHeadersTest.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java create mode 100644 src/adapter/outbound/objectstorage/src/main/resources/META-INF/additional-spring-configuration-metadata.json create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/MutualForeignKeyInvoiceEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/MutualForeignKeyOrderEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/adapter/inbound/messaging/SystemCallerHandlerFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/adapter/inbound/messaging/package-info.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/messaging/SystemCallerRestControllerFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/messaging/UnmarkedSystemInvokedHandlerFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemCallerControllerFixture.java create mode 100644 src/application-core/src/main/java/dev/caskeleton/application/security/SystemCaller.java create mode 100644 src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/TaskSelectors.java create mode 100644 src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/TaskSelectorsTest.java create mode 100644 src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxLongRetryRunbookContractTest.java create mode 100644 src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java create mode 100644 src/messaging/messaging-spring-boot-starter-kafka/src/test/java/dev/caskeleton/messaging/autoconfigure/KafkaDeadLetterQuarantineTest.java create mode 100644 src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoProfilesStartupSystemTest.java create mode 100644 src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationLockWaitTest.java diff --git a/.github/workflows/object-storage-qualification.yml b/.github/workflows/object-storage-qualification.yml index 8a1a43d0..da628638 100644 --- a/.github/workflows/object-storage-qualification.yml +++ b/.github/workflows/object-storage-qualification.yml @@ -1,7 +1,8 @@ name: object-storage-qualification # Only pull requests that touch object storage start the MinIO container (review BUILD-계획-B3). The -# MinIO lanes left the object storage leaf's `check`; they run in its `mainCheck` on main and here. +# MinIO lanes left the object storage leaf's `check`; they run in the root `integrationCheck` (main push +# and nightly, integration-main.yml) and here. on: pull_request: paths: diff --git a/AGENTS.md b/AGENTS.md index 0b68af7d..bf95ad38 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,8 +82,9 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 `releaseCheck`, optional-platforms 빌드: `-p optional-platforms`로 부르는 `ci`·`integrationCheck`· `performanceCheck`·`releaseCheck`) 중 하나에 들어 있는지, 그리고 workflow의 접힌(`>`) run 블록이 빈 줄 때문에 옵션을 별개 명령으로 떼어 내지 않는지 검사한다. 두 빌드가 각자 검사를 돌린다. `-x`로 뺀 - lane, `continue-on-error` 아래 명령, 상태 함수(`always()`·`success()`·`!cancelled()`)가 아닌 `if:` - 아래 명령은 실행으로 세지 않는다. + lane(Gradle처럼 축약 이름도 맞춰 본다), `continue-on-error` 아래 명령, 상태 함수(`always()`·`success()`· + `!cancelled()`)가 아닌 `if:` 아래 명령, `workflow_dispatch`로만 시작하는 workflow의 명령은 실행으로 세지 + 않는다. 명령이 어느 빌드를 실행하는지는 `working-directory`와 `-p`를 합친 디렉터리로 정한다. 작업 파일의 소유 leaf는 registry의 `source_path`로 판단하고 가장 가까운 `src/**/CLAUDE.md`를 함께 읽는다. focused test는 registry의 `gradle_path`에서 diff --git a/CLAUDE.md b/CLAUDE.md index facf5c12..fb3b1eca 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,8 +40,10 @@ If this summary drifts from `AGENTS.md`, `AGENTS.md` wins and this summary must `releaseCheck` and the named repository-wide gates). `verifyStrictLaneStages --dry-run` (pull request; the main build and, as `-p optional-platforms`, the optional build each run their own) fails when a non-`explicitOnly` strict lane is in no stage a workflow executes — a lane the - command removes with `-x` and a command under `continue-on-error` or a non-status `if:` do not - count — or a folded workflow `run:` block splits an option off its command. + command removes with `-x` (abbreviations matched as Gradle does), a command under + `continue-on-error` or a non-status `if:`, and a `workflow_dispatch`-only workflow do not count; + the build a command runs is its `working-directory` joined with `-p` — or a folded workflow + `run:` block splits an option off its command. Commit policy is `human-only`: agents do not stage, commit, amend, or push implementation changes. diff --git a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md index 7307c654..78984639 100644 --- a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md +++ b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md @@ -83,6 +83,17 @@ load-check-save let two commits that both read `IN_PROGRESS` both write; now exa A claim whose conflicting row is purged between insert and read retries the insert once instead of failing the call. +`release(identity, claimToken)` is fenced the same way (re-review 2026-11-03 round 2, RR-01-15): it is a +conditional `DELETE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt` and returns whether it +deleted. It used to delete by key alone, so any caller could erase the claim of the attempt that held +it, or a finished record a retry replays. The counter lives in the row, so a deleted row's key starts +again at attempt 1: the token separates the attempts of one row, not attempts across a delete. Both +deletions are limited accordingly — release only for a claim whose owner is known to be gone, purge +only for rows finished longer ago than any retry. Rejected: dropping `release` from the port +(`markFailed` then `reclaimFailed` keeps the counter, but a deployment that must free a key for a +different request has no other path), and a tombstone row that keeps the counter (a second state to +purge, for a window the two limits already close). + Chosen over the claim moment as the token (`WHERE claimed_at = :claimedAt`), which needs no column: PostgreSQL stores microseconds while `Instant` carries nanoseconds, so the token a caller holds and the one stored can differ by rounding, and two processes' clocks can give two attempts the same diff --git a/docs/capability-status.md b/docs/capability-status.md index 7b701ff0..b70e0120 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -39,7 +39,7 @@ lanes and CI; it is not a deployment artifact. | GraphQL transport | `backend.graphql.enabled` / `APP_GRAPHQL_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:graphql')`) | leaf-level | On when present; `false` also excludes Spring GraphQL's own auto-configuration, so no `/graphql` (`GraphQlCapabilityActivationTest`). `graphqlTransportQualificationTest` runs the HTTP boundary. The deployment-mode/runtime-profile rule is the module's own `GraphQlPlatformStartupValidator`. The default jar does not ship GraphQL, so a compose lane that exercises it runs the qualification jar. | | Object storage | `app.object-storage.enabled` / `APP_OBJECTSTORAGE_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:objectstorage')`) | MinIO only | Own `ObjectStorageAutoConfiguration` (was bound through bootstrap's properties scan); on when present, `false` leaves only the explicit legacy seam (`ObjectStorageAutoConfigurationTest`). `app-bootstrap:integrationTest` assembles it against digest-pinned MinIO. | | gRPC platform | — (build-level) | yes | **no** | yes | Absent from the main build entirely: `optional-platforms` is a separate Gradle build, so the switch is the `include`, not an environment variable. `-p optional-platforms ci` runs on every PR and `integrationCheck` certifies the operation ledger against real PostgreSQL. | -| gRPC transport (`adapter:inbound:grpc`) | `ca-skeleton.grpc.server.enabled` (no `APP_*` row), `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:grpc')`) | leaf-level | Own `AutoConfiguration.imports` (`GrpcServerConfig`); on when present, and the loopback plaintext listener still needs `ca-skeleton.grpc.server.allow-insecure-local=true` (`GrpcSafeActivationTest`, `grpcTransportQualificationTest`). | +| gRPC transport (`adapter:inbound:grpc`) | `app.grpc.server.enabled` / `APP_GRPC_SERVER_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:grpc')`) | leaf-level | Own `AutoConfiguration.imports` (`GrpcServerConfig`); on when present, and the loopback plaintext listener still needs `app.grpc.server.allow-insecure-local=true` (`GrpcSafeActivationTest`, `grpcTransportQualificationTest`). | | WebSocket transport | `app.websocket.enabled` / `APP_WEBSOCKET_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:websocket')`) | — | Own `AutoConfiguration.imports` (`WebSocketConfig`), on in a servlet app when present (`WebSocketAutoConfigurationTest`); `ConditionalTransportBuildContractTest` asserts it has no default production edge. | | Web Advanced library (`adapter:inbound:web-advanced`) | — (build-level; three `backend.web.advanced.*.enabled` switches inside) | yes | **no** | — | No composition root depends on it; `app-bootstrap` takes it `testRuntimeOnly` for the ArchUnit import. No real-provider lane: `webAdvancedTest` (the `web-advanced` tag, run by `release.yml` → `web-stable-release-gate`) is unit and context-runner level. The Nginx lane went with the proxy library on 2026-09-25. | diff --git a/docs/fileserver/operations.md b/docs/fileserver/operations.md index 2c24969a..cc7a14b0 100644 --- a/docs/fileserver/operations.md +++ b/docs/fileserver/operations.md @@ -126,3 +126,72 @@ curl -s -X POST "$ADMIN/internal/fileserver/uploads:cleanup?maxItems=500&maxByte If the deferrals are all `ACTIVE_WRITER_LEASE`, the backlog resolves itself as those uploads expire. Never delete staging content to clear a backlog: an upload that is mid-flight will corrupt. + +## Namespace quota drift + +**Signal** — a namespace's usage (`fileserver.quota` rejections, or the drift query below) disagrees +with the bytes its files actually hold. The known cause is history: before the 2026-11 maturity +review, `move` relocated a file without moving its quota. The bytes of every file moved before that +fix are still booked on the namespace it left, and deleting such a file reclaims from the namespace +it now lives in, where the reclaim stops at zero and leaves the old booking behind. A derived +service that moved files across namespaces before taking the fix has this drift; one that never did +should see none. + +What the ledger must equal: quota is committed when a file is published and reclaimed when cleanup +deletes its content, so a namespace's committed bytes are the sizes of its published files that are +not yet `DELETED`. The query compares the two and changes nothing. + +```sql +WITH booked AS ( + SELECT scope_value AS namespace, sum(committed_bytes) AS booked_bytes + FROM fs_quota_reservation + WHERE scope_type = 'namespace' AND status = 'COMMITTED' + GROUP BY scope_value), +held AS ( + SELECT namespace, sum(actual_size) AS held_bytes + FROM fs_file + WHERE published_at IS NOT NULL AND state <> 'DELETED' + GROUP BY namespace) +SELECT coalesce(b.namespace, h.namespace) AS namespace, + coalesce(b.booked_bytes, 0) AS booked_bytes, + coalesce(h.held_bytes, 0) AS held_bytes, + coalesce(b.booked_bytes, 0) - coalesce(h.held_bytes, 0) AS drift_bytes + FROM booked b + FULL JOIN held h ON h.namespace = b.namespace + WHERE coalesce(b.booked_bytes, 0) <> coalesce(h.held_bytes, 0); +``` + +A positive `drift_bytes` is booked capacity no file holds (the namespace a file left); a negative one +is held content nothing booked (the namespace it arrived in). While uploads, copies, moves or +cleanup run, a row can show a drift that only means work in flight, so judge drift with the +fileserver's writes stopped. + +To correct a namespace, stop every fileserver write to it first — uploads, copy, move, delete, and +the cleanup worker (`APP_FILESERVER_PLATFORM_CLEANUP_ENABLED=false`) — because the statement below +recomputes from `fs_file` and a publish or reclaim that lands between its two steps would be lost. +It zeroes the namespace's committed rows and books the recomputed total as one row; the per-row +split has no meaning once reclaims have drawn rows down, and enforcement only ever reads the sum. +`RESERVED` rows (uploads in progress) are left alone. + +```sql +BEGIN; +SET LOCAL lock_timeout = '5s'; +UPDATE fs_quota_reservation + SET committed_bytes = 0, version = version + 1, updated_at = now() + WHERE scope_type = 'namespace' AND scope_value = :'namespace' + AND status = 'COMMITTED' AND committed_bytes > 0; +INSERT INTO fs_quota_reservation ( + reservation_id, scope_type, scope_value, reserved_bytes, committed_bytes, + expires_at, status, version, created_at, updated_at) +SELECT gen_random_uuid(), 'namespace', :'namespace', held, held, + now(), 'COMMITTED', 0, now(), now() + FROM (SELECT coalesce(sum(actual_size), 0) AS held + FROM fs_file + WHERE namespace = :'namespace' + AND published_at IS NOT NULL AND state <> 'DELETED') AS recomputed + WHERE held > 0; +COMMIT; +``` + +Run it with `psql -v namespace=`, then run the drift query again: the namespace must be gone +from its result before writes resume. diff --git a/docs/httpclient/configuration-reference.md b/docs/httpclient/configuration-reference.md index 206d81f7..7172e5c2 100644 --- a/docs/httpclient/configuration-reference.md +++ b/docs/httpclient/configuration-reference.md @@ -106,9 +106,12 @@ instead, so a long download is not cut at an arbitrary total (design §15.3). Th transports. The JDK transport keeps its exchange-wide timeout off a streamed body and bounds each read with its own `read-idle` timer, because the JDK client has no socket read timeout; before review 2026-11-03 RR-04-03 every JDK download longer than `response-header` was cut mid-body. A body -failure after hand-over is thrown as `HttpResponseTimeoutException` (a gap longer than `read-idle`) -or `HttpResponseTruncatedException` (the connection ended early), stage `RESPONSE_BODY`, evidence -`PARTIAL_RESPONSE`. +failure after hand-over is thrown from `read` as `HttpBodyReadException` — an `IOException`, as +`InputStream` promises, so `catch (IOException)` still sees it — whose `failure()` is +`HttpResponseTimeoutException` (a wait longer than `read-idle`) or `HttpResponseTruncatedException` +(the connection ended early), stage `RESPONSE_BODY`, evidence `PARTIAL_RESPONSE` (re-review +2026-11-04 RR-03-14). On the JDK transport `read-idle` bounds each read's wait, `skip` included, and +time the caller spends between reads does not count (RR-03-12). ### Removed settings @@ -140,6 +143,15 @@ RR-04-01): | The caller's own deadline (`HttpOperation.deadline()`, when earlier than `total-call`) | Not recorded; the permission is given back | The caller ran out of time. Counting it opened the circuit on a healthy upstream whenever callers passed short budgets | | The profile's `timeout.total-call` | Recorded as a failure | `total-call` is the operator's statement of how long a healthy upstream may take; a slow-drip upstream that never trips a per-gap timeout is seen only through it | +The first row has a blind spot (re-review 2026-11-04 RR-03-16). The attempt is let off whenever the +caller's deadline was the earlier one and had passed when the attempt failed — the code does not ask +whether the upstream was still answering within the profile's limits. If every caller of a profile +passes a budget shorter than `connect` or `response-header`, an upstream that hangs (drops packets, +never answers) ends every attempt at the caller's deadline first, so no attempt is recorded and the +circuit never opens; every call waits out its own budget. A failure that comes before the caller's +deadline — a refused connection — is still counted. For such a profile, set `connect` and +`response-header` shorter than the shortest caller budget. + | Property | Default | Meaning | |---|---|---| | `failure-rate-threshold` | `50` | Percent of failed calls in the window that opens the circuit, 1–100 | diff --git a/docs/httpclient/operations.md b/docs/httpclient/operations.md index b4bfc59d..bf95cfae 100644 --- a/docs/httpclient/operations.md +++ b/docs/httpclient/operations.md @@ -111,6 +111,11 @@ evidence, replayability, stage, retryability, attempt, elapsed, remaining deadli | `HttpUnknownTransportException` | the engine failed in a way no category above describes; the metadata evidence, not the type, says whether it was sent | never | | `HttpAmbiguousExecutionException` | a non-idempotent request was sent and the outcome is unknown | never — reconcile instead | +A streamed body that fails after hand-over is the one place these arrive wrapped: `read` throws +`HttpBodyReadException`, an `IOException` as `InputStream` promises, and its `failure()` is the +`HttpResponseTimeoutException` or `HttpResponseTruncatedException` above (re-review 2026-11-04 +RR-03-14). + ## Traces ```text diff --git a/docs/jpa/entity-mapping-guide.md b/docs/jpa/entity-mapping-guide.md index 4d3aa55e..8c3b39d7 100644 --- a/docs/jpa/entity-mapping-guide.md +++ b/docs/jpa/entity-mapping-guide.md @@ -85,8 +85,15 @@ reason those are ID references. bidirectional pair, on `@Entity`, `@MappedSuperclass` and `@Embeddable` types: an association that declares `mappedBy` (only that inverse half is reported), and two entities whose associations point at each other without `mappedBy` (both halves are reported — the `@JoinColumn` form above, review -RR-03-04). A class that links to itself is a pair only when a second member points back the other -way (`@ManyToOne parent` with `@OneToMany children`). `JpaProductionArchitectureTest` (app-bootstrap +RR-03-04). That last check also refuses two entities that each hold their own foreign key to the +other (`Order.@OneToOne latestInvoice` with `Invoice.@ManyToOne order`). It is not one link mapped +twice, and the message says so; it is refused on purpose, because the two tables then reference each +other: neither row can be inserted or deleted first, one key has to be nullable and written by a +second `UPDATE`, and the entity graph is a cycle. Keep the association on one side and give the other +an ID or a query (re-review round 2, RR-02-15). A class that links to itself is a pair only when a +second member points back the other way (`@ManyToOne parent` with `@OneToMany children`); two +`@ManyToOne` links of a class to itself (a manager and a mentor) pass, because both keys point into +the one table and there are no two tables to order. `JpaProductionArchitectureTest` (app-bootstrap `architectureTest`) runs it over the production graph and `SampleArchitectureTest` over the sample. The failure message names the fields and these alternatives. diff --git a/docs/jpa/migration-guide.md b/docs/jpa/migration-guide.md index 550e4b03..d79e63c8 100644 --- a/docs/jpa/migration-guide.md +++ b/docs/jpa/migration-guide.md @@ -32,6 +32,34 @@ reason, and an approval (design §8.4). Only Flyway's structured error codes reach the exception. Its messages embed the script path and part of the failing statement. +## Bound the lock wait + +A migration that locks a table already in use starts with `SET LOCAL lock_timeout = '5s';`, before +the first statement that takes the lock. `ALTER TABLE` takes the strongest lock there is, which +conflicts even with a plain read; a non-concurrent `CREATE INDEX` takes one that stops every write; +`UPDATE` and `DELETE` wait on the rows other transactions hold. Unbounded, the migration waits for +the oldest open transaction that touched the table — an operator's forgotten `BEGIN` in psql has no +deadline — and every read and write that arrives meanwhile queues behind the migration, holding a +pool connection while it waits. With the bound, the migration fails after five seconds, Flyway +rolls it back whole, the database stays on the version before it and the new release does not +start: a failed deploy instead of an outage. Deploy again when the transaction has ended. + +`LOCAL`, because a plain `SET` outlives the migration on the pooled connection Flyway borrowed and +changes every statement that later runs on it. A statement on a table the same migration created a +moment earlier waits for nothing and needs no bound. + +Enforced, not remembered: `LockWaitMigrationInspector` (persistence-jpa testkit) reads a script +and names every statement that locks an existing table before the bound. `MigrationLockWaitTest` +runs it over every tree this leaf's database runs, `SampleMigrationLockWaitTest` over the sample's +stream; a service stream copies the latter with its own directory. The migrations released before +the rule wait unbounded and stay that way (they are applied, and applied files are never edited); +the test lists them and refuses any new one. `PostgreSqlMigrationLockWaitIntegrationTest` +(`postgresqlMigrationLockWaitIntegrationTest`) and the gRPC ledger's +`GrpcOperationLedgerMigrationLockWaitIT` show on real PostgreSQL that a bounded migration gives up +within the bound while another transaction holds the table, and leaves the version below it. The +rule came from V21 having the bound and V22, in the same commit, not having it (re-review +2026-11-03 round 2, RR-02-09). + ## Concurrent index builds `CREATE INDEX CONCURRENTLY` cannot run inside a transaction block, and Flyway wraps migrations in diff --git a/docs/manual/04-persistence.md b/docs/manual/04-persistence.md index 4d5faddd..ec7e99dd 100644 --- a/docs/manual/04-persistence.md +++ b/docs/manual/04-persistence.md @@ -128,6 +128,12 @@ capability 스트림 db/migration/jpa/ 각자 histor (리뷰 README 13.2, 09-02). - 기존 데이터가 새 제약을 어기면 마이그레이션이 이유를 남기고 멈추게 쓴다(`V8_1`의 `DO $$` 블록). 조용히 지우지 않는다. +- 운영 중인 테이블을 잠그는 문장(`ALTER TABLE`, `CONCURRENTLY` 없는 `CREATE INDEX`, `UPDATE`·`DELETE`)이 있으면 + 그 앞에 `SET LOCAL lock_timeout = '5s';`를 둔다(`V8_1`, `V22`). 상한이 없으면 그 테이블을 건드린 열린 + 트랜잭션 하나(`ALTER TABLE`이면 읽기만 한 것도) 뒤에서 마이그레이션이 끝없이 기다리고, 그동안 뒤에 온 그 + 테이블의 쓰기(`ALTER TABLE`이면 읽기까지)가 모두 마이그레이션 뒤에 줄을 선다. 상한이 있으면 5초 뒤 실패·롤백되고 새 버전이 뜨지 않을 뿐이다. 자기 스트림에도 + `SampleMigrationLockWaitTest`처럼 `LockWaitMigrationInspector`(persistence-jpa testkit) 검사를 둔다 + (`docs/jpa/migration-guide.md` "Bound the lock wait"). ## 지금 이해하면 되는 것 diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md index 1883f5a7..0effa752 100644 --- a/docs/manual/05-idempotency.md +++ b/docs/manual/05-idempotency.md @@ -54,6 +54,11 @@ DB 커밋 중 연결 끊김 ───────────────── | 500 `IDEMPOTENCY_RECOVERY_REQUIRED` | 이전 시도 효과를 증명 못함 | 재전송·재실행 모두 위험. 업무 데이터로 확인 | | 500 `DB_COMPLETION_UNKNOWN`, `retryable=false` | DB 커밋 중 연결 끊김. 커밋됐을 수도 있음 | 키 없이 재시도 금지. KEYED면 같은 키로 재전송하면 서버가 판정 | +같은 키 재전송은 작업을 다시 돌리지 않는다. 첫 시도가 실행을 시작한 뒤 processing lease(기본 30s)가 +지나면 두 저장소 모두 그 기록을 넘겨주지 않고 500 `IDEMPOTENCY_RECOVERY_REQUIRED`로 답한다. 넘겨받는 것은 +실행 전 claim과 재시도 가능한 실패뿐이다. 기록은 lease + `replay-ttl` 동안 남고, `replay-ttl`이 lease보다 +짧으면 기동이 실패한다(`IdempotencyStoreContract`, 재리뷰 2026-11-04 RR-01-11·RR-03-11). + 409를 `retryable=true`로 바꾼 이유(리뷰 02-01 결정): 같은 키 재전송은 서버가 안전하게 판정하므로 다시 보내는 것이 맞고, 새 키로 보내면 서버가 막지 못한다. 짝 프론트 분류기도 이 표를 따른다. diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index 4aef0641..a6b8443a 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -64,18 +64,34 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re ## 시스템이 부르는 쓰기: `@SystemInvoked` -스케줄러·relay처럼 사람이 아니라 시스템이 부르는 쓰기 유스케이스는 `@RequiresPermission` 대신 +스케줄러·relay·메시지 소비자처럼 사람이 아니라 시스템이 부르는 쓰기 유스케이스는 `@RequiresPermission` 대신 `@SystemInvoked(reason = "...")`를 단다(`src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java`). -스케줄러 스레드에는 인증이 없어 권한 선언은 장식이 되기 때문이다. 이 표시가 붙은 유스케이스는 **권한 -검사가 없는 쓰기**이므로 전송 계층이 닿으면 안 된다. 그래서 두 가지가 막는다. +스케줄러·소비 스레드에는 인증(`Authentication`)이 없어서 권한 선언은 매번 거부되거나 아예 검사되지 않는 +장식이 되기 때문이다. 이 표시가 붙은 유스케이스는 **권한 검사가 없는 쓰기**다. 그래서 사용자 요청이 +닿으면 안 된다. -| 막는 것 | 어디 | -| --- | --- | -| bean으로 등록하면 기동 실패. 조립 모듈이 `new`로 만들어 스케줄러에만 준다(예: `composition:outbox-relay`) | `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java` | -| inbound adapter가 그 클래스를 직접 쓰면 빌드 실패 | `INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | +```text +사용자 요청 ─▶ web·GraphQL·gRPC·WebSocket ──✗──▶ @SystemInvoked 유스케이스 (빌드 실패) +시스템 ─▶ 스케줄러(조립 모듈이 new로 넘김) ─────▶ @SystemInvoked 유스케이스 +시스템 ─▶ 메시지 handler(@SystemCaller, 직접 new) ─▶ @SystemInvoked 유스케이스 +어디서든 ─▶ @SystemInvoked 유스케이스를 bean으로 등록 ──✗ (기동 실패) +``` + +- 사용자 전송: 사용자가 보낸 요청이 들어오는 inbound adapter다(web·GraphQL·gRPC·WebSocket). +- 시스템 호출자: broker 전달이나 시간(tick)이 깨우는 코드다. 사용자 요청은 여기로 들어오지 않는다. + +| 규칙 | 무엇을 막나 | 어디 | +| --- | --- | --- | +| bean 금지 | `@SystemInvoked` 유스케이스가 bean이면 기동 실패. 호출자가 `new`로 만들어 혼자 들고 있는 것만 허용한다 | `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java` | +| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | +| 표시 검사 | `@SystemCaller`는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·GraphQL·STOMP mapping·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) | + +규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 그래서 나중에 새 전송이 생겨도 따로 +고치지 않아도 막힌다. 메시지 소비자의 작업 순서는 09장 「소비」 4단계다. D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표시를 쓰지 않는다. 사용자가 부르는 -쓰기라면 권한을 선언하고 역할에 매핑한다. +쓰기라면 권한을 선언하고 역할에 매핑한다. 같은 쓰기를 사용자도 시스템도 부르면 유스케이스를 둘로 나눈다 +(사용자용 `@RequiresPermission`, 시스템용 `@SystemInvoked`). 업무 규칙은 domain에 두고 둘이 같이 쓴다. ## web 없는 조립 @@ -86,6 +102,7 @@ web이 빠진 조립(gRPC 전용·배치 전용)에는 `@RequiresPermission`을 ## 지금 이해하면 되는 것 - 쓰기 = `@RequiresPermission` + non-final + bean + 역할 매핑. -- 시스템만 부르는 쓰기 = `@SystemInvoked` + bean 아님 + 전송에서 안 닿음. +- 시스템만 부르는 쓰기 = `@SystemInvoked` + bean 아님 + 사용자 전송에서 안 닿음. 부르는 쪽은 스케줄러 + 조립이나 `@SystemCaller` 메시지 handler뿐이다. - 객체 판정은 유스케이스 안, 남의 것은 404. - 역할은 자기 client 것만 읽는다. diff --git a/docs/manual/09-outbox-events.md b/docs/manual/09-outbox-events.md index 753781b4..61b75b94 100644 --- a/docs/manual/09-outbox-events.md +++ b/docs/manual/09-outbox-events.md @@ -73,7 +73,9 @@ draft는 `IntegrationEventDrafts.draft(contract, eventId, aggregate, order, occu 시각(벽시계)은 쓰지 않는다 — 서버 시계가 어긋나면 순서가 뒤집힌다(리뷰 06-07). 벽시계 번호를 쓰던 서비스가 포트로 옮기면 V21 floor 덕분에 새 번호는 옛 번호 뒤에서 시작한다. 그래서 첫 번호가 1이 아니라 약 1.7×10¹⁵일 수 있다. 소비자는 번호를 "마지막으로 본 값보다 큰가"로만 비교하고 연속성을 - 가정하지 않는다. + 가정하지 않는다. 비교는 aggregate identity(tenant scope 포함) 단위다. tenant scope를 바꾸는 배포는 옛 + 버전 인스턴스를 모두 멈춘 뒤 새 버전을 띄운다 — 섞여 돌면 새 scope의 번호가 옛 버전이 방금 쓴 번호보다 + 작을 수 있다(runbook `outbox-dead-letter.md` §8, 재리뷰 2차 RR-02-10). ## relay와 실패 @@ -112,17 +114,47 @@ Kafka ─▶ platform consumer ─▶ (INBOX_TRANSACTIONAL이면) InboxMessageHa 적용한다. 3. destination을 선언한다: `guarantees.external-side-effect: INBOX_TRANSACTIONAL`, `consumer.group`, `retry.mode`·`retry.max-attempts`, `dlq.destination`. 예: `src/adapter/inbound/messaging/README.md`. -4. handler(`MessageHandler`)를 `adapter:inbound:messaging`에 둔다. delivery 하나를 use case 호출 - 하나로 바꾸고 업무 규칙은 use case에 둔다. use case는 평소처럼 `tx.inWrite`로 쓴다. 바깥 inbox - 트랜잭션에 합류한다. +4. 쓰기 use case와 handler를 만든다. 소비 스레드에는 인증이 없어서 `@RequiresPermission` use case는 + 매번 거부된다. 그래서 handler가 부르는 쓰기 use case는 `@SystemInvoked`이고, handler는 그 use case를 + **직접 `new`로 만들어 혼자 들고 있는** `@SystemCaller`다(07장 「시스템이 부르는 쓰기」). 이 방법 하나만 + 기동 가드와 빌드 규칙을 모두 통과한다. + - use case: `@SystemInvoked(reason = ...)` + `@UseCaseCapability(WRITE, …, WRITE_REPOSITORY)`. 평소처럼 + `tx.inWrite`로 쓰고, 바깥 inbox 트랜잭션에 합류한다. 업무 규칙은 여기에 둔다. + - handler(`MessageHandler`): `adapter:inbound:messaging`(또는 서비스의 `..adapter.inbound.messaging..` + 패키지)에 두고 `@SystemCaller(reason = ...)`를 단다. 생성자가 port를 받아 use case를 만든다. + delivery 하나를 use case 호출 하나로 바꾼다. + - bean은 handler 하나다. use case를 bean으로 등록하면 `PermissionEnforcementGuard`가 기동을 막는다. + 표시 없이 use case에 의존하면 `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`가 빌드를 막는다. + + ```java + @SystemCaller(reason = "order-events 소비자: platform consumer 스레드만 부른다") + public final class OrderCreatedHandler implements MessageHandler { + private final ProjectOrderUseCase useCase; // @SystemInvoked, bean 아님 + + public OrderCreatedHandler(TransactionPort tx, OrderProjectionPort projections) { + this.useCase = new ProjectOrderUseCase(tx, projections); + } + // destination(), handle(delivery) → useCase.project(...) + } + + @Bean // 이 leaf의 설정 클래스 + OrderCreatedHandler orderCreatedHandler(TransactionPort tx, OrderProjectionPort projections) { + return new OrderCreatedHandler(tx, projections); + } + ``` + + 같은 쓰기를 사용자 요청(HTTP 등)도 부르면 use case를 둘로 나눈다. 사용자용은 `@RequiresPermission`, + 소비용은 `@SystemInvoked`이고 업무 규칙은 domain에 둔다. payload는 다른 서비스가 보낸 입력이므로 use + case가 검증한다 — 권한 검사가 없다는 것이지 검증이 없다는 것이 아니다. 5. payload 타입을 정한다. 템플릿 relay가 보낸 메시지의 payload는 canonical envelope JSON 전체다 (`eventId`, `payload` 등). handler의 record는 그 모양이다. 등록 코드는 쓰지 않는다: handler의 `destination()`(계약 id, record class)과 `schemaVersions()`(읽는 payloadVersion, 기본 v1)가 decode 목록이 된다. 발행 쪽이 v2를 보내기 시작하면 handler가 `schemaVersions()`에 v2를 더한다 — 선언하지 않은 버전은 `SCHEMA_VERSION_NOT_REGISTERED`로 DLQ에 간다. -6. 테스트 본보기: `InboxRedeliveryIntegrationTest`(lane `messagingInboxRedeliveryIntegrationTest`, 실제 - Kafka + PostgreSQL). offset을 되감아 다시 전달해도, 처리 중 예외 뒤 재전달돼도 효과와 inbox 행이 - 하나인지 본다. +6. 테스트 본보기: `SystemInvokedConsumePathTest`(단위, 4단계 모양이 권한 가드 아래에서 기동하고 delivery가 + use case에 한 번 닿는지, use case를 bean으로 두면 기동이 막히는지)와 `InboxRedeliveryIntegrationTest` + (lane `messagingInboxRedeliveryIntegrationTest`, 실제 Kafka + PostgreSQL, 같은 handler 모양). offset을 + 되감아 다시 전달해도, 처리 중 예외 뒤 재전달돼도 효과와 inbox 행이 하나인지 본다. ### 판단 지점 @@ -162,3 +194,4 @@ Kafka ─▶ platform consumer ─▶ (INBOX_TRANSACTIONAL이면) InboxMessageHa - 계약(id·버전·schema·해시)을 먼저 정하고 계약 bean을 등록한다. - 전달은 적어도 한 번. 소비자는 inbox(`INBOX_TRANSACTIONAL`)로 예약과 업무 쓰기를 한 트랜잭션에 묶는다. - 실패한 처리는 예약까지 롤백되어 재전달에서 다시 처리된다. inbox 보존 기간은 재전달 창보다 길게. +- 소비 handler = `@SystemCaller` + `@SystemInvoked` use case를 직접 `new`. use case는 bean이 아니다. diff --git a/docs/messaging/outbox-inbox.md b/docs/messaging/outbox-inbox.md index 08f18189..1567cc93 100644 --- a/docs/messaging/outbox-inbox.md +++ b/docs/messaging/outbox-inbox.md @@ -154,7 +154,9 @@ consume 계약은 `MessageHandler` 하나다. handler를 bean으로 등록하 실제 왕복·중복 제거·DLQ는 `MessagingKafkaConsumeQualificationTest`(Kafka + PostgreSQL Testcontainers)가 확인한다. 애플리케이션 경로(앱 outbox relay가 발행 → `adapter:inbound:messaging`이 조립한 inbox와 JPA 트랜잭션 → handler)의 중복 전달·실패 재처리는 `InboxRedeliveryIntegrationTest`(lane -`messagingInboxRedeliveryIntegrationTest`)가 확인한다. +`messagingInboxRedeliveryIntegrationTest`)가 확인한다. 애플리케이션 handler가 쓰기 use case를 부르는 방법 +(`@SystemCaller` handler가 `@SystemInvoked` use case를 직접 만든다)은 `docs/manual/09-outbox-events.md` +「소비」 4단계다. ### 복합 키 diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 61e9ea02..85391be2 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -1601,7 +1601,9 @@ env_keys: - name: APP_IDEMPOTENCY_TTL # app.capabilities.idempotency.replay-ttl: how long a completed response stays - # replayable. One value for every provider; IdempotencySettings refuses more than 72h at startup. + # replayable. One value for every provider; IdempotencySettings refuses more than 72h, and less + # than APP_IDEMPOTENCY_PROCESSING_LEASE, at startup (re-review 2026-11-04 RR-03-11). Each record + # lives for the processing lease plus this value in both stores. type: duration default: 24h allowed_values: null @@ -1609,7 +1611,7 @@ env_keys: required: false reload_policy: restart-only owner_branch: feature-rate-limit-idempotency-contract - validation: spring_duration_shorthand_le_72h + validation: spring_duration_shorthand_le_72h_ge_processing_lease compatibility_impact: behavior-change required_test: idempotency-contract:ttl-applied @@ -1663,6 +1665,10 @@ env_keys: required_test: redis-idempotency-contract:key-namespace - name: APP_IDEMPOTENCY_PROCESSING_LEASE + # app.capabilities.idempotency.processing-lease: how long one attempt holds its claim. Longer + # than the in-flight Retry-After (2s), at most 1h, and not longer than APP_IDEMPOTENCY_TTL. A + # claim whose lease runs out is taken over only if it never started; an execution whose lease + # ran out is answered IDEMPOTENCY_RECOVERY_REQUIRED and never run again. type: duration default: 30s allowed_values: null diff --git a/docs/registries/metrics.yaml b/docs/registries/metrics.yaml index 043fccf4..a3ba89d8 100644 --- a/docs/registries/metrics.yaml +++ b/docs/registries/metrics.yaml @@ -390,7 +390,10 @@ metrics: allowed_values: [PENDING, IN_FLIGHT, PUBLISHED, FAILED, DEAD, PARKED] percentiles: null histogram_buckets: null + # DEAD > 0: the claim moves a row it will not hand out to DEAD without a relay result, so + # outbox.publisher.published.total{outcome=DEAD} misses it (re-review round 2, RR-02-12). alert_severity_thresholds: + p1: "DEAD > 0 (runbook://outbox/dead-letter)" p2: "PENDING size growing for 10m" owner_branch: feature-domain-event-outbox-contract log_field_mapping: [status] @@ -550,8 +553,11 @@ metrics: - name: outcome cardinality_limit: 2 allowed_values: [admitted, refused] - percentiles: [0.5, 0.9, 0.95, 0.99] - histogram_buckets: slo_driven + # As RedisLaneMetrics registers it: a percentile histogram (publishPercentileHistogram, expected + # range 1ms..10s) and no client-side percentiles and no SLO boundaries. The p99 below is a + # histogram_quantile over the buckets (re-review 2026-11-04 RR-03-17). + percentiles: null + histogram_buckets: percentile_histogram alert_severity_thresholds: p2: "SCRIPT admitted p99 > 100ms for 10m (the correctness lane is queueing)" p3: "CACHE_SCRIPT admitted p99 > 100ms for 30m" diff --git a/docs/registries/secrets-classification.yaml b/docs/registries/secrets-classification.yaml index c10c2c2a..e6b4e67f 100644 --- a/docs/registries/secrets-classification.yaml +++ b/docs/registries/secrets-classification.yaml @@ -10,9 +10,11 @@ # (feature-secrets-config-source-contract 2026-05-22: "dev/local sentinel value prefix = __LOCAL_DEV_"). # - prod profile에서 `__LOCAL_DEV_` prefix 발견 시 startup fail # (feature-secrets-config-source-contract 2026-05-22). -# - prod profile에서 `fixture-` prefix 값(이 저장소에 적힌 lane fixture 비밀번호 — infra/redis-sdk/acl, -# compose lane의 REDIS_LANE_*)도 같은 이유로 startup fail. 어떤 변수 이름이든 검사한다 -# (review 2026-11-03 RR-07-04). +# - prod profile에서 비밀값이 `fixture-`로 시작하면(이 저장소에 적힌 lane fixture 비밀번호 — +# infra/redis-sdk/acl, compose lane의 REDIS_LANE_*) 같은 이유로 startup fail (review 2026-11-03 +# RR-07-04). 비밀값만 본다: 이 파일의 `secret` 행(SecretSourceValidator.CLASSIFIED_SECRETS, +# SecretsClassificationRegistryTest가 1:1로 묶음), 모듈이 기여한 비밀, `secret://…/` 참조가 +# 가리키는 변수. HOSTNAME·앱 이름 같은 비밀이 아닌 값은 보지 않는다 (review 2026-11-04 RR2-04-01). # - Masking 기본 = `full_except_last_4` (feature-secrets-config-source-contract 2026-05-22: # "full mask except last 4 chars for non-secret tokens"). 진짜 secret(password/private key)은 `full`. # - Naming suffix는 보조 신호 (feature-secrets-config-source-contract: "_TOKEN, _KEY, _PASSWORD"). diff --git a/docs/reviews/2026-11-03-rereview/README.md b/docs/reviews/2026-11-03-rereview/README.md index 5fbe2cb2..bf9aba83 100644 --- a/docs/reviews/2026-11-03-rereview/README.md +++ b/docs/reviews/2026-11-03-rereview/README.md @@ -143,3 +143,44 @@ Important 7건: | RR-02-09 V22 잠금 | V21과 같은 `SET LOCAL lock_timeout`과 같은 모양의 lane 테스트 | 같은 커밋 안의 두 마이그레이션이 다른 규칙을 따르면 안 된다 | 멈추는 기준: 3차 수정 뒤 그 diff만 보는 확인 리뷰에서 새 Important가 0이면 멈춘다. + +## 10. 3차 수정 결과 (2026-11-04) + +9.1절 결정대로 2차 재리뷰 발견 29건(Important 7, Minor 22)을 영역 묶음 4개가 `ecc74b7d`에서 `test-driven-development` 스킬 절차로 RED→GREEN 했다. 오케스트레이터가 합쳤다. 하위 에이전트 없음. + +| 묶음 | 발견 | 상태 | 검증 (에이전트) | 처리 내용 | 결정 | +|---|---|---|---|---|---| +| r5-a 멱등성·outbound | RR-01-11, RR-03-11~18 | 완료 | leaf check 9, Redis 컨테이너 계약, PG 멱등성 계약 19/19, `postgresqlIdempotencyIntegrationTest` 8/8, architectureCheck, verifyEnvKeys, documentContractTest, topology standalone·cluster | RR-01-11 Redis CLAIM이 lease 지난 EXECUTING을 ABANDONED로 바꾸고 `RECOVERY_REQUIRED`로 답한다(PG와 같음, RED 실 Redis), 공유 계약에 시간 케이스 5개. RR-03-11 두 store의 기록 수명을 lease + replay TTL로(claim·takeover·renew), `replay-ttl < processing-lease`면 기동 실패(RED 실 Redis·PG). RR-03-12 skip을 read 단위로(RED). RR-03-13 read마다 걸던 타이머를 스트림당 watchdog 하나로(read당 2.6–3.1µs → 25–32ns). RR-03-14 본문 실패를 `IOException` 하위 `HttpBodyReadException`으로(RED). RR-03-15 시스템 속성 목록을 Spring과 비교(RED). RR-03-16 breaker 맹점 문서. RR-03-17 listener 첫 실패 WARN(RED). RR-03-18 문서 | lease가 지난 실행은 abandon해서, 늦게 끝난 첫 시도의 결과도 기록하지 않는다(9.1절 "다시 돌리지 않는다"와 같은 방향, PG 동작 유지). cluster topology 첫 실행의 캐시 테스트 2건 실패는 재실행·기준 커밋에서 재현 안 됨 | +| r5-b core·inbound | RR-01-12~17 | 완료 | application-core·fileserver·web·graphql·grpc·inbound messaging·service-runtime check, app-bootstrap architectureTest, architectureCheck, verifyDependencyLocks, inbox Kafka+PG, gRPC ledger PG 44, jpaPlatformContract | RR-01-12 새 표시 `@SystemCaller(reason)`: 메시지 handler·scheduler가 `@SystemInvoked` use case를 생성자에서 `new`로 만든다. ArchUnit `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`·`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, 매뉴얼 09장 경로를 `SystemInvokedConsumePathTest`로 고정. RR-01-13 `/error` status 접기를 문서·`EnvelopeErrorControllerTest`로. RR-01-14 `GraphQlClientPolicy`의 page 규칙 복사본 삭제. RR-01-15 ledger `release(identity, claimToken)`(RED 2). RR-01-16 `DirectTransactionPort`가 스레드별 트랜잭션(RED). RR-01-17 쿼터 롤백 계약 케이스(RED) | scheduler 패키지도 `@SystemCaller` 허용, `/error`는 코드 표에 없는 status를 class 코드로 접는다, release도 claim token으로 막는다 | +| r5-c persistence·messaging | RR-02-09~16 | 완료 | persistence-jpa(587)·persistence-notification·starter-kafka·outbox-relay·application-core·sample check, 실 PG lane 11개, `-p optional-platforms integrationCheck`, architectureCheck, documentContractTest, verifyStrictLaneStages | RR-02-09 V20·V22·알림 V11~V13·sample V8_1·grpc V002·V003에 `SET LOCAL lock_timeout = '5s'`, 텍스트 검사기 `LockWaitMigrationInspector`(testkit)와 실 PG lane `postgresqlMigrationLockWaitIntegrationTest`(RED 9). RR-02-10 scope를 바꾸는 배포는 rolling 금지 문서. RR-02-11 모르는 상태 값은 집계에서 빼고 WARN 1회(RED). RR-02-12 claim이 DEAD로 옮길 때 `last_failure_code`를 쓰고 `outbox.pending.size{status=DEAD} > 0` p1 경보(RED 단위·실 PG). RR-02-13 Javadoc. RR-02-14 runbook 숫자를 상수와 비교하는 document-contract lane. RR-02-15 메시지·가이드·fixture. RR-02-16 header 테스트, 업그레이드 안내 B-39 | 브리프에 없던 V20·V8_1도 같은 근거(아직 어디에도 미적용)로 수정. 규칙 이전에 배포된 마이그레이션 24개는 고칠 수 없어 동결 목록(줄기만 함). DEAD 원인 코드는 claim의 row lock 아래 flush | +| r5-d bootstrap·build·sample | RR2-04-01~06 | 완료 | support·app-bootstrap·sample·objectstorage check, app-bootstrap systemTest·documentContractTest, sample systemTest·webSystemTest, `-p build-logic check`, 두 빌드 verifyStrictLaneStages, verifyEnvKeys, compose 18 lane, `docker build`와 실제 기동(프로필 없음 exit 71, `demo` 8초 ready) | RR2-04-01 prod `fixture-` 검사는 비밀값만(레지스트리 `secret` 행, 모듈 기여 비밀, `secret://…/` 대상)(RED). RR2-04-02 sample `application.yml`이 `local`·`test`·`demo`에서 object storage를 끔(RED 9). RR2-04-03 rule·비밀 목록 bean에 주입 멤버·`@ConfigurationProperties`가 있으면 모든 프로필에서 기동 실패(RED 4). RR2-04-04 축약 `-x`, `workflow_dispatch` 전용 workflow, `working-directory`+`-p`, `uses:`의 `with: run:`(RED 7). RR2-04-05 lane json의 `APP_` 밖 키 거부, `property:` 행은 설정 metadata에 있을 때만 읽힘(RED 2). RR2-04-06 문서 | 리뷰어 제안 "static @Bean 선언 강제" 대신 bean이 실제로 필요로 하는 것을 본다(선언 강제는 문제없는 등록을 막고 `@Value` 필드는 통과시킨다). `workflowProjectDirectory` 설정을 없애고 저장소 구조로 정한다 — `working-directory` 없이 `./gradlew`를 부르는 workflow 명령은 실행으로 세지 않는다(B-36). `ca.spring-config`의 `compileJava`가 `processResources` 뒤에 돈다 | + +### 10.1 합칠 때 오케스트레이터가 한 것 + +- 업그레이드 안내 `docs/upgrade/2026-11-maturity-review.md`를 세 방향(r5-b·r5-c·r5-d)에서 손으로 합쳤다. B-14·B-15는 r5-d, B-16은 r5-b, B-39는 r5-c. +- RR-01-17의 남은 절반(이 수정 전에 move된 파일의 장부)을 직접 마무리했다. `docs/fileserver/operations.md` 「Namespace quota drift」에 차이를 찾는 쿼리와 namespace 하나를 다시 계산하는 SQL을 적었다. 실 PostgreSQL 16에 V1 스키마와 move 전 상태(출발 +100, 도착 −100, 삭제된 파일, 진행 중 예약)를 넣고 돌려, 차이 2행 → 0행, `RESERVED` 행은 그대로인 것을 확인했다. 업그레이드 안내 4절의 "재계산 SQL은 아직 없다"를 이 절로 바꿨다. +- 프론트 인계 문서에 이번 계약 변화(같은 키 재전송은 작업을 다시 돌리지 않음, `replay-ttl` 24h, `/error` status 접기)를 더했다. + +### 10.2 게이트 (2026-11-04, 합친 메인 작업 트리, 공유 잠금) + +첫 실행에서 모두 통과했다. + +| 게이트 | 결과 | 시간 | 실행 직전 부하(1분) | +|---|---|---|---| +| `ci` | rc=0 | 6분 22초 | 7.75 | +| `verifyStrictLaneStages --dry-run` (주 빌드 / `-p optional-platforms`) | rc=0 / rc=0 | 10초 / 3초 | 16.51 / 15.10 | +| `mainCheck` | rc=0 | 3분 6초 | 14.37 | +| `:integrationCheck` | rc=0 | 14분 22초 | 15.03 | +| `-p optional-platforms ci integrationCheck performanceCheck` | rc=0 | 1분 3초 | 1.88 | +| `:performanceCheck` | rc=0 | 22초 | 9.69 | +| `:releaseCheck -PgitRevision=` | rc=0 | 3초 | 7.63 | +| `scripts/verify-compose-profile-contracts.sh` | rc=0, 18 lane | 4초 | 7.82 | + +`integrationCheck`는 입력이 없는 lane 4개(`redisTopologyTest` 3개, `objectStorageAwsQualificationTest`)를 이름을 대며 뺐다(설계대로). 이 절과 `docs/fileserver/operations.md`·업그레이드 안내 문구는 `ci`가 도는 동안 고쳤다. 그 뒤의 `mainCheck`(document-contract lane 포함)는 고친 문서로 돌았다. + +### 10.3 남은 것 + +- `spotbugsTestFixtures`: 게이트 밖이고 `ecc74b7d`에서도 실패한다. r5-c의 새 검사기(`LockWaitMigrationInspector`)가 정규식 ReDoS 경고 8건을 더했다(입력은 저장소 마이그레이션 파일뿐). +- 실제 CI runner 실행: Gitea repo의 Actions가 꺼져 있어(`has_actions: false`) workflow가 돈 적이 없다. 켜는 것은 소유자 일이다. +- 소유자 확인이 필요한 기본값: 10절 "결정" 칸 — 특히 lease 뒤 늦게 끝난 첫 시도의 결과를 버리는 것, workflow 명령에 `working-directory`가 필요해진 것. +- 다음: 이 수정 커밋만 보는 확인 리뷰. 새 Important가 0이면 멈춘다(9.1절). diff --git a/docs/runbooks/migration-failed.md b/docs/runbooks/migration-failed.md index 540c6ef2..4a1c5c32 100644 --- a/docs/runbooks/migration-failed.md +++ b/docs/runbooks/migration-failed.md @@ -4,7 +4,7 @@ category: INTERNAL error_codes: [MIGRATION_FAILED] severity: P1 owner: oncall -last_updated: 2026-07-29 +last_updated: 2026-11-04 status: active --- @@ -40,7 +40,13 @@ status: active 4. Check whether any owned relation was created without a successful history entry. Compare only against the owned tables in the reviewed migration; do not drop unrelated relations. 5. Classify the failure: - - lock/statement timeout: remove the blocker or reduce rollout concurrency, then rerun; + - lock/statement timeout: remove the blocker or reduce rollout concurrency, then rerun. A + migration that locks a table already in use gives up after its own `SET LOCAL lock_timeout` + (5 s; SQLState `55P03` `lock_not_available`) and rolls back whole, so the history ends one + version below it. The blocker is a transaction that touched the table and is still open — + often an idle-in-transaction session: `SELECT pid, state, xact_start, query FROM + pg_stat_activity WHERE xact_start < now() - interval '5 seconds' ORDER BY xact_start;`. End + it, then rerun (`docs/jpa/migration-guide.md` "Bound the lock wait"); - SQL/data precondition: create a new forward migration that makes the precondition explicit; a duplicate outbox order key stopping V21 (`ux_outbox_event_aggregate_order`) is the known case — clean it up with `outbox-dead-letter.md` §8 and rerun, the migration stays as it is; diff --git a/docs/runbooks/outbox-dead-letter.md b/docs/runbooks/outbox-dead-letter.md index f0d212bd..1ccd6d13 100644 --- a/docs/runbooks/outbox-dead-letter.md +++ b/docs/runbooks/outbox-dead-letter.md @@ -4,7 +4,7 @@ category: INTERNAL error_codes: [OUTBOX_DEAD_LETTER] severity: P1 owner: oncall -last_updated: 2026-11-03 +last_updated: 2026-11-04 status: stub --- @@ -16,7 +16,10 @@ status: stub - alert name: `outbox_dead_letter` - alert payload 필수 field: `error.code=OUTBOX_DEAD_LETTER`, `event_type`, `event_id`, `correlation_id`, `runbook_link` -- 임계: `outbox.publisher.published.total{outcome=DEAD}` > 0 (DEAD 전이는 자동 회복이 없으므로 단건도 점검 대상) +- 임계: `outbox.publisher.published.total{outcome=DEAD}` > 0 또는 `outbox.pending.size{status=DEAD}` > 0 (DEAD 전이는 + 자동 회복이 없으므로 단건도 점검 대상). 두 번째 조건이 필요한 이유: claim이 행을 DEAD로 옮기는 경우 + (`ATTEMPT_COUNTERS_INCONSISTENT`, `UNREADABLE_ROW`)는 relay 결과를 거치지 않아 첫 번째 카운터가 오르지 않는다 + (재리뷰 2026-11-03 2차 RR-02-12) ## 2. First Response (5분 이내) @@ -26,7 +29,8 @@ status: stub `last_failure_code`에 남는다. ERROR가 없고 WARN `outbox claim moved a row ... to DEAD`만 있으면 relay가 아니라 claim이 행을 DEAD로 옮긴 것이다 — `error.reason`이 `ATTEMPT_COUNTERS_INCONSISTENT`면 `deferred_attempt_count`를 되돌리지 않은 수동 재발행이 원인이니 §4의 SQL로 다시 재발행한다. `UNREADABLE_ROW`면 행 자체가 event로 읽히지 - 않는다(canonical 봉투 없음, 저장된 해시와 바이트 불일치) + 않는다(canonical 봉투 없음, 저장된 해시와 바이트 불일치). 이 경우에도 같은 코드가 행의 `last_failure_code`에 + 남는다 — 그 전 발행 실패의 코드는 덮어쓴다 2. DB에서 DEAD row 확인: `SELECT * FROM outbox_event WHERE status = 'DEAD' ORDER BY occurred_at;` 3. **차단 영향 파악 (중요)**: strict per-aggregate FIFO 정책상 DEAD row는 같은 aggregate(`tenant_scope`, `aggregate_type`, `aggregate_id`)의 후행 이벤트를 계속 차단함. 순서는 `(aggregate_sequence, event_index)`로 비교한다(claim SQL `PostgreSqlOutboxClaimRepository`와 같은 키) — `SELECT count(*) FROM outbox_event b WHERE b.status <> 'PUBLISHED' AND EXISTS (SELECT 1 FROM outbox_event d WHERE d.status='DEAD' AND d.tenant_scope=b.tenant_scope AND d.aggregate_type=b.aggregate_type AND d.aggregate_id=b.aggregate_id AND (d.aggregate_sequence < b.aggregate_sequence OR (d.aggregate_sequence = b.aggregate_sequence AND d.event_index < b.event_index)));` @@ -121,10 +125,24 @@ V21이 하는 일은 세 가지 더 있다. 5초 안에 못 잡으면 V21이 실패하고 V20에 남는다(`MIGRATION_FAILED`). 덜 바쁜 시각에 다시 배포하거나 Step 0으로 인덱스를 먼저 만든다. +V20(`deferred_attempt_count`)과 V22(`last_failure_code`)도 같은 상한을 둔다(재리뷰 2026-11-03 2차 RR-02-09). +둘 다 `ALTER TABLE outbox_event`라 가장 강한 잠금(ACCESS EXCLUSIVE)을 건다. 이 잠금은 읽기와도 충돌하므로, +`outbox_event`를 읽기만 한 트랜잭션 하나(운영자가 `BEGIN` 안에서 조회하고 둔 psql 세션 포함)가 열려 있어도 +기다린다. 5초 안에 못 잡으면 그 마이그레이션이 실패·롤백되고 DB는 한 버전 아래(V19 또는 V21)에 남으며 새 버전은 +기동하지 않는다(`MIGRATION_FAILED`, exit 70). 열린 트랜잭션을 찾아 끝낸 뒤 다시 배포한다 — +`SELECT pid, state, xact_start, query FROM pg_stat_activity WHERE xact_start < now() - interval '5 seconds' ORDER BY xact_start;` + rolling 배포 중 아직 옛 버전인 인스턴스가 벽시계 번호로 쓴 행은 floor보다 크다. 새 버전의 counter는 그 aggregate의 가장 큰 행 번호보다 작아지지 않으므로 그 행 뒤에 번호를 준다. 서로 커밋되지 않은 채 겹친 옛·새 쓰기 사이의 순서는 보장하지 않는다 — 옛 벽시계 방식도 보장하지 않던 것이다. +이 "그 행 뒤에"는 **같은 aggregate identity**의 행에만 성립한다. tenant scope를 바꾸는 배포에서는 옛 버전이 +옛 scope로, 새 버전이 새 scope로 쓴다. 새 버전의 counter는 옛 scope 행을 보지 못하므로 floor + 1부터 시작하고, +rolling 중 옛 버전이 방금 쓴 번호(floor보다 초당 10⁶씩 큰 벽시계 번호)보다 **작은** 번호를 준다(재리뷰 +2026-11-03 2차 RR-02-10, 실 PG 확인). scope를 무시하고 aggregate id로 "마지막 번호보다 작으면 버린다"를 구현한 +소비자는 그 사이 새 이벤트를 버린다. 그래서 **tenant scope를 바꾸는 배포는 rolling으로 하지 않는다**: 옛 버전 +인스턴스를 모두 멈춘 뒤(옛·새 버전이 함께 쓰는 구간 없이) 새 버전을 띄운다. + tenant scope를 바꾼 서비스(샘플은 `portfolio` → 단일 scope)는 배포 전에 옛 scope의 미발행 행이 없는지 확인한다. 옛 scope 행과 새 scope 행은 서로 다른 aggregate로 보여 claim gate가 서로를 막지 않고, partition key도 달라 다른 partition으로 간다. @@ -231,7 +249,8 @@ Step 1을 다시 돌려 0행이면 배포한다. 정리와 배포 사이에 옛 확인 쿼리, 정리 SQL, Step 0의 인덱스 SQL은 이 문서에서 그대로 읽어 실제 PostgreSQL에서 실행하는 테스트가 있다(`PostgreSqlOutboxOrderKeyRunbookIntegrationTest`, lane `postgresqlOutboxOrderKeyRunbookIntegrationTest`). 같은 lane이 V21의 counter·floor, 잠금 대기 실패, -INVALID 인덱스 거부도 본다. 이 절의 `runbook-sql` 블록을 고치면 그 lane을 다시 돌린다. +INVALID 인덱스 거부도 본다. 이 절의 `runbook-sql` 블록을 고치면 그 lane을 다시 돌린다. V20·V22의 잠금 대기 +실패는 `PostgreSqlMigrationLockWaitIntegrationTest`(lane `postgresqlMigrationLockWaitIntegrationTest`)가 본다. --- diff --git a/docs/runbooks/outbox-publish-failed.md b/docs/runbooks/outbox-publish-failed.md index 41e9dd6b..b676e14e 100644 --- a/docs/runbooks/outbox-publish-failed.md +++ b/docs/runbooks/outbox-publish-failed.md @@ -4,7 +4,7 @@ category: TRANSIENT_DEPENDENCY error_codes: [OUTBOX_PUBLISH_FAILED] severity: P2 owner: oncall -last_updated: 2026-11-03 +last_updated: 2026-11-04 status: stub --- @@ -86,7 +86,8 @@ status: stub **Step 1 — 찾기 (읽기 전용).** 미룬 claim(`deferred_attempt_count`)이 10번 이상인 FAILED 행이다. backoff 상한이 5분이라 10번은 적어도 약 35분 동안 계속 실패했다는 뜻이다. `outbox.retry.long.size`·`outbox.retry.long.age`가 -같은 기준(`OutboxMetrics.LONG_RETRY_DEFERRED_CLAIMS`)으로 센다. +같은 기준(`OutboxMetrics.LONG_RETRY_DEFERRED_CLAIMS`)으로 센다. 아래 SQL의 숫자를 바꾸면 그 상수도 같이 바꾼다 — +`OutboxLongRetryRunbookContractTest`(lane `:composition:outbox-relay:outboxRelayDocumentContractTest`)가 둘을 비교한다. ```sql @@ -114,6 +115,12 @@ UPDATE outbox_event SET status = 'PARKED' WHERE event_id = '' AND status = ' `UPDATE 0`이면 그 사이 relay가 행을 claim해 IN_FLIGHT다. `next_attempt_at`이 지난 뒤 다시 실행한다. 보류된 행 수는 `outbox.pending.size{status=PARKED}`로 보인다. +**롤백 전에 보류를 푼다.** `PARKED`는 이 버전(`bbe944bd` 이후)에 생긴 상태다. 그보다 옛 버전은 이 이름을 몰라 +상태별 집계 전체가 실패하고, `outbox.pending.size` 게이지가 PENDING까지 통째로 꺼진다 — `PENDING size growing` +경보의 입력이 사라진다(재리뷰 2026-11-03 2차 RR-02-11). 옛 버전으로 롤백해야 하면 그 전에 보류한 행을 모두 +Step 3으로 재개하거나 버린다. 이 버전부터는 모르는 상태가 있어도 그 상태만 빼고 세고 WARN 한 번으로 이름을 +말한다(`outbox_event holds rows in a status this version does not know`). + **Step 3 — 재개(resume) 또는 버리기(skip).** 원인을 고쳤으면 재개한다. 행은 FAILED로 돌아가 바로 claim 대상이 된다. 시도 횟수는 그대로 둔다(미룬 claim은 예산을 쓰지 않으므로 DEAD로 바로 가지 않는다). diff --git a/docs/runbooks/redis-capability-incident.md b/docs/runbooks/redis-capability-incident.md index a40d93b4..481bb7fd 100644 --- a/docs/runbooks/redis-capability-incident.md +++ b/docs/runbooks/redis-capability-incident.md @@ -47,7 +47,9 @@ Redis liveness 실패만으로 pod를 재시작하지 않는다. 재시작 폭 로그와 health detail에서 확인한다. timeout이나 연결 끊김은 미실행 증거가 아니다. - readiness는 최신 health detail의 state/reason/requirement로 본다. optional cache의 degraded serving과 required coordination/session의 fail-closed 결정을 같은 availability 의미로 합치지 않는다. -- reconnect, cache source-load, session repository error 지표의 변화를 함께 본다. +- 재연결은 `redis.lane.connections.opened.total`과 `discarded.total`을 함께 본다(Cluster `TRANSACTION` + lane은 borrow마다 열어 opened가 꾸준히 오른다 — `cache-redis/README.md`). cache source-load·session + repository 오류 지표는 내보내는 코드가 없다(설계만 있음). - Redis server 측에서는 memory/eviction, rejected clients, replication link/lag, persistence error, Cluster coverage를 operator dashboard에서 확인한다. - `NOSCRIPT`, result-schema mismatch, ACL denial, TLS/auth failure, OOM, timeout을 서로 다른 @@ -57,21 +59,21 @@ Redis liveness 실패만으로 pod를 재시작하지 않는다. 재시작 폭 - `redis.lane.*` meter의 tag는 닫힌 lane 이름뿐이다. key, subject, session id, token, endpoint, exception text, script/SHA, value 같은 identity/wire material을 metric이나 ticket에 복사하지 않는다. -- semantic operation 계측은 logical provider가 실제로 반환한 hit/miss/denied/conflict/ - unavailable/indeterminate 결과를 기록한다. cache의 `stale`/`skipped`, session의 - `tombstoned`/`absolute_expired`도 정상 hit/miss와 분리한다. meter registry, classifier, - monotonic ticker 장애는 command 결과나 원래 exception instance를 바꾸지 않는다. +- semantic operation 단위 계측(hit/miss/denied/conflict/unavailable/indeterminate 결과, cache의 + `stale`/`skipped`, session의 `tombstoned`/`absolute_expired`)은 **설계만 있고 내보내지 않는다** + (`redis.capability.*`, 위 Detection 절). operation 결과는 로그와 health detail로 본다. `redis.lane.*` + 계측(listener)이 실패해도 borrow 결과나 원래 exception은 바뀌지 않는다. 처음 실패는 WARN 로그 한 줄로 + 남고(`RedisRuntimeOwner`), 그 뒤는 DEBUG다 — 지표가 통째로 비면 그 WARN을 찾는다. - route 응답이 설정된 byte/collection bound를 넘으면 동일 logical operation을 `unavailable`로 종료한다. GET/read-only 응답은 `not_applied`, mutation VALUE/MULTI 응답은 - 서버 실행 여부를 되돌릴 수 없으므로 `indeterminate`다. 앞선 `success` 표본과 이 실패를 두 - operation으로 합산하지 않는다. + 서버 실행 여부를 되돌릴 수 없으므로 `indeterminate`다. - Spring 종료의 dependency order는 invalidation subscription 같은 capability dependent를 먼저 닫고, capability bean을 닫은 다음 canonical registry가 router admission을 닫아 in-flight를 bounded drain하고 마지막에 runtime을 닫는 순서다. 종료 중 새 command를 허용하거나 drain timeout 뒤 무기한 기다리지 않는다. - 현재 composition에는 active Redis scheduler나 dormant credential-rotation coordinator가 없다. 존재하지 않는 lifecycle coordinator를 복구 절차에서 찾거나 수동 호출하지 않는다. -- 이 meter와 단일-process lifecycle test는 Sentinel/Cluster failover, TLS/ACL 배포 적합성, +- `redis.lane.*` meter와 단일-process lifecycle test는 Sentinel/Cluster failover, TLS/ACL 배포 적합성, k3s multi-node, L1/L2 분산 일관성, distributed session 동작의 qualification 증거가 아니다. 해당 label은 별도 topology/conformance lane의 실제 증거가 있어야 한다. diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index 6a96a80a..995b634a 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -21,13 +21,13 @@ |---|---|---|---| | 1 | JWT 모드면 `APP_SECURITY_JWT_AUDIENCE`에 이 서비스의 client id를 쉼표로 넣는다 | 기동 실패 `APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required` | JWT 모드(기본값) 전부 | | 2 | dev·prod 환경 변수의 `APP_FLYWAY_ENABLED` 값을 확인한다 | `false`가 남아 있으면 이제 정말로 마이그레이션이 안 돈다 | persistence-jpa 선택 | -| 3 | prod 설정 어디에도 `fixture-`로 시작하는 값이 없게 한다 | prod 기동 실패(exit 78) | prod 배포 전부 | -| 4 | 직접 만든 `StartupRule`·`RequiredProductionSecrets` bean을 `static @Bean`, 의존성 없이 바꾼다 | 기동 실패 `startup rule '<이름>' created [...]`(exit 78) | 자기 rule이 있는 서비스 | +| 3 | prod 비밀값(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/`이 가리키는 변수)이 `fixture-`로 시작하지 않게 한다 | prod 기동 실패(exit 78) | prod 배포 전부 | +| 4 | 직접 만든 `StartupRule`·`RequiredProductionSecrets` bean을 `static @Bean`, 의존성 없이 바꾸고, 그 클래스에서 `@Value`·`@Autowired` 멤버와 `@ConfigurationProperties`를 뺀다 | 기동 실패 `startup rule '<이름>' created [...]` 또는 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one`(exit 78) | 자기 rule이 있는 서비스 | | 5 | 직접 구현한 outbox·발행·알림·파일 서버 포트를 새 시그니처로 고친다(3.1절) | 컴파일 오류 | 해당 포트를 구현·호출하는 서비스 | | 6 | `dev.caskeleton.application.outbound.*` import를 `application.secret.*`·`application.objectstorage.content.CallBudget`으로 바꾼다 | 컴파일 오류 | 해당 타입을 쓰는 서비스 | | 7 | 이벤트 id를 소문자 UUIDv7로 만들고 `IntegrationEventDraft`는 `IntegrationEventDrafts.draft(...)`로만 만든다 | 쓰기 요청이 `IllegalArgumentException`으로 실패, architectureTest 실패 | 통합 이벤트를 내는 서비스 | | 8 | V21 배포 전에 `docs/runbooks/outbox-dead-letter.md` §8 Step 1 쿼리를 운영 DB에 돌린다 | 중복 순서 키가 있으면 기동 실패(exit 70, V20에 남음) | persistence-jpa + outbox | -| 9 | 이 브랜치의 이전 V21을 적용한 개발 DB를 다시 만든다(4.2절) | Flyway checksum 불일치로 기동 실패(exit 70) | 이 브랜치를 미리 받아 돌린 개발 DB | +| 9 | 이 브랜치의 이전 V21(또는 3차 수정 전 V20·V22·V11~V13·V8_1·V002·V003)을 적용한 개발 DB를 다시 만든다(4.2절) | Flyway checksum 불일치로 기동 실패(exit 70) | 이 브랜치를 미리 받아 돌린 개발 DB | | 10 | 자기 SecurityFilterChain이 있으면 `DispatcherType.ERROR`를 허용한다 | 핸들러 밖 오류가 401로 바뀌어 나간다 | 자기 보안 체인을 둔 서비스 | | 11 | 짝 프론트(또는 다른 클라이언트)에 7절 계약을 맞추게 한다 | 409를 재시도 불가로 읽거나, `null` 키를 기대하다 깨진다 | HTTP 클라이언트가 있는 서비스 | | 12 | 자기 Flyway 마이그레이션 번호가 템플릿의 새 번호와 겹치지 않는지 본다(4절) | 같은 버전 두 개로 Flyway 실패 | 같은 stream에 자기 마이그레이션을 둔 서비스 | @@ -56,8 +56,9 @@ | B-07 | 패키지 이동: `dev.caskeleton.application.outbound.SecretSourcePort`·`SecretReference` → `dev.caskeleton.application.secret.*`. `dev.caskeleton.application.outbound.CallBudget` → `dev.caskeleton.application.objectstorage.content.CallBudget`(leaf `application-objectstorage`). `application.outbound` 패키지 삭제 | `package dev.caskeleton.application.outbound does not exist` | import를 바꾼다. `CallBudget`을 쓰는 leaf가 `application-objectstorage`에 의존해도 되는지 `modules.json` 간선을 확인 | `5786126c` · `src/application-core/.../secret/`, `src/application-objectstorage/.../content/CallBudget.java` | | B-08 | `shared-contract`에서 `dev.caskeleton.shared.operation.Operation`·`OperationStatus` 삭제. sample-portfolio(`...sample.portfolio.adapter.inbound.web.operation`)로 옮겨졌다 | import 실패 | 쓰고 있었다면 자기 inbound adapter로 복사한다 | `1400dc15` · `src/shared-contract/src/main/java/dev/caskeleton/shared/operation/`(삭제) | | B-09 | `SecuritySettings`(adapter:inbound:web): `audience`가 `String` → `List`. `@ConfigurationProperties` 제거, `SecuritySettings.bind(Environment)`로 strict 바인딩. 생성자 `(String, String, List)` → `(String, List, List)`. `bootstrap.security.AuthenticationModeSettings` 삭제 | `audience()`를 문자열로 쓰는 코드, 직접 생성하는 테스트 컴파일 오류 | `List`으로 바꾼다. 인증 모드는 `SecuritySettings.authMode()`에서 읽는다 | `34565130`(List), `5786126c`(strict·삭제) · `src/adapter/inbound/web/.../settings/SecuritySettings.java` | -| B-10 | adapter 공개 타입 삭제·이동: graphql `execution.GraphQlTimeoutPolicy`·`dataloader.GraphQlDataLoaderRequestRegistry` 삭제(`runtime.GraphQlDeadlineInstrumentation`·`GraphQlPerParentFetchInstrumentation` 추가). jpa `experimental.tenant.TenantId` 삭제 → `dev.caskeleton.application.tenant.TenantId`. persistence-notification의 엔티티는 `...platform.entity`, 저장소는 `...platform.repository`로 이동, `inbox` 하위 클래스는 `platform`으로 올라옴, `PreferenceJpaRepository`·`SuppressionJpaRepository` 삭제, `JpaNotificationSideEffect` → application-notification `dispatch.SuppressionSideEffect` | import 실패. leaf `check`의 API surface 비교가 스냅샷과 달라 실패(자기 공개 타입을 더했다면 merge 충돌) | import를 바꾼다. 스냅샷 파일은 upstream 것을 받고 자기 추가분을 다시 승인한다 | `1400dc15`·`5786126c` · `docs/architecture/graphql-api-surface.txt`, `docs/architecture/jpa-api-surface.txt`(166→165), `docs/notification/api-surface-snapshot.txt`(362→364) | +| B-10 | adapter 공개 타입 삭제·이동: graphql `execution.GraphQlTimeoutPolicy`·`dataloader.GraphQlDataLoaderRequestRegistry` 삭제(`runtime.GraphQlDeadlineInstrumentation`·`GraphQlPerParentFetchInstrumentation` 추가). jpa `experimental.tenant.TenantId` 삭제 → `dev.caskeleton.application.tenant.TenantId`. persistence-notification의 엔티티는 `...platform.entity`, 저장소는 `...platform.repository`로 이동, `inbox` 하위 클래스는 `platform`으로 올라옴, `PreferenceJpaRepository`·`SuppressionJpaRepository` 삭제, `JpaNotificationSideEffect` → application-notification `dispatch.SuppressionSideEffect`. graphql `GraphQlClientPolicy.effectivePageSize(Integer, Integer)` 삭제 → `pagination.GraphQlConnectionPolicy.effectivePageSize`(상한 검사 포함, 재리뷰 RR-01-14). grpc(optional-platforms) `GrpcOperationLedger.release(identity)` → `boolean release(identity, GrpcClaimToken)`: 진행 중이고 그 token이 가진 claim만 지운다(RR-01-15) | import 실패, 호출부·직접 구현한 ledger 컴파일 오류. leaf `check`의 API surface 비교가 스냅샷과 달라 실패(자기 공개 타입을 더했다면 merge 충돌) | import를 바꾼다. 스냅샷 파일은 upstream 것을 받고 자기 추가분을 다시 승인한다 | `1400dc15`·`5786126c` · `docs/architecture/graphql-api-surface.txt`, `docs/architecture/jpa-api-surface.txt`(166→165), `docs/notification/api-surface-snapshot.txt`(362→364) | | B-11 | 조립·지원 타입: `bootstrap.autoconfigure.operation.DurableOperationConfig` → `composition:durable-operation`의 `composition.operation.DurableOperationAutoConfiguration`. `bootstrap.settings.LoggingSettings` 삭제. `composition.outbox.OutboxLeaderElectionToken` 삭제. `TracingSamplingEnvironmentPostProcessor` → `TracingEnvironmentPostProcessor`, `StartupOrder.TRACING_SAMPLING` → `TRACING_PROPERTIES`. `StartupRuleRunner(Environment, List)` → `StartupRuleRunner(Environment)`. `SecretSourceValidator(ConfigurableEnvironment, SecretSourcePort, List)` → `SecretSourceValidator(Supplier>)` | 이 타입을 참조하는 코드·테스트 컴파일 오류 | 새 이름으로 바꾼다 | `1400dc15`, `34565130`, `bbe944bd` · `src/composition/durable-operation/`, `src/adapter/outbound/support/.../startup/` | +| B-39 | vendored messaging SPI `KafkaQuarantinePublisher`(`messaging-kafka`): `quarantine(ConsumerRecord, Throwable)` → `quarantine(ConsumerRecord, FailureCategory category, Throwable reason)`. 호출자가 격리 이유(읽을 수 없는 레코드 `DESERIALIZATION`, 시도 예산 소진은 실패의 category 또는 `POISON_MESSAGE`)를 넘기고, 구현은 그것을 `msg.failure-category` header로 쓴다 | 이 SPI를 직접 구현한 서비스는 `does not override abstract method` 컴파일 오류. 람다로 만든 것도 인자 수 오류 | 세 인자 메서드로 고친다. category를 header나 저장소에 그대로 남겨야 redrive가 두 경우를 가른다(템플릿 `KafkaDeadLetterQuarantine`, 테스트 `KafkaDeadLetterQuarantineTest`) | `bbe944bd`(리뷰 06-14), 3차 수정에서 목록에 추가(재리뷰 2차 RR-02-16) · `src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaQuarantinePublisher.java` | ### 3.2 설정·기동 — 기동이 실패하거나 런타임 예외가 난다 @@ -65,9 +66,9 @@ |---|---|---|---|---| | B-12 | JWT 모드에서 `APP_SECURITY_JWT_AUDIENCE` 필수(빈 값 거부, `${...}`가 안 풀린 값도 없는 값으로 봄). 토큰 `aud`가 목록 중 하나를 담아야 통과. `resource_access` role은 audience에 적은 client 것만 읽는다(realm role은 그대로) | 기동 실패 `APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required`(exit 코드 확인 못 함). `.env.example`이 `APP_SECURITY_JWT_AUDIENCE=`(빈 값)를 싣고 있다. 다른 client의 role에 기대던 권한이 사라짐 | client id를 쉼표로 넣는다. 다른 client role로 권한을 받던 사용자가 있는지 IdP에서 확인 | `34565130`(필수·role), `1400dc15`(안 풀린 `${...}`) · `src/adapter/inbound/web/.../auth/JwtDecoderConfig.java`, `.../JwtToAuthenticatedPrincipalConverter.java`, `.../settings/SecuritySettings.java` | | B-13 | `app.security.*` strict 바인딩: 접두어 아래 오타 키, 또는 설정·placeholder 어디에도 쓰이지 않는 `APP_SECURITY_*` 환경 변수가 기동을 막는다 | 기동 실패(메시지는 `StrictSettingsBinder`가 키 이름을 담아 냄, 정확한 문구 확인 못 함) | 쓰지 않는 `APP_SECURITY_*` 변수를 지운다 | `5786126c` · `SecuritySettings.bind`, `src/adapter/outbound/support/.../StrictSettingsBinder.java` | -| B-14 | prod 프로필에서 `fixture-`로 시작하는 설정 값(변수 이름 무관)을 거부. Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로 | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` | -| B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다 | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule '<이름>' created [] while creating it ... Declare the rule with a static @Bean method ...`(exit 78) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` | -| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES` 추가 | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). inbound adapter가 그 유스케이스를 부르면 architectureTest 실패 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 호출자(scheduler 등)에 넘긴다. `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd` · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java` | +| B-14 | prod 프로필에서 `fixture-`로 시작하는 비밀값을 거부(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/` 참조 대상. `HOSTNAME`·앱 이름 같은 비밀 아닌 값은 보지 않는다 — RR2-04-01). Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로 | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` | +| B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다. 두 타입의 클래스는 `@Value`·`@Autowired`·`@Inject`·`@Resource` 멤버, `@PostConstruct`·`@PreDestroy`, `@ConfigurationProperties`를 가질 수 없다(post-processor보다 먼저 만들어져 비어 있게 된다, RR2-04-03) | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule '<이름>' created [] while creating it ... Declare the rule with a static @Bean method ...`, 위 멤버가 있으면 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one: [...]`(둘 다 exit 78, 후자는 모든 프로필) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 값은 `violations(Environment)`가 받는 `Environment`에서 읽는다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` | +| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르면 architectureTest 실패 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 호출자(scheduler 등)에 넘기거나, 메시지 handler면 handler에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다(매뉴얼 09장 「소비」 4단계). `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd` · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` | | B-17 | `IntegrationEventDraft`: `eventId`·`causationId`는 소문자 UUIDv7만. ArchUnit `INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`: `new IntegrationEventDraft<>(...)` 금지, `IntegrationEventDrafts.draft(...)`만 | 이벤트를 만드는 쓰기 요청이 `IllegalArgumentException: eventId must be a canonical lower-case UUIDv7...`로 실패. architectureTest 실패 | event id를 UUIDv7로 만든다(예: sample `UuidOutboxEventIdFactory`가 `UuidCreator.getTimeOrderedEpochPlus1()`). draft는 헬퍼로 만든다. tenant가 없는 이벤트는 `IntegrationEventDrafts.SINGLE_TENANT_SCOPE`(`global`) | `1400dc15`, `bbe944bd` · `src/application-core/.../messaging/event/IntegrationEventDraft.java`, `IntegrationEventDrafts.java` | | B-18 | `MessageHandler.schemaVersions()`(vendored `messaging-core-api`, default `{v1}`): 소비자 decode 목록을 handler 선언으로 만든다. 같은 (메시지 타입, 버전)에 다른 payload class를 선언하면 실패 | 컴파일은 된다. v1이 아닌 메시지는 `SCHEMA_VERSION_NOT_REGISTERED`로 거부. 발행 등록(`MessageContracts`)과 class가 다르면 기동 실패 `MESSAGING_CONTRACT_CONFLICT` | v2 이상을 읽는 handler는 `schemaVersions()`를 override한다. 소비 타입을 `MessageContracts`에 따로 등록하던 코드는 지운다 | `5786126c` · `src/messaging/messaging-core-api/.../delivery/MessageHandler.java`, `messaging-spring-boot-starter/.../MessageContracts.java` | | B-19 | `APP_FLYWAY_ENABLED`가 모든 프로필에서 읽힌다. dev·prod 프로필 파일의 `spring.flyway.enabled: true`·`app.persistence.vendor` 고정값을 지우고 persistence-jpa `config/module-defaults`가 `${APP_FLYWAY_ENABLED:true}`를 싣는다 | dev·prod 환경에 `APP_FLYWAY_ENABLED=false`가 있으면 전에는 무시됐지만 이제 기동 때 마이그레이션이 안 돈다 | dev·prod 환경 값을 확인한다. 자기 `application-dev.yml`·`application-prod.yml`에 같은 고정값을 다시 넣지 않는다 | `5786126c` · `src/app-bootstrap/src/main/resources/application-{dev,prod}.yml`, `src/adapter/outbound/persistence-jpa/.../module-defaults/persistence-jpa.yml` | @@ -75,10 +76,10 @@ | B-21 | 트랜잭션 제한: `TransactionPort` 쓰기·읽기 트랜잭션 30초(`app.persistence-jpa.transaction.write-timeout`·`read-timeout`, env 키 아님) | 30초를 넘는 트랜잭션은 문장이 취소되고 `DB_QUERY_CANCELED`로 실패 | 긴 일괄 작업은 쪼갠다. 꼭 필요하면 프로필 yml에서 값을 올린다 | `1400dc15` · `persistence-jpa.yml` | | B-22 | 격리 수준을 Hikari에서 고정: `spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED`. 다른 값이면 거부. `TransactionPort`는 트랜잭션마다 격리 수준을 정하지 않는다 | 다른 격리 수준을 설정했다면 기동 실패(`HikariPoolConstraintValidator`) | 값을 지운다. 더 높은 격리가 필요한 곳은 따로 설계한다 | `1400dc15` · `src/adapter/outbound/persistence-jpa/.../startup/HikariPoolConstraintValidator.java` | | B-23 | H2 드라이버가 운영 jar에서 빠짐(persistence-jpa `runtimeOnly` → `testRuntimeOnly`). `bootRunH2` 작업만 따로 넣는다 | `APP_PERSISTENCE_VENDOR=h2`로 `bootRunH2` 밖에서 띄우면 드라이버가 없다(정확한 오류 확인 못 함) | 로컬은 Compose PostgreSQL 또는 `bootRunH2`를 쓴다 | `1400dc15` · `src/adapter/outbound/persistence-jpa/build.gradle` | -| B-24 | `APP_IDEMPOTENCY_PROCESSING_LEASE`는 2초(`IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER`)보다 길어야 한다 | 2초 이하면 기동 실패 | 값을 2초보다 길게(기본 30s) | `5786126c`, `bbe944bd` · `src/composition/idempotency/.../IdempotencySettings.java` | +| B-24 | `APP_IDEMPOTENCY_PROCESSING_LEASE`는 2초(`IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER`)보다 길어야 한다. `APP_IDEMPOTENCY_TTL`(replay TTL)은 그 lease보다 짧으면 안 된다(재리뷰 RR-03-11) | 2초 이하면, 또는 replay TTL < lease면 기동 실패 | lease를 2초보다 길게(기본 30s), replay TTL을 lease 이상으로(기본 24h) | `5786126c`, `bbe944bd`, 3차 수정 · `src/composition/idempotency/.../IdempotencySettings.java` | | B-25 | 알림 콜백 본문 상한 65508 → 65251(바인딩에서 상한 검사) | `.env`에 옛 예제 값 `APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES=65508`이 있으면 기동 실패 `max-body-bytes must be 1..65251` | 값을 지우거나 65251 이하로 | `5786126c` · `src/adapter/outbound/notification/.../autoconfigure/NotificationPlatformSettings.java` | | B-26 | `config/module-defaults/`에 같은 이름 파일이 둘이거나, 두 파일이 같은 키를 실으면 기동 실패 | 기동 실패 `two capability modules ship config/module-defaults/` 또는 `... both ship `(exit 78) | 자기 leaf의 module-defaults 파일 이름·키가 템플릿 모듈과 겹치지 않게 한다 | `1400dc15` · `src/adapter/outbound/support/.../startup/ModuleDefaultsEnvironmentPostProcessor.java` | -| B-27 | (sample-portfolio를 남겨 둔 경우) 데모 계정은 활성 프로필이 모두 `local`·`test`·`demo` 중 하나일 때만. 프로필이 없어도 거부 | 기동 실패 `the sample's demo accounts authenticate only under the local, test or demo profile` | `SPRING_PROFILES_ACTIVE=local` 등으로 띄우거나 sample 보안 설정을 지운다 | `5786126c`, `bbe944bd` · `src/sample-portfolio/.../security/SampleDemoAccountsProductionGuard.java` | +| B-27 | (sample-portfolio를 남겨 둔 경우) 데모 계정은 활성 프로필이 모두 `local`·`test`·`demo` 중 하나일 때만. 프로필이 없어도 거부 | 기동 실패 `the sample's demo accounts authenticate only under the local, test or demo profile` | `SPRING_PROFILES_ACTIVE=demo`(이미지·jar), `local`(bootRun)로 띄우거나 sample 보안 설정을 지운다. 세 프로필 모두 sample `application.yml`이 object storage를 끈다(RR2-04-02) | `5786126c`, `bbe944bd` · `src/sample-portfolio/.../security/SampleDemoAccountsProductionGuard.java` | ### 3.3 HTTP wire — 응답이 달라진다 @@ -88,7 +89,7 @@ |---|---|---|---|---| | B-28 | 처리 중 409 `IDEMPOTENT_IN_FLIGHT`: `retryable` false→true, `Retry-After: 2` 추가. gRPC trailer `error-retryable`과 GraphQL extension `retryable`도 true | 409를 "재시도 금지"로 처리하던 클라이언트가 틀린다 | **같은 `Idempotency-Key`로** `Retry-After` 뒤 재전송하게 한다. 새 키 금지 | `34565130` · `src/shared-contract/.../error/OperationalError.java`, `docs/registries/error-codes.yaml` | | B-29 | Envelope의 `null` 필드를 키째 생략: 성공은 `error` 키 없음, 실패는 `data` 키 없음, `meta.page`·`meta.correlationId`·`error.details`도 값이 없으면 키 없음. 빈 목록은 그대로 | `"error": null`·`"data": null`을 기대하던 클라이언트·계약 테스트가 깨진다 | `success`로 가르고 키 존재로 판단하지 않는다 | `34565130` · `src/adapter/inbound/web/.../envelope/EnvelopeWireFormatConfig.java` | -| B-30 | 새 코드 `IDEMPOTENCY_COMPLETION_UNKNOWN`(503, `TRANSIENT_DEPENDENCY`, retryable=true): 작업 실행 **뒤** complete 단계에서 멱등성 저장소가 응답하지 않음. 전에는 `IDEMPOTENCY_UNAVAILABLE` | 503을 "적용 안 됨"으로 읽던 클라이언트가 새 키로 다시 보내 중복이 생길 수 있다 | `error.code`로 가른다. 결과 불명이므로 같은 키로만 재전송 | `bbe944bd` · `src/application-core/.../idempotency/IdempotencyCompletionUnknownException.java`, `IdempotencyExecutor.java` | +| B-30 | 새 코드 `IDEMPOTENCY_COMPLETION_UNKNOWN`(503, `TRANSIENT_DEPENDENCY`, retryable=true): 작업 실행 **뒤** complete 단계에서 멱등성 저장소가 응답하지 않음. 전에는 `IDEMPOTENCY_UNAVAILABLE` | 503을 "적용 안 됨"으로 읽던 클라이언트가 새 키로 다시 보내 중복이 생길 수 있다 | `error.code`로 가른다. 결과 불명이므로 같은 키로만 재전송. 실행 중 lease가 지난 기록은 두 저장소 모두 500 `IDEMPOTENCY_RECOVERY_REQUIRED`로 답한다 — Redis 저장소는 전에 넘겨받아 작업을 다시 돌렸다(재리뷰 RR-01-11) | `bbe944bd`, 3차 수정 · `src/application-core/.../idempotency/IdempotencyCompletionUnknownException.java`, `IdempotencyExecutor.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java` | | B-31 | 핸들러 밖 오류(`/error` 디스패치)를 `EnvelopeErrorController`가 실패 Envelope로 답한다. 전에는 Boot `/error` 맵이 `success:true`로 감싸져 요청 경로까지 실려 나갔다. 기본 JWT 체인에서 익명 400이 401로 바뀌지 않는다. 4xx·5xx 본문은 `success:true`로 감싸지 않는다. 보안 체인이 `DispatcherType.ERROR`를 허용한다 | 오류 본문 모양이 바뀐다. 자기 SecurityFilterChain이 ERROR 디스패치를 막으면 400이 401로 나간다 | 자기 체인에 `auth.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()`을 넣는다(템플릿 `SecurityConfig`와 같게) | `bbe944bd` · `src/adapter/inbound/web/.../error/EnvelopeErrorController.java`, `.../auth/SecurityConfig.java` | | B-32 | 새·바뀐 오류 코드: 비동기 요청 timeout 500 `INTERNAL_ERROR` → 503 `REQUEST_TIMEOUT`(retryable). `IDEMPOTENCY_KEY_INVALID` 400(`details.reason`=`MISSING`·`MALFORMED`, `IdempotencyKeyHeader.parse`를 쓰는 엔드포인트, sample은 `BAD_PARAMETER`에서 바뀜). web-advanced 예외 10종이 모두 500 `INTERNAL_ERROR`였다가 각자 코드(`ADMISSION_REFUSED` 503 등) | 코드로 분기하던 클라이언트가 새 코드를 모른다 | 클라이언트 분기표에 더한다. web-advanced 표는 `src/adapter/inbound/web-advanced/README.md` 「오류 응답」 | `1400dc15` · `src/adapter/inbound/web/.../error/WebTransportError.java`, `HttpStatusErrorCodes.java`, `src/adapter/inbound/web-advanced/.../error/WebAdvancedError.java` | | B-33 | DB 실패 분류: 낙관적 잠금 충돌 500 → 409 `DB_OPTIMISTIC_CONFLICT`. 커밋 단계 연결 끊김(08xxx, 40003 등)을 재시도 가능으로 답하던 것 → 500 `DB_COMPLETION_UNKNOWN`(retryable=false) | 응답 status·code가 바뀐다 | 409는 다시 읽고 재시도, `DB_COMPLETION_UNKNOWN`은 업무 데이터로 결과를 확인 | `34565130`, `1400dc15` · `src/adapter/outbound/persistence-jpa/.../failure/PersistenceExceptionTranslator.java` | @@ -99,7 +100,7 @@ |---|---|---|---|---| | B-34 | 템플릿 패키지 규칙(ArchUnit): `FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`, `TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`. 템플릿 이름: application `usecase command query capability transaction security tenant observability secret messaging outbox idempotency operation lease lock cache realtime notification fileserver objectstorage`, domain `identifier stereotype` | 기능 패키지 이름이 이 목록과 겹치거나(예: `domain.lock`), 업무 코드를 템플릿 패키지(예: `application.usecase.*`)에 두고 기능 패키지를 import하면 `:app-bootstrap:architectureTest` 실패 | 기능 패키지 이름을 바꾸고, 업무 코드를 `dev.caskeleton.application.`로 옮긴다. 규칙 정본은 `src/application-core/CLAUDE.md` "Package ownership" | `5786126c` · `src/app-bootstrap/src/architectureTest/.../TemplatePackageOwnership.java` | | B-35 | JPA 규칙: 양방향 연관은 한쪽에서만 매핑(`mappedBy`), notification·fileserver 저장소 엔티티는 그 leaf 안에서만, `@Version` 엔티티의 bulk update는 version을 올려야 함 | 위반 엔티티·쿼리가 있으면 architectureTest 실패 | 매핑·쿼리를 고친다 | `34565130`, `1400dc15`, `bbe944bd` · `src/app-bootstrap/src/architectureTest/.../JpaProductionArchitectureTest.java` | -| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c` · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` | +| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. 명령의 빌드는 `working-directory`(단계·job·workflow `defaults`)와 `-p`를 합친 디렉터리로 정하고, `workflow_dispatch`로만 시작하는 workflow의 명령은 세지 않으며, 축약한 `-x`도 Gradle처럼 맞춰 본다(RR2-04-04). `verifyEnvKeys`: lane 계약 json의 `APP_` 밖 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_`이거나 `secret://…/`가 가리키는 변수여야 하고, 레지스트리 `property:` 행은 그 property가 설정 metadata에 있어야 읽히는 것으로 친다(`@ConditionalOnProperty`로만 읽는 스위치는 `META-INF/additional-spring-configuration-metadata.json`에 선언, RR2-04-05). SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다. `working-directory: src` 없이 `./gradlew`를 부르는 자기 workflow 단계는 실행으로 세지 않는다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. 단계를 부르는 workflow 명령에 `working-directory`를 둔다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c` · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` | | B-37 | app-bootstrap 테스트 lane 분리: 저장소 파일을 읽는 테스트는 태그 `document-contract`(main 단계) 또는 `repository-contract`(`check`)여야 하고, 일반 `test` lane에는 `ca.repository.root`가 없다 | app-bootstrap에 둔 자기 테스트가 저장소 파일을 읽으면 `test`에서 실패 | 태그를 단다 | `1400dc15` · `src/app-bootstrap/build.gradle` | ### 3.5 모듈 registry·새 leaf @@ -114,26 +115,37 @@ | stream (history 표) | 버전 | 하는 일 | 기존 데이터 영향 | 실패 조건 | 근거 | |---|---|---|---|---|---| -| postgresql (`flyway_schema_history`, persistence-jpa 선택 시) | V20 | `outbox_event.deferred_attempt_count INTEGER NOT NULL DEFAULT 0` + CHECK ≥ 0 | 기존 행 0. 지난 claim은 전부 시도 예산에 센다 | 확인된 것 없음 | `1400dc15` | +| postgresql (`flyway_schema_history`, persistence-jpa 선택 시) | V20 | `outbox_event.deferred_attempt_count INTEGER NOT NULL DEFAULT 0` + CHECK ≥ 0 | 기존 행 0. 지난 claim은 전부 시도 예산에 센다 | `outbox_event`를 건드린 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V19에 남음(exit 70) | `1400dc15`, 3차 수정(RR-02-09) | | 〃 | V21 | `outbox_aggregate_sequence`(aggregate별 counter), `outbox_aggregate_sequence_floor`(V21 적용 시각 마이크로초 한 행), 남은 행 최대 번호로 counter 미리 생성, 유일 인덱스 `ux_outbox_event_aggregate_order (tenant_scope, aggregate_type, aggregate_id, aggregate_sequence, event_index)` | 새로 생기는 aggregate의 첫 번호가 floor+1(약 1.7×10¹⁵)부터. 순서 열이 NULL인 옛 행은 비교 안 함 | ① 같은 순서 키 행이 이미 둘 이상 → 실패, V21 전체 롤백, V20에 남음(exit 70). ② `SET LOCAL lock_timeout = '5s'` 안에 `outbox_event` 잠금을 못 잡으면 실패·롤백. ③ 같은 이름 인덱스가 유효한 유일 인덱스가 아니면(실패한 CONCURRENTLY) `RAISE EXCEPTION` | `1400dc15`, `bbe944bd` · `docs/runbooks/outbox-dead-letter.md` §8 | -| 〃 | V22 | `outbox_event.last_failure_code VARCHAR(120)` NULL, 기본값 없음. 새 상태 `PARKED`는 DDL 없음 | 행 재작성 없음. 기존 행은 다음 실패 때까지 NULL | 확인된 것 없음 | `bbe944bd` | -| notification (`flyway_jpa_notification_history`, notification-platform 선택 시) | V11 | `notification_reconciliation_job.claimed_until timestamptz`, `claim_fence bigint NOT NULL DEFAULT 0` + CHECK | 기존 job은 fence 0, lease 없음 | 확인된 것 없음 | `34565130` | -| 〃 | V12 | `notification_suppression`의 `(tenant_id, normalized_target_hmac, reason)` 중복 행을 **삭제**(만료 없는 것 > 늦은 만료 > 이른 `effective_at` > 이른 `created_at` > 작은 id 순으로 하나 남김) 후 UNIQUE `uk_notification_suppression_target` | 지운 행의 `SuppressionId`는 더 이상 조회되지 않는다. 되돌리려면 백업 필요 | 확인된 것 없음(잠금 대기 제한 없음) | `1400dc15` | -| 〃 | V13 | `notification_request.acceptance varchar(40) NOT NULL DEFAULT 'ACCEPTED'` + CHECK(`ACCEPTED`, `DROPPED_AS_DUPLICATE`) | 기존 요청은 모두 `ACCEPTED` | 확인된 것 없음 | `5786126c` | -| sample (`flyway_sample_schema_history`, sample-portfolio를 남긴 경우) | V8_1 | 유일 인덱스 `uq_poster_title_ci ON poster (upper(title))` | 없음 | 대소문자만 다른 제목이 있으면 `poster has titles that differ only by case or repeat: ...`로 실패 | `34565130` | -| grpc-ledger (optional-platforms, history 표 확인 못 함) | V002 | 부분 인덱스 `ix_grpc_operation_ledger_finished_completed_at` (일반 `CREATE INDEX`) | 없음 | 큰 ledger면 만드는 동안 쓰기가 멈춘다. 파일 주석은 손으로 `CONCURRENTLY`를 먼저 돌리라고 한다 | `1400dc15` | -| 〃 | V003 | `grpc_operation_ledger.claim_attempt BIGINT NOT NULL DEFAULT 1` + CHECK > 0 | 기존 행은 첫 시도(1) | 확인된 것 없음 | `bbe944bd` | +| 〃 | V22 | `outbox_event.last_failure_code VARCHAR(120)` NULL, 기본값 없음. 새 상태 `PARKED`는 DDL 없음 | 행 재작성 없음. 기존 행은 다음 실패 때까지 NULL | `outbox_event`를 건드린(읽기만 한 것도) 트랜잭션이 열려 있어 5초(`SET LOCAL lock_timeout`) 안에 잠금을 못 잡으면 실패·롤백, V21에 남음(exit 70) | `bbe944bd`, 3차 수정(RR-02-09) | +| notification (`flyway_jpa_notification_history`, notification-platform 선택 시) | V11 | `notification_reconciliation_job.claimed_until timestamptz`, `claim_fence bigint NOT NULL DEFAULT 0` + CHECK | 기존 job은 fence 0, lease 없음 | 그 표를 건드린 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V10에 남음(exit 70) | `34565130`, 3차 수정(RR-02-09) | +| 〃 | V12 | `notification_suppression`의 `(tenant_id, normalized_target_hmac, reason)` 중복 행을 **삭제**(만료 없는 것 > 늦은 만료 > 이른 `effective_at` > 이른 `created_at` > 작은 id 순으로 하나 남김) 후 UNIQUE `uk_notification_suppression_target` | 지운 행의 `SuppressionId`는 더 이상 조회되지 않는다. 되돌리려면 백업 필요 | 그 표를 건드린 트랜잭션이 열려 있어 5초 안에 잠금(행 잠금 포함)을 못 잡으면 실패·롤백(삭제도 롤백), V11에 남음(exit 70) | `1400dc15`, 3차 수정(RR-02-09) | +| 〃 | V13 | `notification_request.acceptance varchar(40) NOT NULL DEFAULT 'ACCEPTED'` + CHECK(`ACCEPTED`, `DROPPED_AS_DUPLICATE`) | 기존 요청은 모두 `ACCEPTED` | 그 표를 건드린 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V12에 남음(exit 70) | `5786126c`, 3차 수정(RR-02-09) | +| sample (`flyway_sample_schema_history`, sample-portfolio를 남긴 경우) | V8_1 | 유일 인덱스 `uq_poster_title_ci ON poster (upper(title))` | 없음 | 대소문자만 다른 제목이 있으면 `poster has titles that differ only by case or repeat: ...`로 실패. `poster`에 쓴 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V8에 남음 | `34565130`, 3차 수정(RR-02-09) | +| grpc-ledger (optional-platforms, history 표 확인 못 함) | V002 | 부분 인덱스 `ix_grpc_operation_ledger_finished_completed_at` (일반 `CREATE INDEX`) | 없음 | 큰 ledger면 만드는 동안 쓰기가 멈춘다. 파일 주석은 손으로 `CONCURRENTLY`를 먼저 돌리라고 한다. ledger에 쓴 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V001에 남음 | `1400dc15`, 3차 수정(RR-02-09) | +| 〃 | V003 | `grpc_operation_ledger.claim_attempt BIGINT NOT NULL DEFAULT 1` + CHECK > 0 | 기존 행은 첫 시도(1) | ledger를 건드린 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V002에 남음 | `bbe944bd`, 3차 수정(RR-02-09) | - **새로 연결된 stream**: `adapter:inbound:messaging`을 `runtimeOnly`로 넣으면 platform의 `V1101__messaging_inbox.sql`을 `MessagingInboxSchemaStream`이 `flyway_messaging_inbox_history`에 적용한다(baseline 1100). 넣지 않으면 영향 없음 (`src/adapter/inbound/messaging/README.md`). +- **잠금 대기 상한(3차 수정, RR-02-09)**: 위 표에서 이미 쓰이는 테이블을 잠그는 마이그레이션은 모두 그 잠금 앞에 + `SET LOCAL lock_timeout = '5s'`를 둔다. 실패하면 SQLState `55P03`이고, 열린 트랜잭션을 끝낸 뒤 다시 배포한다 + (`docs/runbooks/migration-failed.md` "Classify the failure"). 자기 스트림에도 같은 규칙과 검사 + (`LockWaitMigrationInspector`, 예: `SampleMigrationLockWaitTest`)를 둔다(`docs/jpa/migration-guide.md` "Bound the lock wait"). - **번호 충돌**: 템플릿이 이제 postgresql V20~V22, notification V11~V13, sample V8_1, grpc V002·V003을 쓴다. 파생 서비스가 같은 위치에 같은 번호를 두었다면 Flyway가 같은 버전 두 개로 실패한다. 자기 마이그레이션은 템플릿과 떨어진 번호대로 옮긴다 (이미 적용된 파일 이름을 바꾸면 checksum·history가 어긋나므로 운영 DB에 적용된 것이면 DB 담당과 정한다). - **migration-on-startup=false로 운영하는 서비스**: `infra/postgres/apply-capability-streams.sh`가 바뀌었다(stream을 `/flyway/streams/`에서 먼저 찾음). 운영자가 직접 적용한다. -### 4.2 이 브랜치의 이전 V21을 적용한 DB +### 4.2 이 브랜치의 이전 V21(과 3차 수정 전 V20·V22·V11~V13·V8_1·V002·V003)을 적용한 DB + +3차 수정(RR-02-09)은 이 브랜치가 더한 마이그레이션 중 이미 쓰이는 테이블을 잠그는 여덟 개(postgresql V20·V22, +notification V11·V12·V13, sample V8_1, grpc-ledger V002·V003)에 `SET LOCAL lock_timeout`을 넣으려고 파일을 직접 +고쳤다. V21과 같은 전제(어느 배포에도 적용되지 않음)다. 그 이전 내용을 적용한 개발 DB도 아래 V21과 같이 checksum +불일치로 기동이 실패하므로 다시 만든다. 새 checksum은 `applied-migrations.sha256`에 있다(sample·grpc-ledger는 고정 목록 +없음). + V21은 `bbe944bd`에서 V22를 따로 두지 않고 직접 고쳤다(floor 표와 counter 미리 만들기를 넣음). `1400dc15`·`5786126c` 시점의 V21(sha256 `f830cda5…`)을 적용한 DB는 새 V21(sha256 `21744ea1…`, `src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256`)과 @@ -182,7 +194,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | 영역 | 바뀐 것 | 영향 | 근거 | |---|---|---|---| -| outbox relay | 일시 거부(`REJECTED_RETRYABLE`)·무응답(`AMBIGUOUS`)은 시도 예산을 쓰지 않고 최대 5분 간격(`OutboxBackoffPolicy.MAX_DELAY`)으로 끝없이 재시도. 실패 원인 코드를 `last_failure_code`에 남김. 수동 보류 상태 `PARKED`. 지표 `outbox.retry.long.size`·`outbox.retry.long.age` | 진짜 인증 오류도 DEAD가 아니라 계속 재시도한다. 경보는 새 지표로 잡는다. 처분 SQL은 `docs/runbooks/outbox-dead-letter.md`·`outbox-publish-failed.md` | `34565130`, `1400dc15`, `bbe944bd` | +| outbox relay | 일시 거부(`REJECTED_RETRYABLE`)·무응답(`AMBIGUOUS`)은 시도 예산을 쓰지 않고 최대 5분 간격(`OutboxBackoffPolicy.MAX_DELAY`)으로 끝없이 재시도. 실패 원인 코드를 `last_failure_code`에 남김. 수동 보류 상태 `PARKED`. 지표 `outbox.retry.long.size`·`outbox.retry.long.age`. claim이 DEAD로 옮긴 행(`ATTEMPT_COUNTERS_INCONSISTENT`·`UNREADABLE_ROW`)도 그 이유를 `last_failure_code`에 쓰고, 경보에 `outbox.pending.size{status=DEAD}` > 0을 더함(RR-02-12). 이 버전이 모르는 상태 값은 `outbox.pending.size`에서 빼고 WARN 한 번(RR-02-11) | 진짜 인증 오류도 DEAD가 아니라 계속 재시도한다. 경보는 새 지표로 잡는다. 처분 SQL은 `docs/runbooks/outbox-dead-letter.md`·`outbox-publish-failed.md` | `34565130`, `1400dc15`, `bbe944bd` | | outbox append | 읽기 전용 트랜잭션 안의 `append`도 거부(`CallerTransaction.requireReadWrite`). 전에는 트랜잭션 밖만 거부했고 읽기 전용에서는 이벤트가 조용히 사라졌다 | `inRead` 안에서 이벤트를 쓰던 코드가 이제 예외로 드러난다 | `5786126c` · `JpaOutboxStore.java` | | 순서 번호 | aggregate 순서 번호를 DB counter가 매긴다(`OutboxAggregateSequencePort.nextSequence`). 한 aggregate에 이벤트가 하나면 `AggregateOrder.first()`. 같은 순서 키 두 번째 append는 유일 인덱스가 거부(정확한 오류 코드 확인 못 함) | 소비자가 보는 번호가 새 aggregate에서 floor+1부터 시작해 크게 뛴다. 벽시계로 번호를 만들던 코드는 바꾼다 | `1400dc15`, `bbe944bd` | | durable operation | operation id가 UUIDv7(`UuidV7DurableOperationIdFactory`). 제출 이벤트의 event id·aggregate id가 UUIDv7이고 tenant scope는 `global` | 전에는 이 이벤트가 messaging bridge에서 전부 DEAD가 됐다(커밋 `1400dc15` 본문). 소비자가 보는 id 모양이 바뀐다 | `1400dc15`, `bbe944bd` · `SubmitDurableOperationUseCase.java` | @@ -192,7 +204,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | GraphQL | 크기를 선언하지 않은 list를 원소 20개로 계산, `first`·`last` 둘 다면 큰 쪽. per-parent 경고 임계 10(`APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD`). deadline instrumentation이 `REQUEST_TIMEOUT` | 전에 통과하던 깊은 목록 쿼리가 복잡도로 거부될 수 있다. 필요한 필드에 `estimatedListSize`를 선언 | `34565130`, `1400dc15`, `bbe944bd` | | WebSocket | 노드당 STOMP 세션 1000개(`APP_WEBSOCKET_MAX_CONNECTIONS`), 초과 시 연결 후 1013으로 닫음. 메시지 64KB, 송신 버퍼 512KB, 송신 시간 10s, 첫 메시지 60s를 명시 | 동시 연결이 많은 서비스는 상한을 올린다 | `1400dc15` · `env-keys.yaml` | | gRPC 서버(inbound adapter) | 수신 메시지 1 MiB(io.grpc 기본 4 MiB에서 줄어듦), 메타데이터 8 KiB, 연결당 동시 호출 100, 실행 스레드 32·대기열 256, 기본 deadline 10s, keepalive 30s/10s, 최대 연결 수명 30분, drain 2s | 1 MiB를 넘는 메시지는 거부된다 | `1400dc15` · `src/adapter/inbound/grpc/.../GrpcServerSettings.java` | -| 파일 서버 | 정리 worker 기본 켜짐(`APP_FILESERVER_PLATFORM_CLEANUP_ENABLED` false→true, 끄면 기동 경고). copy·move 대상은 기본 namespace만(`APP_FILESERVER_PLATFORM_TARGET_NAMESPACES`, 그 밖은 `ACCESS_DENIED`). namespace 쿼터 상한(`APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT`, 비우면 무제한, 넘으면 413 `QUOTA_EXCEEDED`). move가 쿼터를 옮긴다 | 다른 namespace로 copy·move하던 서비스는 허용 목록을 설정해야 한다. 정리 worker가 물리 객체를 지운다 | `5786126c`, `bbe944bd` · `CopyFileApplicationUseCase.java`, `env-keys.yaml` | +| 파일 서버 | 정리 worker 기본 켜짐(`APP_FILESERVER_PLATFORM_CLEANUP_ENABLED` false→true, 끄면 기동 경고). copy·move 대상은 기본 namespace만(`APP_FILESERVER_PLATFORM_TARGET_NAMESPACES`, 그 밖은 `ACCESS_DENIED`). namespace 쿼터 상한(`APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT`, 비우면 무제한, 넘으면 413 `QUOTA_EXCEEDED`). move가 쿼터를 옮긴다 | 다른 namespace로 copy·move하던 서비스는 허용 목록을 설정해야 한다. 정리 worker가 물리 객체를 지운다. 이 수정 전에 다른 namespace로 move된 파일의 바이트는 여전히 출발 namespace 사용량에 잡혀 있고 도착 namespace에는 없다 — 그 파일을 지우면 도착 namespace에서 회수되어(0에서 멈춘다) 출발 쪽은 그대로 남는다. 상한을 켜기 전에 `docs/fileserver/operations.md` 「Namespace quota drift」의 쿼리로 namespace별 차이를 보고, 있으면 같은 절의 재계산 SQL로 고친다(쓰기를 멈춘 뒤, 재리뷰 RR-01-17) | `5786126c`, `bbe944bd` · `CopyFileApplicationUseCase.java`, `env-keys.yaml` | | 알림 | SES 콜백 replay 허용 차이 5m→1h. 중복 제거 창에서 버린 제출을 `CANCELED`·`DROPPED_AS_DUPLICATE`로 저장해 같은 멱등성 키에 같은 영수증. reconciliation job은 DB lease로 소유. INGEST_ONLY도 accept 때 route 이름 기록 | 콜백·영수증 결과가 바뀐다 | `34565130`, `5786126c` | | Redis | 캐시 조건부 쓰기가 자기 SCRIPT lane(`APP_CACHE_REDIS_MAXIMUM_SCRIPT_CONNECTIONS`, 기본 4)을 쓴다. registry에서 `redis.capability.*` 지표 6개를 빼고 `redis.lane.*` 6개를 더했다 | Redis 연결이 캐시 lane만큼 늘어난다. 옛 지표 이름으로 만든 대시보드·경보는 바꾼다 | `bbe944bd` · `docs/registries/metrics.yaml` | | 설정 바인딩 | strict 설정에서 선택 숫자·크기·기간 키의 빈 값은 "미설정". 목록 원소 아래 오타 키도 거부(`StrictSettingsBinder`) | `.env.example`의 빈 값으로 기동 가능. 목록 원소 아래 오타는 이제 기동 실패 | `5786126c` · `StrictSettingsBinder.java` | diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index 3e8c1f9b..de18900b 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -56,9 +56,16 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). ** 컨트롤러에 닿기 전에 거부된 요청(보안 방화벽이 막은 경로, 필터의 `sendError`, 필터가 던진 예외)도 같은 실패 Envelope다. 컨테이너가 `/error`로 넘긴 요청을 `EnvelopeErrorController`가 status에 맞는 코드로 답한다. -본문에 요청 경로나 시각을 싣지 않는다. 원래 status가 그대로 나가고, 기본 JWT 체인에서도 익명 400이 401로 -바뀌지 않는다(재리뷰 RR-02-02). 다만 요청 id 필터를 지나기 전에 끊긴 응답은 `meta`의 id 키가 빠질 수 있다. -클라이언트는 `meta`의 모르는 키를 무시한다. +본문에 요청 경로나 시각을 싣지 않는다. 기본 JWT 체인에서도 익명 400이 401로 바뀌지 않는다(재리뷰 RR-02-02). +다만 요청 id 필터를 지나기 전에 끊긴 응답은 `meta`의 id 키가 빠질 수 있다. 클라이언트는 `meta`의 모르는 키를 +무시한다. + +status는 코드 표(`HttpStatusErrorCodes`)에 있는 것만 그대로 나간다: 401·403·404·405·406·412·413·414·415·429·503. +표에 없는 status는 그 class의 코드로 접힌다 — 4xx(408·409·410·422 등)는 `BAD_PARAMETER` 400, 5xx(501·502·504 +등)는 `INTERNAL_ERROR` 500(재리뷰 RR-01-13, `EnvelopeErrorControllerTest`). `error.code`와 status가 registry +(`docs/registries/error-codes.yaml`)와 어긋나지 않게 하려는 것이다. 클라이언트는 status가 아니라 `error.code`로 +가르기 때문이다. 필터가 다른 status를 내야 하면 `sendError` 대신 그 status의 코드로 `EnvelopeResponseWriter`를 +쓰거나, 표에 행을 더한다. 4xx·5xx status로 나가는 본문은 `success:true`로 감싸지 않는다. 실패 Envelope가 아닌 본문을 오류 status로 돌려주는 핸들러는 그 본문이 그대로 나간다. @@ -105,13 +112,19 @@ JSON 응답은 모두 `Envelope` 하나의 모양이다(소유자 결정 2). ** | 작업 실행 뒤 결과 기록(complete 단계) 중 저장소 응답 없음 — **결과 불명** | 503 | `IDEMPOTENCY_COMPLETION_UNKNOWN` | `true` | 없음 | "적용되지 않았다"고 알리지 않는다. **같은 키로** 나중에 다시 보낸다. 새 키 금지 | | 이전 시도의 효과를 증명할 수 없음 | 500 | `IDEMPOTENCY_RECOVERY_REQUIRED` | `false` | 없음 | 재전송도 재실행도 안전하지 않다. 업무 데이터로 결과를 확인한다 | -- **결과 불명이 무엇을 뜻하나.** 작업은 이미 돌았다. 그 작업의 트랜잭션 안 DB 변경은 예외와 함께 - 롤백되지만, 트랜잭션 밖 효과(다른 시스템 호출, 메시지)는 일어났을 수 있다. 그래서 실행 전 거부와 같은 +- **결과 불명이 무엇을 뜻하나.** 작업은 이미 돌았다. 유스케이스가 executor를 쓰기 트랜잭션 안에서 + 불렀다면 그 트랜잭션의 DB 변경은 예외와 함께 롤백된다. 작업이 자기 트랜잭션을 따로 커밋했다면 그 변경은 + 남는다. 트랜잭션 밖 효과(다른 시스템 호출, 메시지)는 일어났을 수 있다. 그래서 실행 전 거부와 같은 503이어도 code가 다르다. 클라이언트는 status가 아니라 `error.code`로 가른다. -- **같은 키로 다시 보내면 서버가 판정한다.** 결과가 실제로는 기록됐으면 재생(첫 요청의 성공 응답), 첫 시도의 - processing lease가 아직 남았으면 409 `IDEMPOTENT_IN_FLIGHT`, lease가 지났으면 500 - `IDEMPOTENCY_RECOVERY_REQUIRED`다. 새 키로 보내면 서버는 다른 요청으로 보고 막지 못한다 - (재리뷰 2026-11-03 README 4절 결정, RR-02-03). +- **같은 키로 다시 보내면 서버가 판정하고, 작업을 다시 돌리지 않는다.** 결과가 실제로는 기록됐으면 + 재생(첫 요청의 성공 응답), 첫 시도의 processing lease(`processing-lease`, 기본 30s)가 아직 남았으면 409 + `IDEMPOTENT_IN_FLIGHT`, lease가 지났으면 500 `IDEMPOTENCY_RECOVERY_REQUIRED`다. lease가 지난 실행 기록을 다음 + 요청이 만나면 두 저장소(PostgreSQL·Redis) 모두 넘겨주지 않고 포기(abandoned)로 표시한다 — 그 뒤 첫 시도가 + 늦게 끝나도 결과는 기록되지 않고 그 요청도 500을 받는다. 새 키로 보내면 서버는 다른 요청으로 보고 막지 못한다 + (재리뷰 2026-11-03 README 4절 결정 RR-02-03, 2026-11-04 9.1절 결정 RR-01-11). +- **서버가 기억하는 기간.** 완료된 응답은 완료부터 `replay-ttl`(기본 24h), 끝나지 않은 시도의 기록은 + claim부터 processing lease + `replay-ttl` 동안 남는다. 그 뒤 같은 키는 새 요청으로 실행된다. + `replay-ttl`이 `processing-lease`보다 짧으면 기동이 실패한다(재리뷰 2026-11-04 RR-03-11). ## 3. 헤더 diff --git a/infra/redis-sdk/acl/README.md b/infra/redis-sdk/acl/README.md index 0117e9b1..6c20d498 100644 --- a/infra/redis-sdk/acl/README.md +++ b/infra/redis-sdk/acl/README.md @@ -8,9 +8,12 @@ a real Redis, that line alone gives anyone who can reach the server and read thi control of it (`CONFIG`, `MODULE`, every key). A deployment writes its own ACL file of the same shape: the application accounts it actually uses, passwords from its secret store, and none of the lane-only accounts (review 2026-11-03 RR-07-04). The application enforces its half of that: under -the `prod` runtime profile it refuses to start while any setting or environment variable holds a -value beginning with `fixture-` (`SecretSourceValidator`), so a deployment that copied a lane's -`REDIS_LANE_*` values stops before it connects. +the `prod` runtime profile it refuses to start while a secret holds a value beginning with +`fixture-` (`SecretSourceValidator`): a key the secrets registry classifies `secret`, or the +variable a `secret://…/` credential reference names. A deployment that copied a lane's +`APP_REDIS_AUTHENTICATION_*_REFERENCE` and `REDIS_LANE_*` values stops before it connects. Values +that are not secrets — a pod's `HOSTNAME`, an application name — are not read, because `fixture-` +is an ordinary word as well. One file per `CommandAccess` level. Each account is deliberately narrower than the SDK's own rules: the account is the last enforcement boundary and a permit issued inside the process never widens it, diff --git a/src/.env.example b/src/.env.example index 200bb942..e1b49131 100644 --- a/src/.env.example +++ b/src/.env.example @@ -121,6 +121,7 @@ APP_RATE_LIMIT_REFILL_TOKENS=100 APP_RATE_LIMIT_REFILL_PERIOD=1s APP_RATE_LIMIT_MAXIMUM_COST=10 APP_RATE_LIMIT_CLEANUP_GRACE=5s +# Replay TTL: at most 72h and not shorter than APP_IDEMPOTENCY_PROCESSING_LEASE (startup fails). APP_IDEMPOTENCY_TTL=24h # disabled | redis | postgresql. postgresql refuses a non-PostgreSQL data source, so bootRunH2 # runs with disabled or redis. @@ -294,7 +295,8 @@ APP_GRAPHQL_PER_PARENT_FETCH_WARNING_THRESHOLD=10 # Optional build-composition: these bind only when :adapter:inbound:websocket is present. # The default bootJar does not contain that leaf. APP_WEBSOCKET_ENABLED=true -# Explicit offs for two more capabilities that are on when present (the Compose lanes set them). +# Switches for two more capabilities that are on when present: `true` here is their default, and +# `false` is the explicit off the Compose lanes set. APP_OBJECTSTORAGE_ENABLED=true APP_GRPC_SERVER_ENABLED=true APP_WEBSOCKET_ENDPOINT=/ws diff --git a/src/Dockerfile.sample b/src/Dockerfile.sample index 7c04fa00..064714f5 100644 --- a/src/Dockerfile.sample +++ b/src/Dockerfile.sample @@ -5,14 +5,20 @@ # Builds and runs the REFERENCE app (SamplePortfolioApplication), not the # production composition root (CaSkeletonApplication) that src/Dockerfile builds. # The sample is the demo-friendly entrypoint: its application.yml self-provides -# defaults for every env placeholder, so the only external dependency it needs -# to boot is a reachable PostgreSQL (datasource + Flyway sample migrations). +# defaults for every env placeholder, so what it needs to boot is a demo profile +# and a reachable PostgreSQL (datasource + Flyway sample migrations). +# +# The profile is not baked in. The demo accounts (a published admin password) start only under an +# explicitly active `demo`, `local` or `test` profile (SampleDemoAccountsProductionGuard), and an +# image that defaulted to one would carry them into any deployment that ran it as is. Without +# SPRING_PROFILES_ACTIVE the container stops with exit code 71 and says so. # # Build (no build-args required — this is a disposable demo, not a release artifact): # docker build -f src/Dockerfile.sample src/ -t ca-sample:local # # Run (point APP_DATASOURCE_URL at a reachable Postgres; localhost default shown): # docker run --rm -p 8080:8080 -p 9001:9001 \ +# -e SPRING_PROFILES_ACTIVE=demo \ # -e APP_DATASOURCE_URL=jdbc:postgresql://host.docker.internal:5432/ca_skeleton \ # ca-sample:local # diff --git a/src/README.md b/src/README.md index 5e77ea3c..a1ffcf78 100644 --- a/src/README.md +++ b/src/README.md @@ -236,7 +236,8 @@ drift하기 시작하면 그때 자동화합니다. 진짜 항목을 상대로, `postgresql` 은 PostgreSQL data source 가 아니면 기동을 거부하므로 `bootRunH2` 에서는 `disabled` 나 `redis` 를 씁니다. - **`APP_IDEMPOTENCY_TTL`** — 완료 응답을 재생할 수 있는 기간(`replay-ttl`). duration(예: `24h`). - 최대 72h 이고 넘으면 기동을 거부합니다. (D6) + 최대 72h 이고 넘으면 기동을 거부합니다. (D6) `APP_IDEMPOTENCY_PROCESSING_LEASE`(기본 30s)보다 + 짧아도 기동을 거부합니다. ### Async executor diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java index 71a9c11b..d00ea632 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java @@ -23,7 +23,10 @@ import java.time.Duration; * @param maxFragments most accepted fragment definitions * @param maxInputListElements most accepted elements in one input list * @param defaultPageSize page size used for cost when a connection omits {@code first}/{@code last} - * @param maxPageSize largest accepted page size + * @param maxPageSize largest accepted page size. This record only holds the two numbers; the page a + * resolver serves is decided by {@code GraphQlConnectionPolicy.effectivePageSize} and the page + * a document is charged for by the complexity scorer — one rule each, not a third copy here + * (review 2026-11-03 RR-01-14) * @param maxComplexity largest accepted pre-execution complexity score * @param maxExecutionTime request execution budget * @param introspectionAllowed whether this profile may run introspection @@ -92,20 +95,6 @@ public record GraphQlClientPolicy( false); } - /** - * The effective page size for a connection request. - * - *

        An omitted {@code first}/{@code last} must cost the default page size rather than one, or a - * client could bypass the cost budget simply by leaving the argument out. - */ - public int effectivePageSize(Integer first, Integer last) { - int requested = first != null ? first : last != null ? last : defaultPageSize; - if (requested < 1) { - throw new IllegalArgumentException("page size must be positive"); - } - return requested; - } - private static void requirePositive(long value, String name) { if (value < 1) { throw new IllegalArgumentException(name + " must be positive"); diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionAssemblerTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionAssemblerTest.java index 09b63d6f..a3217aa2 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionAssemblerTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionAssemblerTest.java @@ -91,6 +91,18 @@ class GraphQlConnectionAssemblerTest { .hasMessageContaining("exceeds the maximum"); } + /** The {@code last} case of the page-size rule that used to be copied in the client policy. */ + @Test + void aBackwardPageIsSizedByItsLastAndAnOmittedOneByTheDefault() { + var policy = GraphQlConnectionPolicy.from(clientPolicy()); + + assertThat( + List.of( + policy.effectivePageSize(GraphQlConnectionRequest.backward(30, null)), + policy.effectivePageSize(GraphQlConnectionRequest.backward(null, null)))) + .containsExactly(30, 20); + } + @Test void totalCountIsOptInRatherThanAlwaysComputed() { var connection = diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicyTest.java index cb3dbed2..785d02e4 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicyTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicyTest.java @@ -38,15 +38,6 @@ class GraphQlClientPolicyTest { .isInstanceOf(IllegalArgumentException.class); } - @Test - void omittedPageSizeCostsTheDefaultRatherThanOne() { - GraphQlClientPolicy policy = policy(65536, 20, 100, Duration.ofSeconds(5)); - - assertThat(policy.effectivePageSize(null, null)).isEqualTo(20); - assertThat(policy.effectivePageSize(50, null)).isEqualTo(50); - assertThat(policy.effectivePageSize(null, 30)).isEqualTo(30); - } - @Test void productionProfileCanRequireNamedOperations() { GraphQlClientPolicy publicProfile = diff --git a/src/adapter/inbound/messaging/CLAUDE.md b/src/adapter/inbound/messaging/CLAUDE.md index 44f14572..a13b56d8 100644 --- a/src/adapter/inbound/messaging/CLAUDE.md +++ b/src/adapter/inbound/messaging/CLAUDE.md @@ -10,6 +10,9 @@ else: the platform decodes what its `destination()` and `schemaVersions()` declare. - Boundaries: no business rule in a handler (HARD-STOP 4); no persistence entity or repository; no broker SDK type. Allowed edges come only from the registry entry. +- A handler that calls a write use case is `@SystemCaller(reason = ...)` and constructs the + `@SystemInvoked` use case itself; the use case is never a bean (manual 09 「소비」 step 4, + `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`). - Tests: focused auto-configuration and inbox behavior tests; `./gradlew :adapter:inbound:messaging:check`. The real Kafka + PostgreSQL redelivery lane is `messagingInboxRedeliveryIntegrationTest` (`:integrationCheck`). diff --git a/src/adapter/inbound/messaging/README.md b/src/adapter/inbound/messaging/README.md index 042b5d84..3443f2a8 100644 --- a/src/adapter/inbound/messaging/README.md +++ b/src/adapter/inbound/messaging/README.md @@ -31,6 +31,10 @@ Kafka ─▶ platform consumer (starter-kafka) 만든다. platform은 애플리케이션의 datasource·트랜잭션을 스스로 고르지 않는다는 기존 설계를 그대로 둔다. - 애플리케이션의 handler(`MessageHandler` 구현)는 이 leaf에 둔다. 컨트롤러가 HTTP 요청을 use case 호출로 바꾸듯 delivery를 use case 호출 하나로 바꾸는 inbound adapter다. 업무 규칙은 use case에 둔다. +- 쓰기 use case를 부르는 handler는 `@SystemCaller(reason = ...)`이고, `@SystemInvoked` use case를 생성자에서 + `new`로 만들어 혼자 든다. use case는 bean이 아니다. 소비 스레드에는 인증이 없어 `@RequiresPermission` + use case는 매번 거부되기 때문이다. 작업 순서는 `docs/manual/09-outbox-events.md` 「소비」 4단계, 규칙은 + 07장 「시스템이 부르는 쓰기」(리뷰 2026-11-03 RR-01-12, 결정 9.1). ## 추가할 한 줄 @@ -85,7 +89,8 @@ app: destination: order-events-dlq ``` -handler 예시는 `MessagingInboxAutoConfigurationTest#exampleHandler`다. +handler 예시: 쓰기 use case를 부르는 모양은 `SystemInvokedConsumePathTest`의 `OrderCreatedHandler`, 실제 Kafka + +PostgreSQL에서 같은 모양은 `InboxRedeliveryIntegrationTest`의 `ProjectionHandler`다. ## 고른 방법과 버린 대안 @@ -96,6 +101,19 @@ handler 예시는 `MessagingInboxAutoConfigurationTest#exampleHandler`다. (HARD-STOP 4). - 버림: `adapter:outbound:messaging`(발행 bridge)에 소비까지 넣기 — 발행 bridge는 `messaging-core-api`만 보는 anti-corruption 경계이고, 소비는 inbound 방향이다. +- 고름(RR-01-12): handler가 `@SystemCaller`를 달고 `@SystemInvoked` use case를 직접 `new`로 만든다. 사용자 + 요청이 들어오는 전송(web·GraphQL·gRPC·WebSocket)만 그 use case에 닿지 못하고, 표시는 ArchUnit이 검사한다 + (`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`: messaging·scheduler inbound 패키지에만, 사용자 전송 + 타입에 의존하지 않음). 기동 가드는 바꾸지 않는다: `@SystemInvoked` bean은 예외 없이 실패다. + - 버림: use case를 bean으로 두고 가드에 "handler만 주입받으면 허용" 예외 — 누가 주입받는지는 기동 때 + 확정되지 않는다(`ObjectProvider`, `getBean`, 나중에 추가된 bean). 예외 조건이 곧 우회 경로가 된다. + - 버림: handler는 `CommandUseCase` 인터페이스만 받고 조립 모듈이 `new`로 넣기 — 소비자마다 composition + 모듈이 필요하거나 app-bootstrap에 업무 조립이 들어간다(위 HARD-STOP 4). 조립 클래스도 결국 그 use case + 클래스에 의존한다. + - 버림: ArchUnit 대상에서 messaging 패키지를 통째로 빼기 — 클래스에 표시가 없어 의도가 안 보이고, 그 + 패키지의 아무 클래스(HTTP endpoint 포함)나 닿는다. + - 버림: 사용자 전송 패키지만 나열해 금지 — 나중에 새 전송이 생기면 조용히 열린다. 규칙은 "닿아도 되는 + 쪽"을 적는다. - 버림: application-core에 소비 포트를 새로 만들어 platform `MessageHandler`로 감싸는 범용 bridge — payload 타입 매핑과 결과 매핑 규칙을 먼저 정해야 해서 이번 범위보다 크다. 지금은 handler가 직접 use case를 부른다. @@ -104,12 +122,17 @@ handler 예시는 `MessagingInboxAutoConfigurationTest#exampleHandler`다. - 단위: `MessagingInboxAutoConfigurationTest` — 조립 조건, inbox 마이그레이션 stream 조립 스위치, runner의 커밋·롤백, in-memory inbox로 중복 1회. decode 목록은 starter `MessagingConsumeConfigurationTest`. +- 단위: `SystemInvokedConsumePathTest` — 이 leaf의 inbox와 `composition:service-runtime`의 권한 가드를 함께 + 띄워, `@SystemCaller` handler가 만든 `@SystemInvoked` use case로 기동하고 같은 delivery 두 번에 쓰기가 + 한 번인지, use case를 bean으로 두면 기동이 실패하는지 본다. - 실제 Kafka + PostgreSQL: `InboxRedeliveryIntegrationTest`(lane `messagingInboxRedeliveryIntegrationTest`). Kafka capability, outbox relay, persistence-jpa, 이 leaf를 auto-configuration으로 띄운다. 앱 relay가 PostgreSQL outbox 행을 Kafka로 발행하고, 소비자가 inbox 예약과 업무 쓰기를 한 JPA 트랜잭션에서 한다. - offset을 0으로 되감고 다시 띄워 같은 레코드를 다시 읽혀도 handler 호출 1회, 업무 행 1개, inbox 행 1개. - handler가 업무 쓰기 뒤 예외를 던지면 예약과 쓰기가 함께 롤백되고, platform 재시도에서 다시 처리돼 handler 호출 2회, 업무 행 1개, inbox 행 1개. + - handler는 4단계 모양(`@SystemCaller` + 직접 만든 `@SystemInvoked` use case)이고, `composition:service-runtime`이 + classpath에 있어 서비스와 같은 권한 가드 아래에서 기동한다. - 소비 leaf가 기동하면 inbox 마이그레이션만 `flyway_messaging_inbox_history`에 적용되고 platform outbox 표는 생기지 않는다. - 테스트는 payload 타입을 등록하지 않고 inbox 표도 만들지 않는다 — 서비스가 받는 그대로다. diff --git a/src/adapter/inbound/messaging/build.gradle b/src/adapter/inbound/messaging/build.gradle index c3de3ac8..11ed657a 100644 --- a/src/adapter/inbound/messaging/build.gradle +++ b/src/adapter/inbound/messaging/build.gradle @@ -46,6 +46,12 @@ dependencies { implementation 'org.springframework:spring-tx' testImplementation 'org.springframework.boot:spring-boot-starter-test' + // The consume path a service runs (review 2026-11-03 RR-01-12): the permission guard every + // service takes from composition:service-runtime, the typed startup failure it raises, and the + // transaction port's fake. Test edges are outside the registry gate. + testImplementation project(':composition:service-runtime') + testImplementation project(':adapter:outbound:support') + testImplementation testFixtures(project(':application-core')) } testing { @@ -73,7 +79,6 @@ dependencies { integrationTestImplementation project(':adapter:outbound:persistence-jpa') integrationTestImplementation project(':application-core') integrationTestImplementation testFixtures(project(':application-core')) - integrationTestImplementation project(':shared-contract') integrationTestImplementation project(':messaging:messaging-core-api') integrationTestImplementation project(':messaging:messaging-spring-boot-starter') integrationTestImplementation 'org.springframework:spring-jdbc' diff --git a/src/adapter/inbound/messaging/gradle.lockfile b/src/adapter/inbound/messaging/gradle.lockfile index 30469b12..fb62ebfa 100644 --- a/src/adapter/inbound/messaging/gradle.lockfile +++ b/src/adapter/inbound/messaging/gradle.lockfile @@ -1,6 +1,7 @@ # This is a Gradle generated file for dependency locking. # Manual edits can break the build and are not advised. # This file is expected to be part of source control. +aopalliance:aopalliance:1.0=integrationTestRuntimeClasspath,testRuntimeClasspath at.yawk.lz4:lz4-java:1.10.1=integrationTestRuntimeClasspath biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=integrationTestCompileClasspath,testCompileClasspath ch.qos.logback:logback-classic:1.5.38=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -14,6 +15,7 @@ com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,integrationTest com.github.docker-java:docker-java-api:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath com.github.docker-java:docker-java-transport-zerodep:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath com.github.docker-java:docker-java-transport:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath +com.github.f4b6a3:uuid-creator:6.1.1=integrationTestRuntimeClasspath,testRuntimeClasspath com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.github.luben:zstd-jni:1.5.6-10=integrationTestRuntimeClasspath com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs @@ -53,9 +55,28 @@ commons-logging:commons-logging:1.3.6=compileClasspath,integrationTestCompileCla info.picocli:picocli:4.7.7=checkstyle io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor +io.micrometer:context-propagation:1.2.1=integrationTestRuntimeClasspath,testRuntimeClasspath io.micrometer:micrometer-commons:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath +io.micrometer:micrometer-jakarta9:1.16.7=integrationTestRuntimeClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-tracing-bridge-otel:1.6.7=integrationTestRuntimeClasspath,testRuntimeClasspath +io.micrometer:micrometer-tracing:1.6.7=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry.semconv:opentelemetry-semconv:1.37.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-api:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-common:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-context:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-common:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-otlp-common:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-sender-jdk:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-common:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-logs:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-metrics:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-trace:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk:1.55.0=integrationTestRuntimeClasspath,testRuntimeClasspath io.projectreactor:reactor-core:3.8.7=integrationTestRuntimeClasspath jakarta.activation:jakarta.activation-api:2.1.4=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -68,7 +89,7 @@ jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy-agent:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -net.logstash.logback:logstash-logback-encoder:8.0=integrationTestRuntimeClasspath +net.logstash.logback:logstash-logback-encoder:8.0=integrationTestRuntimeClasspath,testRuntimeClasspath net.minidev:accessors-smart:2.6.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath net.minidev:json-smart:2.6.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs @@ -109,7 +130,7 @@ org.glassfish.jaxb:jaxb-core:4.0.9=integrationTestRuntimeClasspath org.glassfish.jaxb:jaxb-runtime:4.0.9=integrationTestRuntimeClasspath org.glassfish.jaxb:txw2:4.0.9=integrationTestRuntimeClasspath org.hamcrest:hamcrest:3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.hdrhistogram:HdrHistogram:2.2.2=integrationTestRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=integrationTestRuntimeClasspath,testRuntimeClasspath org.hibernate.models:hibernate-models:1.0.1=integrationTestRuntimeClasspath org.hibernate.orm:hibernate-core:7.2.24.Final=integrationTestRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle @@ -125,7 +146,7 @@ org.junit.platform:junit-platform-engine:6.0.3=integrationTestRuntimeClasspath,t org.junit.platform:junit-platform-launcher:6.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs -org.latencyutils:LatencyUtils:2.0.3=integrationTestRuntimeClasspath +org.latencyutils:LatencyUtils:2.0.3=integrationTestRuntimeClasspath,testRuntimeClasspath org.mockito:mockito-core:5.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,mockitoAgent,testCompileClasspath,testRuntimeClasspath org.mockito:mockito-junit-jupiter:5.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.objenesis:objenesis:3.3=integrationTestRuntimeClasspath,testRuntimeClasspath @@ -150,21 +171,30 @@ org.slf4j:jul-to-slf4j:2.0.18=integrationTestCompileClasspath,integrationTestRun org.slf4j:slf4j-api:2.0.18=integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springframework.boot:spring-boot-actuator:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-actuator-autoconfigure:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-actuator:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor org.springframework.boot:spring-boot-data-commons:4.0.8=integrationTestRuntimeClasspath org.springframework.boot:spring-boot-data-jpa:4.0.8=integrationTestRuntimeClasspath org.springframework.boot:spring-boot-flyway:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-health:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-hibernate:4.0.8=integrationTestRuntimeClasspath org.springframework.boot:spring-boot-http-converter:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-jackson:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-jdbc:4.0.8=integrationTestRuntimeClasspath org.springframework.boot:spring-boot-jpa:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-metrics:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-observation:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-tracing-opentelemetry:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-tracing:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-opentelemetry:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-persistence:4.0.8=integrationTestRuntimeClasspath org.springframework.boot:spring-boot-resttestclient:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-servlet:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-sql:4.0.8=integrationTestRuntimeClasspath +org.springframework.boot:spring-boot-starter-actuator:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-data-jpa:4.0.8=integrationTestRuntimeClasspath org.springframework.boot:spring-boot-starter-flyway:4.0.8=integrationTestRuntimeClasspath org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -172,6 +202,8 @@ org.springframework.boot:spring-boot-starter-jackson:4.0.8=integrationTestCompil org.springframework.boot:spring-boot-starter-jdbc:4.0.8=integrationTestRuntimeClasspath org.springframework.boot:spring-boot-starter-json:4.0.8=integrationTestRuntimeClasspath org.springframework.boot:spring-boot-starter-logging:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-micrometer-metrics:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-security:4.0.8=integrationTestRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-test:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-tomcat:4.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -190,6 +222,10 @@ org.springframework.data:spring-data-commons:4.0.7=integrationTestRuntimeClasspa org.springframework.data:spring-data-jpa:4.0.7=integrationTestRuntimeClasspath org.springframework.integration:spring-integration-core:7.0.6=integrationTestRuntimeClasspath org.springframework.integration:spring-integration-jdbc:7.0.6=integrationTestRuntimeClasspath +org.springframework.security:spring-security-config:7.0.7=integrationTestRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-core:7.0.7=integrationTestRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-crypto:7.0.7=integrationTestRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-web:7.0.7=integrationTestRuntimeClasspath,testRuntimeClasspath org.springframework:spring-aop:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-aspects:7.0.9=integrationTestRuntimeClasspath org.springframework:spring-beans:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/src/adapter/inbound/messaging/src/integrationTest/java/dev/caskeleton/adapter/inbound/messaging/InboxRedeliveryIntegrationTest.java b/src/adapter/inbound/messaging/src/integrationTest/java/dev/caskeleton/adapter/inbound/messaging/InboxRedeliveryIntegrationTest.java index 0670293e..527e3fe0 100644 --- a/src/adapter/inbound/messaging/src/integrationTest/java/dev/caskeleton/adapter/inbound/messaging/InboxRedeliveryIntegrationTest.java +++ b/src/adapter/inbound/messaging/src/integrationTest/java/dev/caskeleton/adapter/inbound/messaging/InboxRedeliveryIntegrationTest.java @@ -3,9 +3,15 @@ package dev.caskeleton.adapter.inbound.messaging; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.testkit.OutboxEvents; +import dev.caskeleton.application.security.SystemCaller; +import dev.caskeleton.application.security.SystemInvoked; +import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.messaging.api.MessageId; import dev.caskeleton.messaging.api.MessageType; @@ -14,8 +20,6 @@ import dev.caskeleton.messaging.api.delivery.MessageDelivery; import dev.caskeleton.messaging.api.delivery.MessageHandler; import dev.caskeleton.messaging.api.destination.DestinationName; import dev.caskeleton.messaging.api.destination.MessageDestination; -import dev.caskeleton.shared.concurrency.DomainContextPropagator; -import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -60,8 +64,11 @@ import org.testcontainers.postgresql.PostgreSQLContainer; * from the PostgreSQL outbox and publishes it through the platform bridge; the platform consumer * decodes it and, because the destination declares {@code INBOX_TRANSACTIONAL}, runs the handler * inside the inbox this leaf assembles — the platform's JDBC inbox over the application datasource - * and a runner over the application's (JPA) transaction manager. The handler writes its effect the - * way a use case does, through the application's {@code TransactionPort}. + * and a runner over the application's (JPA) transaction manager. The handler is the shape manual 09 + * 「소비」 step 4 teaches (review 2026-11-03 RR-01-12): a {@code @SystemCaller} that constructs the + * {@code @SystemInvoked} write use case it calls, which writes through the application's {@code + * TransactionPort}. {@code composition:service-runtime} is on the classpath as it is in a service, + * so its permission guard looks at this context and lets it start: the use case is not a bean. * *

        What only this lane can show is that those parts share one transaction for real: a JDBC inbox * that took a connection of its own, or a runner over a different transaction manager, passes every @@ -387,7 +394,15 @@ class InboxRedeliveryIntegrationTest { } } - /** A use case's write, in the application's transaction (joined, never opened beside it). */ + /** + * A write only the consumer calls, in the application's transaction (joined, never opened beside + * it). No permission: the consumer thread has no {@code Authentication}. + */ + @SystemInvoked(reason = "the lane's consumer calls it for each delivery") + @UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.NOT_IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) static final class RecordProjection { private final TransactionPort transactions; private final JdbcTemplate jdbc; @@ -407,14 +422,18 @@ class InboxRedeliveryIntegrationTest { } } - /** The shape of an application handler: one delivery, one use case call. */ + /** + * The shape of an application handler: one delivery, one use case call. It constructs its use + * case from the ports its bean method receives, so the use case is never a bean. + */ + @SystemCaller(reason = "the platform consumer calls it for each lane delivery") static final class ProjectionHandler implements MessageHandler { private final Handled handled; private final RecordProjection useCase; - ProjectionHandler(Handled handled, RecordProjection useCase) { + ProjectionHandler(Handled handled, TransactionPort transactions, JdbcTemplate jdbc) { this.handled = handled; - this.useCase = useCase; + this.useCase = new RecordProjection(transactions, jdbc); } @Override @@ -445,14 +464,7 @@ class InboxRedeliveryIntegrationTest { @Bean ProjectionHandler projectionHandler( Handled handled, TransactionPort transactions, DataSource dataSource) { - return new ProjectionHandler( - handled, new RecordProjection(transactions, new JdbcTemplate(dataSource))); - } - - /** What composition:service-runtime gives a service; the JPA audit context reads it. */ - @Bean - DomainContextPropagator domainContextPropagator() { - return new ThreadLocalDomainContextPropagator(); + return new ProjectionHandler(handled, transactions, new JdbcTemplate(dataSource)); } @Bean diff --git a/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/SystemInvokedConsumePathTest.java b/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/SystemInvokedConsumePathTest.java new file mode 100644 index 00000000..040d33fd --- /dev/null +++ b/src/adapter/inbound/messaging/src/test/java/dev/caskeleton/adapter/inbound/messaging/SystemInvokedConsumePathTest.java @@ -0,0 +1,286 @@ +package dev.caskeleton.adapter.inbound.messaging; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.security.SystemCaller; +import dev.caskeleton.application.security.SystemInvoked; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.composition.runtime.authorization.PermissionEnforcementConfig; +import dev.caskeleton.messaging.api.ContentType; +import dev.caskeleton.messaging.api.MessageEnvelope; +import dev.caskeleton.messaging.api.MessageId; +import dev.caskeleton.messaging.api.MessageType; +import dev.caskeleton.messaging.api.ProducerId; +import dev.caskeleton.messaging.api.SchemaVersion; +import dev.caskeleton.messaging.api.TraceContext; +import dev.caskeleton.messaging.api.delivery.DeliveryContext; +import dev.caskeleton.messaging.api.delivery.DeliveryMetadata; +import dev.caskeleton.messaging.api.delivery.HandleResult; +import dev.caskeleton.messaging.api.delivery.MessageDelivery; +import dev.caskeleton.messaging.api.delivery.MessageHandler; +import dev.caskeleton.messaging.api.destination.DestinationName; +import dev.caskeleton.messaging.api.destination.MessageDestination; +import dev.caskeleton.messaging.api.header.MessageHeaders; +import dev.caskeleton.messaging.inbox.IdempotentConsumer; +import dev.caskeleton.messaging.inbox.InboxMessageHandler; +import dev.caskeleton.messaging.reliability.InboxRepository; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import javax.sql.DataSource; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; + +/** + * The consume path manual 09 「소비」 step 4 teaches, assembled the way a service assembles it: this + * leaf's inbox, the permission guard every service runs ({@code composition:service-runtime}), and + * a handler that calls a write use case only the system calls (review 2026-11-03 RR-01-12, decision + * 9.1). + * + *

        The use case is {@code @SystemInvoked}: a consumer thread has no {@code Authentication}, so a + * permission gate would refuse every delivery. The handler is {@code @SystemCaller} and constructs + * the use case from the ports its bean method receives; the use case is never a bean, which is the + * one condition under which the guard lets a system-invoked use case into a running service. The + * architecture rules that check the marks run over production code in {@code + * :app-bootstrap:architectureTest}; this test checks that the same shape starts and runs. + */ +class SystemInvokedConsumePathTest { + + private static final Instant NOW = Instant.parse("2026-11-04T09:00:00Z"); + private static final DestinationName ORDERS = new DestinationName("order-events"); + + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + MessagingInboxAutoConfiguration.class, PermissionEnforcementConfig.class)) + .withBean(DataSource.class, () -> Mockito.mock(DataSource.class)) + .withBean(PlatformTransactionManager.class, NoTransactions::new) + .withBean(TransactionPort.class, DirectTransactionPort::new) + .withBean(InMemoryOrderProjections.class, InMemoryOrderProjections::new) + .withPropertyValues("app.runtime.migration-on-startup=false"); + + @Test + void aHandlerThatConstructsItsSystemInvokedUseCaseStartsUnderThePermissionGuard() { + // when + runner + .withUserConfiguration(OrderConsumerConfig.class) + .run( + context -> { + // then + assertThat(context) + .hasNotFailed() + .hasSingleBean(OrderCreatedHandler.class) + .doesNotHaveBean(ProjectOrderUseCase.class); + }); + } + + @Test + void aDeliveryReachesTheSystemInvokedUseCaseOnceThroughTheInbox() { + runner + .withUserConfiguration(OrderConsumerConfig.class) + .run( + context -> { + // given: the platform's inbox around the assembled handler, over this leaf's runner + IdempotentConsumer inbox = + new IdempotentConsumer( + new InMemoryInbox(), + context.getBean(IdempotentConsumer.TransactionRunner.class)); + MessageHandler consumer = + new InboxMessageHandler<>( + context.getBean(OrderCreatedHandler.class), + inbox, + "order-projection", + () -> NOW); + MessageDelivery delivery = delivery("o-1"); + consumer.handle(delivery).toCompletableFuture().join(); + + // when + consumer.handle(delivery).toCompletableFuture().join(); + + // then + assertThat(context.getBean(InMemoryOrderProjections.class).recorded) + .containsExactly("o-1"); + }); + } + + /** The way the guard refuses: the use case as a bean, which any transport could inject. */ + @Test + void registeringTheSystemInvokedUseCaseAsABeanFailsStartup() { + // when + runner + .withUserConfiguration(UseCaseAsABeanConfig.class) + .run( + context -> { + // then + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("never registered as a bean") + .hasMessageContaining(ProjectOrderUseCase.class.getName()); + }); + } + + private static MessageDelivery delivery(String orderId) { + return new MessageDelivery<>( + new MessageEnvelope<>( + MessageId.newId(), + new MessageType("order.created"), + new SchemaVersion(1), + NOW, + Optional.empty(), + new ProducerId("orders"), + Optional.empty(), + Optional.empty(), + ContentType.JSON, + Optional.empty(), + Optional.empty(), + Optional.empty(), + TraceContext.none(), + MessageHeaders.empty(), + orderId), + new DeliveryMetadata( + ORDERS, 1, false, Optional.empty(), Optional.empty(), Optional.empty(), NOW), + new DeliveryContext(NOW.plusSeconds(30), false, "order-projection")); + } + + /** The application's write port for the projection; this test owns it, so its fake is here. */ + interface OrderProjectionPort { + void record(String orderId); + } + + static final class InMemoryOrderProjections implements OrderProjectionPort { + private final List recorded = new ArrayList<>(); + + @Override + public void record(String orderId) { + recorded.add(orderId); + } + } + + /** A write only the consumer calls: no permission, because its caller has no Authentication. */ + @SystemInvoked(reason = "the order-events consumer calls it for each delivery") + @UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) + static final class ProjectOrderUseCase { + private final TransactionPort tx; + private final OrderProjectionPort projections; + + ProjectOrderUseCase(TransactionPort tx, OrderProjectionPort projections) { + this.tx = tx; + this.projections = projections; + } + + void project(String orderId) { + tx.inWrite( + () -> { + projections.record(orderId); + return null; + }); + } + } + + /** Manual 09 step 4: one delivery, one use case call; the handler owns its use case. */ + @SystemCaller(reason = "the platform consumer calls it for each order-events delivery") + static final class OrderCreatedHandler implements MessageHandler { + private final ProjectOrderUseCase useCase; + + OrderCreatedHandler(TransactionPort tx, OrderProjectionPort projections) { + this.useCase = new ProjectOrderUseCase(tx, projections); + } + + @Override + public MessageDestination destination() { + return new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class); + } + + @Override + public CompletionStage handle(MessageDelivery delivery) { + useCase.project(delivery.message().payload()); + return CompletableFuture.completedFuture(HandleResult.success()); + } + } + + @Configuration(proxyBeanMethods = false) + static class OrderConsumerConfig { + @Bean + OrderCreatedHandler orderCreatedHandler( + TransactionPort tx, InMemoryOrderProjections projections) { + return new OrderCreatedHandler(tx, projections); + } + } + + @Configuration(proxyBeanMethods = false) + static class UseCaseAsABeanConfig { + @Bean + ProjectOrderUseCase projectOrderUseCase( + TransactionPort tx, InMemoryOrderProjections projections) { + return new ProjectOrderUseCase(tx, projections); + } + + @Bean + OrderCreatedHandler orderCreatedHandler( + TransactionPort tx, InMemoryOrderProjections projections) { + return new OrderCreatedHandler(tx, projections); + } + } + + /** The inbox runner's transaction manager; the mocked datasource has nothing to open. */ + private static final class NoTransactions extends AbstractPlatformTransactionManager { + + private static final long serialVersionUID = 1L; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } + + private static final class InMemoryInbox implements InboxRepository { + private final Set reserved = new LinkedHashSet<>(); + + @Override + public boolean reserve(MessageId messageId, String consumerId, Instant now) { + return reserved.add(messageId.value() + "|" + consumerId); + } + + @Override + public boolean isProcessed(MessageId messageId, String consumerId) { + return reserved.contains(messageId.value() + "|" + consumerId); + } + + @Override + public int purgeProcessedBefore(Instant processedBefore, int limit) { + return 0; + } + } +} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorController.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorController.java index 2b60ccd8..7693316a 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorController.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorController.java @@ -28,6 +28,14 @@ import tools.jackson.databind.ObjectMapper; * status is classified by the same table the exception handler uses, and the body is the failure * envelope, with nothing from the request in it. * + *

        The status sent is the code's registered status. A status in {@link HttpStatusErrorCodes} + * keeps its value; any other folds into the code of its class — {@code BAD_PARAMETER} 400 for a + * 4xx, {@code INTERNAL_ERROR} 500 for a 5xx — so the {@code error.code} a client branches on never + * disagrees with the status beside it (review 2026-11-03 RR-01-13). Rejected: keeping the + * dispatched status beside the folded code, which is what Boot did but would send {@code + * BAD_PARAMETER} with a 409 the registry does not give it. A filter that needs another status + * writes that status's code with {@link EnvelopeResponseWriter} or adds a row to the table. + * *

        Written straight to the response by {@link EnvelopeResponseWriter}, like the other refusals * made outside a converter. An error dispatch has no handler of its own to negotiate for, and a * browser's {@code Accept: text/html} would otherwise turn the error into a 406 about the error. diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java new file mode 100644 index 00000000..074f8f8d --- /dev/null +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/EnvelopeErrorControllerTest.java @@ -0,0 +1,58 @@ +package dev.caskeleton.adapter.inbound.web.error; + +import static org.assertj.core.api.Assertions.assertThat; + +import jakarta.servlet.RequestDispatcher; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import tools.jackson.databind.ObjectMapper; + +/** + * Which status and code the container's error dispatch is answered with (review 2026-11-03 + * RR-01-13). A status in {@link HttpStatusErrorCodes} keeps its value; any other folds to the code + * of its class and that code's registered status, so the {@code error.code} a client branches on + * never disagrees with {@code docs/registries/error-codes.yaml}. + */ +class EnvelopeErrorControllerTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private final EnvelopeErrorController controller = new EnvelopeErrorController(mapper); + + @DisplayName("오류 디스패치 status: 표에 있으면 그대로, 없으면 4xx는 400·5xx는 500으로 접힌다") + @ParameterizedTest(name = "{0} → {1} {2}") + @CsvSource({ + "401, 401, UNAUTHENTICATED", + "404, 404, ROUTE_NOT_FOUND", + "429, 429, RATE_LIMIT_EXCEEDED", + "409, 400, BAD_PARAMETER", + "422, 400, BAD_PARAMETER", + "500, 500, INTERNAL_ERROR", + "502, 500, INTERNAL_ERROR", + "504, 500, INTERNAL_ERROR" + }) + void anErrorDispatchKeepsATabledStatusAndFoldsAnyOtherIntoItsClassCode( + int dispatched, int answered, String code) throws Exception { + // given + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/error"); + request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, dispatched); + MockHttpServletResponse response = new MockHttpServletResponse(); + + // when + controller.error(request, response); + + // then + assertThat( + List.of( + response.getStatus(), + mapper + .readTree(response.getContentAsString()) + .path("error") + .path("code") + .asString())) + .containsExactly(answered, code); + } +} diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 99026fa9..da0bd2e8 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -215,7 +215,7 @@ typed SDK's — tagged `lane=` (`RedisLaneMetrics`; rows in `docs/registri | --- | --- | --- | | `redis.lane.acquire.wait.seconds` (`outcome` = `admitted`/`refused`) | timer, histogram | how long a borrow queued for a connection; a growing admitted p99 comes before refusals | | `redis.lane.acquire.refused.total` (`reason` = `saturated`/`closing`/`interrupted`/`connect_failed`) | counter | a borrow that got no connection, nothing sent; `saturated` on `SCRIPT` is the starvation this lane exists to prevent | -| `redis.lane.connections.opened.total` | counter | new connections; after warm-up every one is a reconnect | +| `redis.lane.connections.opened.total` | counter | new connections; after warm-up a pooled lane opens one only to replace a discarded one. A routed lease (a Cluster `TRANSACTION` borrow) is opened for each borrow and closed after it without being counted as discarded, so on that lane a steady rate is normal use, not reconnects | | `redis.lane.connections.discarded.total` (`reason` = `invalidated`/`broken`) | counter | connections closed instead of pooled — `invalidated` is a timed-out or failed call (the lease is not reused), and is what the reconnects replace | | `redis.lane.connections.active`, `redis.lane.connections.pending` | gauge | connections lent out now; borrows waiting now | @@ -283,6 +283,18 @@ A lost renewal reply is recognised by what the renewal recorded — the revision the lease it asked for: the same lease is `ALREADY_RENEWED_SAME_OPERATION` with the current handle, a different lease is `OPERATION_CONFLICT`. +A lease that runs out is taken over only from a claim that never started or an attempt marked +retryable. A record still `EXECUTING` when its lease ran out has an unknown effect: the claim +program marks it `ABANDONED` and answers `RECOVERY_REQUIRED`, and the late holder can no longer +complete it. The PostgreSQL store answers the same; the shared `IdempotencyStoreContract` holds both +to it on a real server (re-review 2026-11-04 RR-01-11 — this store used to take the record over and +run the work a second time). + +The record key lives for the processing lease plus the replay TTL (`afterLease`, kept on the record), +and a renewal stretches it to the new lease plus that margin. With the replay TTL alone, a replay +TTL shorter than the lease dropped the key of a running operation and the next claim ran it again, +and one equal to the lease left no record to answer `RECOVERY_REQUIRED` from (RR-03-11). + Redis `TIME` determines lease deadlines. A failure after a command may have executed is returned as an indeterminate outcome; the adapter does not convert an ambiguous write into a clean unavailable result that would invite duplicate execution. @@ -334,8 +346,9 @@ Useful focused checks: ./gradlew architectureCheck ``` -`redisContainerContractTest` runs the cache-region and lease port contracts (the ones the in-memory -fakes pass) and the live semantic-port tests against a Redis it starts itself, under the standalone +`redisContainerContractTest` runs the cache-region, lease and idempotency-store port contracts (the +ones the in-memory fakes pass; the idempotency contract's timed cases run only here, on the server's +own clock) and the live semantic-port tests against a Redis it starts itself, under the standalone topology's ACL file. It is in `integrationCheck` (integration-main.yml's `integration-check` job), and only there: listing it in `mainCheck` as well ran it twice on every push to main. The image is `config/testing/container-images.properties` `redis`. diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java index 47e32400..7e47507c 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java @@ -30,19 +30,36 @@ public final class IdempotencyScripts { *

        The fingerprint is compared before anything else. Two different requests that hash to the * same idempotency scope are a client error, and treating the second as a replay of the first * would return somebody else's response. + * + *

        A lease that ran out is taken over only when nothing can have happened under it: a claim + * that never started, or an attempt its holder marked retryable. A record that was {@code + * EXECUTING} has an unknown effect, so it is abandoned and answered {@code RECOVERY_REQUIRED} — + * running it again is the duplicate this store exists to prevent, and it is what a client + * resending after a result-unknown 503 was promised would not happen (re-review 2026-11-04 + * RR-01-11). The PostgreSQL store answers the same; {@code IdempotencyStoreContract} holds both + * to it. + * + *

        The key lives for the lease plus the replay TTL ({@code afterLease}), not for the replay TTL + * alone. With the replay TTL alone, a replay TTL shorter than the lease dropped the key while the + * holder still ran and the next claim acquired it fresh — a second run (RR-03-11); and a replay + * TTL equal to the lease dropped it with the lease, leaving no record to answer "recovery + * required" from. {@code afterLease} is kept on the record so {@link #RENEW} can keep the same + * margin behind a lease it extends. */ private static final String CLAIM = """ local state = redis.call('HGET', KEYS[1], 'state') local t = redis.call('TIME') local nowMillis = (tonumber(t[1]) * 1000) + math.floor(tonumber(t[2]) / 1000) + local leaseMillis = tonumber(ARGV[6]) + local afterLease = tonumber(ARGV[7]) if state == false then redis.call('HSET', KEYS[1], 'state', 'CLAIMED', 'owner', ARGV[1], 'attempt', 1, 'rev', 1, 'op', ARGV[2], 'fp', ARGV[3], 'codec', ARGV[4], 'policy', ARGV[5], - 'leaseUntil', nowMillis + tonumber(ARGV[6])) - redis.call('PEXPIRE', KEYS[1], ARGV[7]) - return {'ACQUIRED', 1, 1, ARGV[1], '', tostring(nowMillis + tonumber(ARGV[6]))} + 'leaseUntil', nowMillis + leaseMillis, 'afterLease', afterLease) + redis.call('PEXPIRE', KEYS[1], leaseMillis + afterLease) + return {'ACQUIRED', 1, 1, ARGV[1], '', tostring(nowMillis + leaseMillis)} end local fingerprint = redis.call('HGET', KEYS[1], 'fp') if fingerprint ~= ARGV[3] then @@ -68,15 +85,23 @@ public final class IdempotencyScripts { redis.call('HGET', KEYS[1], 'leaseUntil')} end local leaseUntil = tonumber(redis.call('HGET', KEYS[1], 'leaseUntil')) - if state == 'FAILED_RETRYABLE' or (leaseUntil ~= nil and leaseUntil <= nowMillis) then - -- The previous holder's processing lease expired, or they marked the attempt retryable. - -- Taking over bumps the attempt so the new holder can tell it is not the first. + local leaseOver = leaseUntil ~= nil and leaseUntil <= nowMillis + if state == 'EXECUTING' and leaseOver then + -- The holder started and its lease ran out: whether the work took effect is unknown. + -- Abandon it, so the late holder cannot complete over the verdict, and keep the key's TTL: + -- the record stays as evidence for its remaining afterLease window. + redis.call('HSET', KEYS[1], 'state', 'ABANDONED', 'rev', rev + 1) + return {'RECOVERY_REQUIRED', attempt, rev + 1, owner, '', ''} + end + if state == 'FAILED_RETRYABLE' or (state == 'CLAIMED' and leaseOver) then + -- Nothing ran under the previous holder: they never started, or they marked the attempt + -- retryable. Taking over bumps the attempt so the new holder can tell it is not the first. redis.call('HSET', KEYS[1], 'state', 'CLAIMED', 'owner', ARGV[1], 'attempt', attempt + 1, 'rev', rev + 1, - 'op', ARGV[2], 'leaseUntil', nowMillis + tonumber(ARGV[6])) - redis.call('PEXPIRE', KEYS[1], ARGV[7]) + 'op', ARGV[2], 'leaseUntil', nowMillis + leaseMillis, 'afterLease', afterLease) + redis.call('PEXPIRE', KEYS[1], leaseMillis + afterLease) return {'TAKEN_OVER', attempt + 1, rev + 1, ARGV[1], '', - tostring(nowMillis + tonumber(ARGV[6]))} + tostring(nowMillis + leaseMillis)} end return {'IN_PROGRESS', attempt, rev, owner, '', tostring(leaseUntil - nowMillis)} """; @@ -142,11 +167,13 @@ public final class IdempotencyScripts { * the same renewal; with a different lease it is a different request, because confirming it would * leave the caller believing it holds the record for a lease the record does not carry. * - *

        The key's own TTL is stretched to cover the new lease. Claim sets it to the replay TTL, - * which may be shorter than a lease renewed past it; the key then expired while the holder was - * still executing, and the next request got a fresh claim and ran the side effect again (review - * 2026-11-03 RR-04-08). The TTL is only ever lengthened here — completion sets the replay TTL - * again. + *

        The key's own TTL is stretched to cover the new lease and the {@code afterLease} margin the + * claim recorded behind it, so a renewed lease ends with the same evidence window as the first. + * Without it a lease renewed past the key's TTL expired the key while the holder was still + * executing, and the next request got a fresh claim and ran the side effect again (review + * 2026-11-03 RR-04-08, re-review 2026-11-04 RR-03-11). A record claimed before {@code afterLease} + * existed has none and keeps only the lease. The TTL is only ever lengthened here — completion + * sets the replay TTL again. */ private static final String RENEW = """ @@ -183,9 +210,11 @@ public final class IdempotencyScripts { redis.call('HSET', KEYS[1], 'leaseUntil', nowMillis + tonumber(ARGV[4]), 'rev', rev + 1, 'renewedFromRev', ARGV[2], 'renewedLease', ARGV[4]) + local keep = tonumber(ARGV[4]) + + tonumber(redis.call('HGET', KEYS[1], 'afterLease') or '0') local ttl = redis.call('PTTL', KEYS[1]) - if ttl >= 0 and ttl < tonumber(ARGV[4]) then - redis.call('PEXPIRE', KEYS[1], ARGV[4]) + if ttl >= 0 and ttl < keep then + redis.call('PEXPIRE', KEYS[1], keep) end return {'APPLIED', attempt, rev + 1, owner, '', ''} """; diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java index 16af2059..c0bbb8c5 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java @@ -130,6 +130,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort request.responseCodecId(), Integer.toString(request.policyRevision()), Long.toString(request.processingLeaseTtl().toMillis()), + // How long the record outlives its lease: the key lives for both. Long.toString(request.replayTtl().toMillis())))), now), IdempotencyClaimOutcome.Unavailable::new, diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java index 48d09e4a..7b992580 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java @@ -353,8 +353,8 @@ class RedisIdempotencyStoreAdapterTest { } @Test - @DisplayName("lease를 넘겨받은 뒤 이전 owner는 renew할 수 없다") - void aTakenOverOwnerCannotRenew() { + @DisplayName("lease가 지나 다른 요청이 회복 필요로 판정한 실행은 이전 owner가 renew할 수 없다") + void anOwnerWhoseExpiredExecutionWasAbandonedCannotRenew() { // given IdempotencyOwner executing = executing(); gateway.advance(Duration.ofSeconds(60)); @@ -368,7 +368,26 @@ class RedisIdempotencyStoreAdapterTest { } @Test - @DisplayName("an expired processing lease can be taken over, and the attempt increments") + @DisplayName("lease가 지난 실행 중 기록은 넘겨주지 않고 회복 필요로 답한다") + void anExpiredExecutionIsAnsweredRecoveryRequiredNotTakenOver() { + // given + IdempotencyOwner executing = executing(); + gateway.advance(Duration.ofSeconds(60)); + + // when + IdempotencyClaimOutcome next = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION))); + + // then + // TAKEN_OVER would run work whose effect is unknown a second time. The live contract proves + // the program; this proves the fixture's copy of it agrees. + assertThat(next) + .isInstanceOfSatisfying( + IdempotencyClaimOutcome.RecoveryRequired.class, + recovery -> assertThat(recovery.currentAttempt()).isEqualTo(executing.attempt())); + } + + @Test + @DisplayName("an expired claim that never started can be taken over, and the attempt increments") void anExpiredLeaseIsTakenOver() { store.claim(claim(store.newClaimAttempt(OPERATION))); diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisServerTimeScriptContractTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisServerTimeScriptContractTest.java index a678f21e..2ee0ef98 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisServerTimeScriptContractTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisServerTimeScriptContractTest.java @@ -28,7 +28,10 @@ class RedisServerTimeScriptContractTest { String transition = script(IdempotencyScripts.class, "TRANSITION"); assertThat(claim).contains("redis.call('TIME')"); - assertThat(claim).contains("leaseUntil', nowMillis + tonumber(ARGV[6])"); + assertThat(claim).contains("local leaseMillis = tonumber(ARGV[6])"); + assertThat(claim).contains("leaseUntil', nowMillis + leaseMillis"); + // The key outlives the lease by the replay TTL (re-review 2026-11-04 RR-03-11). + assertThat(claim).contains("redis.call('PEXPIRE', KEYS[1], leaseMillis + afterLease)"); assertThat(transition).contains("redis.call('TIME')"); assertThat(transition).contains("leaseUntil', nowMillis + tonumber(ARGV[7])"); } diff --git a/src/adapter/outbound/httpclient/README.md b/src/adapter/outbound/httpclient/README.md index b80f46d8..f79afca1 100644 --- a/src/adapter/outbound/httpclient/README.md +++ b/src/adapter/outbound/httpclient/README.md @@ -43,9 +43,10 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d `HttpDeadlineExceededException`. A streaming download's setup (up to the response headers) runs inside the same deadline; after hand-over each body gap is bounded by `read-idle` and nothing else, on both transports — the JDK transport arms its own per-read timer for this, because the JDK client - has no socket read timeout. A body that fails after hand-over throws the same stable exceptions as - a buffered call (`HttpResponseTimeoutException` for a stalled body, `HttpResponseTruncatedException` - for a cut one). + has no socket read timeout. A body that fails after hand-over throws `HttpBodyReadException`, an + `IOException` as `InputStream.read` promises, whose `failure()` is the same stable exception a + buffered call throws (`HttpResponseTimeoutException` for a stalled body, + `HttpResponseTruncatedException` for a cut one). - **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or `PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it. - **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline, diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/api/error/HttpBodyReadException.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/api/error/HttpBodyReadException.java new file mode 100644 index 00000000..da25f976 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/api/error/HttpBodyReadException.java @@ -0,0 +1,42 @@ +package dev.caskeleton.adapter.outbound.httpclient.api.error; + +import java.io.IOException; +import java.util.Objects; + +/** + * A streamed response body failed after it was handed over; {@link #failure()} says how. + * + *

        An {@link IOException}, because {@code InputStream.read} promises one: a caller that reads the + * body with {@code catch (IOException)} — to delete a partial file, to retry — still sees the + * failure. The classified failure the gateway would have thrown for a buffered call ({@link + * HttpResponseTimeoutException} for a stalled body, {@link HttpResponseTruncatedException} for a + * cut one, stage {@code RESPONSE_BODY}, evidence {@code PARTIAL_RESPONSE}) is the cause and {@link + * #failure()}, for a retry policy or a log that branches on category. + * + *

        Re-review 2026-11-04 RR-03-14: the body threw the unchecked {@link HttpClientException} + * itself, which a {@code catch (IOException)} let through. Rejected: keeping the unchecked type and + * only documenting it — the {@code InputStream} contract is what every reader of a stream relies + * on, and a document does not reach a library that reads the stream for its caller. + */ +public final class HttpBodyReadException extends IOException { + + private static final long serialVersionUID = 1L; + + /** + * Wraps a classified body failure. + * + * @param failure the classified failure; its message is the caller-safe phrase + */ + public HttpBodyReadException(HttpClientException failure) { + super(Objects.requireNonNull(failure, "classified body failure").getMessage(), failure); + } + + /** + * The classified failure: category, metadata and evidence. + * + * @return the failure this exception carries + */ + public HttpClientException failure() { + return (HttpClientException) getCause(); + } +} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/api/result/BlockingStreamingResponse.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/api/result/BlockingStreamingResponse.java index 260ef842..7992080f 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/api/result/BlockingStreamingResponse.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/api/result/BlockingStreamingResponse.java @@ -17,6 +17,16 @@ public interface BlockingStreamingResponse extends AutoCloseable { Map> headers(); + /** + * The body, bounded after hand-over by {@code read-idle} per wait. + * + *

        A read that fails throws {@link + * dev.caskeleton.adapter.outbound.httpclient.api.error.HttpBodyReadException} — an {@code + * IOException} whose {@code failure()} is the classified {@code HttpResponseTimeoutException} + * (stalled) or {@code HttpResponseTruncatedException} (cut). + * + * @return the body stream; closing the response closes it + */ InputStream body(); @Override diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpRequest.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpRequest.java index f38f1459..679e48be 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpRequest.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingClientHttpRequest.java @@ -9,6 +9,7 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; +import java.util.Collections; import java.util.Objects; import java.util.Set; import java.util.TreeSet; @@ -19,6 +20,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.AbstractBufferingClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; +import org.springframework.util.StringUtils; /** * A JDK request for a streaming download, whose timeouts end at the response headers (review @@ -40,6 +42,9 @@ import org.springframework.http.client.ClientHttpResponse; */ final class JdkStreamingClientHttpRequest extends AbstractBufferingClientHttpRequest { + /** The JDK property that lets a deployment send some restricted headers after all. */ + private static final String ALLOW_RESTRICTED_HEADERS = "jdk.httpclient.allowRestrictedHeaders"; + /** Headers the JDK client refuses to set, as Spring's own JDK request lists them. */ private static final Set RESTRICTED_HEADERS = restrictedHeaders(); @@ -120,9 +125,21 @@ final class JdkStreamingClientHttpRequest extends AbstractBufferingClientHttpReq } } - private static Set restrictedHeaders() { + /** + * Spring's {@code JdkClientHttpRequest.disallowedHeaders()}, which is private, step for step: the + * five names, less any the {@code jdk.httpclient.allowRestrictedHeaders} property allows. A fixed + * copy ignored the property, so a deployment that set it sent {@code Host} on ordinary calls and + * dropped it on streamed ones (re-review 2026-11-04 RR-03-15). {@code + * JdkStreamingRestrictedHeadersTest} compares the two lists for several property values, so a + * Spring change shows up as a failing test rather than as two lists that quietly differ. + */ + static Set restrictedHeaders() { Set restricted = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); restricted.addAll(Set.of("connection", "content-length", "expect", "host", "upgrade")); - return restricted; + String allowed = System.getProperty(ALLOW_RESTRICTED_HEADERS); + if (allowed != null) { + restricted.removeAll(StringUtils.commaDelimitedListToSet(allowed)); + } + return Collections.unmodifiableSet(restricted); } } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java index 02643336..a836ec1d 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java @@ -15,24 +15,48 @@ import java.util.concurrent.atomic.AtomicBoolean; * RR-04-03). * *

        The JDK client has no socket read timeout, so a streamed body that stopped arriving held the - * caller's thread and the connection forever. Each read arms a timer on the JDK's shared delay - * scheduler; when it fires the stream is closed, which wakes the blocked read, and the read reports - * a {@link SocketTimeoutException} — the same exception Apache's socket timeout raises, so one - * classifier reading names both. A read that returns first disarms its timer. + * caller's thread and the connection forever. A read that has waited {@code read-idle} for the + * server closes the stream, which wakes it, and it reports a {@link SocketTimeoutException} — the + * same exception Apache's socket timeout raises, so one classifier reading names both. Only the + * time a read spends waiting counts: time the caller spends between reads is not the server's. + * + *

        One watchdog per stream, not a timer per read (re-review 2026-11-04 RR-03-13). A read only + * records when it started; the watchdog wakes once per {@code read-idle}, closes the stream if the + * read in progress has waited that long, and otherwise sleeps until that read's deadline. Arming a + * timer on every read put a task on the JVM's single delay scheduler and took it off again — + * measured at about 3 µs a read, and a JVM-wide ceiling near 0.5–0.75 million reads a second shared + * with every other {@code CompletableFuture} timeout in the process. The watchdog costs a clock + * read and two volatile writes per read, and one scheduled task per {@code read-idle} while reads + * keep coming. Rejected: a transport-owned {@code ScheduledExecutorService} with a timer per read — + * it moves the queue off the shared scheduler but keeps a queue insertion and removal on every + * read. + * + *

        {@link #skip} reads through this stream rather than delegating: the JDK body does not override + * {@code skip}, so {@code InputStream.skip} ran many reads inside one guarded call and a long skip + * over a steady body timed out as one long wait (re-review 2026-11-04 RR-03-12). */ final class ReadIdleInputStream extends FilterInputStream { + /** The largest scratch buffer {@link #skip} reads into, as {@code InputStream.skip} uses. */ + private static final int SKIP_BUFFER_BYTES = 2048; + + /** {@link #readStartedAt} while no read is waiting. */ + private static final long NOT_READING = Long.MIN_VALUE; + @FunctionalInterface private interface Read { long run() throws IOException; } - private final Duration readIdle; + private final long readIdleNanos; + private final AtomicBoolean watchdogArmed = new AtomicBoolean(); private final AtomicBoolean idled = new AtomicBoolean(); + private volatile long readStartedAt = NOT_READING; + private volatile boolean closed; ReadIdleInputStream(InputStream delegate, Duration readIdle) { super(Objects.requireNonNull(delegate, "body stream")); - this.readIdle = Objects.requireNonNull(readIdle, "read idle timeout"); + this.readIdleNanos = Objects.requireNonNull(readIdle, "read idle timeout").toNanos(); } @Override @@ -47,14 +71,33 @@ final class ReadIdleInputStream extends FilterInputStream { @Override public long skip(long count) throws IOException { - return guarded(() -> super.skip(count)); + if (count <= 0) { + return 0; + } + byte[] scratch = new byte[(int) Math.min(SKIP_BUFFER_BYTES, count)]; + long remaining = count; + while (remaining > 0) { + int read = read(scratch, 0, (int) Math.min(scratch.length, remaining)); + if (read < 0) { + break; + } + remaining -= read; + } + return count - remaining; + } + + @Override + public void close() throws IOException { + closed = true; + super.close(); } private long guarded(Read read) throws IOException { requireNotIdled(); - CompletableFuture timer = new CompletableFuture<>(); - CompletableFuture expiry = - timer.completeOnTimeout(null, readIdle.toNanos(), TimeUnit.NANOSECONDS).thenRun(this::idle); + readStartedAt = System.nanoTime(); + if (!watchdogArmed.get() && watchdogArmed.compareAndSet(false, true)) { + watchFrom(readStartedAt); + } try { long result = read.run(); requireNotIdled(); @@ -63,9 +106,37 @@ final class ReadIdleInputStream extends FilterInputStream { requireNotIdled(); throw failure; } finally { - // Completing first skips the idle action and lets the scheduler drop the pending task. - timer.cancel(false); - expiry.cancel(false); + readStartedAt = NOT_READING; + } + } + + /** Wakes the watchdog when a read that started at {@code started} reaches read-idle. */ + private void watchFrom(long started) { + long left = Math.max(0, readIdleNanos - (System.nanoTime() - started)); + CompletableFuture.delayedExecutor(left, TimeUnit.NANOSECONDS).execute(this::watch); + } + + private void watch() { + if (closed || idled.get()) { + return; + } + long started = readStartedAt; + if (started != NOT_READING) { + // The second read of readStartedAt: a read that ended at its deadline and was followed at + // once by another must not have the new one closed under it. + if (System.nanoTime() - started >= readIdleNanos && readStartedAt == started) { + idle(); + } else { + watchFrom(started); + } + return; + } + watchdogArmed.set(false); + // A read that started after the check above saw the watchdog armed and left it alone; look + // again, or that read would wait unwatched. + started = readStartedAt; + if (started != NOT_READING && watchdogArmed.compareAndSet(false, true)) { + watchFrom(started); } } @@ -79,7 +150,7 @@ final class ReadIdleInputStream extends FilterInputStream { } /** - * After the timer fired, whatever the read returned — data, end of stream or "closed" — is not + * After the watchdog fired, whatever the read returned — data, end of stream or "closed" — is not * the rest of the body. */ private void requireNotIdled() throws SocketTimeoutException { diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptResiliencePipeline.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptResiliencePipeline.java index df8c946e..e37346a4 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptResiliencePipeline.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/resilience/AttemptResiliencePipeline.java @@ -23,10 +23,14 @@ import java.util.function.Supplier; * circuit error: the upstream never saw the request, and counting our own back-pressure as upstream * failure would open the breaker on a healthy dependency. * - *

        An attempt its caller abandoned is not recorded either, for the same reason: an attempt that a - * caller's own deadline ended while the upstream was still answering within the profile's limits is - * the caller running out of time, not the upstream failing (review 2026-11-03 RR-04-01). Its - * permission is given back instead. + *

        An attempt its caller abandoned is not recorded either: an attempt that failed after a + * caller's own deadline — set earlier than the profile's, and passed by the time it failed — is + * taken as the caller running out of time, not the upstream failing (review 2026-11-03 RR-04-01). + * Its permission is given back instead. The check does not ask whether the upstream was still + * answering within the profile's limits, and that is a blind spot: when every caller's budget is + * shorter than the stage timeouts, a hung upstream ends each attempt at the caller's deadline first + * and is never recorded, so the circuit never opens (re-review 2026-11-04 RR-03-16, + * docs/httpclient/configuration-reference.md "Two deadlines"). */ public final class AttemptResiliencePipeline { diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ClassifiedBodyInputStream.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ClassifiedBodyInputStream.java index f2597bda..aef483fb 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ClassifiedBodyInputStream.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/ClassifiedBodyInputStream.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.httpclient.restclient; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpBodyReadException; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpClientException; import java.io.FilterInputStream; import java.io.IOException; @@ -14,7 +15,9 @@ import java.util.function.Function; *

        A streamed body is read after the gateway has returned, so the gateway's own failure mapping * never sees it. Without this a read-idle timeout or a cut connection reached the caller as the * engine's bare {@code IOException} — no category, no evidence, nothing a retry policy or a log - * could branch on. Closing is the caller's own act and is passed through unclassified. + * could branch on. Each failure is thrown as {@link HttpBodyReadException}: still an {@code + * IOException}, as {@code InputStream} promises, carrying the classified failure (re-review + * 2026-11-04 RR-03-14). Closing is the caller's own act and is passed through unclassified. */ final class ClassifiedBodyInputStream extends FilterInputStream { @@ -31,7 +34,7 @@ final class ClassifiedBodyInputStream extends FilterInputStream { try { return super.read(); } catch (IOException failure) { - throw classifier.apply(failure); + throw new HttpBodyReadException(classifier.apply(failure)); } } @@ -40,7 +43,7 @@ final class ClassifiedBodyInputStream extends FilterInputStream { try { return super.read(buffer, offset, length); } catch (IOException failure) { - throw classifier.apply(failure); + throw new HttpBodyReadException(classifier.apply(failure)); } } @@ -49,7 +52,7 @@ final class ClassifiedBodyInputStream extends FilterInputStream { try { return super.skip(count); } catch (IOException failure) { - throw classifier.apply(failure); + throw new HttpBodyReadException(classifier.apply(failure)); } } @@ -58,7 +61,7 @@ final class ClassifiedBodyInputStream extends FilterInputStream { try { return super.available(); } catch (IOException failure) { - throw classifier.apply(failure); + throw new HttpBodyReadException(classifier.apply(failure)); } } } diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingRestrictedHeadersTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingRestrictedHeadersTest.java new file mode 100644 index 00000000..4cb25e1c --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkStreamingRestrictedHeadersTest.java @@ -0,0 +1,69 @@ +package dev.caskeleton.adapter.outbound.httpclient.jdk; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.lang.reflect.Method; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * The streaming JDK request drops the same headers Spring's own JDK request drops, so a profile + * sends the same headers whether the call streams or not (re-review 2026-11-04 RR-03-15). + * + *

        Spring computes its list from the {@code jdk.httpclient.allowRestrictedHeaders} system + * property; the streaming request used to keep a fixed copy that ignored it, and a deployment that + * set the property sent {@code Host} on ordinary calls and silently dropped it on streamed ones. + * Spring's list is private, so it is read reflectively: if Spring renames it, this test fails and + * says so, rather than the two lists drifting apart unseen. + */ +@ResourceLock(Resources.SYSTEM_PROPERTIES) +class JdkStreamingRestrictedHeadersTest { + + private static final String ALLOW_PROPERTY = "jdk.httpclient.allowRestrictedHeaders"; + + @ParameterizedTest + @ValueSource( + strings = {"", "host", "Host,upgrade", "connection,content-length,expect,host,upgrade"}) + @DisplayName("jdk.httpclient.allowRestrictedHeaders 값이 무엇이든 스트리밍 요청이 버리는 헤더는 Spring JDK 요청과 같다") + void theStreamingRequestDropsWhatSpringsJdkRequestDrops(String allowed) throws Exception { + // given + String previous = System.getProperty(ALLOW_PROPERTY); + if (allowed.isEmpty()) { + System.clearProperty(ALLOW_PROPERTY); + } else { + System.setProperty(ALLOW_PROPERTY, allowed); + } + try { + // when + Set streaming = JdkStreamingClientHttpRequest.restrictedHeaders(); + + // then + assertThat(lowerCased(streaming)).isEqualTo(lowerCased(springsDisallowedHeaders())); + } finally { + if (previous == null) { + System.clearProperty(ALLOW_PROPERTY); + } else { + System.setProperty(ALLOW_PROPERTY, previous); + } + } + } + + @SuppressWarnings("unchecked") + private static Set springsDisallowedHeaders() throws Exception { + Method disallowed = + Class.forName("org.springframework.http.client.JdkClientHttpRequest") + .getDeclaredMethod("disallowedHeaders"); + disallowed.setAccessible(true); + return (Set) disallowed.invoke(null); + } + + private static List lowerCased(Set names) { + return names.stream().map(name -> name.toLowerCase(Locale.ROOT)).sorted().toList(); + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java new file mode 100644 index 00000000..6b70aa42 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java @@ -0,0 +1,152 @@ +package dev.caskeleton.adapter.outbound.httpclient.jdk; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.io.IOException; +import java.io.InputStream; +import java.net.SocketTimeoutException; +import java.time.Duration; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What the JDK transport's read-idle bound promises: each read that waits longer than {@code + * read-idle} for the server ends the body, and nothing else does (re-review 2026-11-04 RR-03-12, + * RR-03-13). + */ +class ReadIdleInputStreamTest { + + private static final Duration READ_IDLE = Duration.ofMillis(300); + private static final Duration GAP = Duration.ofMillis(20); + + @Test + @DisplayName("데이터가 read-idle보다 짧은 간격으로 오면 read-idle보다 오래 걸리는 skip도 끝까지 건너뛴다") + void aSkipLongerThanReadIdleOverASteadyBodySucceeds() throws IOException { + // given + // 40 bytes at 20 ms apart: 800 ms in all, every gap well inside the 300 ms bound. + try (InputStream body = new ReadIdleInputStream(new DrippingStream(40, GAP), READ_IDLE)) { + + // when + long skipped = body.skip(40); + + // then + assertThat(skipped).isEqualTo(40); + } + } + + @Test + @DisplayName("데이터가 read-idle보다 짧은 간격으로 오면 본문 전체가 read-idle보다 오래 걸려도 끝까지 읽힌다") + void aSteadyBodyLongerThanReadIdleIsReadToTheEnd() throws IOException { + // given + try (InputStream body = new ReadIdleInputStream(new DrippingStream(40, GAP), READ_IDLE)) { + + // when + byte[] read = body.readAllBytes(); + + // then + assertThat(read).hasSize(40); + } + } + + @Test + @DisplayName("한 read가 read-idle보다 오래 서버를 기다리면 SocketTimeoutException으로 끝난다") + void aReadThatWaitsLongerThanReadIdleTimesOut() { + // given + long started = System.nanoTime(); + InputStream body = new ReadIdleInputStream(new StalledStream(), READ_IDLE); + + // when + Throwable failure = catchThrowable(body::read); + + // then + Duration waited = Duration.ofNanos(System.nanoTime() - started); + assertThat(failure).isInstanceOf(SocketTimeoutException.class); + assertThat(waited).isGreaterThanOrEqualTo(READ_IDLE).isLessThan(READ_IDLE.multipliedBy(3)); + } + + @Test + @DisplayName("호출자가 read 사이에 오래 머문 시간은 read-idle로 세지 않는다") + void timeTheCallerSpendsBetweenReadsIsNotIdle() throws Exception { + // given + try (InputStream body = new ReadIdleInputStream(new DrippingStream(2, GAP), READ_IDLE)) { + int first = body.read(); + TimeUnit.MILLISECONDS.sleep(READ_IDLE.multipliedBy(2).toMillis()); + + // when + int second = body.read(); + + // then + assertThat(new int[] {first, second}).containsExactly('x', 'x'); + } + } + + /** Gives one byte per read, each after {@code gap}. */ + private static final class DrippingStream extends InputStream { + + private final Duration gap; + private int remaining; + + private DrippingStream(int bytes, Duration gap) { + this.remaining = bytes; + this.gap = gap; + } + + @Override + public int read() throws IOException { + if (remaining == 0) { + return -1; + } + try { + TimeUnit.NANOSECONDS.sleep(gap.toNanos()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IOException("interrupted", interrupted); + } + remaining--; + return 'x'; + } + + @Override + public int read(byte[] buffer, int offset, int length) throws IOException { + if (length == 0) { + return 0; + } + int value = read(); + if (value < 0) { + return -1; + } + buffer[offset] = (byte) value; + return 1; + } + } + + /** Never answers until closed, as a server that stopped sending does; closing wakes the read. */ + private static final class StalledStream extends InputStream { + + private final CountDownLatch closed = new CountDownLatch(1); + + @Override + public int read() throws IOException { + try { + closed.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IOException("interrupted", interrupted); + } + throw new IOException("closed"); + } + + @Override + public int read(byte[] buffer, int offset, int length) throws IOException { + return read(); + } + + @Override + public void close() { + closed.countDown(); + } + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingBodyLifetimeTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingBodyLifetimeTest.java index a19d3c6f..121241d7 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingBodyLifetimeTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/restclient/StreamingBodyLifetimeTest.java @@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.httpclient.api.OperationName; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpBodyReadException; +import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpClientException; import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpResponseTimeoutException; import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; @@ -71,7 +73,7 @@ class StreamingBodyLifetimeTest { @EnumSource( value = TransportType.class, names = {"APACHE", "JDK"}) - @DisplayName("본문 사이 공백이 read-idle을 넘으면 분류된 응답 시간 초과로 끝난다") + @DisplayName("본문 사이 공백이 read-idle을 넘으면 IOException인 본문 읽기 실패에 분류된 응답 시간 초과를 실어 끝난다") void aBodyGapLongerThanReadIdleEndsWithAClassifiedTimeout(TransportType transport) throws Exception { try (MockHttpServer server = MockHttpServer.start(); @@ -93,9 +95,13 @@ class StreamingBodyLifetimeTest { // then Duration elapsed = Duration.ofNanos(System.nanoTime() - started); - assertThat(failure).isInstanceOf(HttpResponseTimeoutException.class); + // An IOException, as InputStream.read promises, so a caller's catch (IOException) still + // sees it; the classified failure rides on it (re-review 2026-11-04 RR-03-14). + assertThat(failure).isInstanceOf(HttpBodyReadException.class); assertThat(elapsed).isLessThan(STALL_GAP); - HttpResponseTimeoutException timeout = (HttpResponseTimeoutException) failure; + HttpClientException classified = ((HttpBodyReadException) failure).failure(); + assertThat(classified).isInstanceOf(HttpResponseTimeoutException.class); + HttpResponseTimeoutException timeout = (HttpResponseTimeoutException) classified; assertThat(timeout.metadata().stage()).isEqualTo(AttemptStage.RESPONSE_BODY); assertThat(timeout.metadata().evidence()).isEqualTo(ExecutionEvidence.PARTIAL_RESPONSE); } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesEventNormalizer.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesEventNormalizer.java index f35bd5b5..f23507d2 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesEventNormalizer.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesEventNormalizer.java @@ -55,9 +55,8 @@ public final class SesEventNormalizer { default -> event(NormalizedEventType.UNKNOWN, type, messageId, occurredAt); }); // One SNS delivery carries one SES event, so the delivery's id is the event's. It is what makes - // a redelivery a duplicate in the ledger: the other identity, the event fingerprint, is keyed - // by - // the active HMAC key and changes when the key rotates (review 2026-11-03 RR-07-07). + // a redelivery a duplicate in the ledger: the other identity, the event fingerprint, uses the + // active HMAC key and changes when the key rotates (review 2026-11-03 RR-07-07). return events.stream().map(event -> withEventId(event, providerEventId)).toList(); } diff --git a/src/adapter/outbound/objectstorage/README.md b/src/adapter/outbound/objectstorage/README.md index 26eed116..97d73e0b 100644 --- a/src/adapter/outbound/objectstorage/README.md +++ b/src/adapter/outbound/objectstorage/README.md @@ -105,8 +105,10 @@ testImplementation testFixtures(project(':adapter:outbound:objectstorage')) ### MinIO qualification lanes -`objectStorageMinioContractTest` and `objectStorageMinioFaultTest` (in `mainCheck`) run a real MinIO -and Toxiproxy. Their images are read from one file, +`objectStorageMinioContractTest` and `objectStorageMinioFaultTest` run a real MinIO and Toxiproxy. +They run in the root `integrationCheck` (main push and nightly) and in +`.github/workflows/object-storage-qualification.yml` on pull requests that touch object storage — +not in this leaf's `mainCheck`, which ran them a second time on every main push. Their images are read from one file, `src/test/resources/object-storage/minio-provider-evidence.json`, whose `image` digest is the release the `status`, `excludedProfiles` and `limitations` beside it were measured on. `MinioQualificationImage` (in `src/test`, checked by the leaf's `test` without Docker) reads it. diff --git a/src/adapter/outbound/objectstorage/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/src/adapter/outbound/objectstorage/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 00000000..2b0d80fa --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,10 @@ +{ + "properties": [ + { + "name": "app.object-storage.enabled", + "type": "java.lang.Boolean", + "description": "Whether the object-storage capability is on. It is on whenever this module is on the classpath; false turns it off and leaves only the explicit legacy seam. Read by @ConditionalOnProperty, which the configuration processor cannot see, so it is declared here for the environment contract (verifyEnvKeys) and the IDE.", + "defaultValue": true + } + ] +} diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index a8c65e89..5e489322 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -38,7 +38,7 @@ packages. | `startup` | package-private startup policy (`JpaStartupAutoConfiguration`): Flyway migration strategy, datasource env/product checks, OSIV/DDL/Hikari/TLS/H2 guards, the `jpaplatform` actuator view, the readiness `db` contribution. Moved here from app-bootstrap | | `cache`, `envers`, `querydsl`, `security`, `observation` | opt-in library capabilities and the runtime-role verifier | | `experimental` | multi-tenancy, RLS, schema/database tenancy, read replica — library code a deployment constructs itself; no flag turns it on | -| `testkit` (`src/testFixtures/java`) | ArchUnit rules, fixtures, query/plan assertions, PostgreSQL matrix, failure injection, Flyway validate gate and concurrent-index inspector | +| `testkit` (`src/testFixtures/java`) | ArchUnit rules, fixtures, query/plan assertions, PostgreSQL matrix, failure injection, Flyway validate gate, concurrent-index inspector and lock-wait inspector | `springdata`, `hibernate` (`.batch`, `.bulk`, `.stateless`, statement inspector), `postgresql` (`.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`), `api.query`, `envers`, @@ -93,6 +93,9 @@ not grow by wiring accident. - A caller that retries re-runs the whole use case in a new transaction and a new Persistence Context. - OSIV is false in every runtime profile; Flyway owns schema change and Hibernate only validates. +- A migration that locks a table already in use starts with `SET LOCAL lock_timeout = '5s';` + (`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest` refuses one + without it; its list of migrations released before the rule only ever shrinks. - Metric tags, exception messages, and logs carry no SQL parameters, entity ids, tenant ids, or PII. - Contracts run against real PostgreSQL. H2 never satisfies one. diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index a2fc8b65..36cdf9e0 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -227,9 +227,14 @@ failure translation contract 다. 여기서는 SPI 구조와 fallback 근거만 - **PostgreSQL 전용**: data source 가 PostgreSQL 이 아니면 기동을 거부한다. `bootRunH2` 는 provider 를 `disabled` 나 `redis` 로 둔다. - **응답 크기**: 완료 응답은 8 KiB 이하만 행에 inline 저장하고, 넘으면 거부한다. -- **만료**: store 가 완료·실패 때 `expires_at` 을 앞으로 옮기고, `IdempotencyReaper` - (`IdempotencyRecordJpaRepository` 사용, 기본 10분 간격 `reaper-interval`)가 지난 행을 지운다. - reaper 는 provider 가 `postgresql` 일 때만 돈다. +- **만료**: claim 은 `expires_at` 을 처리 lease 끝 + replay TTL 로 두고, renew 는 lease 를 늘린 만큼 + `expires_at` 도 뒤로 민다. 완료·실패 때 다시 앞으로 옮긴다. `IdempotencyReaper` + (`IdempotencyRecordJpaRepository` 사용, 기본 10분 간격 `reaper-interval`)가 상태와 상관없이 지난 행을 + 지운다. 그래서 `expires_at` 이 lease 보다 먼저 오면 실행 중인 행이 지워지고 다음 claim 이 같은 작업을 + 다시 돌린다(재리뷰 2026-11-04 RR-03-11). 공유 계약의 PostgreSQL lane 은 시간을 흘린 뒤 이 reaper 를 + 실제로 돌려 이 경우를 본다. reaper 는 provider 가 `postgresql` 일 때만 돈다. +- **lease 가 지난 실행**: lease 가 지난 `EXECUTING` 행은 넘겨받지 않고 `ABANDONED` 로 바꿔 + `RecoveryRequired` 로 답한다. Redis store 도 같다(`IdempotencyStoreContract`, RR-01-11). ## outbox — `JpaOutboxStore` 외 @@ -297,8 +302,11 @@ A가 FAILED로 바꾸면 다시 발행되고(중복 전달), A의 늦은 PUBLISH owner는 비우고 token은 그대로 둔다(token은 증가만 한다). 1 row면 `APPLIED`, 0 row면 `STALE`. `findById` + setter 경로와 `@Version`은 쓰지 않는다. - **실패 원인 코드(`V22`)**: `markFailed`·`markDeferred`·`markDead`는 같은 조건부 UPDATE에서 - `last_failure_code`를 쓴다(publisher가 붙인 코드, 없으면 결과·예외 타입 이름). entity 필드는 읽기 - 전용이라 append INSERT와 claim flush는 이 열을 건드리지 않는다. `longRetries(n, now)`는 미룬 claim이 + `last_failure_code`를 쓴다(publisher가 붙인 코드, 없으면 결과·예외 타입 이름). append INSERT는 이 열을 + 쓰지 않는다. claim이 행을 DEAD로 옮길 때(`ATTEMPT_COUNTERS_INCONSISTENT`, `UNREADABLE_ROW`)는 claim의 row + lock 아래 entity flush로 그 이유를 쓴다 — 앞선 발행 실패의 코드가 남아 원인을 잘못 가리키지 않게(재리뷰 2차 + RR-02-12). 이 DEAD는 relay 결과를 거치지 않아 `outbox.publisher.published.total{outcome=DEAD}`에 안 잡히므로 + 경보는 `outbox.pending.size{status=DEAD}`로도 건다. `longRetries(n, now)`는 미룬 claim이 n번 이상인 FAILED 행 수와 가장 오래된 행의 나이를 센다(`outbox.retry.long.*` 게이지). 상태 `PARKED`는 DDL이 없다 — claim이 PENDING·FAILED·IN_FLIGHT만 고르고, FIFO 게이트는 PUBLISHED 아닌 모든 행을 막는 앞 행으로 본다. claim이 시도 횟수가 어긋난 행(`deferred_attempt_count > attempt_count`)을 만나면 DEAD로 @@ -356,6 +364,9 @@ A가 FAILED로 바꾸면 다시 발행되고(중복 전달), A의 늦은 PUBLISH `JpaOutboxStore.oldestUnpublishedAgeSecondsByEventType` 가 `HashMap` 을 쓰는 건 키가 enum 이 아니라 String(event-type 이름)이기 때문이다 — `countByStatus()` 는 키가 `OutboxEventStatus` enum 이라 `EnumMap` 을 쓴다(두 반환 타입이 의도적으로 다름). +`status` 에는 CHECK 가 없어 이 버전이 모르는 상태(뒤 버전이 쓴 상태, 손으로 친 값)가 있을 수 있다. +`countByStatus()` 는 그 상태만 빼고 세고 처음 한 번 WARN 으로 이름과 행 수를 말한다. 예전에는 그 이름 하나로 +집계 전체가 실패해 PENDING 게이지까지 꺼졌다(재리뷰 2차 RR-02-11). ### `OutboxReaper` PUBLISHED row 는 이미 전달된 terminal-success record 라 무한 보관할 필요가 없다. reaper 가 @@ -374,6 +385,12 @@ machine-readable SSOT다(개수는 registry가 소유한다). `selected` base ca 구분하며, 실제 PostgreSQL 테스트 통과만으로 immutable 운영 evidence가 필요한 R2를 주장하지 않는다. +이미 쓰이는 테이블을 잠그는 migration은 그 잠금 앞에 `SET LOCAL lock_timeout = '5s';`를 둔다. 상한이 없으면 +그 테이블을 건드린 열린 트랜잭션 하나 뒤에서 끝없이 기다리고, 그동안 뒤에 온 읽기·쓰기가 모두 migration 뒤에 줄을 +선다(V22, 재리뷰 2차 RR-02-09). `MigrationLockWaitTest`가 이 leaf DB에 도는 모든 tree를 검사하고, +`postgresqlMigrationLockWaitIntegrationTest` lane이 실제 PostgreSQL에서 상한 안에 실패하는지 본다 +(`docs/jpa/migration-guide.md` "Bound the lock wait"). + 적용된 versioned migration은 수정하지 않는다. Flyway가 기동할 때마다 checksum을 검사하므로 바꾼 파일은 이미 그것을 적용한 모든 DB의 기동을 막는다. 변경은 새 버전으로 추가하고, `src/test/resources/db/applied-migrations.sha256`에 한 줄을 더한다 diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index 9a7e7a7c..a15f558d 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -176,6 +176,7 @@ def readinessLanes = [ postgresqlSecurityBaselineIntegrationTest : ['PostgreSqlSecurityBaselineIntegrationTest', 'runtimeRoleCannotCreateInApplicationSchemaOrTempAndUsesTrustedSearchPath'], postgresqlMigrationIntegrationTest : ['PostgreSqlMigrationIntegrationTest'], + postgresqlMigrationLockWaitIntegrationTest : ['PostgreSqlMigrationLockWaitIntegrationTest'], postgresqlIntLockMigrationCompatibilityIntegrationTest : ['PostgreSqlIntLockMigrationCompatibilityIntegrationTest'], postgresqlTransactionIntegrationTest : ['PostgreSqlTransactionIntegrationTest'], postgresqlDistributedLockIntegrationTest : ['PostgreSqlDistributedLockIntegrationTest'], diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyClaimGateway.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyClaimGateway.java index 7884d1d0..e2d882d4 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyClaimGateway.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyClaimGateway.java @@ -17,6 +17,14 @@ import org.springframework.jdbc.core.JdbcOperations; * rows back rather than an exception. That matters: a unique-violation would abort the caller's * transaction, and the loser has to be able to read the winner's row in the same transaction to * find out what happened. + * + *

        A claimed row expires ({@code expires_at}, which the reaper purges on whatever the row's + * state) at the end of its processing lease plus the replay TTL — {@link #recordLifetimeMillis}. It + * used to expire at the replay TTL alone: with a replay TTL shorter than the lease the reaper + * deleted the row of a running operation and the next claim inserted a fresh one and ran it again + * (re-review 2026-11-04 RR-03-11), and with the two equal the row went with its lease, leaving + * nothing to answer "recovery required" from (RR-01-11). The Redis store keeps its key for the same + * span; {@code IdempotencyStoreContract} holds both to it. */ final class IdempotencyClaimGateway { @@ -122,7 +130,7 @@ final class IdempotencyClaimGateway { request.scope().digest(), request.scope().operationCode(), request.requestFingerprint().hex(), - request.replayTtl().toMillis(), + recordLifetimeMillis(request), request.scope().digest(), request.scope().keyDigestVersion(), request.scope().operationCode(), @@ -151,12 +159,21 @@ final class IdempotencyClaimGateway { request.processingLeaseTtl().toMillis(), request.policyRevision(), request.responseCodecId(), - request.replayTtl().toMillis(), + recordLifetimeMillis(request), request.scope().digest(), row.state().name(), row.stateRevision()); } + /** + * How long a claimed row lives: its processing lease, and then the replay TTL as the window in + * which a resend still finds it — "in progress" during the lease, "recovery required" after an + * execution outlived it. + */ + static long recordLifetimeMillis(IdempotencyClaimRequest request) { + return request.processingLeaseTtl().plus(request.replayTtl()).toMillis(); + } + /** * Abandons an execution whose lease expired, repeating the whole owner tuple. * diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyTransitionGateway.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyTransitionGateway.java index d10e2d3f..af8f021e 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyTransitionGateway.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyTransitionGateway.java @@ -39,11 +39,22 @@ final class IdempotencyTransitionGateway { and processing_lease_until > clock_timestamp() """; + /** + * Extends the lease, and moves {@code expires_at} with it: the row keeps the time it had past its + * old lease (the replay TTL the claim gave it), now past the new one. The right-hand side reads + * the row as it was before this update. Without the move a lease renewed past {@code expires_at} + * let the reaper delete a running operation's row (re-review 2026-11-04 RR-03-11); a row claimed + * before the margin existed keeps at least its new lease. + */ private static final String RENEW_SQL = """ update idempotency_record set state_revision = state_revision + 1, processing_lease_until = clock_timestamp() + (? * interval '1 millisecond'), + expires_at = greatest( + expires_at, + clock_timestamp() + (? * interval '1 millisecond') + + greatest(expires_at - processing_lease_until, interval '0')), last_transition_operation_id = ?, last_transition_kind = 'RENEW', last_transition_result_digest = ?, @@ -151,6 +162,7 @@ final class IdempotencyTransitionGateway { return jdbc.update( RENEW_SQL, processingLeaseTtl.toMillis(), + processingLeaseTtl.toMillis(), operationId, resultDigest, owner.scope().digest(), diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java index fba06bfb..3a933778 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java @@ -28,6 +28,8 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.spi.LoggingEventBuilder; @@ -52,6 +54,9 @@ public class JpaOutboxStore private final OutboxEventJpaRepository repository; private final OutboxClaimRepository claimRepository; + /** Status names {@link #countByStatus} has met and does not know; each is reported once. */ + private final Set reportedUnknownStatuses = ConcurrentHashMap.newKeySet(); + public JpaOutboxStore( OutboxEventJpaRepository repository, OutboxClaimRepository claimRepository) { this.repository = repository; @@ -106,8 +111,11 @@ public class JpaOutboxStore *

        The increment is an {@code UPDATE}, which holds the counter row's lock until the caller * commits: a second writer of the same aggregate waits, then increments the committed value, so * the numbers follow commit order. It never goes below the aggregate's highest outbox row, so a - * row an instance still on the wall-clock scheme writes during a rolling deploy comes first. The - * counter outlives the reaper's deletes, so a number is never handed out twice. + * row an instance still on the wall-clock scheme writes during a rolling deploy comes first — as + * long as it writes under the same identity. A row written under an identity this version does + * not use (a tenant scope the deploy changed) is invisible here, and the next number can be + * smaller than it; such a deploy stops the old writers first (runbook outbox-dead-letter §8, + * RR-02-10). The counter outlives the reaper's deletes, so a number is never handed out twice. * *

        An aggregate's first number is inserted instead, after the larger of its highest remaining * row and the floor V21 recorded — the moment it ran, above every clock number already sent for @@ -150,7 +158,9 @@ public class JpaOutboxStore *

        The WARN names the cause. A row whose deferred claims outnumber its claims is not damaged: * it is what a manual re-drive that reset {@code attempt_count} and left {@code * deferred_attempt_count} produces (re-review 2026-11-03 RR-05-01), and "cannot read" sent the - * operator looking for corruption instead of re-running the corrected runbook SQL. + * operator looking for corruption instead of re-running the corrected runbook SQL. The row says + * it too: the same code goes into {@code last_failure_code}, in place of the code of whatever + * publish failure came before, which no longer explains the row (re-review round 2, RR-02-12). */ @Override public List claimBatch( @@ -165,8 +175,7 @@ public class JpaOutboxStore entity.setLeaseOwner(owner); entity.setLeaseToken(entity.getLeaseToken() + 1); if (entity.getDeferredAttemptCount() > entity.getAttemptCount()) { - deadLetterOnClaim(entity) - .addKeyValue("error.reason", "ATTEMPT_COUNTERS_INCONSISTENT") + deadLetterOnClaim(entity, "ATTEMPT_COUNTERS_INCONSISTENT") .log( "outbox claim moved a row to DEAD: deferred_attempt_count ({}) exceeds" + " attempt_count ({}); a manual re-drive that did not reset" @@ -180,8 +189,7 @@ public class JpaOutboxStore try { event = toClaimedOutboxEvent(entity); } catch (RuntimeException unreadable) { - deadLetterOnClaim(entity) - .addKeyValue("error.reason", "UNREADABLE_ROW") + deadLetterOnClaim(entity, "UNREADABLE_ROW") .setCause(unreadable) .log("outbox claim moved a row it cannot read as an event to DEAD"); continue; @@ -191,12 +199,17 @@ public class JpaOutboxStore return List.copyOf(leases); } - /** Moves a claimed row it will not hand out to DEAD and starts the WARN that says why. */ - private static LoggingEventBuilder deadLetterOnClaim(OutboxEventEntity entity) { + /** + * Moves a claimed row it will not hand out to DEAD under {@code reason}, written to the row's + * {@code last_failure_code} and the WARN it starts. + */ + private static LoggingEventBuilder deadLetterOnClaim(OutboxEventEntity entity, String reason) { entity.setStatus(OutboxEventStatus.DEAD.name()); entity.setLeaseOwner(null); + entity.setLastFailureCode(reason); return log.atWarn() .addKeyValue("event_id", entity.getEventId()) + .addKeyValue("error.reason", reason) .addKeyValue("runbook_link", "runbook://outbox/dead-letter"); } @@ -256,17 +269,45 @@ public class JpaOutboxStore CallerTransaction.require("outbox " + operation); } + /** + * The rows per status this version knows. A status it does not know is left out and named once in + * a WARN: {@code status} has no CHECK, so a version meets a status written after it — an instance + * still on the version before PARKED during a rollout, the version an operator rolled back to, a + * value typed by hand. Failing the whole count on that name took every {@code + * outbox.pending.size} gauge down with it, the PENDING backlog the alert reads included + * (re-review round 2, RR-02-11). + */ @Override public Map countByStatus() { List rows = repository.countGroupedByStatus(); Map result = new EnumMap<>(OutboxEventStatus.class); for (Object[] row : rows) { - OutboxEventStatus status = OutboxEventStatus.valueOf((String) row[0]); - result.put(status, (Long) row[1]); + String name = (String) row[0]; + Long count = (Long) row[1]; + Optional status = knownStatus(name); + if (status.isPresent()) { + result.put(status.get(), count); + } else if (reportedUnknownStatuses.add(name)) { + log.atWarn() + .addKeyValue("outbox.status", name) + .addKeyValue("row_count", count) + .log( + "outbox_event holds rows in a status this version does not know; they are left out" + + " of outbox.pending.size. A later version or a manual UPDATE wrote it"); + } } return result; } + private static Optional knownStatus(String name) { + for (OutboxEventStatus status : OutboxEventStatus.values()) { + if (status.name().equals(name)) { + return Optional.of(status); + } + } + return Optional.empty(); + } + @Override public Map oldestUnpublishedAgeSecondsByEventType(Instant now) { List rows = repository.findOldestUnpublishedOccurredAtByEventType(); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java index 4ed084a8..7f27b394 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/entity/OutboxEventEntity.java @@ -43,7 +43,7 @@ public class OutboxEventEntity implements Persistable { @Column(name = "occurred_at", nullable = false, updatable = false) private Instant occurredAt; - /** Lifecycle status string: PENDING | IN_FLIGHT | PUBLISHED | FAILED | DEAD. */ + /** Lifecycle status string: PENDING | IN_FLIGHT | PUBLISHED | FAILED | DEAD | PARKED. */ @Column(name = "status", nullable = false, length = 16) private String status; @@ -57,19 +57,19 @@ public class OutboxEventEntity implements Persistable { @Column(name = "deferred_attempt_count", nullable = false) private int deferredAttemptCount; - /** Dual-purpose per status (PENDING / IN_FLIGHT / FAILED) — see README "outbox". */ /** - * The code of the row's last failed completion (V22): the publisher's own name for the failure, - * or the outcome or exception type when it gave none. + * Why the row last failed (V22): the publisher's own name for the failure, or the outcome or + * exception type when it gave none, or the claim's reason for moving the row to DEAD. * - *

        Read-only to the entity: only the relay's failed completions write it, each in its one - * fenced UPDATE ({@code OutboxEventJpaRepository#failLease} and its siblings). The append's - * INSERT and the claim's flush leave it out, so they neither clear a code nor need the column on - * a database that has not run V22 yet. + *

        The relay's failed completions write it in their one fenced UPDATE ({@code + * OutboxEventJpaRepository#failLease} and its siblings); the claim writes it through this entity + * when it moves a row it will not hand out to DEAD, under the claim's row lock (re-review round + * 2, RR-02-12). The append's INSERT leaves it out, so a new row has none. */ - @Column(name = "last_failure_code", length = 120, insertable = false, updatable = false) + @Column(name = "last_failure_code", length = 120, insertable = false) private String lastFailureCode; + /** Dual-purpose per status (PENDING / IN_FLIGHT / FAILED) — see README "outbox". */ @Column(name = "next_attempt_at", nullable = false) private Instant nextAttemptAt; @@ -395,4 +395,8 @@ public class OutboxEventEntity implements Persistable { public String getLastFailureCode() { return lastFailureCode; } + + public void setLastFailureCode(String lastFailureCode) { + this.lastFailureCode = lastFailureCode; + } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V20__outbox_event_deferred_attempt_count.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V20__outbox_event_deferred_attempt_count.sql index 1df02290..21336e91 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V20__outbox_event_deferred_attempt_count.sql +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V20__outbox_event_deferred_attempt_count.sql @@ -12,6 +12,20 @@ -- -- The default fills existing rows without a rewrite: every earlier claim counts against the -- budget, which is what the relay assumed until now. +-- +-- This file was edited after it was first written, before any deployment applied it (the branch +-- that added it was not merged), to add the bound below. applied-migrations.sha256 carries the +-- new checksum; a development database that applied the earlier text fails Flyway validation: +-- recreate it. + +-- Bound the wait for the lock this migration takes (ACCESS EXCLUSIVE on outbox_event, held until it +-- commits). Unbounded, it queues behind any open transaction that has touched the table, and every +-- read and write of the table after it queues behind the migration — the relay's claim and every +-- business write that appends an event. Five seconds, then the migration fails, rolls back whole +-- and the database stays at V19: deploy again once that transaction has ended (re-review 2026-11-03 +-- round 2, RR-02-09; the rule is docs/jpa/migration-guide.md "Bound the lock wait"). +SET LOCAL lock_timeout = '5s'; + ALTER TABLE outbox_event ADD COLUMN deferred_attempt_count INTEGER NOT NULL DEFAULT 0 CONSTRAINT ck_outbox_event_deferred_attempt_count CHECK (deferred_attempt_count >= 0); diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V22__outbox_event_last_failure_code.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V22__outbox_event_last_failure_code.sql index dbe4ed59..6215f261 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V22__outbox_event_last_failure_code.sql +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V22__outbox_event_last_failure_code.sql @@ -17,5 +17,19 @@ -- IN_FLIGHT only (so the partial index ix_outbox_event_eligible leaves PARKED out), and the order -- gate and its index ix_outbox_event_unpublished_aggregate_order treat every status but PUBLISHED as -- blocking — which is what holding a row in its aggregate's place means. +-- +-- This file was edited after it was first written, before any deployment applied it (the branch +-- that added it was not merged), to add the bound below. applied-migrations.sha256 carries the +-- new checksum; a development database that applied the earlier text fails Flyway validation: +-- recreate it. + +-- Bound the wait for the lock this migration takes (ACCESS EXCLUSIVE on outbox_event, held until it +-- commits). Unbounded, it queues behind any open transaction that has touched the table, and every +-- read and write of the table after it queues behind the migration — the relay's claim, the gauges +-- and every business write that appends an event. Five seconds, then the migration fails, rolls +-- back whole and the database stays at V21: deploy again once that transaction has ended (re-review +-- 2026-11-03 round 2, RR-02-09; the rule is docs/jpa/migration-guide.md "Bound the lock wait"). +SET LOCAL lock_timeout = '5s'; + ALTER TABLE outbox_event ADD COLUMN last_failure_code VARCHAR(120); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStoreContractTest.java index 04b31d23..cac6ff47 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStoreContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStoreContractTest.java @@ -1,18 +1,29 @@ package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql; +import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyReaper; +import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyRecordJpaRepository; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.application.idempotency.IdempotencyStorePort; import dev.caskeleton.application.idempotency.testkit.IdempotencyStoreContract; +import jakarta.persistence.EntityManagerFactory; +import java.time.Clock; import java.time.Duration; +import java.util.Properties; import java.util.function.Supplier; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; +import org.springframework.data.jpa.repository.support.JpaRepositoryFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.SharedEntityManagerCreator; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.support.TransactionTemplate; /** * The PostgreSQL store, against a real database through the shipped migrations, held to the same @@ -20,7 +31,12 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; * *

        Every call runs in its own {@link SpringTransaction} write transaction, as the executor's * calls do; the store refuses to run outside one. Time is the database's ({@code - * clock_timestamp()}), so the timed case lets it pass for real with a one-second lease. + * clock_timestamp()}), so the timed cases let it pass for real with a one-second lease. + * + *

        Letting time pass also runs the deployment's own {@link IdempotencyReaper}, through the real + * Spring Data repository. The store never expires a row itself — the reaper deletes every row past + * {@code expires_at}, whatever its state — so a contract that slept without reaping could not see a + * row that would have been purged under a live lease (re-review 2026-11-04 RR-03-11). */ @Tag("jpa-contract") class PostgreSqlIdempotencyStoreContractTest extends IdempotencyStoreContract { @@ -28,6 +44,9 @@ class PostgreSqlIdempotencyStoreContractTest extends IdempotencyStoreContract { private static JpaPlatformContractSupport support; private static JdbcTemplate jdbc; private static SpringTransaction transactions; + private static LocalContainerEntityManagerFactoryBean reaperPersistence; + private static IdempotencyReaper reaper; + private static TransactionTemplate reaperTransactions; @BeforeAll static void start() { @@ -44,10 +63,37 @@ class PostgreSqlIdempotencyStoreContractTest extends IdempotencyStoreContract { "update capability_schema_registry set lifecycle_state = 'ACTIVE' " + "where capability_id = 'jpa-idempotency-owner-safe-v2'"); transactions = new SpringTransaction(new DataSourceTransactionManager(support.dataSource())); + startReaper(); + } + + /** + * The reaper as a deployment builds it: its repository from Spring Data over the idempotency + * entity, its purge inside a JPA transaction (the {@code @Transactional} a bean proxy would add). + */ + private static void startReaper() { + reaperPersistence = new LocalContainerEntityManagerFactoryBean(); + reaperPersistence.setDataSource(support.dataSource()); + reaperPersistence.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + reaperPersistence.setPackagesToScan( + "dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.entity"); + Properties properties = new Properties(); + properties.setProperty("hibernate.jdbc.time_zone", "UTC"); + reaperPersistence.setJpaProperties(properties); + reaperPersistence.afterPropertiesSet(); + EntityManagerFactory entityManagers = reaperPersistence.getObject(); + IdempotencyRecordJpaRepository repository = + new JpaRepositoryFactory( + SharedEntityManagerCreator.createSharedEntityManager(entityManagers)) + .getRepository(IdempotencyRecordJpaRepository.class); + reaper = new IdempotencyReaper(repository, Clock.systemUTC()); + reaperTransactions = new TransactionTemplate(new JpaTransactionManager(entityManagers)); } @AfterAll static void stop() { + if (reaperPersistence != null) { + reaperPersistence.destroy(); + } if (support != null) { support.close(); } @@ -81,6 +127,7 @@ class PostgreSqlIdempotencyStoreContractTest extends IdempotencyStoreContract { Thread.currentThread().interrupt(); throw new IllegalStateException("interrupted while letting the lease run", interrupted); } + reaperTransactions.executeWithoutResult(ignored -> reaper.reap()); } /** diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java new file mode 100644 index 00000000..73ccad04 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java @@ -0,0 +1,205 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.zaxxer.hikari.HikariDataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * The migrations that lock a table already in use give up within their bound instead of stopping + * the table, against real PostgreSQL (re-review 2026-11-03 round 2, RR-02-09). + * + *

        Each case is the deploy the bound exists for: a database one version below the migration, and + * a transaction that has read the table and stays open — an operator's {@code BEGIN} in psql, a + * report, an instance of the old version mid-request. The migration needs a lock that conflicts + * with that read. Unbounded, it waits until the reader leaves and every read and write of the table + * queues behind it meanwhile; the reader here leaves after fifteen seconds, so an unbounded + * migration ends up applied. Bounded, it fails with {@code lock_not_available} long before that, + * Flyway rolls it back whole, and the history still ends one version below. V21 has the same case + * against a writer in {@code PostgreSqlOutboxOrderKeyRunbookIntegrationTest}. + */ +class PostgreSqlMigrationLockWaitIntegrationTest { + + private static final String LOCK_NOT_AVAILABLE = "55P03"; + private static final Duration READER_STAYS = Duration.ofSeconds(15); + private static final Duration GIVES_UP_WITHIN = Duration.ofSeconds(10); + + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void setup() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void cleanup() { + if (postgres != null) { + postgres.close(); + } + } + + @ParameterizedTest + @CsvSource({"20, outbox_event", "22, outbox_event"}) + @DisplayName("outbox_event를 읽는 트랜잭션이 열려 있으면 그 테이블을 잠그는 outbox 마이그레이션은 상한 안에 실패하고 한 버전 아래에 남는다") + void anOutboxMigrationGivesUpOnAHeldTableAndLeavesTheVersionBelowIt(int version, String table) + throws Exception { + try (HikariDataSource database = postgres.createDatabase(databaseName())) { + // given + Flyway below = outboxStream(database, version - 1); + below.migrate(); + + // when + Attempt attempt = + whileAReaderHolds(database, table, outboxStream(database, version)::migrate); + + // then + assertThat( + List.of( + String.valueOf(attempt.sqlState()), + attempt.tookLessThan(GIVES_UP_WITHIN), + below.info().current().getVersion().getVersion())) + .containsExactly(LOCK_NOT_AVAILABLE, true, String.valueOf(version - 1)); + } + } + + @ParameterizedTest + @CsvSource({ + "11, notification_reconciliation_job", + "12, notification_suppression", + "13, notification_request" + }) + @DisplayName("알림 테이블을 읽는 트랜잭션이 열려 있으면 그 테이블을 잠그는 알림 마이그레이션은 상한 안에 실패하고 한 버전 아래에 남는다") + void aNotificationMigrationGivesUpOnAHeldTableAndLeavesTheVersionBelowIt( + int version, String table) throws Exception { + try (HikariDataSource database = postgres.createDatabase(databaseName())) { + // given + applyCore(database); + Flyway below = notificationStream(database, version - 1); + below.baseline(); + below.migrate(); + + // when + Attempt attempt = + whileAReaderHolds(database, table, notificationStream(database, version)::migrate); + + // then + assertThat( + List.of( + String.valueOf(attempt.sqlState()), + attempt.tookLessThan(GIVES_UP_WITHIN), + below.info().current().getVersion().getVersion())) + .containsExactly(LOCK_NOT_AVAILABLE, true, String.valueOf(version - 1)); + } + } + + /** + * Runs the migration while another connection holds an open transaction that has read the table, + * and that transaction ends on its own after {@link #READER_STAYS}. + */ + private static Attempt whileAReaderHolds( + HikariDataSource database, String table, Runnable migration) throws SQLException { + try (Connection reader = database.getConnection()) { + reader.setAutoCommit(false); + try (Statement statement = reader.createStatement()) { + statement.execute("SELECT count(*) FROM " + table); + } + ScheduledExecutorService release = Executors.newSingleThreadScheduledExecutor(); + ScheduledFuture released = + release.schedule( + () -> { + reader.rollback(); + return null; + }, + READER_STAYS.toSeconds(), + TimeUnit.SECONDS); + try { + long started = System.nanoTime(); + Throwable thrown = catchThrowable(migration::run); + return new Attempt(thrown, Duration.ofNanos(System.nanoTime() - started)); + } finally { + released.cancel(true); + release.shutdownNow(); + } + } + } + + private static Flyway outboxStream(HikariDataSource database, int target) { + return Flyway.configure() + .dataSource(database) + .locations("classpath:db/migration/postgresql") + .target(String.valueOf(target)) + .load(); + } + + private static Flyway notificationStream(HikariDataSource database, int target) { + PostgreSqlOptionalStreamLifecycle.Stream stream = + PostgreSqlOptionalStreamLifecycle.notificationPlatform(); + return Flyway.configure() + .dataSource(database) + .locations(stream.location()) + .table(stream.historyTable()) + .baselineVersion("0") + .baselineOnMigrate(false) + .target(String.valueOf(target)) + .load(); + } + + /** The core stream, applied and promoted: what a deployment has before any capability stream. */ + private static void applyCore(HikariDataSource database) { + Flyway core = + Flyway.configure() + .dataSource(database) + .locations("classpath:db/migration/jpa/core") + .table("flyway_jpa_core_history") + .baselineVersion("0") + .baselineOnMigrate(false) + .load(); + core.baseline(); + core.migrate(); + new JdbcTemplate(database) + .update( + "UPDATE capability_schema_registry SET lifecycle_state = 'ACTIVE'" + + " WHERE capability_id = ?", + "jpa-flyway-migration"); + } + + private static String databaseName() { + return "lockwait_" + UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ROOT); + } + + /** What the migration did while the reader held the table. */ + private record Attempt(Throwable thrown, Duration took) { + + /** The SQLState of the first SQL failure in the cause chain, or null when it did not fail. */ + String sqlState() { + for (Throwable cause = thrown; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) { + return sql.getSQLState(); + } + } + return null; + } + + boolean tookLessThan(Duration bound) { + return took.compareTo(bound) < 0; + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java index 027408b4..d5b7f9f9 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java @@ -75,6 +75,30 @@ class PostgreSqlOutboxDispositionRunbookIntegrationTest { } } + /** + * A re-drive that reset {@code attempt_count} alone is refused by the next claim, which moves the + * row back to DEAD (RR-05-01). The row then says why: before, it kept the code of the publish + * failure that dead-lettered it first, and the operator went after a broker credential instead of + * re-running the corrected SQL (re-review round 2, RR-02-12). + */ + @Test + @DisplayName("deferred 횟수를 되돌리지 않은 재발행 행을 claim이 DEAD로 옮기면 행의 원인 코드도 그 이유로 바뀐다") + void theClaimThatRefusesAHalfRedrivenRowWritesWhyOnTheRow() throws SQLException { + try (Outbox outbox = Outbox.create()) { + // given: dead after a refused credential, then re-driven by SQL that left the deferred count + String redriven = outbox.append("order-" + UUID.randomUUID(), 1, OCCURRED); + outbox.setCounters(redriven, "PENDING", 0, 2); + outbox.setFailureCode(redriven, "KAFKA_AUTHENTICATIONEXCEPTION"); + + // when + List claimed = outbox.claimedEventIds(); + + // then + assertThat(List.of(claimed, outbox.status(redriven), outbox.failureCode(redriven))) + .containsExactly(List.of(), "DEAD", "ATTEMPT_COUNTERS_INCONSISTENT"); + } + } + @Test @DisplayName("runbook 구간 재발행 SQL은 그 구간의 DEAD 행만 claim 가능하게 되돌린다") void theWindowRedriveReturnsOnlyTheDeadRowsOfTheWindow() throws SQLException { @@ -253,6 +277,11 @@ class PostgreSqlOutboxDispositionRunbookIntegrationTest { "UPDATE outbox_event SET last_failure_code = ? WHERE event_id = ?", failureCode, eventId); } + String failureCode(String eventId) { + return jdbc.queryForObject( + "SELECT last_failure_code FROM outbox_event WHERE event_id = ?", String.class, eventId); + } + String status(String eventId) { return jdbc.queryForObject( "SELECT status FROM outbox_event WHERE event_id = ?", String.class, eventId); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java index cb7afea5..66f6d3e5 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java @@ -9,10 +9,8 @@ import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HexFormat; -import java.util.List; import java.util.Map; import java.util.TreeMap; -import java.util.stream.Stream; import org.junit.jupiter.api.Test; /** @@ -23,33 +21,6 @@ import org.junit.jupiter.api.Test; */ class AppliedMigrationImmutabilityTest { - /** - * Every tree whose migrations run against the database this leaf owns. - * - *

        The notification capability's stream moved to {@code - * adapter:outbound:persistence-notification} with its bytes and its classpath location unchanged - * ({@code db/migration/jpa/notification-platform}), so a database that applied it still - * validates. Its pins stayed in this manifest and are checked where the files now live: moving a - * migration must not be the way it stops being frozen. - * - *

        The fileserver stream ({@code db/migration/jpa/fileserver}, in {@code - * adapter:outbound:persistence-fileserver}) runs against the same database through the same - * Flyway history and was never pinned at all; it is checked here on the same terms. - * - *

        The messaging platform's tree ({@code db/migration/messaging}, in {@code - * messaging-reliability-jdbc-postgresql}) runs against it too once the consume side is selected: - * {@code adapter:inbound:messaging} applies its inbox range (V11xx). The tree is pinned whole — - * the platform outbox range ships from the same location to deployments that use it, and an - * edited migration stops those just the same. - */ - private static final List MIGRATION_ROOTS = - List.of( - Path.of("src/main/resources/db/migration"), - Path.of("../persistence-notification/src/main/resources/db/migration"), - Path.of("../persistence-fileserver/src/main/resources/db/migration"), - Path.of( - "../../../messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration")); - private static final Path MANIFEST = Path.of("src/test/resources/db/applied-migrations.sha256"); @Test @@ -94,20 +65,8 @@ class AppliedMigrationImmutabilityTest { private static Map currentChecksums() throws IOException { Map checksums = new TreeMap<>(); - for (Path root : MIGRATION_ROOTS) { - try (Stream files = Files.walk(root)) { - for (Path file : - files - .filter(path -> path.getFileName().toString().matches("V\\d+__.+\\.sql")) - .toList()) { - String key = root.relativize(file).toString().replace('\\', '/'); - String previous = checksums.put(key, sha256(Files.readString(file))); - if (previous != null) { - throw new IllegalStateException( - key + " exists in two migration trees; the classpath would load one at random"); - } - } - } + for (Map.Entry migration : MigrationTrees.versionedMigrations().entrySet()) { + checksums.put(migration.getKey(), sha256(Files.readString(migration.getValue()))); } return checksums; } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java new file mode 100644 index 00000000..5495c145 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java @@ -0,0 +1,105 @@ +package dev.caskeleton.adapter.outbound.persistence.migration; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.testkit.migration.LockWaitMigrationInspector; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Every migration this leaf's database runs bounds its wait for a lock on a table already in use + * ({@link LockWaitMigrationInspector}; re-review 2026-11-03 round 2, RR-02-09). + * + *

        V21 got the bound and V22, in the same commit, did not: a rule written into one file is not a + * rule for the next one. This test is. + */ +class MigrationLockWaitTest { + + /** + * Migrations released before the rule, which wait without a bound and stay that way: they are + * applied (on {@code main} when the rule came in), and an applied migration is never edited + * ({@link AppliedMigrationImmutabilityTest}). Their waits are behind every database that ran + * them. Nothing is added here — a new migration bounds its wait. + */ + private static final Set RELEASED_BEFORE_THE_RULE = + Set.of( + "jpa/core/V2__widen_capability_schema_stream.sql", + "jpa/idempotency/V2__request_hash_varchar.sql", + "postgresql/V5__int_lock_expired_after.sql", + "postgresql/V9__widen_capability_schema_stream.sql", + "postgresql/V10__idempotency_request_hash_varchar.sql", + "postgresql/V13__outbox_canonical_transport_compatibility.sql", + "postgresql/V14__validate_outbox_canonical_constraints.sql", + "postgresql/V16__outbox_canonical_hash_columns_varchar.sql", + "postgresql/V17__outbox_event_lease_fencing.sql", + "postgresql/V18__outbox_event_unpublished_aggregate_order.sql", + "postgresql/V19__outbox_event_canonical_only.sql", + "jpa/notification-platform/V4__notification_platform_alignment_and_activation.sql", + "jpa/notification-platform/V5__notification_recipient_expiry.sql", + "jpa/notification-platform/V6__notification_projection_facts.sql", + "jpa/notification-platform/V7__notification_collapse.sql", + "jpa/notification-platform/V8__notification_admin_claim.sql", + "jpa/notification-platform/V9__notification_evidence_certainty.sql", + "jpa/fileserver/V2__fileserver_recovery_and_staging_cleanup.sql", + "jpa/fileserver/V3__fileserver_fenced_cleanup_lease.sql", + "jpa/fileserver/V4__fileserver_upload_terminal_state.sql", + "jpa/fileserver/V5__fileserver_file_owner.sql", + "messaging/V1002__messaging_outbox_lease_fencing.sql", + "messaging/V1004__messaging_outbox_canonical_metadata.sql", + "messaging/V1005__messaging_outbox_ordering_key_index.sql"); + + private final LockWaitMigrationInspector inspector = new LockWaitMigrationInspector(); + + @Test + @DisplayName("규칙 이후의 모든 마이그레이션은 기존 테이블 잠금 앞에 SET LOCAL lock_timeout을 둔다") + void everyMigrationAfterTheRuleBoundsItsLockWait() throws IOException { + // given + Map migrations = MigrationTrees.versionedMigrations(); + + // when + Map> unbounded = unboundedStatements(migrations); + + // then + assertThat(unbounded.keySet()) + .as( + "these wait for a table lock without a bound: %s. Put SET LOCAL lock_timeout = '5s';" + + " first (docs/jpa/migration-guide.md, \"Bound the lock wait\")", + unbounded) + .isSubsetOf(RELEASED_BEFORE_THE_RULE); + } + + @Test + @DisplayName("규칙 이전 목록의 파일은 모두 아직 있고 실제로 상한 없이 잠금을 기다린다") + void everyMigrationReleasedBeforeTheRuleStillExistsAndStillWaitsUnbounded() throws IOException { + // given + Map migrations = MigrationTrees.versionedMigrations(); + + // when + Map> unbounded = unboundedStatements(migrations); + + // then + assertThat(unbounded.keySet()) + .as("an entry here that no longer exists or waits for nothing only hides the next file") + .containsAll(RELEASED_BEFORE_THE_RULE); + } + + private Map> unboundedStatements(Map migrations) + throws IOException { + Map> unbounded = new TreeMap<>(); + for (Map.Entry migration : migrations.entrySet()) { + List statements = + inspector.unboundedLockingStatements(Files.readString(migration.getValue())); + if (!statements.isEmpty()) { + unbounded.put(migration.getKey(), statements); + } + } + return unbounded; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java new file mode 100644 index 00000000..04727620 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java @@ -0,0 +1,70 @@ +package dev.caskeleton.adapter.outbound.persistence.migration; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Stream; + +/** + * The migration trees that run against the database this leaf owns, read the one way every + * migration rule here reads them: {@link AppliedMigrationImmutabilityTest} pins their bytes and + * {@link MigrationLockWaitTest} holds them to the lock-wait rule. One list, so a tree added for one + * rule is not quietly missing from the other. + */ +final class MigrationTrees { + + /** + * Every tree whose migrations run against the database this leaf owns. + * + *

        The notification capability's stream moved to {@code + * adapter:outbound:persistence-notification} with its bytes and its classpath location unchanged + * ({@code db/migration/jpa/notification-platform}), so a database that applied it still + * validates. Its pins stayed in this manifest and are checked where the files now live: moving a + * migration must not be the way it stops being frozen. + * + *

        The fileserver stream ({@code db/migration/jpa/fileserver}, in {@code + * adapter:outbound:persistence-fileserver}) runs against the same database through the same + * Flyway history and was never pinned at all; it is checked here on the same terms. + * + *

        The messaging platform's tree ({@code db/migration/messaging}, in {@code + * messaging-reliability-jdbc-postgresql}) runs against it too once the consume side is selected: + * {@code adapter:inbound:messaging} applies its inbox range (V11xx). The tree is pinned whole — + * the platform outbox range ships from the same location to deployments that use it, and an + * edited migration stops those just the same. + */ + static final List ROOTS = + List.of( + Path.of("src/main/resources/db/migration"), + Path.of("../persistence-notification/src/main/resources/db/migration"), + Path.of("../persistence-fileserver/src/main/resources/db/migration"), + Path.of( + "../../../messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration")); + + private MigrationTrees() {} + + /** + * Every versioned migration, keyed by its path below its tree ({@code postgresql/V22__...sql}), + * the key {@code applied-migrations.sha256} uses. + */ + static Map versionedMigrations() throws IOException { + Map migrations = new TreeMap<>(); + for (Path root : ROOTS) { + try (Stream files = Files.walk(root)) { + for (Path file : + files + .filter(path -> path.getFileName().toString().matches("V\\d+__.+\\.sql")) + .toList()) { + String key = root.relativize(file).toString().replace('\\', '/'); + if (migrations.put(key, file) != null) { + throw new IllegalStateException( + key + " exists in two migration trees; the classpath would load one at random"); + } + } + } + } + return migrations; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStoreTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStoreTest.java index 6b359c1e..23b4bc5e 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStoreTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStoreTest.java @@ -329,6 +329,27 @@ class JpaOutboxStoreTest { "runbook_link", "runbook://outbox/dead-letter"))); } + /** + * The claim moves a row to DEAD without the relay, so no failed completion writes the row's + * failure code. Without this the row kept the code of its last publish failure, and an operator + * reading {@code last_failure_code} looked for the wrong cause (re-review round 2, RR-02-12). + */ + @Test + @DisplayName("claim이 읽을 수 없는 행을 DEAD로 옮기면 그 원인 코드를 행에 남긴다") + void claimBatchLeavesTheReasonOnARowItCannotRead() { + // given + OutboxEventEntity tampered = pendingEntity("evt-tampered", "worklog-42"); + tampered.setEnvelopeSha256("2".repeat(64)); + when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(tampered)); + + // when + adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT); + + // then + assertThat(List.of(tampered.getStatus(), String.valueOf(tampered.getLastFailureCode()))) + .containsExactly("DEAD", "UNREADABLE_ROW"); + } + private static Map keyValues(ILoggingEvent event) { Map values = new LinkedHashMap<>(); if (event.getKeyValuePairs() != null) { @@ -421,6 +442,60 @@ class JpaOutboxStoreTest { Map.of(OutboxEventStatus.PENDING, 5L, OutboxEventStatus.IN_FLIGHT, 2L)); } + /** + * The status column has no CHECK, and a version that does not know a status meets it: an instance + * still on the version before PARKED during a rollout, the version an operator rolled back to, a + * value typed by hand. One unknown name failed the whole count, and with it every + * outbox.pending.size gauge, including the PENDING one the backlog alert reads (re-review round + * 2, RR-02-11). + */ + @Test + @DisplayName("이 버전이 모르는 상태 값이 테이블에 있어도 아는 상태의 수는 그대로 센다") + void countByStatusStillCountsTheKnownStatusesWhenTheTableHoldsAnUnknownOne() { + // given + List rows = + List.of( + new Object[] {"PENDING", 5L}, new Object[] {"ARCHIVED", 3L}, new Object[] {"DEAD", 1L}); + when(repo.countGroupedByStatus()).thenReturn(rows); + + // when + Map counts = adapter.countByStatus(); + + // then + assertThat(counts) + .containsExactlyInAnyOrderEntriesOf( + Map.of(OutboxEventStatus.PENDING, 5L, OutboxEventStatus.DEAD, 1L)); + } + + @Test + @DisplayName("모르는 상태 값은 한 번만 WARN으로 그 이름과 행 수를 말한다") + void countByStatusWarnsOnceNamingAStatusItDoesNotKnow() { + // given + List rows = List.of(new Object[] {"ARCHIVED", 3L}); + when(repo.countGroupedByStatus()).thenReturn(rows); + Logger storeLog = (Logger) LoggerFactory.getLogger(JpaOutboxStore.class); + ListAppender captured = new ListAppender<>(); + captured.start(); + storeLog.addAppender(captured); + + // when + try { + for (int poll = 0; poll < 3; poll++) { + adapter.countByStatus(); + } + } finally { + storeLog.detachAppender(captured); + } + + // then + assertThat(captured.list) + .singleElement() + .satisfies( + warn -> + assertThat(List.of(warn.getLevel().toString(), keyValues(warn))) + .containsExactly("WARN", Map.of("outbox.status", "ARCHIVED", "row_count", 3L))); + } + // ---- oldestUnpublishedAgeSecondsByEventType ---- @Test diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java index d9405ea5..bc60ed6b 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java @@ -12,6 +12,8 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseMa import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseOneToOneEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnChildEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnParentEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.MutualForeignKeyInvoiceEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.MutualForeignKeyOrderEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.NoDefaultConstructorEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OrderEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningChildEntity; @@ -202,9 +204,32 @@ class JpaArchitectureRulesTest { .isInstanceOf(AssertionError.class) .hasMessageContaining("JoinColumnParentEntity.children") .hasMessageContaining("JoinColumnChildEntity.parent") + .hasMessageContaining("two fields map one link") .hasMessageContaining("one side only"); } + @Test + @DisplayName("서로 다른 외래 키로 서로를 가리키는 두 엔티티는 한 링크의 사본이 아니라 서로 참조하는 두 테이블로 거부된다") + void twoEntitiesThatEachHoldAForeignKeyToTheOtherAreRefusedForTheirMutualReference() { + // given + var classes = + new ClassFileImporter() + .importClasses(MutualForeignKeyOrderEntity.class, MutualForeignKeyInvoiceEntity.class); + + // when + Throwable failure = + catchThrowable( + () -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)); + + // then + assertThat(failure) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("MutualForeignKeyOrderEntity.latestInvoice") + .hasMessageContaining("MutualForeignKeyInvoiceEntity.order") + .hasMessageContaining("each holds a foreign key to the other") + .hasMessageNotContaining("two fields map one link"); + } + @Test @DisplayName("단방향 연관관계는 통과한다") void unidirectionalAssociationsPass() { diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/MutualForeignKeyInvoiceEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/MutualForeignKeyInvoiceEntity.java new file mode 100644 index 00000000..60566133 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/MutualForeignKeyInvoiceEntity.java @@ -0,0 +1,30 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; + +/** Refused by the association rule: the other half of {@link MutualForeignKeyOrderEntity}. */ +@Entity +public class MutualForeignKeyInvoiceEntity { + + @Id private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "order_id") + private MutualForeignKeyOrderEntity order; + + protected MutualForeignKeyInvoiceEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The order this invoice bills. */ + public MutualForeignKeyOrderEntity order() { + return order; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/MutualForeignKeyOrderEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/MutualForeignKeyOrderEntity.java new file mode 100644 index 00000000..8a71418e --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/MutualForeignKeyOrderEntity.java @@ -0,0 +1,37 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToOne; + +/** + * Refused by the association rule: two entities that each hold a foreign key to the other. + * + *

        {@code latest_invoice_id} here and {@link MutualForeignKeyInvoiceEntity#order}'s {@code + * order_id} are two links, not one mapped twice, so nothing falls out of step. They are refused for + * another reason: the two tables reference each other, so neither row can be inserted or deleted + * first and one key must be nullable and written by a second UPDATE (re-review round 2, RR-02-15). + */ +@Entity +public class MutualForeignKeyOrderEntity { + + @Id private Long id; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "latest_invoice_id") + private MutualForeignKeyInvoiceEntity latestInvoice; + + protected MutualForeignKeyOrderEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The order's most recent invoice. */ + public MutualForeignKeyInvoiceEntity latestInvoice() { + return latestInvoice; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java new file mode 100644 index 00000000..f0358905 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java @@ -0,0 +1,89 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.migration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * A migration that locks a table already in use bounds how long it waits for that lock (re-review + * 2026-11-03 round 2, RR-02-09). + */ +class LockWaitMigrationInspectorTest { + + private final LockWaitMigrationInspector inspector = new LockWaitMigrationInspector(); + + @ParameterizedTest + @ValueSource( + strings = { + "ALTER TABLE outbox_event ADD COLUMN last_failure_code VARCHAR(120);", + "CREATE UNIQUE INDEX ux_poster_title ON poster (upper(title));", + "CREATE INDEX IF NOT EXISTS ix_ledger ON ONLY grpc_operation_ledger (completed_at);", + "DELETE FROM notification_suppression WHERE id = 1;", + "UPDATE outbox_event SET status = 'FAILED';", + "LOCK TABLE outbox_event IN SHARE MODE;", + "ALTER TABLE outbox_event ADD COLUMN c INT;\nSET LOCAL lock_timeout = '5s';", + "SET lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;" + }) + @DisplayName("이미 있는 테이블에 잠금을 거는 문장 앞에 SET LOCAL lock_timeout이 없으면 거부된다") + void aLockOnAnExistingTableWithoutABoundBeforeItIsRefused(String sql) { + // given + MigrationResource migration = new MigrationResource("V99__change.sql", sql); + + // when + Throwable refused = catchThrowable(() -> inspector.requireBoundedLockWait(migration)); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("V99__change.sql") + .hasMessageContaining("SET LOCAL lock_timeout"); + } + + @ParameterizedTest + @ValueSource( + strings = { + "SET LOCAL lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;", + "-- bound first\nset local lock_timeout = '5s';\ndelete from notification_suppression;", + "CREATE TABLE ledger (id BIGINT);\nCREATE INDEX ix_ledger ON ledger (id);\n" + + "ALTER TABLE ledger ADD COLUMN c INT;", + "CREATE TABLE IF NOT EXISTS public.ledger (id BIGINT);\nALTER TABLE ledger ADD c INT;", + "CREATE INDEX CONCURRENTLY ix_outbox ON outbox_event (status);", + "-- ALTER TABLE outbox_event ADD COLUMN c INT;\n/* DELETE FROM outbox_event; */\n" + + "COMMENT ON TABLE outbox_event IS 'update outbox_event set status';", + "CREATE TABLE poster_copy AS SELECT * FROM poster;" + }) + @DisplayName("잠금 대기에 상한을 두었거나 잠글 기존 테이블이 없으면 통과한다") + void aBoundedOrLockFreeMigrationPasses(String sql) { + // given + MigrationResource migration = new MigrationResource("V99__change.sql", sql); + + // when + Throwable refused = catchThrowable(() -> inspector.requireBoundedLockWait(migration)); + + // then + assertThat(refused).isNull(); + } + + @Test + @DisplayName("거부 메시지는 상한 없이 잠금을 기다리는 문장과 대상 테이블을 모두 말한다") + void theRefusalNamesEveryUnboundedStatementAndItsTable() { + // given + MigrationResource migration = + new MigrationResource( + "V12__suppression_unique.sql", + "DELETE FROM notification_suppression WHERE id > 1;\n" + + "ALTER TABLE notification_suppression ADD CONSTRAINT uk UNIQUE (id);"); + + // when + Throwable refused = catchThrowable(() -> inspector.requireBoundedLockWait(migration)); + + // then + assertThat(refused) + .hasMessageContaining("delete from notification_suppression") + .hasMessageContaining("alter table notification_suppression"); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 index bf86884e..1eb57d14 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 +++ b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 @@ -11,9 +11,9 @@ 2ba4214941a5563613b0dcc4f7cbf5f1278e342b900268721466e4bdeaa2fef2 jpa/idempotency/V1__expand_owner_safe_v2.sql 95be788589f01e32c9179acc80817e227e81805f8d518e8a9ac36e1c31b51da7 jpa/idempotency/V2__request_hash_varchar.sql 4379872989af0c97b937ff48527c788a2ba0216218d4df9435eba8c6e053ad8d jpa/notification-platform/V10__variables_payload_envelope_guard.sql -fb1eee652330995e2f761dd0c0cb9ca137b1c50dd99253aa9958c3ec130cf74b jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql -a4c3b56e74bdeaa32be2e716e377aa920bc327b4517bf3d6c6c753cdbcf5c745 jpa/notification-platform/V12__notification_suppression_target_unique.sql -11bd6a456f2d0eb10c89a6f675a7a3af43f2ae1abda061a6f793f9d5a252f144 jpa/notification-platform/V13__notification_request_acceptance.sql +be51fabd07220f9ef885534ba36ada5f1491baf24cdfb54d25d93a19ddc29926 jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql +43f9429f91c07528154ec01b721649b2c25fa98857ac154c7c08f4655634657f jpa/notification-platform/V12__notification_suppression_target_unique.sql +d01aaf59f66834358abf18246faa9a9eb8dfa9f42097ca9d968c44edff564630 jpa/notification-platform/V13__notification_request_acceptance.sql 1ac7cc1c2509868eb0ce202e1917bb36846f98f17ad4922abe3fac0ef128199b jpa/notification-platform/V1__notification_platform_core.sql 0add67aa23580e51712f84fabe9b09e08401ef708cfa1b3292b120fdb5c12fa2 jpa/notification-platform/V2__notification_platform_contact_template_policy.sql f5b98598a59cc4376f5d233b410f8a5ae9f3cd94156291ebdf2d0da5a66f34ef jpa/notification-platform/V3__notification_platform_inbox_admin.sql @@ -39,9 +39,9 @@ c20f1803c6afe84ac323a9fac9007f9a1676ed5ed253b72286c8fc1dee7c21d1 messaging/V100 b8f571e6cada72a8f2776f4462509ce4b535c964c75b1c3cfb34b9dc07446d59 postgresql/V17__outbox_event_lease_fencing.sql 44cacbde7d1381ca5290fb8ec28005e8127ff6b453ff84277ec8d1b3293d76c8 postgresql/V18__outbox_event_unpublished_aggregate_order.sql a0306e5b0fbcaf43984d256362dc4244aec57a0ce5031e4f5263be3762fe1caf postgresql/V19__outbox_event_canonical_only.sql -c997fa20e10b68e0ca1b30cd7275018deaadc99bb0370b7b806332e9826e5217 postgresql/V20__outbox_event_deferred_attempt_count.sql +25db296e55444636c8a017d9b736eecf4a839a9caf1733c0c4a5f37bae5a3161 postgresql/V20__outbox_event_deferred_attempt_count.sql 21744ea1aab2b29fbb3417b9a5c4389522199413048cc7035aa649ffcdd852cf postgresql/V21__outbox_aggregate_sequence.sql -459942722c69d43b15fdab34849c6e34bbca35727e800eca18fbc5b3eebe5f4c postgresql/V22__outbox_event_last_failure_code.sql +20da5649a29bf2305f0e04ab14003b21b7f120d867439fb01f1658c98179dba0 postgresql/V22__outbox_event_last_failure_code.sql 8ab106731d4d04d3719da0692069947736dc490ca46aa5a3ea9bdf65a5d956dc postgresql/V1__idempotency_record.sql 6b62a01a4eeb792b81015b4810ecc6f3f021e0a17dea50c871493f7694d4f0b9 postgresql/V3__outbox_event.sql c57ab8a35a10079190ad8a563be58fae4147c9406c5bb752debb6998324ccdf6 postgresql/V4__int_lock.sql diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java index cbe87cde..592d9d62 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java @@ -36,6 +36,13 @@ import java.util.stream.Stream; * pass. * * + *

        Two to-one links the other way round — {@code Order.@OneToOne latestInvoice} and {@code + * Invoice.@ManyToOne order}, each with its own foreign key — are not one link mapped twice, and the + * report says so. They are refused all the same, on purpose: the two tables reference each other, + * so neither row can be inserted or deleted first, one of the keys has to be nullable and written + * by a second UPDATE, and the entity graph is a cycle. One side holds the association and the other + * holds an ID or asks a query (re-review round 2, RR-02-15). + * *

        A unidirectional {@code @OneToMany} with its own {@code @JoinColumn}, or a {@code @ManyToOne} * nobody points back at, has nothing to keep in step and passes. A self-reference is a pair only * when a second member of the same class points back the other way ({@code @ManyToOne parent} and @@ -108,13 +115,28 @@ public final class SingleSidedAssociationCondition extends ArchCondition{@code ALTER TABLE} takes the strongest lock there is, and a plain {@code CREATE INDEX} one + * that stops every write. Either waits behind any transaction that has so much as read the table, + * and while it waits, every read and write after it queues behind it: one forgotten {@code BEGIN} + * in an operator's session stops the outbox, the relay and every request that writes it for as long + * as that session stays open. {@code SET LOCAL lock_timeout} before the first such statement turns + * that into a migration that fails after the bound, rolls back whole and leaves the database on the + * version before it — a failed deploy, not an outage. {@code LOCAL}, because a plain {@code SET} + * outlives the migration on the pooled connection Flyway borrowed. + * + *

        What counts as waiting for a lock: {@code ALTER TABLE}, {@code CREATE [UNIQUE] INDEX} and + * {@code DROP INDEX} without {@code CONCURRENTLY}, {@code LOCK TABLE}, {@code TRUNCATE}, {@code + * DROP TABLE}, and {@code UPDATE}/{@code DELETE} (they wait on the rows other transactions hold). A + * statement on a table this same migration created earlier waits for nothing and is left out. + * Comments and quoted literals are not read as statements. The check reads text, not a parse tree: + * it is a guard against the forgotten line, not a proof. + */ +public final class LockWaitMigrationInspector { + + private static final String NAME = + "((?:\"[^\"]+\"|[a-z_][a-z0-9_$]*)(?:\\.(?:\"[^\"]+\"|[a-z_][a-z0-9_$]*))?)"; + + private static final Pattern CREATED_TABLE = + Pattern.compile( + "\\bcreate\\s+(?:(?:temp|temporary|unlogged)\\s+)?table\\s+(?:if\\s+not\\s+exists\\s+)?" + + NAME); + + /** Each pattern's group 1, when it has one, is the table the statement locks. */ + private static final List LOCKING = + List.of( + Pattern.compile("\\balter\\s+table\\s+(?:if\\s+exists\\s+)?(?:only\\s+)?" + NAME), + Pattern.compile( + "\\bcreate\\s+(?:unique\\s+)?index\\s+(?!concurrently\\b)(?:if\\s+not\\s+exists\\s+)?" + + "(?:[a-z0-9_$\"]+\\s+)??on\\s+(?:only\\s+)?" + + NAME), + Pattern.compile("\\bdrop\\s+index\\s+(?!concurrently\\b)"), + Pattern.compile("\\block\\s+(?:table\\s+)?(?:only\\s+)?" + NAME), + Pattern.compile("\\btruncate\\s+(?:table\\s+)?(?:only\\s+)?" + NAME), + Pattern.compile("\\bdrop\\s+table\\s+(?:if\\s+exists\\s+)?" + NAME), + Pattern.compile("\\bdelete\\s+from\\s+(?:only\\s+)?" + NAME), + Pattern.compile( + "\\bupdate\\s+(?:only\\s+)?" + NAME + "(?:\\s+(?:as\\s+)?[a-z_]\\w*)?\\s+set\\b")); + + private static final Pattern BOUND = Pattern.compile("\\bset\\s+local\\s+lock_timeout\\b"); + + /** + * Fails when the migration locks a table it did not create before it bounds the wait. + * + * @throws IllegalStateException naming the migration and every statement that waits unbounded + */ + public void requireBoundedLockWait(MigrationResource migration) { + Objects.requireNonNull(migration, "migration"); + List unbounded = unboundedLockingStatements(migration.sql()); + if (unbounded.isEmpty()) { + return; + } + throw new IllegalStateException( + migration.name() + + " waits without a bound for a lock on a table already in use (" + + String.join(", ", unbounded) + + "). Put SET LOCAL lock_timeout = '5s'; before the first of them: while it waits, every" + + " read and write of the table queues behind it. LOCAL, so the setting ends with the" + + " migration's transaction (docs/jpa/migration-guide.md, \"Bound the lock wait\")"); + } + + /** + * The statements that wait for a lock on an existing table before any {@code SET LOCAL + * lock_timeout}, each as its leading words and table; empty when there are none. + */ + public List unboundedLockingStatements(String sql) { + if (sql == null) { + return List.of(); + } + String text = withoutCommentsAndLiterals(sql).toLowerCase(Locale.ROOT).replaceAll("\\s+", " "); + Map createdAt = new HashMap<>(); + Matcher created = CREATED_TABLE.matcher(text); + while (created.find()) { + createdAt.putIfAbsent(table(created.group(1)), created.start()); + } + Matcher bound = BOUND.matcher(text); + int boundAt = bound.find() ? bound.start() : Integer.MAX_VALUE; + List found = new ArrayList<>(); + for (Pattern pattern : LOCKING) { + Matcher statement = pattern.matcher(text); + while (statement.find()) { + if (statement.start() < boundAt && !createdEarlier(statement, createdAt)) { + found.add(new Located(statement.start(), statement.group().trim())); + } + } + } + return found.stream() + .sorted((left, right) -> Integer.compare(left.at(), right.at())) + .map(Located::statement) + .toList(); + } + + private static boolean createdEarlier(Matcher statement, Map createdAt) { + if (statement.groupCount() < 1 || statement.group(1) == null) { + return false; + } + Integer at = createdAt.get(table(statement.group(1))); + return at != null && at < statement.start(); + } + + /** The unqualified, unquoted table name: {@code public.ledger} and {@code ledger} are one. */ + private static String table(String name) { + String last = name.substring(name.lastIndexOf('.') + 1); + return last.replace("\"", ""); + } + + /** + * Blanks out comments and single-quoted literals, keeping every other character in place, so a + * word in a {@code COMMENT ON ... IS '...'} or a {@code -- } line is not read as a statement. + */ + private static String withoutCommentsAndLiterals(String sql) { + StringBuilder kept = new StringBuilder(sql.length()); + int i = 0; + while (i < sql.length()) { + char c = sql.charAt(i); + if (c == '-' && i + 1 < sql.length() && sql.charAt(i + 1) == '-') { + int end = sql.indexOf('\n', i); + i = end < 0 ? sql.length() : end; + kept.append(' '); + } else if (c == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') { + int end = sql.indexOf("*/", i + 2); + i = end < 0 ? sql.length() : end + 2; + kept.append(' '); + } else if (c == '\'') { + i++; + while (i < sql.length()) { + if (sql.charAt(i) == '\'' && i + 1 < sql.length() && sql.charAt(i + 1) == '\'') { + i += 2; + } else if (sql.charAt(i) == '\'') { + i++; + break; + } else { + i++; + } + } + kept.append("''"); + } else { + kept.append(c); + i++; + } + } + return kept.toString(); + } + + private record Located(int at, String statement) {} +} diff --git a/src/adapter/outbound/persistence-notification/CLAUDE.md b/src/adapter/outbound/persistence-notification/CLAUDE.md index 9d736619..0939743d 100644 --- a/src/adapter/outbound/persistence-notification/CLAUDE.md +++ b/src/adapter/outbound/persistence-notification/CLAUDE.md @@ -42,7 +42,10 @@ without a contract (the serving-state read model, consent, inbox), and why, are their own Flyway stream (`NotificationSchemaStream`, history table `flyway_jpa_notification_history`). An applied file is never edited: add the next `V__`, pin its SHA-256 in `applied-migrations.sha256`, and add it to `NotificationFixtures.migrations()`. - A migration that deletes rows states in a SQL comment which row survives and why. + A migration that deletes rows states in a SQL comment which row survives and why. A migration + that locks an existing table starts with `SET LOCAL lock_timeout = '5s';` + (`docs/jpa/migration-guide.md` "Bound the lock wait"; `MigrationLockWaitTest` in persistence-jpa + refuses one without it). - **Insert-or-update is decided by the database.** Never find-then-insert: insert with `ON CONFLICT () DO NOTHING`, and when it inserted nothing, update the existing row through the managed entity (`JpaSuppressionStore.upsert`, `JpaPolicyStores.Preferences.save`, diff --git a/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql index 2b1dc5dd..98319fd6 100644 --- a/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql +++ b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V11__notification_reconciliation_claim_lease.sql @@ -10,6 +10,19 @@ -- has passed, and every write after the claim names the fence it was claimed with, so a holder that -- outlived its lease cannot reschedule or delete a job somebody else now holds. The provider call -- stays outside any transaction, which is the reason for a lease rather than a long-held row lock. +-- +-- This file was edited after it was first written, before any deployment applied it (the branch +-- that added it was not merged), to add the bound below. applied-migrations.sha256 carries the +-- new checksum; a development database that applied the earlier text fails Flyway validation: +-- recreate it. + +-- Bound the wait for the lock this migration takes (ACCESS EXCLUSIVE on +-- notification_reconciliation_job, held until it commits). Unbounded, it queues behind any open +-- transaction that has touched the table, and every read and write of the table after it queues +-- behind the migration. Five seconds, then the migration fails, rolls back whole and the database +-- stays at V10: deploy again once that transaction has ended (re-review 2026-11-03 round 2, +-- RR-02-09; the rule is docs/jpa/migration-guide.md "Bound the lock wait"). +SET LOCAL lock_timeout = '5s'; ALTER TABLE notification_reconciliation_job ADD COLUMN IF NOT EXISTS claimed_until timestamptz, diff --git a/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V12__notification_suppression_target_unique.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V12__notification_suppression_target_unique.sql index a343067f..f595e3b0 100644 --- a/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V12__notification_suppression_target_unique.sql +++ b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V12__notification_suppression_target_unique.sql @@ -14,6 +14,19 @@ -- 4. then the earlier created_at, then the smaller id, so the choice is deterministic. -- The other rows are deleted. A SuppressionId an operator saw for a deleted duplicate no longer -- resolves; the surviving row carries the same target and reason. +-- +-- This file was edited after it was first written, before any deployment applied it (the branch +-- that added it was not merged), to add the bound below. applied-migrations.sha256 carries the +-- new checksum; a development database that applied the earlier text fails Flyway validation: +-- recreate it. + +-- Bound the wait for the lock this migration takes (row locks for the DELETE, then ACCESS EXCLUSIVE +-- on notification_suppression, held until it commits). Unbounded, it queues behind any open +-- transaction that has touched the table, and every read and write of the table after it queues +-- behind the migration — every send checks it. Five seconds, then the migration fails, rolls back +-- whole and the database stays at V11: deploy again once that transaction has ended (re-review +-- 2026-11-03 round 2, RR-02-09; the rule is docs/jpa/migration-guide.md "Bound the lock wait"). +SET LOCAL lock_timeout = '5s'; DELETE FROM notification_suppression AS s USING ( diff --git a/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V13__notification_request_acceptance.sql b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V13__notification_request_acceptance.sql index 9c251db8..2bcdaa7f 100644 --- a/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V13__notification_request_acceptance.sql +++ b/src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform/V13__notification_request_acceptance.sql @@ -7,6 +7,19 @@ -- column records why, so the stored receipt says "dropped" rather than "accepted". -- -- Existing rows were all accepted submissions; the default records exactly that. +-- +-- This file was edited after it was first written, before any deployment applied it (the branch +-- that added it was not merged), to add the bound below. applied-migrations.sha256 carries the +-- new checksum; a development database that applied the earlier text fails Flyway validation: +-- recreate it. + +-- Bound the wait for the lock this migration takes (ACCESS EXCLUSIVE on notification_request, held +-- until it commits). Unbounded, it queues behind any open transaction that has touched the table, +-- and every read and write of the table after it queues behind the migration — every notification +-- submission writes it. Five seconds, then the migration fails, rolls back whole and the database +-- stays at V12: deploy again once that transaction has ended (re-review 2026-11-03 round 2, +-- RR-02-09; the rule is docs/jpa/migration-guide.md "Bound the lock wait"). +SET LOCAL lock_timeout = '5s'; ALTER TABLE notification_request ADD COLUMN IF NOT EXISTS acceptance varchar(40) NOT NULL DEFAULT 'ACCEPTED'; diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java index 5ad8134f..9487f162 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java @@ -14,6 +14,7 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import org.slf4j.Logger; @@ -58,6 +59,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { private final Duration acquireTimeout; private final Duration drainTimeout; private final RedisLaneListener listener; + private final AtomicBoolean listenerFailureLogged = new AtomicBoolean(); private final AtomicReference state = new AtomicReference<>(State.OPEN); private final Object monitor = new Object(); @@ -345,13 +347,25 @@ public final class RedisRuntimeOwner implements AutoCloseable { /** * Tells the listener, outside the lock, and never lets it fail the borrow or the return. * + *

        The first failure is logged at WARN, the rest at DEBUG. At DEBUG alone a listener that + * always fails — a meter registry that refuses the lane meters — emptied every lane meter with no + * trace in an operator's log; at WARN every time it would log on every borrow (re-review + * 2026-11-04 RR-03-17). + * * @param event what to tell it */ private void report(Consumer event) { try { event.accept(listener); } catch (RuntimeException failure) { - LOG.debug("a Redis lane listener failed; the borrow is unaffected", failure); + if (listenerFailureLogged.compareAndSet(false, true)) { + LOG.warn( + "a Redis lane listener failed; the borrow is unaffected, the lane meters may be" + + " missing, and further listener failures are logged at DEBUG", + failure); + } else { + LOG.debug("a Redis lane listener failed; the borrow is unaffected", failure); + } } } diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetricsTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetricsTest.java index 37f4bb85..02d10791 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetricsTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneMetricsTest.java @@ -3,6 +3,10 @@ package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccount; @@ -27,6 +31,7 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; /** * The lanes' own meters: how long a borrow waited, why one was refused, and how often a connection @@ -312,6 +317,39 @@ class RedisLaneMetricsTest { } } + @Test + @DisplayName("지표 기록이 처음 실패하면 WARN 한 줄을 남기고 그 뒤 실패는 WARN으로 되풀이하지 않는다") + void aFailingListenerIsReportedAtWarnOnlyTheFirstTime() { + // given + RedisLaneListener failing = + new RedisLaneListener() { + @Override + public void waited(RedisLane lane, Duration waited, boolean admitted) { + throw new IllegalStateException("meter registry rejected the sample"); + } + }; + Logger ownerLog = (Logger) LoggerFactory.getLogger(RedisRuntimeOwner.class); + ListAppender captured = new ListAppender<>(); + captured.start(); + ownerLog.addAppender(captured); + try (RedisRuntimeOwner owner = + new RedisRuntimeOwner( + client, laneLimits(1), Duration.ofMillis(50), Duration.ofSeconds(1), failing)) { + + // when + for (int borrow = 0; borrow < 3; borrow++) { + owner.borrow(ContributedLane.EXCLUSIVE).close(); + } + } finally { + ownerLog.detachAppender(captured); + } + + // then + // Silent at DEBUG, a registry conflict that empties every lane meter left no trace in an + // operator's log; at WARN on every borrow, it would flood it (re-review 2026-11-04 RR-03-17). + assertThat(captured.list).filteredOn(event -> event.getLevel() == Level.WARN).hasSize(1); + } + @Test @DisplayName("listener 없이 만든 owner는 아무 지표도 내지 않는다") void anOwnerWithoutAListenerRecordsNothing() { diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java index 13d8fbb3..29e2a5d1 100644 --- a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java +++ b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java @@ -223,7 +223,15 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand : reply("OWNER_OPERATION_CONFLICT", attempt, rev, owner, "", ""); } long leaseUntil = Long.parseLong(field(rendered, "leaseUntil")); - if ("FAILED_RETRYABLE".equals(state) || leaseUntil <= nowMillis) { + boolean leaseOver = leaseUntil <= nowMillis; + // As the program: an expired EXECUTING record has an unknown effect, so it is abandoned and + // answered RECOVERY_REQUIRED, never taken over (re-review 2026-11-04 RR-01-11). + if ("EXECUTING".equals(state) && leaseOver) { + setField(rendered, "state", "ABANDONED"); + setField(rendered, "rev", Long.toString(rev + 1)); + return reply("RECOVERY_REQUIRED", attempt, rev + 1, owner, "", ""); + } + if ("FAILED_RETRYABLE".equals(state) || ("CLAIMED".equals(state) && leaseOver)) { setField(rendered, "state", "CLAIMED"); setField(rendered, "owner", ownerToken); setField(rendered, "attempt", Long.toString(attempt + 1)); diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java index 668ef1bd..9ba0fa1e 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java @@ -25,7 +25,11 @@ import org.springframework.core.env.Environment; *

        The runner enforces this: when creating or running a rule brings any other singleton into * existence — a configuration class behind a non-static {@code @Bean} method, a settings bean the * method takes — the boot fails with that bean's name, because a bean created before the - * post-processors would keep unbound settings for the whole run (RR-06-01). + * post-processors would keep unbound settings for the whole run (RR-06-01). The rule itself is held + * to the same reason: a rule class with an {@code @Value} or {@code @Autowired} member, or one + * bound with {@code @ConfigurationProperties}, fails the boot by name in every profile, because + * that member would stay {@code null} (RR2-04-03). Take what the rule needs from the environment + * {@link #violations(Environment)} is given. */ public interface StartupRule { diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java index 51ebba76..b6fe6e2c 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java @@ -1,16 +1,22 @@ package dev.caskeleton.adapter.outbound.support.startup; +import java.lang.reflect.AnnotatedElement; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.Set; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAwareOrderComparator; +import org.springframework.core.annotation.MergedAnnotations; import org.springframework.core.env.Environment; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; /** * Runs every {@link StartupRule} the context holds, once, after the bean definitions are known and @@ -44,12 +50,44 @@ import org.springframework.core.env.Environment; * whole run, and so does every other consumer of that singleton (RR-06-01). The {@code static} * declaration used to be a sentence in Javadoc; now the runner checks it. Any singleton that comes * into existence while a rule is created or run fails the boot with its name — unless it is itself - * a {@link StartupRule} or a {@link RequiredProductionSecrets}, the two kinds that are declared - * {@code static} and argument-free for exactly this reason (a non-static one creates its - * configuration class, which is reported). + * a {@link StartupRule} or a {@link RequiredProductionSecrets}, which are meant to be created here. + * + *

        What a rule or a secret list may not need

        + * + *

        Those two kinds are created early by design, so they must need nothing a post-processor + * provides: no {@code @Value}, {@code @Autowired}, {@code @Inject} or {@code @Resource} member, no + * {@code @PostConstruct}/{@code @PreDestroy} callback, and no {@code @ConfigurationProperties} + * binding on the class or its {@code @Bean} method. Each of those stays unset or uncalled for the + * whole run, silently: a rule then reads {@code null} and its check is off, and a settings class + * that doubles as a secret list keeps its defaults in {@code prod}, where the secret guard reads it + * early, and only there (review 2026-11-04 RR2-04-03). The runner refuses such a bean by name + * before any rule runs, in every profile, and again by its runtime class when it is created. + * + *

        Checked by what the bean needs rather than by how it is declared. Requiring a {@code static} + * factory method was the other way, and it checks the wrong thing: it refuses a rule registered + * with an instance supplier, which needs nothing, and passes a {@code static @Bean} that returns a + * class with an {@code @Value} field, which is the same silent {@code null}. */ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordered { + /** The kinds the runner creates before any bean post-processor exists. */ + private static final List> EARLY_KINDS = + List.of(StartupRule.class, RequiredProductionSecrets.class); + + /** + * What the post-processors that do not exist yet act on: member injection ({@code + * AutowiredAnnotationBeanPostProcessor}, {@code CommonAnnotationBeanPostProcessor}) and lifecycle + * callbacks. Named, not imported, so the check needs no Jakarta API on the classpath. + */ + private static final List POST_PROCESSED_MEMBER_ANNOTATIONS = + List.of( + "org.springframework.beans.factory.annotation.Value", + "org.springframework.beans.factory.annotation.Autowired", + "jakarta.inject.Inject", + "jakarta.annotation.Resource", + "jakarta.annotation.PostConstruct", + "jakarta.annotation.PreDestroy"); + private final Environment environment; /** @@ -63,6 +101,14 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { + // Before anything is created, and whether or not this profile reads them: the secret guard + // creates every RequiredProductionSecrets bean under prod only, so a bean that cannot be + // created early must fail where it is written, not on the first production boot. + for (Class earlyKind : EARLY_KINDS) { + for (String name : beanFactory.getBeanNamesForType(earlyKind, true, false)) { + refuseUnprocessedMembers(beanFactory, name, beanFactory.getType(name, false)); + } + } IdentityHashMap names = new IdentityHashMap<>(); List rules = new ArrayList<>(); for (String name : beanFactory.getBeanNamesForType(StartupRule.class, true, false)) { @@ -95,7 +141,9 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere /** * Fails when creating or running the rule {@code ruleName} brought a singleton into existence * other than a rule or a {@link RequiredProductionSecrets}: that bean was built before the bean - * post-processors, so its settings are unbound and it is not proxied, for the rest of the run. + * post-processors, so its settings are unbound and it is not proxied, for the rest of the run. A + * rule or secret list it created is held to {@link #refuseUnprocessedMembers} by its runtime + * class, which a {@code @Bean} method's declared return type may hide. */ private static void refusePulledForward( ConfigurableListableBeanFactory beanFactory, @@ -104,9 +152,15 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere Set before) { Set pulled = new LinkedHashSet<>(); for (String name : beanFactory.getSingletonNames()) { - if (!before.contains(name) - && !beanFactory.isTypeMatch(name, StartupRule.class) - && !beanFactory.isTypeMatch(name, RequiredProductionSecrets.class)) { + if (before.contains(name)) { + continue; + } + if (EARLY_KINDS.stream().anyMatch(kind -> beanFactory.isTypeMatch(name, kind))) { + Object singleton = beanFactory.getSingleton(name); + if (singleton != null) { + refuseUnprocessedMembers(beanFactory, name, ClassUtils.getUserClass(singleton)); + } + } else { pulled.add(name); } } @@ -130,6 +184,49 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere + " bean is not a rule: keep it a bean, ordered before what it protects."); } + /** + * Fails when the rule or secret list {@code name} needs a bean post-processor: it is created + * before any exists, so what one would inject, bind or call never happens, for the whole run. + */ + private static void refuseUnprocessedMembers( + ConfigurableListableBeanFactory beanFactory, String name, Class type) { + List needs = new ArrayList<>(); + if (beanFactory.findAnnotationOnBean(name, ConfigurationProperties.class, false) != null) { + needs.add("@ConfigurationProperties binding"); + } + if (type != null) { + ReflectionUtils.doWithFields( + type, field -> postProcessedBy(field).ifPresent(by -> needs.add(field.getName() + by))); + ReflectionUtils.doWithMethods( + type, + method -> + postProcessedBy(method).ifPresent(by -> needs.add(method.getName() + "()" + by))); + } + if (needs.isEmpty()) { + return; + } + throw StartupFailures.envValidation( + "'" + + name + + "' (" + + (type == null ? "unknown type" : type.getName()) + + ") is a StartupRule or RequiredProductionSecrets, which are created before any bean" + + " post-processor exists, but it needs one: " + + needs + + ". None of that happens for the whole run, so the rule reads null or the settings" + + " keep their defaults, silently. Read the value from the Environment the rule or" + + " the secret list is given, or pass it to the constructor in a static @Bean method;" + + " a settings class is not a secret list."); + } + + private static Optional postProcessedBy(AnnotatedElement member) { + MergedAnnotations annotations = MergedAnnotations.from(member); + return POST_PROCESSED_MEMBER_ANNOTATIONS.stream() + .filter(annotations::isPresent) + .findFirst() + .map(annotation -> " (@" + annotation.substring(annotation.lastIndexOf('.') + 1) + ")"); + } + /** * Runs one rule and raises its violations as its phase's typed failure. * diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java index 398c108d..6e51a550 100644 --- a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java @@ -8,12 +8,14 @@ import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import org.springframework.core.env.Environment; class StartupRuleRunnerTest { @@ -163,6 +165,81 @@ class StartupRuleRunnerTest { }); } + @Test + @DisplayName("비밀 목록을 겸하는 JavaBean 설정 클래스는 일찍 만들어지면 바인딩되지 않으므로 그 bean 이름을 대며 기동을 실패시킨다") + void aSettingsClassThatIsAlsoAProductionSecretsListFailsTheBoot() { + // given + BindingSecretsSettings.SEEN.clear(); + + // when + runner + .withPropertyValues("probe2.name=bound") + .withUserConfiguration(SecretReadingRuleConfig.class, BindingSecretsConfig.class) + .run( + context -> { + // then + assertThat(BindingSecretsSettings.SEEN).doesNotContainNull(); + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("probe2-") + .hasMessageContaining("@ConfigurationProperties"); + }); + } + + @Test + @DisplayName("비밀 목록을 겸하는 JavaBean 설정 클래스는 그것을 읽는 규칙이 없어도 기동을 실패시킨다") + void aSettingsClassThatIsAlsoAProductionSecretsListFailsTheBootInEveryProfile() { + // when + runner + .withPropertyValues("probe2.name=bound") + .withUserConfiguration(BindingSecretsConfig.class) + .run( + context -> { + // then + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("probe2-"); + }); + } + + @Test + @DisplayName("@Value 필드를 가진 규칙 클래스는 필드가 주입되지 않으므로 그 필드 이름을 대며 기동을 실패시킨다") + void aRuleClassWithAValueFieldFailsTheBootNamingTheField() { + // given + FieldInjectedRule.SEEN.clear(); + + // when + runner + .withPropertyValues("probe3.mode=strict") + .withUserConfiguration(FieldInjectedRuleImport.class) + .run( + context -> { + // then + assertThat(FieldInjectedRule.SEEN).doesNotContainNull(); + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("FieldInjectedRule") + .hasMessageContaining("mode"); + }); + } + + @Test + @DisplayName("static @Bean이 돌려준 규칙이라도 @Value 필드가 있으면 기동을 실패시킨다") + void aStaticBeanRuleWhoseClassHasAValueFieldFailsTheBoot() { + // when + runner + .withPropertyValues("probe3.mode=strict") + .withUserConfiguration(StaticFieldInjectedRuleConfig.class) + .run( + context -> { + // then + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("fieldInjectedRule") + .hasMessageContaining("mode"); + }); + } + private static StartupRule rule(StartupPhase phase, String summary, List violations) { return new StartupRule() { @Override @@ -257,6 +334,67 @@ class StartupRuleRunnerTest { } } + /** RR2-04-03 2-a: a JavaBean settings class that is also the module's secret list. */ + @ConfigurationProperties("probe2") + public static class BindingSecretsSettings implements RequiredProductionSecrets { + static final List SEEN = new ArrayList<>(); + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public List requiredSecrets(Environment environment) { + SEEN.add(name); + return List.of(); + } + } + + @Configuration(proxyBeanMethods = false) + @EnableConfigurationProperties(BindingSecretsSettings.class) + static class BindingSecretsConfig {} + + /** RR2-04-03 2-b: the most common way to write a Spring component, as a rule. */ + public static class FieldInjectedRule implements StartupRule { + static final List SEEN = new ArrayList<>(); + + @Value("${probe3.mode}") + private String mode; + + @Override + public StartupPhase phase() { + return StartupPhase.ENV_VALIDATION; + } + + @Override + public String summary() { + return "field"; + } + + @Override + public List violations(Environment environment) { + SEEN.add(mode); + return List.of(); + } + } + + @Configuration(proxyBeanMethods = false) + @Import(FieldInjectedRule.class) + static class FieldInjectedRuleImport {} + + @Configuration(proxyBeanMethods = false) + static class StaticFieldInjectedRuleConfig { + @Bean + static StartupRule fieldInjectedRule() { + return new FieldInjectedRule(); + } + } + @Configuration(proxyBeanMethods = false) static class NonStaticSecretsConfig { @Bean diff --git a/src/app-bootstrap/CLAUDE.md b/src/app-bootstrap/CLAUDE.md index 4d816bcb..6056b12f 100644 --- a/src/app-bootstrap/CLAUDE.md +++ b/src/app-bootstrap/CLAUDE.md @@ -89,7 +89,10 @@ configurations, Redis as one 376-line class. and the one `StartupRuleRunner` raises them before any other singleton exists (declare it with a `static` `@Bean` method that takes only the `Environment`, the bean factory or an `ObjectProvider` of static `RequiredProductionSecrets`; the runner fails the boot naming any other bean a rule - creates). A guard that needs another bean stays a bean. A + creates, and naming any rule or `RequiredProductionSecrets` that has an `@Value`/`@Autowired`/ + `@Inject`/`@Resource` member, a `@PostConstruct`/`@PreDestroy` callback or a + `@ConfigurationProperties` binding — those are created before the post-processors and would stay + unset). A guard that needs another bean stays a bean. A capability's production secrets are the capability's: its module contributes a `RequiredProductionSecrets` bean, and `SecretSourceValidator` checks the names without knowing which roles exist. diff --git a/src/app-bootstrap/README.md b/src/app-bootstrap/README.md index 3f6fc3ab..e4b52f5d 100644 --- a/src/app-bootstrap/README.md +++ b/src/app-bootstrap/README.md @@ -129,11 +129,14 @@ README의 "startup" 절에 있다. ### SecretSourceValidator - **prod 에서 깨지면 부팅 자체를 거부하는 fail-fast 가드다.** 두 가지 prod 불변식을 context refresh 완료 전에 강제한다. (1) `__LOCAL_DEV_` 접두사를 가진 dev/local 가짜 자격증명 값이 prod 프로파일에 - 도달하는 것은 잘못 로드된 사고이므로 부팅을 중단시킨다. `fixture-` 접두사 값도 같다. 이 저장소가 + 도달하는 것은 잘못 로드된 사고이므로 부팅을 중단시킨다. 비밀값이 `fixture-`로 시작해도 같다. 이 저장소가 lane용으로 적어 둔 공개 비밀번호(`infra/redis-sdk/acl`의 Redis ACL fixture, compose lane의 `REDIS_LANE_*`)라서, lane 환경이나 lane ACL 파일을 베낀 배포가 그대로 운영에 뜨는 것을 막는다 - (review 2026-11-03 RR-07-04). 비밀이 아닌 설정값이라도 prod에서 `fixture-`로 시작하면 거부되니 이름을 - 바꾼다. 실패 메시지는 변수 이름만 적고 값은 적지 않는다. (2) 레지스트리에서 `secret` + + (review 2026-11-03 RR-07-04). 이 검사는 비밀값만 본다 — 레지스트리의 `secret` 행 + (`CLASSIFIED_SECRETS`), 모듈이 기여한 비밀, `secret://…/` 참조가 가리키는 변수 + (review 2026-11-04 RR2-04-01). `fixture-`는 평범한 단어라서 `fixture-api` Deployment의 pod 이름 + (`HOSTNAME`)이나 앱 이름까지 거부하면 운영에서만 기동이 막혔다. `__LOCAL_DEV_` 표시는 정당한 값이 가질 + 일이 없으니 모든 값을 본다. 실패 메시지는 변수 이름만 적고 값은 적지 않는다. (2) 레지스트리에서 `secret` + `prod_default: null`로 분류된 모든 키는 prod 에서 비어 있지 않게 주입돼야 한다 — 빈 시크릿으로 부팅하는 것은 금지다. dev/local 프로파일은 두 검사를 건너뛴다(`__LOCAL_DEV_*`가 의도된 로컬 폴백이므로). diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java index d64f500f..664b4f1b 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java @@ -25,6 +25,7 @@ import dev.caskeleton.application.capability.UseCaseCapability; import dev.caskeleton.application.messaging.event.IntegrationEventDraft; import dev.caskeleton.application.messaging.event.IntegrationEventDrafts; import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.security.SystemCaller; import dev.caskeleton.application.security.SystemInvoked; import dev.caskeleton.application.usecase.CommandUseCase; import dev.caskeleton.application.usecase.QueryUseCase; @@ -447,23 +448,109 @@ class ApplicationBoundaryArchitectureTest { .allowEmptyShould(true); /** - * A {@link SystemInvoked} use case is a write with no permission check, so no transport may reach - * it. A bean of one fails startup ({@code PermissionEnforcementGuard}); this closes the other - * path, an inbound adapter that constructs or calls one itself (review 2026-11-03 RR-01-02). + * The inbound packages the system drives rather than a user: a broker delivery, a schedule. Only + * a {@link SystemCaller} may live here and reach a {@link SystemInvoked} use case; every other + * inbound package — web, GraphQL, gRPC, WebSocket, and any transport added later — is a way a + * user request comes in. A new system-driven inbound family joins this list, nowhere else. + */ + private static final String[] SYSTEM_DRIVEN_INBOUND_PACKAGES = { + "..adapter.inbound.messaging..", "..adapter.inbound.scheduler.." + }; + + /** + * What makes a class a way in for a user request: a user-transport adapter package or the + * framework types an endpoint is built from. {@code org.springframework.messaging} is named only + * for STOMP ({@code simp}, {@code @MessageMapping}): a broker listener's {@code @Payload} and + * {@code @Header} live beside them and are a system consumer's, not a user's. + */ + private static final DescribedPredicate ARE_USER_TRANSPORT_TYPES = + JavaClass.Predicates.resideInAnyPackage( + "..adapter.inbound.web..", + "..adapter.inbound.graphql..", + "..adapter.inbound.grpc..", + "..adapter.inbound.websocket..", + "org.springframework.web..", + "org.springframework.graphql..", + "org.springframework.messaging.simp..", + "io.grpc..", + "jakarta.servlet..", + "jakarta.websocket..") + .or( + com.tngtech.archunit.core.domain.properties.HasName.Predicates.name( + "org.springframework.stereotype.Controller")) + .or( + com.tngtech.archunit.core.domain.properties.HasName.Predicates.name( + "org.springframework.messaging.handler.annotation.MessageMapping")) + .as("user-transport types (web, GraphQL, gRPC, WebSocket/STOMP endpoints)"); + + /** + * A class marked {@link SystemCaller}, or nested in one: a handler's anonymous or inner helper + * calls the use case on the handler's behalf. + */ + private static final DescribedPredicate ARE_SYSTEM_CALLERS = + new DescribedPredicate<>("are @SystemCaller classes or nested in one") { + @Override + public boolean test(JavaClass candidate) { + for (JavaClass type = candidate; + type != null; + type = type.getEnclosingClass().orElse(null)) { + if (type.isAnnotatedWith(SystemCaller.class)) { + return true; + } + } + return false; + } + }; + + /** + * A {@link SystemInvoked} use case is a write with no permission check, so no user request may + * reach it. A user comes in through a transport; the system comes in through a delivery or a tick + * (decision 9.1, review 2026-11-03 RR-01-12). An inbound adapter may depend on one only when it + * says it is the second kind — {@link SystemCaller} — and {@code + * SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS} checks that claim. The rule names who may, + * not who may not, so a transport added later is refused without editing it. A bean of one fails + * startup ({@code PermissionEnforcementGuard}). */ @ArchTest - static final ArchRule INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES = + static final ArchRule ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES = noClasses() .that() .resideInAPackage("..adapter.inbound..") + .and(DescribedPredicate.not(ARE_SYSTEM_CALLERS)) .should() .dependOnClassesThat() .areAnnotatedWith(SystemInvoked.class) .as( - "INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES: a @SystemInvoked use case " + "ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES: a @SystemInvoked use case " + "declares no permission because only the system calls it; an inbound adapter " - + "that reaches it runs a write with no authorization check. Its composition " - + "constructs it and hands it to the scheduler that calls it.") + + "a user request reaches (web, GraphQL, gRPC, WebSocket) must not depend on it. " + + "A message handler or scheduled job marks itself @SystemCaller(reason = ...) " + + "and constructs the use case it calls (manual 09 「소비」 step 4); a scheduler " + + "assembled in a composition module gets it the way the outbox relay does.") + .allowEmptyShould(true); + + /** + * {@link SystemCaller} is a claim, so it is checked: the marked class lives in a system-driven + * inbound package and is no endpoint a user can call — a controller, a GraphQL or STOMP mapping, + * a gRPC service. Without this the mark would be the next way to silence the rule above (review + * 2026-11-03 RR-01-12). + */ + @ArchTest + static final ArchRule SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS = + classes() + .that() + .areAnnotatedWith(SystemCaller.class) + .should() + .resideInAnyPackage(SYSTEM_DRIVEN_INBOUND_PACKAGES) + .andShould( + com.tngtech.archunit.lang.conditions.ArchConditions.never( + com.tngtech.archunit.lang.conditions.ArchConditions.dependOnClassesThat( + ARE_USER_TRANSPORT_TYPES))) + .as( + "SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS: a @SystemCaller lives in a " + + "system-driven inbound package (..adapter.inbound.messaging.., " + + "..adapter.inbound.scheduler..) and depends on no user-transport type — the mark " + + "says no user request reaches the class, so a user transport cannot carry it") .allowEmptyShould(true); /** 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 b4da42bc..e959f0e7 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 @@ -114,7 +114,6 @@ class ArchRuleDiscoveryContractTest { "IDENTIFIER_ADAPTER_DOES_NOT_DEPEND_ON_OTHER_ADAPTERS_OR_BOOTSTRAP", "INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES", "INBOUND_ADAPTERS_DO_NOT_DEPEND_ON_OUTBOUND_ADAPTERS", - "INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES", "INBOUND_PORT_IMPLEMENTATIONS_DECLARE_A_CAPABILITY", "INBOUND_PORT_IMPLEMENTATIONS_DECLARE_CAPABILITY", "INBOUND_PORT_IMPLEMENTATIONS_END_WITH_USE_CASE", @@ -144,6 +143,7 @@ class ArchRuleDiscoveryContractTest { "NO_UUID_RANDOM_IN_CONTROLLER", "NO_VARCHAR_255_FOR_ID_COLUMN", "NO_WEBSOCKET_HANDLER", + "ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES", "ONLY_THE_PERSISTENCE_ADAPTER_HOLDS_A_MONGO_HANDLE", "ONLY_THE_SECURITY_PACKAGE_HANDLES_KEY_MATERIAL", "OPTIONAL_ADAPTER_BEANS_ARE_GATED_BY_CONDITIONAL_ON_PROPERTY", @@ -164,6 +164,7 @@ class ArchRuleDiscoveryContractTest { "REQUEST_DTOS_DO_NOT_SILENCE_UNKNOWN_FIELDS", "SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES", "STARTUP_FAILURES_ARE_RAISED_THROUGH_THE_TYPED_FACTORY", + "SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS", "SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION", "TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES", "THROWABLES_ARE_NAMED_EXCEPTION", diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java index 2eb2d35f..cab3c152 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java @@ -6,8 +6,12 @@ import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.lang.EvaluationResult; import dev.caskeleton.application.architecture.violations.ApplicationDiagnosticFrameworkViolation; +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; import dev.caskeleton.bootstrap.architecture.allowed.application.CleanProjectionQueryPort; import dev.caskeleton.bootstrap.architecture.fixtures.application.RootWriteTransactionBoundaryUseCase; +import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.SystemCallerRestControllerFixture; +import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.UnmarkedSystemInvokedHandlerFixture; +import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemInvokedCallingControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.RawExternalResponseFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.messaging.GenericTypeLeakingAdapterFixture; @@ -158,25 +162,90 @@ class ArchitectureViolationFixtureTest { .importPackages("dev.caskeleton.bootstrap.architecture.violations.secrets"); // Review 2026-11-03 RR-01-02: the controller and the use case it reaches, and nothing else, so - // the rule is proven on the one dependency it forbids. + // the rule is proven on the one dependency it forbids. RR-01-12 narrowed the rule to user + // transports; this is the path it must still refuse. private static final JavaClasses SYSTEM_INVOKED_FROM_TRANSPORT_FIXTURE_ONLY = new ClassFileImporter() .importClasses( SystemInvokedCallingControllerFixture.class, SystemInvokedFixtureUseCase.class); + // Review 2026-11-03 RR-01-12: the consume path manual 09 teaches — a marked handler and the use + // case it constructs — and the same handler without the mark. + private static final JavaClasses SYSTEM_CALLER_HANDLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses(SystemCallerHandlerFixture.class, SystemInvokedFixtureUseCase.class); + + private static final JavaClasses UNMARKED_HANDLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + UnmarkedSystemInvokedHandlerFixture.class, SystemInvokedFixtureUseCase.class); + + // A user transport that carries the mark: by its package, and by being an HTTP endpoint inside a + // system-driven package. + private static final JavaClasses SYSTEM_CALLER_IN_A_USER_TRANSPORT_PACKAGE_FIXTURE_ONLY = + new ClassFileImporter().importClasses(SystemCallerControllerFixture.class); + + private static final JavaClasses SYSTEM_CALLER_THAT_IS_AN_HTTP_ENDPOINT_FIXTURE_ONLY = + new ClassFileImporter().importClasses(SystemCallerRestControllerFixture.class); + // Review 2026-11-03 RR-01-03: one class that builds the draft by hand. private static final JavaClasses HAND_BUILT_DRAFT_FIXTURE_ONLY = new ClassFileImporter().importClasses(HandBuiltIntegrationEventDraftFixture.class); @Test - void anInboundAdapterThatCallsASystemInvokedUseCaseIsCaught() { + void aWebAdapterThatCallsASystemInvokedUseCaseIsCaught() { EvaluationResult result = - ApplicationBoundaryArchitectureTest.INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES + ApplicationBoundaryArchitectureTest.ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES .evaluate(SYSTEM_INVOKED_FROM_TRANSPORT_FIXTURE_ONLY); assertThat(result.hasViolation()).isTrue(); } + @Test + void aMessageHandlerMarkedAsASystemCallerMayReachASystemInvokedUseCase() { + EvaluationResult result = + ApplicationBoundaryArchitectureTest.ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES + .evaluate(SYSTEM_CALLER_HANDLER_FIXTURE_ONLY); + + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + + @Test + void aMessageHandlerThatReachesASystemInvokedUseCaseWithoutTheMarkIsCaught() { + EvaluationResult result = + ApplicationBoundaryArchitectureTest.ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES + .evaluate(UNMARKED_HANDLER_FIXTURE_ONLY); + + assertThat(result.hasViolation()).isTrue(); + } + + @Test + void aMessageHandlerMarkedAsASystemCallerIsASystemDrivenInboundAdapter() { + EvaluationResult result = + ApplicationBoundaryArchitectureTest.SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS + .evaluate(SYSTEM_CALLER_HANDLER_FIXTURE_ONLY); + + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + + @Test + void aWebAdapterMarkedAsASystemCallerIsCaught() { + EvaluationResult result = + ApplicationBoundaryArchitectureTest.SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS + .evaluate(SYSTEM_CALLER_IN_A_USER_TRANSPORT_PACKAGE_FIXTURE_ONLY); + + assertThat(result.hasViolation()).isTrue(); + } + + @Test + void anHttpEndpointInAMessagingPackageMarkedAsASystemCallerIsCaught() { + EvaluationResult result = + ApplicationBoundaryArchitectureTest.SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS + .evaluate(SYSTEM_CALLER_THAT_IS_AN_HTTP_ENDPOINT_FIXTURE_ONLY); + + assertThat(result.hasViolation()).isTrue(); + } + @Test void aFeatureThatBuildsAnIntegrationEventDraftByHandIsCaught() { EvaluationResult result = diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/adapter/inbound/messaging/SystemCallerHandlerFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/adapter/inbound/messaging/SystemCallerHandlerFixture.java new file mode 100644 index 00000000..0a5067a8 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/adapter/inbound/messaging/SystemCallerHandlerFixture.java @@ -0,0 +1,18 @@ +package dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging; + +import dev.caskeleton.application.security.SystemCaller; +import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; + +/** + * The shape manual 09 teaches for a consumer: a handler the broker consumer drives, marked as a + * system caller, that constructs the system-invoked use case it calls and keeps it to itself. + */ +@SystemCaller(reason = "fixture: the broker consumer calls it for each delivery") +public final class SystemCallerHandlerFixture { + + private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase(); + + public void handle() { + useCase.handle(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/adapter/inbound/messaging/package-info.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/adapter/inbound/messaging/package-info.java new file mode 100644 index 00000000..e2765663 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/adapter/inbound/messaging/package-info.java @@ -0,0 +1,9 @@ +/** + * "Allowed-as-data" fixture for the system-caller rules (review 2026-11-03 RR-01-12): a message + * handler that the broker consumer drives, marked {@code @SystemCaller}, calling a + * {@code @SystemInvoked} use case it constructed itself. {@code + * ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} and {@code + * SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS} must NOT flag it — it is the one legitimate + * way a consumer reaches a system write (manual 09 「소비」 step 4). + */ +package dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging; diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/messaging/SystemCallerRestControllerFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/messaging/SystemCallerRestControllerFixture.java new file mode 100644 index 00000000..81383c14 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/messaging/SystemCallerRestControllerFixture.java @@ -0,0 +1,23 @@ +package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging; + +import dev.caskeleton.application.security.SystemCaller; +import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Negative fixture for {@code SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS}: an HTTP endpoint + * placed in a system-driven inbound package and marked as a system caller. The package is right; + * the class is still a user transport (review 2026-11-03 RR-01-12). + */ +@SystemCaller(reason = "fixture: an HTTP endpoint hiding in the messaging package") +@RestController +public class SystemCallerRestControllerFixture { + + private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase(); + + @PostMapping("/fixture/system-write") + public void trigger() { + useCase.handle(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/messaging/UnmarkedSystemInvokedHandlerFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/messaging/UnmarkedSystemInvokedHandlerFixture.java new file mode 100644 index 00000000..cb8c183f --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/messaging/UnmarkedSystemInvokedHandlerFixture.java @@ -0,0 +1,17 @@ +package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging; + +import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; + +/** + * Negative fixture for {@code ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES}: a handler in a + * system-driven inbound package that reaches a {@code @SystemInvoked} use case without saying it is + * a system caller. The package alone is not the mark (review 2026-11-03 RR-01-12). + */ +public final class UnmarkedSystemInvokedHandlerFixture { + + private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase(); + + public void handle() { + useCase.handle(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemCallerControllerFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemCallerControllerFixture.java new file mode 100644 index 00000000..a2ca9337 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemCallerControllerFixture.java @@ -0,0 +1,19 @@ +package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller; + +import dev.caskeleton.application.security.SystemCaller; +import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; + +/** + * Negative fixture for {@code SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS}: a web adapter + * that claims to be a system caller to reach a {@code @SystemInvoked} use case. A user transport + * cannot carry the mark (review 2026-11-03 RR-01-12). + */ +@SystemCaller(reason = "fixture: claims a system caller from a user transport") +public class SystemCallerControllerFixture { + + private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase(); + + public void trigger() { + useCase.handle(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemInvokedCallingControllerFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemInvokedCallingControllerFixture.java index dfe5f538..4d0d9f3d 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemInvokedCallingControllerFixture.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemInvokedCallingControllerFixture.java @@ -3,9 +3,9 @@ package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.con import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; /** - * Negative fixture for {@code INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES}: an inbound - * adapter that calls a {@code @SystemInvoked} use case, a write with no permission gate, straight - * from a transport (review 2026-11-03 RR-01-02). + * Negative fixture for {@code ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES}: a user transport + * that calls a {@code @SystemInvoked} use case, a write with no permission gate (review 2026-11-03 + * RR-01-02; still refused after RR-01-12 let system callers through). */ public class SystemInvokedCallingControllerFixture { diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/SystemInvokedFixtureUseCase.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/SystemInvokedFixtureUseCase.java index 00e5fc4d..b01bb447 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/SystemInvokedFixtureUseCase.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/application/SystemInvokedFixtureUseCase.java @@ -3,9 +3,10 @@ package dev.caskeleton.bootstrap.architecture.violations.application; import dev.caskeleton.application.security.SystemInvoked; /** - * A use case only the system calls. Not a violation on its own: it is what {@code - * SystemInvokedCallingControllerFixture} reaches, the transport path {@code - * INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES} forbids. + * A use case only the system calls. Not a violation on its own: it is what the inbound fixtures + * reach — {@code SystemInvokedCallingControllerFixture}, the user-transport path {@code + * ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} forbids, and {@code + * SystemCallerHandlerFixture}, the consume path it allows. */ @SystemInvoked(reason = "fixture: a scheduler calls it") public final class SystemInvokedFixtureUseCase { diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java index 7d4c1662..d781a4b5 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java @@ -4,14 +4,14 @@ import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets; import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; import dev.caskeleton.adapter.outbound.support.startup.StartupRule; +import dev.caskeleton.application.secret.SecretReference; import dev.caskeleton.application.secret.SecretSourcePort; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.function.BiConsumer; import java.util.function.Supplier; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.EnumerablePropertySource; @@ -38,20 +38,47 @@ public final class SecretSourceValidator implements StartupRule { * Prefix of the passwords this repository writes down for its lanes: the Redis ACL fixtures in * {@code infra/redis-sdk/acl} and the Compose lanes' {@code REDIS_LANE_*} values that connect * with them. They are public — anyone who can read the repository has them — so under {@code - * prod} they are refused like the sentinel (review 2026-11-03 RR-07-04). A deployment that copied - * a lane's environment — which is also what an application needs to authenticate against a Redis - * that loaded the lane ACL file — would start with credentials it does not own; this is the one - * place that sees every value before anything connects. It cannot see a Redis server that loaded - * that file while the application uses real passwords; the ACL README says why no deployment - * loads it. + * prod} a secret holding one is refused (review 2026-11-03 RR-07-04). A deployment that copied a + * lane's environment — which is also what an application needs to authenticate against a Redis + * that loaded the lane ACL file — would start with credentials it does not own. It cannot see a + * Redis server that loaded that file while the application uses real passwords; the ACL README + * says why no deployment loads it. + * + *

        Only secrets are read for it (review 2026-11-04 RR2-04-01, owner decision): {@code fixture-} + * is an ordinary word before it is this repository's password prefix, and a pod named after a + * {@code fixture-api} Deployment carries it in {@code HOSTNAME}. Checking every value refused + * that deployment in production only, with no way around it short of renaming the service. The + * {@code __LOCAL_DEV_} sentinel is still looked for in every value: no legitimate value carries + * an invented marker, so the wide scan costs nothing there. */ static final String REPOSITORY_FIXTURE_PREFIX = "fixture-"; - /** Values that are public by construction and so can never be a production secret. */ - private static final Map PUBLIC_CREDENTIAL_PREFIXES = - Map.of( - LOCAL_DEV_SENTINEL_PREFIX, "sentinel credential", - REPOSITORY_FIXTURE_PREFIX, "repository fixture password (public, infra/redis-sdk/acl)"); + /** + * The keys {@code docs/registries/secrets-classification.yaml} classifies {@code secret}: the + * values the {@code fixture-} check reads, together with what a credential reference names and + * what a module contributes. {@code SecretsClassificationRegistryTest} holds this list to the + * registry 1:1, the way it holds {@link #REQUIRED_PROD_SECRETS}. + */ + public static final List CLASSIFIED_SECRETS = + List.of( + "APP_DATASOURCE_PASSWORD", + "SPRING_MAIL_PASSWORD", + "APP_CACHE_REDIS_PASSWORD", + "APP_CACHE_REDIS_KEY_HMAC_SECRET", + "APP_RATE_LIMIT_REDIS_PASSWORD", + "APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET", + "APP_SESSION_REDIS_PASSWORD", + "APP_SESSION_REDIS_KEY_HMAC_SECRET", + "APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET", + "APP_LEASE_REDIS_KEY_HMAC_SECRET", + "APP_PRIVACY_PSEUDONYMIZATION_SALT", + "APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY", + "APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY", + "APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY", + "APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY", + "APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY", + "APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY", + "APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY"); /** * Secret keys that must be injected under the {@code prod} profile whatever the deployment @@ -89,8 +116,8 @@ public final class SecretSourceValidator implements StartupRule { @Override public String remedy() { return "inject real non-blank secrets from the secret manager / mounted environment; " - + "local/dev sentinel credentials and the repository's fixture-* passwords are forbidden" - + " in prod."; + + "local/dev sentinel credentials, and the repository's fixture-* lane passwords in a" + + " secret, are forbidden in prod."; } @Override @@ -98,53 +125,100 @@ public final class SecretSourceValidator implements StartupRule { if (!RuntimeProfileSnapshot.from(environment).isProduction()) { return List.of(); } - List violations = new ArrayList<>(); - collectPublicCredentialViolations(environment, violations); - collectMissingSecretViolations(environment, violations); - return violations; - } - - /** - * Names every property whose value is public by construction. Every property source is read, the - * process environment included, because a credential reference ({@code - * secret://@environment/}) may point at any variable name. The value itself is - * never put in the message. - */ - private static void collectPublicCredentialViolations( - Environment environment, List violations) { - if (!(environment instanceof ConfigurableEnvironment configurable)) { - return; - } - Map offenders = new LinkedHashMap<>(); - for (PropertySource source : configurable.getPropertySources()) { - if (source instanceof EnumerablePropertySource enumerable) { - for (String name : enumerable.getPropertyNames()) { - if (enumerable.getProperty(name) instanceof String text) { - PUBLIC_CREDENTIAL_PREFIXES.keySet().stream() - .filter(text::startsWith) - .findFirst() - .ifPresent(prefix -> offenders.putIfAbsent(name, prefix)); - } - } - } - } - offenders.forEach( - (offender, prefix) -> - violations.add( - "'" - + prefix - + "' " - + PUBLIC_CREDENTIAL_PREFIXES.get(prefix) - + " is configured for " - + offender)); - } - - private void collectMissingSecretViolations(Environment environment, List violations) { SecretSourcePort secretSource = SecretSourceFactory.fromEnvironment(environment); Set required = new LinkedHashSet<>(REQUIRED_PROD_SECRETS); // Each module names the secrets its selected capabilities need. This guard does not know which // capabilities a module has or how they are selected — it only checks the names resolve. contributed.get().forEach(module -> required.addAll(module.requiredSecrets(environment))); + List violations = new ArrayList<>(); + collectSentinelViolations(environment, violations); + collectFixturePasswordViolations(environment, secretSource, required, violations); + collectMissingSecretViolations(secretSource, required, violations); + return violations; + } + + /** + * Names every property whose value carries the dev/local sentinel. Every property source is read, + * the process environment included, because a credential reference ({@code + * secret://@environment/}) may point at any variable name. The value itself is + * never put in the message. + */ + private static void collectSentinelViolations(Environment environment, List violations) { + Set offenders = new LinkedHashSet<>(); + forEachStringValue( + environment, + (name, value) -> { + if (value.startsWith(LOCAL_DEV_SENTINEL_PREFIX)) { + offenders.add(name); + } + }); + offenders.forEach( + offender -> + violations.add( + "'" + + LOCAL_DEV_SENTINEL_PREFIX + + "' sentinel credential is configured for " + + offender)); + } + + /** + * Names every secret that holds a lane fixture password: the keys the registry classifies {@code + * secret}, the ones a module contributed, and every variable a credential reference names. Read + * through the same backend the application resolves them with. The value is never put in the + * message. + */ + private static void collectFixturePasswordViolations( + Environment environment, + SecretSourcePort secretSource, + Set required, + List violations) { + Set secrets = new LinkedHashSet<>(CLASSIFIED_SECRETS); + secrets.addAll(required); + forEachStringValue( + environment, + (name, value) -> { + if (SecretReference.isReference(value)) { + try { + secrets.add(SecretReference.parse(value).name()); + } catch (IllegalArgumentException ignored) { + // Malformed: the capability that reads this reference refuses it with its own + // message. + } + } + }); + for (String secret : secrets) { + secretSource + .resolve(secret) + .filter(value -> value.startsWith(REPOSITORY_FIXTURE_PREFIX)) + .ifPresent( + value -> + violations.add( + "secret " + + secret + + " holds a lane fixture password ('" + + REPOSITORY_FIXTURE_PREFIX + + "…', public in infra/redis-sdk/acl)")); + } + } + + private static void forEachStringValue( + Environment environment, BiConsumer action) { + if (!(environment instanceof ConfigurableEnvironment configurable)) { + return; + } + for (PropertySource source : configurable.getPropertySources()) { + if (source instanceof EnumerablePropertySource enumerable) { + for (String name : enumerable.getPropertyNames()) { + if (enumerable.getProperty(name) instanceof String text) { + action.accept(name, text); + } + } + } + } + } + + private static void collectMissingSecretViolations( + SecretSourcePort secretSource, Set required, List violations) { for (String key : required) { if (secretSource.resolve(key).isEmpty()) { violations.add(key + " is missing/blank"); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java index 5e8c33bf..6dd3794f 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -79,6 +80,30 @@ class SecretsClassificationRegistryTest { .isEqualTo(new LinkedHashSet<>(SecretSourceValidator.REQUIRED_PROD_SECRETS)); } + @Test + @DisplayName("prod fixture 비밀번호 검사가 읽는 비밀 목록은 레지스트리의 secret 분류 행과 1:1로 같다") + void classifiedSecretRowsMatchTheFixtureCheckListOneToOne() { + // given + Set registrySecrets = new LinkedHashSet<>(); + for (Map row : registryRows) { + if ("secret".equals(row.get("classification"))) { + registrySecrets.add((String) row.get("name")); + } + } + + // when + Set checked = new LinkedHashSet<>(SecretSourceValidator.CLASSIFIED_SECRETS); + + // then + assertThat(checked) + .as( + "SecretSourceValidator.CLASSIFIED_SECRETS is what the prod fixture-password check reads" + + " (review 2026-11-04 RR2-04-01: secrets only, not every value). A row classified" + + " 'secret' in docs/registries/secrets-classification.yaml that the list misses is" + + " a secret the check never looks at.") + .isEqualTo(registrySecrets); + } + @Test void everyRegistryRowUsesAValidClassificationTier() { for (Map row : registryRows) { 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 aaeabb20..db81d0a3 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 @@ -8,6 +8,7 @@ import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; import dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration; import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -15,6 +16,7 @@ import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.SystemEnvironmentPropertySource; /** * Contract test for the secret/config-source startup fail-fast guard @@ -106,16 +108,20 @@ class SecretSourceValidatorTest { // ---- repository fixture passwords (review 2026-11-03 RR-07-04) -------------------------- @Test - @DisplayName("prod에서 비밀값이 저장소 fixture 비밀번호(fixture-)면 그 변수를 짚어 기동을 거부한다") + @DisplayName("prod에서 비밀 참조가 가리키는 변수가 저장소 fixture 비밀번호(fixture-)면 그 변수를 짚어 기동을 거부한다") void prodProfileWithARepositoryFixturePasswordFailsStartup() { // given ApplicationContextRunner prodWithLaneFixture = runner .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) .withPropertyValues(allRequiredSecretsPresent()) - // The Compose Redis lanes' value: a public password from infra/redis-sdk/acl, which a - // deployment that copied the lane's environment would carry into production. - .withPropertyValues("REDIS_LANE_APPLICATION_PASSWORD=fixture-application"); + // The Compose Redis lanes' shape: a credential reference, and the variable it names + // holding a public password from infra/redis-sdk/acl. A deployment that copied the + // lane's environment would carry both into production. + .withPropertyValues( + "APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE=" + + "secret://ca-skeleton-application@environment/REDIS_LANE_APPLICATION_PASSWORD", + "REDIS_LANE_APPLICATION_PASSWORD=fixture-application"); // when prodWithLaneFixture.run( @@ -133,6 +139,55 @@ class SecretSourceValidatorTest { }); } + @Test + @DisplayName("prod에서 비밀로 분류된 키의 값이 저장소 fixture 비밀번호(fixture-)면 그 키를 짚어 기동을 거부한다") + void prodProfileWithAFixturePasswordInAClassifiedSecretFailsStartup() { + // given + ApplicationContextRunner prodWithFixtureSecret = + runner + .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) + .withPropertyValues(allRequiredSecretsPresent()) + .withPropertyValues("APP_CACHE_REDIS_PASSWORD=fixture-application"); + + // when + prodWithFixtureSecret.run( + context -> { + // then + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("APP_CACHE_REDIS_PASSWORD") + .hasMessageContaining("lane fixture password"); + }); + } + + @Test + @DisplayName("prod에서 비밀이 아닌 값(HOSTNAME·앱 이름·topic)이 fixture-로 시작해도 기동한다") + void prodStartsWhenOnlyNonSecretValuesStartWithTheFixturePrefix() { + // given + ApplicationContextRunner prodWithFixtureNamedService = + runner + .withInitializer( + ctx -> { + ctx.getEnvironment().setActiveProfiles("prod"); + // Kubernetes names the pod after its Deployment and hands it in as HOSTNAME. + ctx.getEnvironment() + .getPropertySources() + .addLast( + new SystemEnvironmentPropertySource( + "podEnvironment", Map.of("HOSTNAME", "fixture-api-6d5f7c9b8-x2k4q"))); + }) + .withPropertyValues(allRequiredSecretsPresent()) + .withPropertyValues( + "spring.application.name=fixture-service", "app.messaging.topic=fixture-updates"); + + // when + prodWithFixtureNamedService.run( + context -> { + // then + assertThat(context).hasNotFailed(); + }); + } + @Test @DisplayName("prod가 아니면 저장소 fixture 비밀번호(fixture-)로도 기동한다") void nonProdProfileWithARepositoryFixturePasswordStarts() { diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index 93780a35..5a7b5071 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -130,7 +130,7 @@ goes. `docs/manual/03-placement.md` points here. | `usecase`, `command`, `query` | application-core | inbound port base types and the command/query markers | | `capability` | application-core | `@UseCaseCapability` and its enums | | `transaction` | application-core | `TransactionPort` and its modes | -| `security` | application-core | authorization port, `@RequiresPermission`, `@SystemInvoked`, `ObjectAccessPolicy` | +| `security` | application-core | authorization port, `@RequiresPermission`, `@SystemInvoked`, `@SystemCaller`, `ObjectAccessPolicy` | | `tenant` | application-core | `TenantId` | | `observability` | application-core | `CorrelationIdPort`, `UserPrincipalPseudonymizerPort` | | `secret` | application-core | `SecretSourcePort`, `SecretReference` | @@ -200,10 +200,14 @@ application-core never self-registers with a DI framework. It is **not final**: declares `@RequiresPermission`, the web adapter enforces it through a CGLIB proxy, and CGLIB cannot subclass a final class (`RequiresPermissionProxyabilityTest`). It is registered as a bean for the same reason — a use case built with `new` is never checked. A use case only the system calls (a -scheduler, a relay) carries `@SystemInvoked(reason = ...)` instead of a permission and is not a bean: -it is a write with no permission check, so a transport must not reach it. Both halves are enforced — -a `@SystemInvoked` bean fails startup, and an inbound adapter that depends on one fails -`INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES`. A composition with `@RequiresPermission` +scheduler, a relay, a message consumer) carries `@SystemInvoked(reason = ...)` instead of a +permission and is not a bean: it is a write with no permission check, so no user request may reach +it. Its system caller constructs it — a composition module for a scheduler, or a +`@SystemCaller(reason = ...)` message handler in `..adapter.inbound.messaging..` (manual 09 +「소비」 step 4). Both halves are enforced — a `@SystemInvoked` bean fails startup, and an inbound +adapter that depends on one without being a `@SystemCaller` fails +`ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES` (`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS` +keeps the mark off user transports). A composition with `@RequiresPermission` beans but no enforcing advisor fails startup too (`composition:service-runtime` `PermissionEnforcementGuard`, both checks). @@ -255,13 +259,17 @@ generation; the V1 `IdempotencyScope`/`tryBegin` API is gone. `app.capabilities.idempotency.provider` (`redis` → `cache-redis`, `postgresql` → `persistence-jpa`; default `disabled`). In-memory prod storage is forbidden. - **Executor**: built once by `composition:idempotency` `IdempotencyAutoConfiguration` from - `IdempotencySettings` (processing lease 30s, replay TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h, - failure retention 24h). Do not construct it in a use case or a sample config. + `IdempotencySettings` (processing lease 30s, replay TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h and not + shorter than the lease, failure retention 24h). Do not construct it in a use case or a sample config. - The action returns `IdempotentAction.Outcome` (`Success` / `RetryableNoEffect` / `EffectUnknown`); a thrown exception counts as effect-unknown. In progress → 409 `IDEMPOTENT_IN_FLIGHT`, fingerprint mismatch (SHA-256) → 422 `IDEMPOTENT_REQUEST_MISMATCH`; `IdempotencyUnavailableException` and `IdempotencyRecoveryRequiredException` mean the store could not prove the outcome, so do not blindly retry. +- Every store answers an execution whose processing lease ran out with `RecoveryRequired` and never + takes it over; only a claim that never started or a retryable failure is taken over. A record lives + for the lease plus the replay TTL. `IdempotencyStoreContract` holds the fake, Redis and PostgreSQL + to both on real servers (re-review 2026-11-04 RR-01-11, RR-03-11). The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency` and its fixture were removed when this branch merged. diff --git a/src/application-core/README.md b/src/application-core/README.md index b86059ed..3a71c1db 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -454,10 +454,11 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. `@RequiresPermission("outbox:relay")`는 D4 규칙을 통과시키려고 붙인 장식이었다(빈이 아니라 한 번도 검사되지 않았고, 빈이었다면 매 tick 거부됐다). ArchUnit D4는 `@SystemInvoked`를 권한 선언 대신 받고, `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`이 둘을 함께 다는 것을 막는다. - 면제의 전제(전송 계층이 닿지 않는다)도 코드가 지킨다: `@SystemInvoked` 빈은 - `PermissionEnforcementGuard`가 기동을 실패시키고, inbound adapter가 그 클래스에 의존하면 - `INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES`가 빌드를 실패시킨다(review 2026-11-03 - RR-01-02). + 면제의 전제(사용자 요청이 닿지 않는다)도 코드가 지킨다: `@SystemInvoked` 빈은 + `PermissionEnforcementGuard`가 기동을 실패시키고, `@SystemCaller`가 아닌 inbound adapter가 그 클래스에 + 의존하면 `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`가 빌드를 실패시킨다(review 2026-11-03 + RR-01-02, RR-01-12). 메시지 소비자는 `@SystemCaller` handler가 use case를 직접 만든다(매뉴얼 09장 + 「소비」 4단계). ### OutboxBackoffPolicy diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimOutcome.java index a23fc9d2..64eb0246 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimOutcome.java @@ -24,6 +24,13 @@ public sealed interface IdempotencyClaimOutcome { } } + /** + * This caller now holds a record somebody else held before: a claim whose lease ran out before it + * started executing, or an attempt marked retryable without effect. Nothing ran under the + * previous holder, so running the action is safe. A record whose execution had started is never + * taken over — its effect is unknown, and the claim answers {@link RecoveryRequired} instead + * (re-review 2026-11-04 RR-01-11, {@code IdempotencyStoreContract}). + */ record TakenOverClaimed(IdempotencyOwner owner, Instant processingLeaseUntil) implements IdempotencyClaimOutcome { public TakenOverClaimed { @@ -50,6 +57,11 @@ public sealed interface IdempotencyClaimOutcome { } } + /** + * An earlier attempt may have taken effect and nobody can say whether it did: it was marked + * abandoned with an unknown effect, or its processing lease ran out while it was executing. The + * action must not run again under this key; the outcome is settled from business data. + */ record RecoveryRequired(long currentAttempt) implements IdempotencyClaimOutcome { public RecoveryRequired { if (currentAttempt < 1) { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompletionUnknownException.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompletionUnknownException.java index 2d067c1b..13448bcc 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompletionUnknownException.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompletionUnknownException.java @@ -8,13 +8,18 @@ import dev.caskeleton.shared.error.OperationalError; * The action ran, and the store did not answer when its result was being recorded. * *

        Not {@link IdempotencyUnavailableException}: that one is raised before the action, so the - * request certainly did not apply. Here it may have. Effects inside the action's own transaction - * roll back with this exception; anything else the action did — a call to another system, a message - * — has happened. Telling the client "not applied" would invite a resend under a new key, which is - * the duplicate the key exists to prevent (re-review 2026-11-03, RR-02-03). + * request certainly did not apply. Here it may have. When {@code execute} was called inside the + * caller's write transaction, the action's database writes roll back with this exception; an action + * that committed a transaction of its own has kept them, and anything else it did — a call to + * another system, a message — has happened. Telling the client "not applied" would invite a resend + * under a new key, which is the duplicate the key exists to prevent (re-review 2026-11-03, + * RR-02-03). * - *

        A resend with the same key is safe: the server judges it as a replay when the result was in - * fact recorded, as in-flight while the attempt's lease lasts, and as recovery-required after that. + *

        A resend with the same key does not run the action again: the server judges it as a replay + * when the result was in fact recorded, as in-flight while the attempt's processing lease lasts, + * and as recovery-required after that. Both stores answer so ({@code IdempotencyStoreContract}, + * re-review 2026-11-04 RR-01-11). The record lasts the lease plus the replay TTL; a resend after + * that finds no record and is a new request. */ public final class IdempotencyCompletionUnknownException extends RuntimeException implements ApiErrorCarrier { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java index 6dae5a62..4ca9e5f5 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java @@ -133,6 +133,9 @@ public final class IdempotencyExecutor { startAndRun(request, acquired.owner(), action, codec, false); case IdempotencyClaimOutcome.ReplayedAcquire replayed -> startAndRun(request, replayed.owner(), action, codec, false); + // Only a claim that never started or failed without effect is taken over, so running here is + // the first run that can have an effect. An execution whose lease ran out is not: the store + // answers RecoveryRequired for it above (IdempotencyStoreContract, RR-01-11). case IdempotencyClaimOutcome.TakenOverClaimed takenOver -> startAndRun(request, takenOver.owner(), action, codec, false); }; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java index 73a17469..b1eac0c8 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAggregateSequencePort.java @@ -27,10 +27,14 @@ import dev.caskeleton.application.messaging.event.AggregateIdentity; * for events the retention reaper has since deleted, and greater than any number an outbox * row of the aggregate carries when the call is made. *

      12. Where an implementation replaced an earlier numbering (the sample's wall clock), greater - * than any number that numbering could have sent for the aggregate — also for rows deleted - * since, or written under an identity that has since changed. The first number is therefore - * not necessarily 1: the JPA counter starts above the moment its migration ran, in epoch - * microseconds (review RR-03-02). + * than any number that numbering sent for the aggregate before the replacement took effect — + * also for rows deleted since, or written then under an identity that has since changed. The + * first number is therefore not necessarily 1: the JPA counter starts above the moment its + * migration ran, in epoch microseconds (review RR-03-02). A number an instance still on the + * earlier numbering writes after that is covered only under the same identity (the item + * above): under an identity this call no longer uses it is invisible, and the new number can + * be smaller. A deploy that changes the identity therefore stops every old writer before the + * new version writes (runbook outbox-dead-letter §8; re-review round 2, RR-02-10). *
      13. Two first calls for one aggregate that overlap both succeed, with consecutive numbers. *
      14. Independent per aggregate identity: one aggregate's numbers say nothing about another's. * diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java index b96ac1da..2a590b14 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java @@ -103,9 +103,12 @@ public interface OutboxStorePort { * {@code outbox.pending.size} metric. Called outside a transaction (read-only). * *

        PUBLISHED is never counted: those rows wait on nothing, and counting them would scan the - * whole retention window on every poll. + * whole retention window on every poll. A status this version has no constant for (written by a + * later version, or by hand) is left out rather than failing the whole count, so the gauges of + * the statuses it does know stay up. * - * @return map from status to row count; PUBLISHED and statuses with zero rows are absent + * @return map from status to row count; PUBLISHED, unknown statuses and statuses with zero rows + * are absent */ Map countByStatus(); diff --git a/src/application-core/src/main/java/dev/caskeleton/application/security/SystemCaller.java b/src/application-core/src/main/java/dev/caskeleton/application/security/SystemCaller.java new file mode 100644 index 00000000..851dfebe --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/security/SystemCaller.java @@ -0,0 +1,34 @@ +package dev.caskeleton.application.security; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marks an inbound adapter that the system drives — a message handler the broker consumer calls, a + * scheduled job — and that therefore may call a {@link SystemInvoked} use case. + * + *

        A {@code @SystemInvoked} use case is a write with no permission check, so no user request may + * reach it. A user reaches the service through a transport (web, GraphQL, gRPC, WebSocket); the + * system reaches it through a delivery or a tick. This marker is how an inbound adapter of the + * second kind says so, in code, next to the reason. Without it an inbound adapter that depends on a + * {@code @SystemInvoked} use case fails {@code ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES}; + * with it, {@code SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS} checks the claim: the class + * lives in a system-driven inbound package ({@code ..adapter.inbound.messaging..}, {@code + * ..adapter.inbound.scheduler..}) and depends on no user-transport type. A controller cannot carry + * it. + * + *

        The marked adapter constructs the use case it calls with {@code new} from the ports it is + * given and keeps it to itself: the use case is never a bean ({@code PermissionEnforcementGuard} + * refuses one), so nothing but this adapter holds it. Review 2026-11-03 RR-01-12, decision 9.1. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface SystemCaller { + + /** What drives this adapter and why no user request reaches it. */ + String reason(); +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java b/src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java index 54b9cb18..ab646e1a 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/security/SystemInvoked.java @@ -7,22 +7,25 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Marks a mutating use case that only the system calls — a scheduler, a relay — and that therefore - * carries no {@link RequiresPermission}. + * Marks a mutating use case that only the system calls — a scheduler, a relay, a message consumer — + * and that therefore carries no {@link RequiresPermission}. * *

        A permission gate on such a use case is decoration: the method-security advisor checks the - * caller's {@code Authentication}, a scheduler thread has none, so the gate either never runs (the - * use case is not a bean) or refuses every call (it is). This marker states that instead, and the - * architecture rule that otherwise requires a permission on every {@code WRITE_REPOSITORY} use case - * accepts it in place of one. + * caller's {@code Authentication}, a scheduler or consumer thread has none, so the gate either + * never runs (the use case is not a bean) or refuses every call (it is). This marker states that + * instead, and the architecture rule that otherwise requires a permission on every {@code + * WRITE_REPOSITORY} use case accepts it in place of one. * - *

        A use case marked this way is a write with no permission check, so a transport must never - * reach it. The composition that runs it constructs it directly and hands it to its system caller. - * Both ways a transport could reach it are refused: a bean of it fails startup ({@code + *

        A use case marked this way is a write with no permission check, so no user request may reach + * it. Its system caller constructs it directly and keeps it: a composition module hands it to a + * scheduler (the outbox relay), or a {@link SystemCaller} inbound adapter — a message handler, a + * scheduled job — constructs it from the ports its bean method receives (manual 09 「소비」 step 4). + * Both ways a user could reach it are refused: a bean of it fails startup ({@code * composition:service-runtime} {@code PermissionEnforcementGuard}), and an inbound adapter that - * depends on it fails the architecture rule {@code - * INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES}. It is not a way to silence the rule that - * a mutating use case declares a permission: a write a user triggers declares one. + * depends on it without being a {@link SystemCaller} fails the architecture rule {@code + * ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} (review 2026-11-03 RR-01-02, RR-01-12). It is + * not a way to silence the rule that a mutating use case declares a permission: a write a user + * triggers declares one, and a write both a user and the system trigger is two use cases. */ @Documented @Retention(RetentionPolicy.RUNTIME) diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java index 29bfef2f..ce58c450 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java @@ -31,14 +31,28 @@ import org.junit.jupiter.api.Test; * against the in-memory fake and every store: the fake, the Redis store over the command fake and * over a real server, and the PostgreSQL store over a real database. * - *

        Mostly time-free: expiry and take-over of an abandoned lease depend on whose clock the store - * trusts, and those cases stay with each store's own tests. The one timed case is the one a caller - * relies on whichever store is composed — {@code renew} really extends the lease (review 05-02: the - * Redis store answered a renew as already applied and let the lease run out). A store reaches time - * through {@link #elapse(Duration)}. A store that cannot move its clock — the in-memory fake, which - * models no expiry, and the Redis store over the command fake — keeps the default, which aborts the - * timed case so the report shows it skipped instead of passing a case that never ran its clock - * (review 2026-11-03 RR-01-06). + *

        Mostly time-free. The timed cases are the ones a caller relies on whichever store is composed, + * because the stores used to differ on them and every gate stayed green: + * + *

          + *
        • {@code renew} really extends the lease (review 05-02: the Redis store answered a renew as + * already applied and let the lease run out); + *
        • a lease that runs out takes over only what never ran or failed without effect. A record + * whose execution had started is answered "recovery required" and never run again: its effect + * is unknown, and a client resending the same key after a result-unknown 503 was told exactly + * that (re-review 2026-11-04 RR-01-11 — the Redis store took it over and ran it a second + * time, the PostgreSQL store did not); + *
        • a record outlives its processing lease by the replay TTL, whatever the two are set to. A + * record that expired first — Redis at its key TTL, PostgreSQL at the reaper — let the next + * claim of a running operation acquire it fresh (re-review 2026-11-04 RR-03-11), and one that + * expired with its lease left no record to answer "recovery required" from. + *
        + * + *

        A store reaches time through {@link #elapse(Duration)}, which also runs whatever expires the + * store's records (Redis does it itself; the PostgreSQL contract runs the reaper). A store that + * cannot move its clock — the in-memory fake, which models no expiry, and the Redis store over the + * command fake — keeps the default, which aborts the timed case so the report shows it skipped + * instead of passing a case that never ran its clock (review 2026-11-03 RR-01-06). * *

        Every call goes through {@link #inTransaction(Supplier)}, the way the store's callers make it: * the PostgreSQL store refuses to run outside an application-owned write transaction. @@ -85,9 +99,11 @@ public abstract class IdempotencyStoreContract { } /** - * Lets {@code duration} pass on the clock the store trusts. The default aborts the calling test: - * a store without a clock the contract can move cannot run a timed case, and a no-op here would - * let that case pass without time ever passing. + * Lets {@code duration} pass on the clock the store trusts, and then lets the store expire what + * it expires on its own — so a record the store would have dropped by then is gone when the next + * call arrives. The default aborts the calling test: a store without a clock the contract can + * move cannot run a timed case, and a no-op here would let that case pass without time ever + * passing. * * @param duration how long to let pass */ @@ -107,8 +123,26 @@ public abstract class IdempotencyStoreContract { private static IdempotencyClaimRequest claim( IdempotencyClaimAttempt attempt, RequestFingerprint fingerprint, Duration processingLease) { + return claim(attempt, fingerprint, processingLease, Duration.ofHours(24)); + } + + private static IdempotencyClaimRequest claim( + IdempotencyClaimAttempt attempt, + RequestFingerprint fingerprint, + Duration processingLease, + Duration replayTtl) { return new IdempotencyClaimRequest( - SCOPE, fingerprint, attempt, processingLease, Duration.ofHours(24), "json-v2", 1); + SCOPE, fingerprint, attempt, processingLease, replayTtl, "json-v2", 1); + } + + /** Claims and starts the operation with the given lease and replay TTL. */ + private static IdempotencyOwner executingWith( + IdempotencyStorePort store, Duration processingLease, Duration replayTtl) { + IdempotencyOwner claimed = + ownerOf( + store.claim( + claim(store.newClaimAttempt(OPERATION), FINGERPRINT, processingLease, replayTtl))); + return store.markExecutionStarted(claimed, OPERATION).owner().orElseThrow(); } private static IdempotencyOwner acquire(IdempotencyStorePort store) { @@ -392,6 +426,93 @@ public abstract class IdempotencyStoreContract { assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class); } + @Test + @DisplayName("처리 lease가 지난 실행 전 claim은 다음 요청이 attempt 2로 넘겨받는다") + void aClaimThatNeverStartedIsTakenOverWhenItsLeaseRunsOut() { + // given + IdempotencyStorePort store = subject(); + Duration lease = processingLease(); + store.claim(claim(store.newClaimAttempt(OPERATION), FINGERPRINT, lease)); + elapse(lease.multipliedBy(2)); + + // when + IdempotencyClaimOutcome next = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT, lease)); + + // then + assertThat(next).isInstanceOf(IdempotencyClaimOutcome.TakenOverClaimed.class); + assertThat(ownerOf(next).attempt()).isEqualTo(2); + } + + @Test + @DisplayName("실행을 시작한 기록의 처리 lease가 지나면 다음 요청은 작업을 다시 돌리지 않고 회복 필요를 받는다") + void anExecutionWhoseLeaseRanOutRequiresRecoveryInsteadOfASecondRun() { + // given + IdempotencyStorePort store = subject(); + Duration lease = processingLease(); + executingWith(store, lease, Duration.ofHours(24)); + elapse(lease.multipliedBy(2)); + + // when + IdempotencyClaimOutcome next = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT, lease)); + + // then + assertThat(next).isInstanceOf(IdempotencyClaimOutcome.RecoveryRequired.class); + } + + @Test + @DisplayName("lease가 지나 회복 필요로 판정된 실행은 원래 holder가 늦게 complete해도 기록되지 않는다") + void anExecutionFoundExpiredCannotBeCompletedByItsLateHolder() { + // given + IdempotencyStorePort store = subject(); + Duration lease = processingLease(); + IdempotencyOwner late = executingWith(store, lease, Duration.ofHours(24)); + elapse(lease.multipliedBy(2)); + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT, lease)); + + // when + IdempotencyCompleteOutcome outcome = + store.complete(late, new StoredResponse("{}"), Duration.ofHours(1), OPERATION); + + // then + assertThat(outcome).isEqualTo(IdempotencyCompleteOutcome.NOT_OWNER); + } + + @Test + @DisplayName("replay TTL보다 긴 처리 lease로 claim해도 lease가 끝날 때까지 기록이 남아 다른 요청은 진행 중으로 막힌다") + void aLeaseLongerThanTheReplayTtlKeepsTheRecordForTheWholeLease() { + // given + IdempotencyStorePort store = subject(); + Duration replayTtl = processingLease(); + executingWith(store, replayTtl.multipliedBy(3), replayTtl); + elapse(replayTtl.multipliedBy(2)); + + // when + IdempotencyClaimOutcome other = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT, processingLease())); + + // then + assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class); + } + + @Test + @DisplayName("replay TTL이 처리 lease와 같아도 lease가 지난 실행 기록은 남아 다음 요청에 회복 필요로 답한다") + void anExecutionIsRememberedPastItsLeaseEvenWhenTheReplayTtlIsNoLonger() { + // given + IdempotencyStorePort store = subject(); + Duration lease = processingLease(); + executingWith(store, lease, lease); + elapse(lease.multipliedBy(3).dividedBy(2)); + + // when + IdempotencyClaimOutcome next = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT, lease)); + + // then + assertThat(next).isInstanceOf(IdempotencyClaimOutcome.RecoveryRequired.class); + } + /** Routes every call of the store through {@link #inTransaction(Supplier)}. */ private final class EachCallInTransaction implements IdempotencyStorePort { diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java index fd0e237b..5ecafe46 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java @@ -3,7 +3,10 @@ package dev.caskeleton.application.transaction.testkit; import dev.caskeleton.application.transaction.NestedRootTransactionRejectedException; import dev.caskeleton.application.transaction.TransactionPort; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; /** @@ -30,7 +33,11 @@ import java.util.function.Supplier; * * *

        {@link TransactionPortContract} holds it to the same cases as the Spring adapter on a real - * database. Single-threaded: one instance per test. + * database. A transaction belongs to the thread that opened it, as a connection does: a boundary on + * another thread opens a transaction of its own rather than joining this one, so an overlapping- + * writes case ({@link OverlappingWrites}) runs two transactions here too (review 2026-11-03 + * RR-01-16). {@link #active()}, {@link #readOnly()} and {@link #onRollback} answer for the calling + * thread. One instance per test. */ public final class DirectTransactionPort implements TransactionPort { @@ -43,8 +50,10 @@ public final class DirectTransactionPort implements TransactionPort { } private final boolean rejectNesting; - private final List committed = new ArrayList<>(); - private Transaction current; + private final List committed = Collections.synchronizedList(new ArrayList<>()); + // Per thread, keyed by the thread itself; an entry lives only while that thread's outermost + // boundary runs. + private final Map current = new ConcurrentHashMap<>(); public DirectTransactionPort() { this(false); @@ -59,19 +68,22 @@ public final class DirectTransactionPort implements TransactionPort { return new DirectTransactionPort(true); } - /** Boundaries whose work committed, in completion order. */ + /** Boundaries whose work committed, on any thread, in completion order. */ public List committed() { - return List.copyOf(committed); + synchronized (committed) { + return List.copyOf(committed); + } } - /** Whether an action is running right now. */ + /** Whether an action is running on this thread right now. */ public boolean active() { - return current != null; + return current.containsKey(Thread.currentThread()); } - /** Whether the transaction running right now is a read-only one, opened by {@link #inRead}. */ + /** Whether this thread's running transaction is a read-only one, opened by {@link #inRead}. */ public boolean readOnly() { - return current != null && current.readOnly; + Transaction transaction = current.get(Thread.currentThread()); + return transaction != null && transaction.readOnly; } /** @@ -80,10 +92,11 @@ public final class DirectTransactionPort implements TransactionPort { * @throws IllegalStateException when no transaction is active */ public void onRollback(Runnable undo) { - if (current == null) { + Transaction transaction = current.get(Thread.currentThread()); + if (transaction == null) { throw new IllegalStateException("no transaction is active to roll back"); } - current.undo.add(undo); + transaction.undo.add(undo); } @Override @@ -93,7 +106,7 @@ public final class DirectTransactionPort implements TransactionPort { @Override public T inRootWrite(Supplier action) { - if (current != null) { + if (current.containsKey(Thread.currentThread())) { throw new NestedRootTransactionRejectedException(); } return run(Boundary.ROOT_WRITE, action); @@ -110,15 +123,15 @@ public final class DirectTransactionPort implements TransactionPort { } private T run(Boundary boundary, Supplier action) { - if (current != null && rejectNesting) { + Transaction suspended = current.get(Thread.currentThread()); + if (suspended != null && rejectNesting) { throw new IllegalStateException(boundary + " transaction opened inside another"); } - if (current != null && boundary != Boundary.NEW) { - return join(boundary, action); + if (suspended != null && boundary != Boundary.NEW) { + return join(suspended, boundary, action); } - Transaction suspended = current; Transaction transaction = new Transaction(boundary == Boundary.READ); - current = transaction; + current.put(Thread.currentThread(), transaction); try { T result; try { @@ -132,16 +145,21 @@ public final class DirectTransactionPort implements TransactionPort { throw new IllegalStateException( boundary + " transaction rolled back: a boundary that joined it failed"); } - committed.addAll(transaction.joined); - committed.add(boundary); + synchronized (committed) { + committed.addAll(transaction.joined); + committed.add(boundary); + } return result; } finally { - current = suspended; + if (suspended == null) { + current.remove(Thread.currentThread()); + } else { + current.put(Thread.currentThread(), suspended); + } } } - private T join(Boundary boundary, Supplier action) { - Transaction joined = current; + private static T join(Transaction joined, Boundary boundary, Supplier action) { try { T result = action.get(); joined.joined.add(boundary); diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionPortContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionPortContract.java index 69b7d2d8..1856dc51 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionPortContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/TransactionPortContract.java @@ -6,6 +6,11 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.transaction.NestedRootTransactionRejectedException; import dev.caskeleton.application.transaction.TransactionPort; import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import org.junit.jupiter.api.DisplayName; @@ -294,6 +299,55 @@ public abstract class TransactionPortContract { .containsExactly("runnable-new", "runnable-root", "runnable-write"); } + /** + * A transaction belongs to the thread that opened it, as a database connection does. A boundary + * opened on another thread while this one is open is a transaction of its own: it commits when it + * returns and this thread's rollback does not take its write. A port that shared one open + * transaction across threads would make every overlapping-writes contract case two calls in one + * transaction instead of two transactions (review 2026-11-03 RR-01-16). + */ + @Test + @DisplayName("다른 스레드의 경계는 이 스레드의 열린 트랜잭션에 합류하지 않고 따로 커밋한다") + void aBoundaryOnAnotherThreadIsATransactionOfItsOwn() { + // given + TransactionPort transactions = transactions(); + TransactionProbe probe = probe(); + ExecutorService otherThread = Executors.newSingleThreadExecutor(); + + // when + Throwable thrown; + try { + thrown = + catchThrowable( + () -> + transactions.inWrite( + () -> { + probe.write("this-thread"); + awaitOn( + otherThread, + () -> transactions.inWrite(() -> probe.write("other-thread"))); + throw new IllegalStateException("this thread rolls back"); + })); + } finally { + otherThread.shutdownNow(); + } + + // then + assertThat(List.of(thrown.getMessage(), probe.committed())) + .containsExactly("this thread rolls back", List.of("other-thread")); + } + + private static void awaitOn(ExecutorService thread, Runnable work) { + try { + thread.submit(work).get(30, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } catch (ExecutionException | TimeoutException failed) { + throw new IllegalStateException("the other thread's boundary failed", failed); + } + } + private static Supplier written(TransactionProbe probe, String mark, T value) { return () -> { probe.write(mark); diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryQuotaLedgerContractTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryQuotaLedgerContractTest.java index 2494b443..c96285d9 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryQuotaLedgerContractTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryQuotaLedgerContractTest.java @@ -12,6 +12,7 @@ import java.time.Instant; import java.util.Optional; import java.util.OptionalLong; import java.util.UUID; +import java.util.function.Supplier; class InMemoryQuotaLedgerContractTest extends FileQuotaLedgerContract { @@ -50,6 +51,11 @@ class InMemoryQuotaLedgerContractTest extends FileQuotaLedgerContract { return FileserverFixtures.session(fileId, 1_000, 1_000); } + @Override + protected T inTransaction(Supplier work) { + return ledger.inTransaction(work); + } + @Override protected void elapse(Duration duration) { now = now.plus(duration); diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java index 7a5e189b..018f6317 100644 --- a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FakeFileQuotaService.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.function.Supplier; /** * The in-memory quota ledger: the fake of {@link FileQuotaPort}, and the ledger that {@link @@ -45,6 +46,27 @@ public final class FakeFileQuotaService implements FileQuotaPort { this.now = instant; } + /** + * Runs {@code work} as one caller transaction over the ledger's rows: what it wrote is undone if + * it throws, as the reservation table is when the JPA adapters' caller rolls back. The recorded + * calls ({@link #reservedScopes()} and the like) are not undone. For {@link + * FileQuotaLedgerContract}, whose rollback case holds the fake and PostgreSQL to the same answer + * (review 2026-11-03 RR-01-17). + */ + public T inTransaction(Supplier work) { + Map before = new LinkedHashMap<>(); + rows.forEach((id, row) -> before.put(id, row.copy())); + long writesBefore = writes; + try { + return work.get(); + } catch (RuntimeException | Error failure) { + rows.clear(); + rows.putAll(before); + writes = writesBefore; + throw failure; + } + } + /** Books usage the scope already holds, as if earlier uploads had committed it. */ public void alreadyHolds(QuotaScope scope, long bytes) { Row row = newRow(scope, bytes, now); @@ -215,6 +237,13 @@ public final class FakeFileQuotaService implements FileQuotaPort { this.updatedAt = createdAt; } + private Row copy() { + Row copy = new Row(id, scope, reservedBytes, expiresAt, updatedAt); + copy.committedBytes = committedBytes; + copy.status = status; + return copy; + } + private boolean isLiveAt(Instant instant) { return status == QuotaReservationStatus.RESERVED && expiresAt.isAfter(instant); } diff --git a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileQuotaLedgerContract.java b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileQuotaLedgerContract.java index b217dad1..546dba28 100644 --- a/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileQuotaLedgerContract.java +++ b/src/application-fileserver/src/testFixtures/java/dev/caskeleton/application/fileserver/testkit/FileQuotaLedgerContract.java @@ -48,10 +48,11 @@ public abstract class FileQuotaLedgerContract { /** Lets {@code duration} pass on the clock the ledger reads. */ protected abstract void elapse(Duration duration); - /** Runs one ledger call inside the caller transaction the adapters require, and commits it. */ - protected T inTransaction(Supplier work) { - return work.get(); - } + /** + * Runs ledger calls inside the caller transaction the adapters require: commits when {@code work} + * returns, rolls back what it wrote when it throws. + */ + protected abstract T inTransaction(Supplier work); @Test @DisplayName("살아 있는 예약은 그 scope의 사용량에 들어간다") @@ -307,6 +308,38 @@ public abstract class FileQuotaLedgerContract { assertThat(refused).isInstanceOf(IllegalArgumentException.class); } + /** + * A move books the file's bytes on its target and reclaims them from its source inside the + * caller's transaction that also relocates the record ({@code MoveFileApplicationUseCase}). When + * that transaction rolls back — the relocate lost a version race — neither namespace may keep its + * half. So every write of the ledger joins the caller's transaction; a port moved into a + * transaction of its own fails here (review 2026-11-03 RR-01-17). + */ + @Test + @DisplayName("호출자 트랜잭션이 롤백되면 그 안의 예약·확정·회수가 양쪽 scope에서 모두 사라진다") + void ledgerWritesInACallerTransactionThatRollsBackLeaveBothScopesAsTheyWere() { + // given + QuotaScope source = newScope(); + QuotaScope target = newScope(); + commit(source, 400); + + // when + Throwable thrown = + catchThrowable( + () -> + inTransaction( + () -> { + QuotaReservation booked = quota().reserve(target, 400, TTL); + quota().commit(booked, 400); + reclaims().reclaim(source, 400); + throw new IllegalStateException("the relocate lost its version race"); + })); + + // then + assertThat(List.of(thrown.getMessage(), usedBytes(source), usedBytes(target))) + .containsExactly("the relocate lost its version race", 400L, 0L); + } + private QuotaReservation reserve(QuotaScope scope, long bytes) { return inTransaction(() -> quota().reserve(scope, bytes, TTL)); } diff --git a/src/build-logic/README.md b/src/build-logic/README.md index 97afbfdb..bfdb77e9 100644 --- a/src/build-logic/README.md +++ b/src/build-logic/README.md @@ -16,7 +16,7 @@ capability, and the files it reads are declared as that test task's inputs. | `ca.java-library` / `ca.spring-library` / `ca.spring-config` | leaf-level composition of the Java/quality conventions for plain and Spring libraries | | `ca.platform-module` / `ca.grpc-platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library`, plus the gRPC BOM for the leaves that had it | | `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason. Extra test source sets are Gradle `jvm-test-suite` suites declared in the leaf (`testing { suites { … } }`); a lane named after its suite makes the suite's own `Test` task strict, and `ca.java-conventions` gives every suite the BOM's JUnit | -| `ca.strict-lane-stages` (root of each build with strict lanes: the main build and optional-platforms) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane of that build that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow. A `--dry-run`, a command for another build (`workflowProjectDirectory` names the `-p` value that starts this one), and a command under `continue-on-error` or an `if:` other than `always()`/`success()`/`!cancelled()` do not count, and a lane the command removes with `-x` is not covered. The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01, 2026-11-03 RR-06-03/04) | +| `ca.strict-lane-stages` (root of each build with strict lanes: the main build and optional-platforms) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane of that build that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow. A `--dry-run`, a command for another build (the build a command starts is its step's `working-directory`, or the job's or workflow's `defaults.run.working-directory`, joined with `-p`; the plugin reads this build's own directory from where it sits under the repository that holds `.github/workflows`), a command under `continue-on-error` or an `if:` other than `always()`/`success()`/`!cancelled()`, and a command of a workflow that starts only on `workflow_dispatch` do not count, and a lane the command removes with `-x` is not covered — matched the way Gradle matches task and project names, abbreviations included (`TaskSelectors`, a copy of Gradle's internal `NameMatcher`). A `run:` input of a `uses:` step is not a command. The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04) | | `ca.redis-topology-lane` | the Redis topology lane (mode selection, `-P` property validation, per-mode required classes) the redis-sdk-topology workflow drives | | `ca.api-surface` | read-only public API surface verification with a separate update task, wired into the leaf's `check` (owner decision 20); optionally holds other leaves' imports to a reviewed adopter subset (`adopterBaseline`) | | `ca.config-contract` | app-bootstrap's `verifyEnvKeys` (moved from the deleted build-tools included build; owner decision 4 keeps the task in app-bootstrap) | diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java index 19aa949a..bf045466 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java @@ -45,8 +45,10 @@ public final class ConfigContractPlugin implements Plugin { // What an operator edits or runs: the root Compose files, the Logback // configuration, and the Compose lane contract with the smoke wrapper that drives it // (each lane's activationEnv, the wrapper's CAPABILITIES_OFF). Their APP_ names must - // be registered and read (07-10; RR-06-07: an unread CASKELETON_GRPC_ENABLED-style - // switch in a lane was found by hand, not by this task). + // be registered and read (07-10, RR-06-07), and a lane's other variables must be read + // too — a Spring Boot namespace or a secret://…/ target — so an unread + // CASKELETON_GRPC_ENABLED-style switch fails here (RR2-04-05) instead of being found + // by hand. task.getOperatorFiles() .from( root.fileTree( diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java index c6cd6192..c3ef68b9 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java @@ -42,6 +42,17 @@ public final class EnvContractVerifier { * argument the wrapper passes on) is not a key and is not matched. */ private static final Pattern JSON_KEY = Pattern.compile("\"(APP_[A-Z][A-Z0-9_]*)\"\\s*:"); + /** Every variable a JSON object sets, {@code APP_} or not. */ + private static final Pattern JSON_VARIABLE_KEY = Pattern.compile("\"([A-Z][A-Z0-9_]*)\"\\s*:"); + /** The variable a credential reference names: the last segment of {@code secret://…/}. */ + private static final Pattern REFERENCED_VARIABLE = + Pattern.compile("secret://[^\\s\"']*/([A-Z][A-Z0-9_]*)"); + /** + * Spring Boot's own namespaces: a variable under one is bound to its {@code spring.*}, {@code + * management.*} or {@code server.*} property by relaxed binding, so the framework reads it. + */ + private static final List FRAMEWORK_VARIABLE_PREFIXES = + List.of("SPRING_", "MANAGEMENT_", "SERVER_"); /** * A list element ({@code APP_HTTPCLIENT_CLIENTS_0_NAME}). Its field template is registered by the * owning module's field registry ({@code docs/httpclient/env-fields.yaml}, held by that module's @@ -92,6 +103,46 @@ public final class EnvContractVerifier { Collection metadataScopes, Collection enforcedPrefixes, Collection operatorFiles) { + Set declared = new TreeSet<>(); + for (MetadataScope scope : metadataScopes) { + if (scope.metadataFile().exists()) { + parseMetadata(scope.metadataFile()).properties().stream() + .map(SpringConfigurationProperty::name) + .forEach(declared::add); + } + } + return verify( + envFile, + configurationFiles, + registryFile, + productionSources, + metadataScopes, + enforcedPrefixes, + operatorFiles, + declared); + } + + /** + * Verifies the contract, with every configuration property the composition declares. + * + *

        An operator-file key whose registry row names a {@code property:} counts as read only when + * that property is declared — a registry row alone is what the operator file was already trusted + * for (review 2026-11-04 RR2-04-05). A non-{@code APP_} key of a JSON object counts as read only + * under a Spring Boot namespace or as the variable a {@code secret://…/} reference names: + * the {@code CASKELETON_GRPC_ENABLED} switch that started RR-06-07 was neither, and nothing read + * it. + * + * @param declaredProperties every property name the composition's configuration metadata declares + */ + public static EnvContractResult verify( + File envFile, + Collection configurationFiles, + File registryFile, + Collection productionSources, + Collection metadataScopes, + Collection enforcedPrefixes, + Collection operatorFiles, + Collection declaredProperties) { requireFile( envFile, "missing " @@ -209,22 +260,28 @@ public final class EnvContractVerifier { consumed.addAll(scanProductionSourceConsumers(productionSources)); Set operatorReferences = new TreeSet<>(); + Set unreadOperatorVariables = new TreeSet<>(); for (File operatorFile : operatorFiles) { requireFile(operatorFile, "missing operator file " + operatorFile); - Matcher matcher = operatorKeyPattern(operatorFile.getName()).matcher(read(operatorFile)); + String content = read(operatorFile); + Matcher matcher = operatorKeyPattern(operatorFile.getName()).matcher(content); while (matcher.find()) { if (!INDEXED_KEY.matcher(matcher.group(1)).matches()) { operatorReferences.add(matcher.group(1)); } } + if (operatorKeyPattern(operatorFile.getName()) == JSON_KEY) { + unreadOperatorVariables.addAll(unreadNonApplicationVariables(content)); + } } failUnlessEmpty( difference(operatorReferences, registryAppKeys), "operator files (Compose, logback-spring.xml, the Compose lane contract, the smoke wrapper)" + " set APP_ keys absent from docs/registries/env-keys.yaml: "); Set typedRows = new TreeSet<>(); + Set declared = new HashSet<>(declaredProperties); registryRows.stream() - .filter(row -> row.property().isPresent()) + .filter(row -> row.property().filter(declared::contains).isPresent()) .forEach(row -> typedRows.add(row.name())); Set unreadOperatorReferences = new TreeSet<>(); for (String name : operatorReferences) { @@ -237,6 +294,12 @@ public final class EnvContractVerifier { "operator files (Compose, logback-spring.xml, the Compose lane contract, the smoke" + " wrapper) set APP_ keys nothing reads — no shipped configuration placeholder," + " production source or typed property: "); + failUnlessEmpty( + unreadOperatorVariables, + "the Compose lane contract or the smoke wrapper sets variables outside APP_ that nothing" + + " reads — not a Spring Boot namespace (SPRING_, MANAGEMENT_, SERVER_) and not named" + + " by a secret://…/ reference: ", + " — a switch spelled this way changes nothing, and the lane can pass for another reason."); Set unconsumed = new TreeSet<>(); for (EnvRegistryRow row : registryRows) { @@ -278,6 +341,29 @@ public final class EnvContractVerifier { warnings); } + /** + * The non-{@code APP_} variables a JSON object in {@code content} sets that nothing reads: outside + * Spring Boot's namespaces and named by no {@code secret://} reference in the same file. + */ + private static Set unreadNonApplicationVariables(String content) { + Set referenced = new TreeSet<>(); + Matcher reference = REFERENCED_VARIABLE.matcher(content); + while (reference.find()) { + referenced.add(reference.group(1)); + } + Set unread = new TreeSet<>(); + Matcher variable = JSON_VARIABLE_KEY.matcher(content); + while (variable.find()) { + String name = variable.group(1); + if (!name.startsWith("APP_") + && FRAMEWORK_VARIABLE_PREFIXES.stream().noneMatch(name::startsWith) + && !referenced.contains(name)) { + unread.add(name); + } + } + return unread; + } + private static Pattern operatorKeyPattern(String fileName) { if (fileName.endsWith(".xml")) { return LOGBACK_SOURCE; diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java index 9ff45763..9e98f3c8 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/VerifyEnvKeysTask.java @@ -83,7 +83,8 @@ public abstract class VerifyEnvKeysTask extends DefaultTask { getProductionSources().getFiles(), scopes, ENFORCED_PREFIXES, - getOperatorFiles().getFiles()); + getOperatorFiles().getFiles(), + ConfigurationMetadataClasspath.propertiesUnder(getMetadataClasspath().getFiles(), "")); } catch (IllegalStateException invalidContract) { throw new GradleException(invalidContract.getMessage(), invalidContract); } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/convention/SpringConfigConventionPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/convention/SpringConfigConventionPlugin.java index f6b98a04..40a641eb 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/convention/SpringConfigConventionPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/convention/SpringConfigConventionPlugin.java @@ -2,12 +2,43 @@ package dev.caskeleton.buildlogic.convention; import org.gradle.api.Plugin; import org.gradle.api.Project; +import org.gradle.api.tasks.PathSensitivity; public final class SpringConfigConventionPlugin implements Plugin { + /** + * How a module declares a property the processor cannot see — a switch read only by + * {@code @ConditionalOnProperty} — so the environment contract finds it in the metadata. + */ + private static final String ADDITIONAL_METADATA = + "src/main/resources/META-INF/additional-spring-configuration-metadata.json"; + @Override public void apply(Project project) { project .getDependencies() .add("annotationProcessor", "org.springframework.boot:spring-boot-configuration-processor"); + // The processor merges the additional metadata from the processed resources, so compileJava + // runs after processResources and reruns when that one file changes. Without this it could run + // first, or stay up to date when only that file changed, and the declared switch was missing + // from the metadata verifyEnvKeys reads (review 2026-11-04 RR2-04-05). Only that file is an + // input: every other resource leaves compileJava's cache key alone. + project + .getPluginManager() + .withPlugin( + "java", + ignored -> + project + .getTasks() + .named( + "compileJava", + compile -> { + compile.dependsOn(project.getTasks().named("processResources")); + // files(), not file(): most modules have no such file. + compile + .getInputs() + .files(project.file(ADDITIONAL_METADATA)) + .withPropertyName("additionalConfigurationMetadata") + .withPathSensitivity(PathSensitivity.RELATIVE); + })); } } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java index ac09e803..6a140481 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java @@ -2,7 +2,6 @@ package dev.caskeleton.buildlogic.strictlane; import org.gradle.api.file.DirectoryProperty; import org.gradle.api.provider.ListProperty; -import org.gradle.api.provider.Property; /** * The stages a strict lane may belong to, and where the workflows that run them live. @@ -14,15 +13,14 @@ import org.gradle.api.provider.Property; public abstract class StrictLaneStagesExtension { public abstract ListProperty getStages(); - public abstract DirectoryProperty getWorkflowDirectory(); - /** - * The {@code -p} directory a workflow step passes to start this build, relative to the step's - * working directory — {@code optional-platforms} for the optional build, which steps run as - * {@code ./gradlew -p optional-platforms } from {@code src}. Unset for the build a step - * starts in its working directory. Only commands that start this build execute its stages. + * The repository's {@code .github/workflows}. Its grandparent is the repository root, and a + * command executes this build's stages only when it starts in this build's directory from there + * — its step's {@code working-directory} joined with its {@code -p}. The directory is read from + * where the build is, so no build states it (review 2026-11-04 RR2-04-04: a {@code -p} value + * alone missed {@code working-directory: src/optional-platforms} with {@code ../gradlew}). */ - public abstract Property getWorkflowProjectDirectory(); + public abstract DirectoryProperty getWorkflowDirectory(); public void stage(String... taskPaths) { getStages().addAll(taskPaths); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java index 64bcef82..0cf9de12 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java @@ -30,16 +30,19 @@ import org.gradle.api.execution.TaskExecutionGraph; * *

          *
        1. every strict lane that is not {@code explicitOnly} is in the task plan of a declared stage - * as a workflow runs it — a lane the command removes with {@code -x} is not covered; + * as a workflow runs it — a lane the command removes with {@code -x} is not covered, matched + * the way Gradle matches it, abbreviations included ({@link TaskSelectors}); *
        2. every declared stage is executed by a workflow — a {@code --dry-run}, a command for another - * build, and a command under {@code continue-on-error} or an {@code if:} other than a status - * function do not count (review 2026-11-03 RR-06-04). + * build, a command under {@code continue-on-error} or an {@code if:} other than a status + * function, and a command of a workflow that starts only on {@code workflow_dispatch} do not + * count (review 2026-11-03 RR-06-04, 2026-11-04 RR2-04-04). *
        * *

        Each build that holds strict lanes applies it at its own root: the main build, and the - * optional-platforms build, whose stages workflows start with {@code -p optional-platforms} - * ({@link StrictLaneStagesExtension#getWorkflowProjectDirectory()}). Applied to the main build only, - * it said "every strict lane" while the optional build's performance lane ran nowhere (RR-06-03).

        + * optional-platforms build. A command executes this build when it starts in this build's directory + * — its step's {@code working-directory} joined with its {@code -p}, from the repository root, + * which is where GitHub keeps {@code .github/workflows}. Applied to the main build only, it said + * "every strict lane" while the optional build's performance lane ran nowhere (RR-06-03).

        * *

        The task plan is Gradle's own: {@code verifyStrictLaneStages} depends on the stages, so a * {@code --dry-run} of it builds the real plan, and the check reads it when the graph is ready. It @@ -85,13 +88,14 @@ public final class StrictLaneStagesPlugin implements Plugin { + extension.getStages().get() + " and would execute all of them; run it with --dry-run."); } + File workflowDirectory = extension.getWorkflowDirectory().get().getAsFile(); List problems = problems( project, graph, extension.getStages().get(), - extension.getWorkflowDirectory().get().getAsFile(), - extension.getWorkflowProjectDirectory().getOrNull()); + workflowDirectory, + buildDirectory(project, workflowDirectory)); if (!problems.isEmpty()) { throw new GradleException( TASK_NAME @@ -119,6 +123,10 @@ public final class StrictLaneStagesPlugin implements Plugin { List invocations = invocations(workflowDirectory); // Only an executed stage covers a lane — a stage no workflow runs is the same gap one level // up — and only as the command runs it: what its -x removes is not covered. + Map> tasksByProject = new LinkedHashMap<>(); + root.getAllprojects() + .forEach( + project -> tasksByProject.put(project.getPath(), Set.copyOf(project.getTasks().getNames()))); Map> plans = new LinkedHashMap<>(); for (String stage : stages) { List executions = @@ -131,17 +139,20 @@ public final class StrictLaneStagesPlugin implements Plugin { + stage + " is executed by no workflow in " + workflowDirectory.getName() - + " (a --dry-run, a command for another build, and a command under" - + " continue-on-error or an if: other than always()/success()/!cancelled() do not" - + " count)"); + + " for the build in " + + buildDirectory + + " (a --dry-run, a command started in another directory, a command under" + + " continue-on-error or an if: other than always()/success()/!cancelled(), and a" + + " workflow that starts only on workflow_dispatch do not count)"); continue; } Task stageTask = root.getTasks().findByPath(stage); int run = 0; for (WorkflowGradleInvocations.Invocation execution : executions) { + Set excluded = + TaskSelectors.excludedPaths(execution.excludedTasks(), tasksByProject); plans.put( - stage + "#" + run++, - stageTask == null ? Set.of() : plan(graph, stageTask, execution)); + stage + "#" + run++, stageTask == null ? Set.of() : plan(graph, stageTask, excluded)); } } List lanes = new ArrayList<>(); @@ -168,14 +179,13 @@ public final class StrictLaneStagesPlugin implements Plugin { return problems; } - /** The tasks {@code stage} reaches as {@code execution} runs it: what its -x removes is cut off. */ - private static Set plan( - TaskExecutionGraph graph, Task stage, WorkflowGradleInvocations.Invocation execution) { + /** The tasks {@code stage} reaches as a command runs it: what its -x removes is cut off. */ + private static Set plan(TaskExecutionGraph graph, Task stage, Set excluded) { Set seen = new HashSet<>(); Deque pending = new ArrayDeque<>(List.of(stage)); while (!pending.isEmpty()) { Task task = pending.pop(); - if (!execution.excludes(task.getPath()) && seen.add(task.getPath())) { + if (!excluded.contains(task.getPath()) && seen.add(task.getPath())) { pending.addAll(graph.getDependencies(task)); } } @@ -222,6 +232,22 @@ public final class StrictLaneStagesPlugin implements Plugin { return invocations; } + /** + * This build's directory from the repository root, which holds {@code .github/workflows}: {@code + * src} for the main build, {@code src/optional-platforms} for the optional one. + */ + private static String buildDirectory(Project root, File workflowDirectory) { + File repository = workflowDirectory.getAbsoluteFile().getParentFile().getParentFile(); + String relative = + repository + .toPath() + .normalize() + .relativize(root.getRootDir().getAbsoluteFile().toPath().normalize()) + .toString() + .replace(File.separatorChar, '/'); + return WorkflowGradleInvocations.Invocation.normalized(relative); + } + private static String taskPath(Project project, String name) { return project == project.getRootProject() ? ":" + name : project.getPath() + ":" + name; } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/TaskSelectors.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/TaskSelectors.java new file mode 100644 index 00000000..6dad58eb --- /dev/null +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/TaskSelectors.java @@ -0,0 +1,214 @@ +package dev.caskeleton.buildlogic.strictlane; + +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Which tasks a command line's {@code -x} selectors remove, matched the way Gradle matches them. + * + *

        Gradle accepts an abbreviation wherever it accepts a task or project name: {@code -x + * grpcPerformanceT} removes {@code grpcPerformanceTest}, and {@code :g-t:gPT} a task of {@code + * :grpc-testkit}. The workflow reader compared names exactly, so an abbreviated {@code -x} — the + * form people type in a terminal and paste into a workflow — removed a lane from Gradle's plan while + * the stage check still counted it (review 2026-11-04 RR2-04-04). + * + *

        The matching is a copy of Gradle's {@code org.gradle.util.internal.NameMatcher} (9.0): exact, + * then case-insensitive, then camel-case, then kebab-case abbreviation. It is copied rather than + * called because that class is internal API. Where Gradle would refuse the selector as ambiguous, + * every candidate counts as removed: the command cannot run, so it covers none of them. + */ +final class TaskSelectors { + private static final Pattern CAMEL_CASE_BOUNDARY = + Pattern.compile( + "((^|\\p{Punct})\\p{javaLowerCase}+)|((\\p{javaUpperCase}|\\p{Digit})\\p{javaLowerCase}*)"); + private static final Pattern KEBAB_BOUNDARY = + Pattern.compile("((^|\\p{Punct})\\p{javaLowerCase}+)|(\\p{javaUpperCase}\\p{javaLowerCase}*)"); + + private TaskSelectors() {} + + /** + * The paths of the tasks the selectors remove from a command started at the root project. + * + * @param selectors the {@code -x} values, as written + * @param tasksByProject each project's path ({@code :} for the root) and its task names + * @return the removed task paths + */ + static Set excludedPaths( + List selectors, Map> tasksByProject) { + Set excluded = new LinkedHashSet<>(); + for (String selector : selectors) { + excluded.addAll(selected(selector, tasksByProject)); + } + return excluded; + } + + private static Set selected( + String selector, Map> tasksByProject) { + Set paths = new LinkedHashSet<>(); + if (!selector.contains(":")) { + // A bare name is matched against every task name in the build and removes the task of that + // name in every project. + Set names = new TreeSet<>(); + tasksByProject.values().forEach(names::addAll); + for (String name : matches(selector, names)) { + tasksByProject.forEach( + (project, tasks) -> { + if (tasks.contains(name)) { + paths.add(taskPath(project, name)); + } + }); + } + return paths; + } + String relative = selector.startsWith(":") ? selector.substring(1) : selector; + String[] segments = relative.split(":", -1); + Set projects = Set.of(":"); + for (int index = 0; index < segments.length - 1; index++) { + Set next = new LinkedHashSet<>(); + for (String project : projects) { + for (String child : matches(segments[index], children(project, tasksByProject.keySet()))) { + next.add(project.equals(":") ? ":" + child : project + ":" + child); + } + } + projects = next; + } + String taskName = segments[segments.length - 1]; + for (String project : projects) { + Collection tasks = tasksByProject.get(project); + for (String name : matches(taskName, tasks == null ? List.of() : tasks)) { + paths.add(taskPath(project, name)); + } + } + return paths; + } + + private static Set children(String project, Set projects) { + String prefix = project.equals(":") ? ":" : project + ":"; + Set children = new TreeSet<>(); + for (String candidate : projects) { + if (candidate.startsWith(prefix) && candidate.length() > prefix.length()) { + String rest = candidate.substring(prefix.length()); + if (!rest.contains(":")) { + children.add(rest); + } + } + } + return children; + } + + private static String taskPath(String project, String name) { + return project.equals(":") ? ":" + name : project + ":" + name; + } + + /** + * The names {@code pattern} selects among {@code items}: one when Gradle would accept it, several + * when Gradle would refuse it as ambiguous, none when nothing matches. + */ + static Set matches(String pattern, Collection items) { + if (items.contains(pattern)) { + return Set.of(pattern); + } + if (pattern.isEmpty()) { + return Set.of(); + } + Pattern camelCase = Pattern.compile(camelCasePattern(pattern)); + Pattern camelCaseIgnoringCase = + Pattern.compile(camelCasePattern(pattern), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + String kebabCasePattern = kebabCasePattern(pattern); + Pattern kebabCase = Pattern.compile(kebabCasePattern); + Pattern kebabCasePrefix = Pattern.compile(kebabCasePattern + "[\\p{javaLowerCase}\\p{Digit}-]*"); + Set ignoringCase = new TreeSet<>(); + Set camelCaseWhole = new TreeSet<>(); + Set camelCaseStart = new TreeSet<>(); + Set camelCaseStartIgnoringCase = new TreeSet<>(); + Set kebabCaseWhole = new TreeSet<>(); + Set kebabCaseStart = new TreeSet<>(); + for (String candidate : items) { + if (candidate.equalsIgnoreCase(pattern)) { + ignoringCase.add(candidate); + } + if (camelCase.matcher(candidate).matches()) { + camelCaseWhole.add(candidate); + } + if (camelCase.matcher(candidate).lookingAt()) { + camelCaseStart.add(candidate); + } + if (camelCaseIgnoringCase.matcher(candidate).lookingAt()) { + camelCaseStartIgnoringCase.add(candidate); + } + if (kebabCase.matcher(candidate).matches()) { + kebabCaseWhole.add(candidate); + } + if (kebabCasePrefix.matcher(candidate).matches()) { + kebabCaseStart.add(candidate); + } + } + Set matches = new TreeSet<>(); + if (!ignoringCase.isEmpty()) { + matches.addAll(ignoringCase); + } else if (!camelCaseWhole.isEmpty()) { + matches.addAll(camelCaseWhole); + } else if (!camelCaseStart.isEmpty()) { + matches.addAll(camelCaseStart); + } else if (kebabCaseWhole.isEmpty() && kebabCaseStart.isEmpty()) { + matches.addAll(camelCaseStartIgnoringCase); + } + if (!kebabCaseWhole.isEmpty()) { + matches.addAll(kebabCaseWhole); + } else if (!kebabCaseStart.isEmpty()) { + matches.addAll(kebabCaseStart); + } + return matches; + } + + private static String camelCasePattern(String name) { + return pattern( + name, + CAMEL_CASE_BOUNDARY, + (builder, position, part) -> + builder.append(Pattern.quote(part)).append("[\\p{javaLowerCase}]*")); + } + + private static String kebabCasePattern(String name) { + return pattern( + name, + KEBAB_BOUNDARY, + (builder, position, part) -> { + if (position > 0) { + builder.append('-'); + } + builder + .append(Pattern.quote(part.toLowerCase(Locale.ROOT))) + .append("[\\p{javaLowerCase}\\p{Digit}]*"); + }); + } + + private interface PartWriter { + void write(StringBuilder builder, int position, String part); + } + + private static String pattern(String name, Pattern boundary, PartWriter writer) { + Matcher matcher = boundary.matcher(name); + int position = 0; + StringBuilder builder = new StringBuilder(); + while (matcher.find()) { + String prefix = name.substring(position, matcher.start()); + if (!prefix.isEmpty()) { + builder.append(Pattern.quote(prefix)); + } + writer.write(builder, position, matcher.group()); + position = matcher.end(); + } + if (position < name.length()) { + builder.append(Pattern.quote(name.substring(position))); + } + return builder.toString(); + } +} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java index 22dc2291..b4d0e0d8 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java @@ -1,6 +1,9 @@ package dev.caskeleton.buildlogic.strictlane; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Deque; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Set; @@ -19,7 +22,14 @@ import java.util.regex.Pattern; *

        A command is read with what decides whether it gates anything (review 2026-11-03 RR-06-04): * its {@code -x} exclusions, and the {@code continue-on-error} and {@code if:} of its step and its * job. A command whose failure cannot fail the run, or that runs only under a condition other than - * a status function, is still returned, with the reason it does not count. + * a status function, is still returned, with the reason it does not count. So is a command of a + * workflow that starts only on {@code workflow_dispatch}: nothing runs it unless someone asks, the + * same reason an {@code if:} on the event name does not count (review 2026-11-04 RR2-04-04). + * + *

        Which build a command starts is where it starts: the step's {@code working-directory} (or the + * job's or the workflow's {@code defaults.run.working-directory}) joined with its {@code -p}, as a + * path from the repository root. A {@code run:} that is an input of a {@code uses:} step ({@code + * with: run:}) is not a shell command and is not read. */ public final class WorkflowGradleInvocations { private static final Pattern RUN_KEY = Pattern.compile("^(\\s*)(?:-\\s+)?run:(.*)$"); @@ -27,6 +37,8 @@ public final class WorkflowGradleInvocations { private static final Pattern MAPPING_KEY = Pattern.compile("^(\\s*)(?:-\\s+)?([A-Za-z0-9_-]+):(?:\\s+(.*?))?\\s*$"); private static final Pattern JOB_KEY = Pattern.compile("^(\\s*)([A-Za-z0-9_-]+):\\s*(#.*)?$"); + /** The top-level {@code on:} key, which YAML 1.1 readers want quoted. */ + private static final Pattern TRIGGER_KEY = Pattern.compile("^(?:on|\"on\"|'on'):(?:\\s+(.*?))?\\s*$"); /** Conditions under which a step still runs on every run whose earlier steps passed. */ private static final Set STATUS_CONDITIONS = Set.of("always()", "success()", "!cancelled()", "true"); @@ -54,6 +66,8 @@ public final class WorkflowGradleInvocations { /** * One Gradle command. * + * @param workingDirectory the directory the step runs in, from the repository root, or {@code + * null} for the repository root itself * @param projectDir the {@code -p} directory, or {@code null} for the build in the step's working * directory * @param tasks the task selectors it requests, in order @@ -63,6 +77,7 @@ public final class WorkflowGradleInvocations { * continue-on-error}, or a condition other than a status function — or {@code null} */ public record Invocation( + String workingDirectory, String projectDir, List tasks, boolean dryRun, @@ -74,50 +89,43 @@ public final class WorkflowGradleInvocations { } /** - * Whether this command executes the task at {@code taskPath} (for example {@code :ci}) in the - * build its step starts in. {@code ci} and {@code :ci} name the same root task. + * The directory of the build this command starts, from the repository root: the step's working + * directory joined with {@code -p}. {@code .} is the repository root. */ - public boolean executesInStartBuild(String taskPath) { - return executes(taskPath, null); + public String buildDirectory() { + return normalized( + (workingDirectory == null ? "." : workingDirectory) + + "/" + + (projectDir == null ? "." : projectDir)); } /** - * Whether this command executes, and gates on, the task at {@code taskPath} of the build a - * workflow starts with {@code -p buildDirectory} ({@code null}: the build in the step's working - * directory). + * Whether this command executes, and gates on, the task at {@code taskPath} (for example {@code + * :ci}; {@code ci} names the same root task) of the build in {@code buildDirectory}, a path from + * the repository root such as {@code src}. */ public boolean executes(String taskPath, String buildDirectory) { String wanted = absolute(taskPath); - return sameDirectory(projectDir, buildDirectory) + return buildDirectory().equals(normalized(buildDirectory)) && !dryRun && uncountedReason == null && tasks.stream().map(Invocation::absolute).anyMatch(wanted::equals); } - /** - * Whether the task at {@code taskPath} is one this command's {@code -x} removes. An absolute - * or project-qualified selector names one task; a bare name removes that task in every project, - * as Gradle does for a command started at the root. - */ - public boolean excludes(String taskPath) { - String name = taskPath.substring(taskPath.lastIndexOf(':') + 1); - for (String selector : excludedTasks) { - if (selector.contains(":") ? absolute(selector).equals(taskPath) : selector.equals(name)) { - return true; + /** A relative path with {@code .} and {@code ..} resolved; {@code .} for the root itself. */ + static String normalized(String directory) { + Deque parts = new ArrayDeque<>(); + for (String part : directory.split("/")) { + if (part.isEmpty() || part.equals(".")) { + continue; + } + if (part.equals("..") && !parts.isEmpty() && !parts.peekLast().equals("..")) { + parts.removeLast(); + } else { + parts.addLast(part); } } - return false; - } - - private static boolean sameDirectory(String left, String right) { - return left == null || right == null - ? left == null && right == null - : normalized(left).equals(normalized(right)); - } - - private static String normalized(String directory) { - String plain = directory.startsWith("./") ? directory.substring(2) : directory; - return plain.endsWith("/") ? plain.substring(0, plain.length() - 1) : plain; + return parts.isEmpty() ? "." : String.join("/", parts); } private static String absolute(String selector) { @@ -125,8 +133,11 @@ public final class WorkflowGradleInvocations { } } - /** The script of one {@code run:} step, and why its commands gate nothing, if they do not. */ - private record RunStep(String script, String uncountedReason) {} + /** + * The script of one {@code run:} step, the directory it runs in, and why its commands gate + * nothing, if they do not. + */ + private record RunStep(String script, String workingDirectory, String uncountedReason) {} private WorkflowGradleInvocations() {} @@ -134,7 +145,8 @@ public final class WorkflowGradleInvocations { List invocations = new ArrayList<>(); for (RunStep step : runSteps(workflow)) { for (String command : shellCommands(step.script())) { - Invocation invocation = gradleInvocation(command, step.uncountedReason()); + Invocation invocation = + gradleInvocation(command, step.workingDirectory(), step.uncountedReason()); if (invocation != null) { invocations.add(invocation); } @@ -157,7 +169,7 @@ public final class WorkflowGradleInvocations { List problems = new ArrayList<>(); for (int index = 0; index < lines.size(); index++) { Matcher run = RUN_KEY.matcher(lines.get(index)); - if (!run.matches()) { + if (!run.matches() || !isStepRun(lines, index)) { continue; } Matcher header = BLOCK_HEADER.matcher(run.group(2).trim()); @@ -197,17 +209,22 @@ public final class WorkflowGradleInvocations { private static List runSteps(String workflow) { List lines = workflow.lines().toList(); List scripts = new ArrayList<>(); + String dispatchOnly = dispatchOnlyReason(lines); for (int index = 0; index < lines.size(); index++) { Matcher run = RUN_KEY.matcher(lines.get(index)); - if (!run.matches()) { + if (!run.matches() || !isStepRun(lines, index)) { continue; } int keyIndent = run.group(1).length(); String value = run.group(2).trim(); String uncounted = uncountedReason(lines, index); + if (uncounted == null) { + uncounted = dispatchOnly; + } + String directory = workingDirectory(lines, index); Matcher header = BLOCK_HEADER.matcher(value); if (!header.matches()) { - scripts.add(new RunStep(stripScalarComment(value), uncounted)); + scripts.add(new RunStep(stripScalarComment(value), directory, uncounted)); continue; } List block = new ArrayList<>(); @@ -224,25 +241,182 @@ public final class WorkflowGradleInvocations { block.stream().map(line -> line.isBlank() ? "" : line.substring(blockIndent)).toList(); scripts.add( new RunStep( - header.group(1).equals("|") ? String.join("\n", content) : fold(content), uncounted)); + header.group(1).equals("|") ? String.join("\n", content) : fold(content), + directory, + uncounted)); } return scripts; } /** - * Why the {@code run:} key at {@code runIndex} gates nothing: a {@code continue-on-error} other - * than {@code false}, or an {@code if:} other than a status function, on its step or its job. + * Whether the {@code run:} key at {@code index} is a step's: a key of a {@code steps:} item, not + * an input under a {@code uses:} step's {@code with:} or a {@code defaults.run} mapping. */ - private static String uncountedReason(List lines, int runIndex) { - Matcher run = RUN_KEY.matcher(lines.get(runIndex)); - if (!run.matches()) { + private static boolean isStepRun(List lines, int index) { + String line = lines.get(index); + if (line.trim().startsWith("-")) { + return true; + } + int keyIndent = indentOf(line); + for (int previous = index - 1; previous >= 0; previous--) { + String candidate = lines.get(previous); + if (candidate.isBlank() || candidate.trim().startsWith("#")) { + continue; + } + if (indentOf(candidate) < keyIndent) { + return candidate.trim().startsWith("-") && keyColumn(candidate) == keyIndent; + } + } + return false; + } + + /** + * Why every command of the workflow gates nothing, when it starts only on {@code + * workflow_dispatch}; {@code null} when it has another trigger or none is written. + */ + private static String dispatchOnlyReason(List lines) { + Set triggers = new LinkedHashSet<>(); + for (int index = 0; index < lines.size(); index++) { + Matcher on = TRIGGER_KEY.matcher(lines.get(index)); + if (!on.matches()) { + continue; + } + String inline = + on.group(1) == null || on.group(1).startsWith("#") ? "" : stripScalarComment(on.group(1)); + if (!inline.isEmpty()) { + String list = + inline.startsWith("[") && inline.endsWith("]") + ? inline.substring(1, inline.length() - 1) + : inline; + for (String trigger : list.split(",")) { + if (!trigger.isBlank()) { + triggers.add(stripScalarComment(trigger.trim())); + } + } + break; + } + int childIndent = -1; + for (int next = index + 1; next < lines.size(); next++) { + String line = lines.get(next); + if (line.isBlank() || line.trim().startsWith("#")) { + continue; + } + int indent = indentOf(line); + if (indent == 0) { + break; + } + if (childIndent < 0) { + childIndent = indent; + } + if (indent == childIndent) { + String key = line.trim(); + key = key.startsWith("-") ? key.substring(1).trim() : key; + int colon = key.indexOf(':'); + triggers.add(stripScalarComment(colon < 0 ? key : key.substring(0, colon))); + } + } + break; + } + return !triggers.isEmpty() && triggers.stream().allMatch("workflow_dispatch"::equals) + ? "its workflow starts only on workflow_dispatch, so nothing runs it unless asked" + : null; + } + + /** + * The directory the {@code run:} at {@code runIndex} runs in: its step's {@code + * working-directory}, else its job's, else the workflow's {@code defaults.run.working-directory}; + * {@code null} for the repository root. + */ + private static String workingDirectory(List lines, int runIndex) { + StepScope step = stepScope(lines, runIndex); + String directory = mappingValue(lines, step.start(), step.keyIndent(), "working-directory"); + if (directory != null) { + return directory; + } + int jobHeader = jobHeader(lines, runIndex); + if (jobHeader >= 0) { + int jobKeyIndent = childIndent(lines, jobHeader); + if (jobKeyIndent > indentOf(lines.get(jobHeader))) { + directory = defaultsWorkingDirectory(lines, jobHeader + 1, jobKeyIndent); + if (directory != null) { + return directory; + } + } + } + return defaultsWorkingDirectory(lines, 0, 0); + } + + /** {@code defaults.run.working-directory} of the mapping whose keys sit at {@code keyIndent}. */ + private static String defaultsWorkingDirectory(List lines, int start, int keyIndent) { + int defaults = mappingKey(lines, start, keyIndent, "defaults"); + if (defaults < 0) { return null; } + int runIndent = childIndent(lines, defaults); + int run = runIndent > keyIndent ? mappingKey(lines, defaults + 1, runIndent, "run") : -1; + if (run < 0) { + return null; + } + int directoryIndent = childIndent(lines, run); + return directoryIndent > runIndent + ? mappingValue(lines, run + 1, directoryIndent, "working-directory") + : null; + } + + /** The value of {@code key} in the mapping at {@code keyIndent} starting at {@code start}. */ + private static String mappingValue(List lines, int start, int keyIndent, String key) { + int index = mappingKey(lines, start, keyIndent, key); + if (index < 0) { + return null; + } + Matcher matcher = MAPPING_KEY.matcher(lines.get(index)); + return matcher.matches() && matcher.group(3) != null + ? stripScalarComment(matcher.group(3)) + : null; + } + + /** The line of {@code key} in the mapping at {@code keyIndent} starting at {@code start}, or -1. */ + private static int mappingKey(List lines, int start, int keyIndent, String key) { + for (int index = start; index < lines.size(); index++) { + String line = lines.get(index); + if (line.isBlank() || line.trim().startsWith("#")) { + continue; + } + if (index > start && indentOf(line) < keyIndent) { + break; + } + if (index > start && keyColumn(line) == keyIndent && line.trim().startsWith("-")) { + break; + } + Matcher matcher = MAPPING_KEY.matcher(line); + if (matcher.matches() && keyColumn(line) == keyIndent && matcher.group(2).equals(key)) { + return index; + } + } + return -1; + } + + /** The indentation of the first content line after {@code index}. */ + private static int childIndent(List lines, int index) { + for (int next = index + 1; next < lines.size(); next++) { + String line = lines.get(next); + if (!line.isBlank() && !line.trim().startsWith("#")) { + return indentOf(line); + } + } + return -1; + } + + /** Where the step holding the {@code run:} at {@code runIndex} starts, and its key column. */ + private record StepScope(int start, int keyIndent) {} + + private static StepScope stepScope(List lines, int runIndex) { + Matcher run = RUN_KEY.matcher(lines.get(runIndex)); boolean itemLine = lines.get(runIndex).trim().startsWith("-"); int stepKeyIndent = itemLine ? lines.get(runIndex).indexOf("run:") - : run.group(1).length(); + : run.matches() ? run.group(1).length() : indentOf(lines.get(runIndex)); int stepStart = runIndex; if (!itemLine) { while (stepStart > 0) { @@ -256,7 +430,16 @@ public final class WorkflowGradleInvocations { } } } - String step = gatingProblem(lines, stepStart, stepKeyIndent, "step"); + return new StepScope(stepStart, stepKeyIndent); + } + + /** + * Why the {@code run:} key at {@code runIndex} gates nothing: a {@code continue-on-error} other + * than {@code false}, or an {@code if:} other than a status function, on its step or its job. + */ + private static String uncountedReason(List lines, int runIndex) { + StepScope scope = stepScope(lines, runIndex); + String step = gatingProblem(lines, scope.start(), scope.keyIndent(), "step"); if (step != null) { return step; } @@ -264,14 +447,7 @@ public final class WorkflowGradleInvocations { if (jobHeader < 0) { return null; } - int jobKeyIndent = -1; - for (int next = jobHeader + 1; next < lines.size(); next++) { - String line = lines.get(next); - if (!line.isBlank() && !line.trim().startsWith("#")) { - jobKeyIndent = indentOf(line); - break; - } - } + int jobKeyIndent = childIndent(lines, jobHeader); return jobKeyIndent <= indentOf(lines.get(jobHeader)) ? null : gatingProblem(lines, jobHeader + 1, jobKeyIndent, "job"); @@ -397,7 +573,8 @@ public final class WorkflowGradleInvocations { return commands; } - private static Invocation gradleInvocation(String command, String uncountedReason) { + private static Invocation gradleInvocation( + String command, String workingDirectory, String uncountedReason) { List tokens = new ArrayList<>(); for (String token : command.trim().split("\\s+")) { if (token.startsWith("#")) { @@ -443,7 +620,7 @@ public final class WorkflowGradleInvocations { tasks.add(token); } } - return new Invocation(projectDir, tasks, dryRun, excluded, uncountedReason); + return new Invocation(workingDirectory, projectDir, tasks, dryRun, excluded, uncountedReason); } private static String unquote(String token) { diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java index a14483c5..a70e2ade 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java @@ -273,6 +273,58 @@ class EnvContractVerifierTest { assertTrue(!failure.getMessage().contains("APP_NAME"), failure.getMessage()); } + @Test + @DisplayName("lane activationEnv의 APP_ 밖 키는 Spring 이름공간도 비밀 참조 대상도 아니면 아무도 읽지 않으므로 실패한다") + void aLaneActivationKeyOutsideEveryReadNamespaceFails(@TempDir Path temp) throws Exception { + // given + Fixture fixture = fixture(temp); + Path contracts = fixture.repositoryRoot().resolve("compose-profile-contracts.json"); + Files.writeString( + contracts, + "{\"lanes\":[{\"id\":\"grpc\",\"activationEnv\":{" + + "\"CASKELETON_GRPC_ENABLED\":\"true\"," + + "\"SPRING_MAIL_HOST\":\"mailpit\"," + + "\"APP_REDIS_HOST\":\"secret://lane@environment/REDIS_LANE_APPLICATION_PASSWORD\"," + + "\"REDIS_LANE_APPLICATION_PASSWORD\":\"fixture-application\"}}]}"); + + // when + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> verifyWithOperatorFiles(fixture, contracts)); + + // then + assertTrue(failure.getMessage().contains("CASKELETON_GRPC_ENABLED"), failure.getMessage()); + assertTrue(!failure.getMessage().contains("SPRING_MAIL_HOST"), failure.getMessage()); + assertTrue( + !failure.getMessage().contains("REDIS_LANE_APPLICATION_PASSWORD"), failure.getMessage()); + } + + @Test + @DisplayName("레지스트리 행의 property가 어떤 설정 metadata에도 없으면 그 키는 읽히는 것으로 치지 않는다") + void anOperatorKeyWhoseRegisteredPropertyNothingDeclaresFails(@TempDir Path temp) + throws Exception { + // given + Fixture fixture = fixture(temp); + Files.writeString( + fixture.envFile(), Files.readString(fixture.envFile()) + "APP_GHOST_ENABLED=true\n"); + Files.writeString( + fixture.registry(), + Files.readString(fixture.registry()) + + "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n"); + Path compose = fixture.repositoryRoot().resolve("docker-compose.yml"); + Files.writeString( + compose, "services:\n app:\n environment:\n APP_GHOST_ENABLED: \"true\"\n"); + + // when + IllegalStateException failure = + assertThrows(IllegalStateException.class, () -> verifyWithOperatorFiles(fixture, compose)); + + // then + assertTrue(failure.getMessage().contains("nothing reads"), failure.getMessage()); + assertTrue(failure.getMessage().contains("APP_GHOST_ENABLED"), failure.getMessage()); + } + private static EnvContractResult verifyWithOperatorFiles(Fixture fixture, Path operatorFile) { return EnvContractVerifier.verify( fixture.envFile().toFile(), diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java index 9c038036..3540d55a 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java @@ -102,6 +102,9 @@ class StrictLaneStagesFunctionalTest { """); workflow( """ + defaults: + run: + working-directory: src jobs: main: steps: @@ -197,6 +200,9 @@ class StrictLaneStagesFunctionalTest { """); workflow( """ + defaults: + run: + working-directory: src jobs: main: steps: @@ -223,6 +229,9 @@ class StrictLaneStagesFunctionalTest { """); workflow( """ + defaults: + run: + working-directory: src jobs: gate: steps: @@ -258,6 +267,9 @@ class StrictLaneStagesFunctionalTest { """); workflow( """ + defaults: + run: + working-directory: src jobs: gate: steps: @@ -284,17 +296,37 @@ class StrictLaneStagesFunctionalTest { } @Test - @DisplayName("다른 빌드로 실행되는 빌드는 workflow가 -p 그 디렉터리로 부른 단계만 실행으로 센다") - void aBuildStartedWithDashPCountsOnlyCommandsThatNameItsDirectory() throws Exception { + @DisplayName("다른 빌드로 실행되는 빌드는 workflow가 그 디렉터리에서 시작한 단계만 실행으로 센다") + void aBuildStartedWithDashPCountsOnlyCommandsThatStartInItsDirectory() throws Exception { // given - leafLanes( + Path optional = gradleRoot.resolve("optional"); + Files.createDirectories(optional.resolve("leaf/src/test/java")); + Files.writeString( + optional.resolve("settings.gradle"), "rootProject.name = 'optional'\ninclude 'leaf'\n"); + Files.writeString( + optional.resolve("build.gradle"), """ - lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + plugins { id 'ca.strict-lane-stages' } + tasks.register('ci') { dependsOn ':leaf:check' } + tasks.register('integrationCheck') { dependsOn ':leaf:integrationTestLaneCheck' } + tasks.register('performanceCheck') { dependsOn ':leaf:check' } + strictLaneStages { + stage ':ci', ':integrationCheck', ':performanceCheck' + workflowDirectory = layout.projectDirectory.dir('../../.github/workflows') + } """); Files.writeString( - gradleRoot.resolve("build.gradle"), - Files.readString(gradleRoot.resolve("build.gradle")) - + "strictLaneStages { workflowProjectDirectory = 'optional' }\n"); + optional.resolve("leaf/build.gradle"), + """ + plugins { + id 'java' + id 'ca.strict-test-lane' + } + strictTestLanes { + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + } + """); + Files.writeString(optional.resolve("leaf/src/test/java/LaneTest.java"), "class LaneTest {}\n"); workflow( """ jobs: @@ -302,6 +334,74 @@ class StrictLaneStagesFunctionalTest { steps: - working-directory: src run: ./gradlew -p optional ci --stacktrace + - working-directory: src/optional + run: ../gradlew performanceCheck + - working-directory: src + run: ./gradlew :integrationCheck + """); + + // when + BuildResult result = + GradleRunner.create() + .withProjectDir(optional.toFile()) + .withPluginClasspath() + .withArguments(":verifyStrictLaneStages", "--dry-run") + .buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("stage :integrationCheck is executed by no workflow") + .doesNotContain("stage :ci is executed by no workflow") + .doesNotContain("stage :performanceCheck is executed by no workflow"); + } + + @Test + @DisplayName("축약한 -x로 뺀 lane도 Gradle처럼 맞춰 보아 덮이지 않은 것으로 실패한다") + void aLaneExcludedWithAnAbbreviatedDashXIsNotCovered() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + lane('cacheLane') { integration(); tag = 'cache'; description = 'Real cache.' } + """); + workflow( + """ + defaults: + run: + working-directory: src + jobs: + main: + steps: + - run: ./gradlew :ci --stacktrace + - run: ./gradlew :integrationCheck -x databaseL --continue + """); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("strict lane :leaf:databaseLane is in no executed stage") + .doesNotContain("strict lane :leaf:cacheLane"); + } + + @Test + @DisplayName("workflow_dispatch로만 시작하는 workflow가 부르는 단계는 실행으로 세지 않는다") + void aStageRunOnlyByADispatchOnlyWorkflowIsNotAnExecution() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + """); + workflow(EXECUTING_WORKFLOW.replace("./gradlew :integrationCheck", "./gradlew :ci")); + Files.writeString( + repository.resolve(".github/workflows/manual.yml"), + """ + on: + workflow_dispatch: + jobs: + manual: + steps: - working-directory: src run: ./gradlew :integrationCheck """); @@ -312,7 +412,33 @@ class StrictLaneStagesFunctionalTest { // then assertThat(result.getOutput()) .contains("stage :integrationCheck is executed by no workflow") - .doesNotContain("stage :ci is executed by no workflow"); + .contains("strict lane :leaf:databaseLane is in no executed stage"); + } + + @Test + @DisplayName("다른 빌드의 디렉터리를 working-directory로 둔 gradlew는 이 빌드의 단계 실행으로 세지 않는다") + void aCommandStartedInAnotherBuildsDirectoryIsNotThisBuildsExecution() throws Exception { + // given + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + """); + workflow( + """ + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :ci --stacktrace + - working-directory: src/optional + run: ../gradlew :integrationCheck + """); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail(); + + // then + assertThat(result.getOutput()).contains("stage :integrationCheck is executed by no workflow"); } private void leafLanes(String lanes) throws Exception { diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/TaskSelectorsTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/TaskSelectorsTest.java new file mode 100644 index 00000000..76a189dc --- /dev/null +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/TaskSelectorsTest.java @@ -0,0 +1,71 @@ +package dev.caskeleton.buildlogic.strictlane; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class TaskSelectorsTest { + + private static final Map> BUILD = + Map.of( + ":", Set.of("ci", "performanceCheck", "test"), + ":grpc", Set.of("test"), + ":grpc:grpc-testkit", + Set.of("test", "testClasses", "grpcPerformanceTest", "grpcPerformanceTestClasses"), + ":leaf", Set.of("test", "databaseLane", "databaseLoadTest")); + + @Test + @DisplayName("이름이 정확히 같은 태스크가 있으면 그 이름만 모든 프로젝트에서 뺀다") + void anExactNameRemovesOnlyThatNameInEveryProject() { + // when + Set excluded = TaskSelectors.excludedPaths(List.of("test"), BUILD); + + // then + assertThat(excluded) + .containsExactlyInAnyOrder(":test", ":grpc:test", ":grpc:grpc-testkit:test", ":leaf:test"); + } + + @Test + @DisplayName("camel-case 축약 이름은 Gradle처럼 그 태스크를 뺀다") + void aCamelCaseAbbreviationRemovesTheTaskGradleWouldRemove() { + // when + Set excluded = TaskSelectors.excludedPaths(List.of("grpcPerformanceT"), BUILD); + + // then + assertThat(excluded).containsExactly(":grpc:grpc-testkit:grpcPerformanceTest"); + } + + @Test + @DisplayName("경로의 프로젝트 이름도 축약할 수 있다") + void aQualifiedSelectorMayAbbreviateItsProjectNames() { + // when + Set excluded = TaskSelectors.excludedPaths(List.of(":grpc:grpcT:gPT"), BUILD); + + // then + assertThat(excluded).containsExactly(":grpc:grpc-testkit:grpcPerformanceTest"); + } + + @Test + @DisplayName("Gradle이 모호하다고 거부할 축약은 후보 전부를 뺀 것으로 본다") + void anAmbiguousAbbreviationRemovesEveryCandidate() { + // when + Set excluded = TaskSelectors.excludedPaths(List.of("database"), BUILD); + + // then + assertThat(excluded).containsExactlyInAnyOrder(":leaf:databaseLane", ":leaf:databaseLoadTest"); + } + + @Test + @DisplayName("맞는 태스크가 없는 선택자는 아무것도 빼지 않는다") + void aSelectorThatMatchesNothingRemovesNothing() { + // when + Set excluded = TaskSelectors.excludedPaths(List.of(":leaf:cacheLane"), BUILD); + + // then + assertThat(excluded).isEmpty(); + } +} diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java index 3bd5f940..81530956 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java @@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.buildlogic.strictlane.WorkflowGradleInvocations.Invocation; import java.util.List; +import java.util.Map; +import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -30,7 +32,7 @@ class WorkflowGradleInvocationsTest { assertThat(invocations).singleElement().satisfies( invocation -> { assertThat(invocation.tasks()).containsExactly(":mainCheck"); - assertThat(invocation.executesInStartBuild(":mainCheck")).isTrue(); + assertThat(invocation.executes(":mainCheck", "src")).isTrue(); }); } @@ -53,7 +55,7 @@ class WorkflowGradleInvocationsTest { // then assertThat(invocations) .isNotEmpty() - .noneMatch(invocation -> invocation.executesInStartBuild(":integrationCheck")); + .noneMatch(invocation -> invocation.executes(":integrationCheck", ".")); } @Test @@ -73,8 +75,8 @@ class WorkflowGradleInvocationsTest { // then assertThat(invocations) - .noneMatch(invocation -> invocation.executesInStartBuild(":integrationCheck")) - .anyMatch(invocation -> invocation.executesInStartBuild(":ci")); + .noneMatch(invocation -> invocation.executes(":integrationCheck", ".")) + .anyMatch(invocation -> invocation.executes(":ci", ".")); } @Test @@ -93,7 +95,8 @@ class WorkflowGradleInvocationsTest { assertThat(invocations).singleElement().satisfies( invocation -> { assertThat(invocation.projectDir()).isEqualTo("optional-platforms"); - assertThat(invocation.executesInStartBuild(":integrationCheck")).isFalse(); + assertThat(invocation.executes(":integrationCheck", ".")).isFalse(); + assertThat(invocation.executes(":integrationCheck", "optional-platforms")).isTrue(); }); } @@ -140,8 +143,8 @@ class WorkflowGradleInvocationsTest { // then assertThat(invocations).singleElement().satisfies( invocation -> { - assertThat(invocation.executesInStartBuild(":integrationCheck")).isTrue(); - assertThat(invocation.executesInStartBuild(":sample-portfolio:check")).isTrue(); + assertThat(invocation.executes(":integrationCheck", ".")).isTrue(); + assertThat(invocation.executes(":sample-portfolio:check", ".")).isTrue(); assertThat(invocation.tasks()).doesNotContain("*Contract*"); }); } @@ -211,10 +214,16 @@ class WorkflowGradleInvocationsTest { Invocation invocation = WorkflowGradleInvocations.read(workflow).get(0); // then - assertThat(invocation.excludes(":leaf:databaseLane")).isTrue(); - assertThat(invocation.excludes(":other:test")).isTrue(); - assertThat(invocation.excludes(":leaf:cacheLane")).isFalse(); - assertThat(invocation.executesInStartBuild(":integrationCheck")).isTrue(); + assertThat(invocation.excludedTasks()).containsExactly(":leaf:databaseLane", "test"); + assertThat( + TaskSelectors.excludedPaths( + invocation.excludedTasks(), + Map.of( + ":", Set.of("integrationCheck"), + ":leaf", Set.of("databaseLane", "cacheLane", "test"), + ":other", Set.of("test")))) + .containsExactlyInAnyOrder(":leaf:databaseLane", ":leaf:test", ":other:test"); + assertThat(invocation.executes(":integrationCheck", ".")).isTrue(); } @Test @@ -249,4 +258,124 @@ class WorkflowGradleInvocationsTest { reason -> assertThat(reason).contains("step runs only if: github.event_name"), reason -> assertThat(reason).isNull()); } + + @Test + @DisplayName("workflow_dispatch로만 시작하는 workflow의 명령은 아무 실행도 막지 못하므로 세지 않는다") + void aWorkflowThatOnlyRunsOnDispatchGatesNothing() { + // given + String workflow = + """ + on: + workflow_dispatch: + inputs: + lane: + type: string + jobs: + manual: + steps: + - working-directory: src + run: ./gradlew :integrationCheck + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations) + .singleElement() + .extracting(Invocation::uncountedReason) + .asString() + .contains("workflow_dispatch"); + } + + @Test + @DisplayName("workflow_dispatch 말고 다른 트리거도 있으면 명령을 실행으로 센다") + void aWorkflowWithAnotherTriggerBesidesDispatchCounts() { + // given + String workflow = + """ + on: [push, workflow_dispatch] + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :integrationCheck + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).singleElement().extracting(Invocation::uncountedReason).isNull(); + } + + @Test + @DisplayName("working-directory는 -p처럼 읽어서, 하위 디렉터리에서 부른 gradlew는 그 디렉터리의 빌드를 실행한다") + void workingDirectoryIsReadLikeDashP() { + // given + String workflow = + """ + jobs: + optional: + steps: + - working-directory: src/optional-platforms + run: ../gradlew ci --stacktrace + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).singleElement().satisfies( + invocation -> { + assertThat(invocation.executes(":ci", "src/optional-platforms")).isTrue(); + assertThat(invocation.executes(":ci", "src")).isFalse(); + }); + } + + @Test + @DisplayName("job의 defaults.run.working-directory도 그 job 단계의 시작 디렉터리로 읽는다") + void jobDefaultsWorkingDirectoryIsTheStepsStartDirectory() { + // given + String workflow = + """ + jobs: + release: + defaults: + run: + working-directory: src + steps: + - run: ./gradlew -p optional-platforms releaseCheck + - run: ./gradlew :releaseCheck + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).hasSize(2); + assertThat(invocations.get(0).executes(":releaseCheck", "src/optional-platforms")).isTrue(); + assertThat(invocations.get(1).executes(":releaseCheck", "src")).isTrue(); + } + + @Test + @DisplayName("uses 단계의 with 입력에 적힌 run은 셸 명령이 아니므로 읽지 않는다") + void aRunInputOfAnActionIsNotAShellCommand() { + // given + String workflow = + """ + jobs: + main: + steps: + - uses: some/action@v1 + with: + run: ./gradlew :integrationCheck + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).isEmpty(); + } } diff --git a/src/composition/idempotency/README.md b/src/composition/idempotency/README.md index 50a362e9..5ce585b7 100644 --- a/src/composition/idempotency/README.md +++ b/src/composition/idempotency/README.md @@ -45,7 +45,7 @@ executor, 설정 기본값이 함께 빠진다(그때 KEYED use case는 executor | 언제 | 키 | | --- | --- | | 켤 때 | `APP_IDEMPOTENCY_PROVIDER` (`redis` 또는 `postgresql`), 그리고 그 provider 모듈의 줄과 env | -| 조정할 때 | `APP_IDEMPOTENCY_PROCESSING_LEASE`(≤1h), `APP_IDEMPOTENCY_TTL`(≤72h), `APP_IDEMPOTENCY_FAILURE_RETENTION`(≤30d) | +| 조정할 때 | `APP_IDEMPOTENCY_PROCESSING_LEASE`(≤1h), `APP_IDEMPOTENCY_TTL`(≤72h, processing lease 이상), `APP_IDEMPOTENCY_FAILURE_RETENTION`(≤30d) | ## 설계 결정 참조 (app-bootstrap에서 옮김) @@ -73,7 +73,7 @@ executor, 설정 기본값이 함께 빠진다(그때 KEYED use case는 executor | --- | --- | --- | --- | | `provider` | `APP_IDEMPOTENCY_PROVIDER` | `disabled` | `disabled` \| `redis` \| `postgresql` | | `processing-lease` | `APP_IDEMPOTENCY_PROCESSING_LEASE` | 30s | 1h | - | `replay-ttl` | `APP_IDEMPOTENCY_TTL` | 24h | 72h | + | `replay-ttl` | `APP_IDEMPOTENCY_TTL` | 24h | 72h, 그리고 `processing-lease` 이상 | | `failure-retention` | `APP_IDEMPOTENCY_FAILURE_RETENTION` | 24h | 30d | | `response-codec-id` | — | `json-v2` | 1–64자 | | `policy-revision` | — | 2 | 양수 | @@ -81,6 +81,12 @@ executor, 설정 기본값이 함께 빠진다(그때 KEYED use case는 executor Redis store 튜닝값 `key-version`, `command-timeout`(`APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT`)도 같은 prefix 아래 있지만 lifecycle 정책이 아니라서 이 record 에 두지 않고 `cache-redis`가 읽는다. +- **`replay-ttl` 이 `processing-lease` 보다 짧으면 기동을 거부한다.** 같은 키로 다시 보내라는 답을 받은 + 클라이언트는 lease 안 어느 때든 돌아올 수 있다. 재생 창이 그보다 먼저 닫히면 그 재전송은 작업을 한 번 + 더 돌린다(재리뷰 2026-11-04 RR-03-11). 두 store 는 이 관계와 상관없이 기록을 lease + replay TTL 동안 + 둔다 — 이 검사는 store 를 지키는 것이 아니라 재생을 무력하게 만드는 정책을 막는다. + `IdempotencyClaimRequest` 에는 두지 않았다: 포트는 어떤 값 쌍으로도 쓸 수 있고, store 가 모든 쌍에서 + 안전한지는 공유 계약이 본다. - **상한 검사는 컴팩트 생성자에서 fail-fast 로 던진다.** `Duration`의 상한은 JSR-303(`@Valid`) 애너테이션으로 표현할 수 없어 생성자에서 직접 검증한다. 검증을 느슨하게 두면 과도하게 긴 TTL 이 저장소를 조용히 부풀리고 멱등성 키 추측 공격의 유효 시간 창을 넓히기 때문에, 부팅 시점에 즉시 diff --git a/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java b/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java index e56a0ccc..19bf60f7 100644 --- a/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java +++ b/src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencySettings.java @@ -21,7 +21,8 @@ import org.springframework.core.env.Environment; * @param processingLease how long one attempt holds a claim before another may take it over; longer * than the in-flight 409's {@code Retry-After} ({@link * IdempotencyExecutor#IN_FLIGHT_RETRY_AFTER}) - * @param replayTtl how long a completed response is replayable (at most 72h, D6) + * @param replayTtl how long a completed response is replayable (at most 72h, D6), and no shorter + * than {@code processingLease} * @param failureRetention how long a failed attempt's evidence is kept * @param responseCodecId identifier of the codec the stored payload is written with * @param policyRevision replay policy revision written into and compared on each record @@ -63,6 +64,20 @@ public record IdempotencySettings( + processingLease); } replayTtl = bounded("replay-ttl", orDefault(replayTtl, Duration.ofHours(24)), MAX_REPLAY_TTL); + // A duplicate told to resend with the same key may come back anywhere inside the lease. A + // replay window shorter than that closes before such a resend arrives, and the resend runs the + // operation a second time (re-review 2026-11-04 RR-03-11). Both stores also keep a record for + // the lease plus the replay TTL whatever the pair, so this refuses a policy that defeats the + // replay, not a store hazard. Kept here, not in IdempotencyClaimRequest: the port stays usable + // with any pair, and the stores are held to staying safe for every pair by their contract. + if (replayTtl.compareTo(processingLease) < 0) { + throw StartupFailures.envValidation( + PREFIX + + ".replay-ttl must not be shorter than processing-lease (" + + processingLease + + "), was " + + replayTtl); + } failureRetention = bounded( "failure-retention", diff --git a/src/composition/idempotency/src/main/resources/config/module-defaults/idempotency.yml b/src/composition/idempotency/src/main/resources/config/module-defaults/idempotency.yml index 1a4a1b19..7ba85134 100644 --- a/src/composition/idempotency/src/main/resources/config/module-defaults/idempotency.yml +++ b/src/composition/idempotency/src/main/resources/config/module-defaults/idempotency.yml @@ -12,6 +12,9 @@ app: # the lifecycle keys below, whichever provider is selected. disabled binds and builds nothing. provider: ${APP_IDEMPOTENCY_PROVIDER:disabled} # Lifecycle policy (IdempotencySettings), the same whichever provider holds the records. + # replay-ttl must not be shorter than processing-lease (startup fails otherwise): a duplicate + # told to resend with the same key may come back anywhere inside the lease. A record lives + # for the lease plus the replay TTL in both stores. processing-lease: ${APP_IDEMPOTENCY_PROCESSING_LEASE:30s} replay-ttl: ${APP_IDEMPOTENCY_TTL:24h} failure-retention: ${APP_IDEMPOTENCY_FAILURE_RETENTION:24h} diff --git a/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java index 1c573f2d..a4ebe984 100644 --- a/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java +++ b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencySettingsTest.java @@ -176,6 +176,49 @@ class IdempotencySettingsTest { "app.capabilities.idempotency.processing-lease must be longer than PT2S"); } + /** + * A completed response must stay replayable at least as long as one attempt may hold its claim: a + * client told to resend with the same key may arrive anywhere inside the lease, and a replay + * window closed by then turns that resend into a second run (re-review 2026-11-04 RR-03-11). + */ + @ParameterizedTest + @CsvSource({"PT30S, PT10S", "PT1H, PT59M"}) + @DisplayName("replay-ttl이 processing-lease보다 짧으면 기동을 거부한다") + void aReplayTtlShorterThanTheProcessingLeaseIsRefused(Duration lease, Duration replay) { + // when + Throwable thrown = + catchThrowable( + () -> + new IdempotencySettings( + IdempotencySettings.Provider.REDIS, lease, replay, null, null, null, null)); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + StartupFailureException.class, + e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) + .hasMessageContaining( + "app.capabilities.idempotency.replay-ttl must not be shorter than processing-lease"); + } + + @Test + @DisplayName("replay-ttl이 processing-lease와 같으면 받아들인다") + void aReplayTtlEqualToTheProcessingLeaseIsAccepted() { + // when + IdempotencySettings settings = + new IdempotencySettings( + IdempotencySettings.Provider.REDIS, + Duration.ofMinutes(5), + Duration.ofMinutes(5), + null, + null, + null, + null); + + // then + assertThat(settings.replayTtl()).isEqualTo(settings.processingLease()); + } + @ParameterizedTest @CsvSource({"'', response-codec-id must contain 1-64 characters", "' ', response-codec-id"}) void blankCodecIdIsRefused(String codecId, String message) { diff --git a/src/composition/outbox-relay/README.md b/src/composition/outbox-relay/README.md index 87cbc7b8..2c7ddc2b 100644 --- a/src/composition/outbox-relay/README.md +++ b/src/composition/outbox-relay/README.md @@ -118,7 +118,9 @@ poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `a `outbox.retry.long.size`는 미룬 claim이 `LONG_RETRY_DEFERRED_CLAIMS`(10)번 이상인 FAILED 행 수, `outbox.retry.long.age`는 그중 가장 오래된 행의 나이다. 10번은 backoff 상한 5분 기준으로 적어도 약 35분 동안 실패했다는 뜻이라 broker 재시작·credential 교체는 넘긴다. publish-failed runbook §4.1의 조회가 같은 - 기준을 쓴다. + 기준을 쓴다. runbook SQL에는 숫자가 그대로 적혀 있어서(운영자가 psql에 붙여 넣는다) 상수만 바꾸면 경보가 센 행과 + 조회가 보여 주는 행이 갈라진다. `OutboxLongRetryRunbookContractTest`(lane `outboxRelayDocumentContractTest`, + `mainCheck`)가 runbook 블록의 숫자와 상수를 비교한다(재리뷰 2차 RR-02-14). - **MultiGauge 갱신 시 `overwrite=true`로 등록한다.** 매 스케줄러 틱마다 store 를 다시 조회해 게이지를 갱신하는데, 이전 틱에 있었지만 지금은 사라진 event type 같은 오래된 time-series 태그를 덮어써 제거하기 위함이다. diff --git a/src/composition/outbox-relay/build.gradle b/src/composition/outbox-relay/build.gradle index 0a700d77..0b9916bd 100644 --- a/src/composition/outbox-relay/build.gradle +++ b/src/composition/outbox-relay/build.gradle @@ -41,3 +41,21 @@ dependencies { testImplementation 'ch.qos.logback:logback-classic' testRuntimeOnly 'org.yaml:snakeyaml' } + +// OutboxLongRetryRunbookContractTest holds the long-retry gauges' threshold to the number written into +// the publish-failed runbook's query (re-review 2026-11-03 round 2, RR-02-14). A comparison with a +// repository document, so it runs in this module's `mainCheck`, not in the pull-request `test`; the +// runbook is its input, so editing the number reruns it. +strictTestLanes { + lane('outboxRelayDocumentContractTest') { + tag = 'document-contract' + description = 'Holds the long-retry threshold to docs/runbooks/outbox-publish-failed.md.' + rejectSkipped = true + mainStage() + } +} +tasks.named('outboxRelayDocumentContractTest', Test) { + inputs.file(new File(rootProject.projectDir.parentFile, 'docs/runbooks/outbox-publish-failed.md')) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName('publishFailedRunbook') +} diff --git a/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxLongRetryRunbookContractTest.java b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxLongRetryRunbookContractTest.java new file mode 100644 index 00000000..17becf0c --- /dev/null +++ b/src/composition/outbox-relay/src/test/java/dev/caskeleton/composition/outbox/OutboxLongRetryRunbookContractTest.java @@ -0,0 +1,61 @@ +package dev.caskeleton.composition.outbox; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * The long-retry gauges and the runbook query that lists the rows behind them use one threshold + * (re-review 2026-11-03 round 2, RR-02-14). + * + *

        The gauge reads {@link OutboxMetrics#LONG_RETRY_DEFERRED_CLAIMS}; the publish-failed runbook's + * {@code long-retries} block has the number written into its SQL, because an operator pastes it + * into psql. Changing one alone made the alert count rows the runbook query did not show. The + * runbook lane in persistence-jpa runs the SQL against PostgreSQL; this test holds its number to + * the constant. + */ +@Tag("document-contract") +class OutboxLongRetryRunbookContractTest { + + private static final Path RUNBOOK = Path.of("../../../docs/runbooks/outbox-publish-failed.md"); + private static final Pattern LONG_RETRIES_BLOCK = + Pattern.compile("\\s*```sql\\n(.*?)```", Pattern.DOTALL); + private static final Pattern THRESHOLD = + Pattern.compile("deferred_attempt_count\\s*>=\\s*(\\d+)"); + + @Test + @DisplayName("runbook의 오래 재시도 조회는 게이지와 같은 미룬 claim 기준을 쓴다") + void theRunbookQueryUsesTheThresholdTheGaugeCounts() throws IOException { + // given + String runbook = Files.readString(RUNBOOK, StandardCharsets.UTF_8); + + // when + List thresholds = thresholdsIn(runbook); + + // then + assertThat(thresholds) + .as("the long-retries block of %s", RUNBOOK) + .containsExactly(OutboxMetrics.LONG_RETRY_DEFERRED_CLAIMS); + } + + private static List thresholdsIn(String runbook) { + Matcher block = LONG_RETRIES_BLOCK.matcher(runbook); + if (!block.find()) { + return List.of(); + } + return THRESHOLD + .matcher(block.group(1)) + .results() + .map(match -> Integer.valueOf(match.group(1))) + .toList(); + } +} diff --git a/src/composition/service-runtime/README.md b/src/composition/service-runtime/README.md index 46112736..dd2d6b4c 100644 --- a/src/composition/service-runtime/README.md +++ b/src/composition/service-runtime/README.md @@ -30,7 +30,9 @@ composition:service-runtime "어떤 advisor든 pointcut이 맞으면 통과"라 인가가 아닌 advisor를 구분하지 못한다. `new`로 만든 유스케이스는 검사 대상이 아니다(시스템 호출용은 `@SystemInvoked`). 반대로 `@SystemInvoked` 유스케이스가 빈으로 등록돼 있으면 같은 가드가 기동을 멈춘다 — 권한 검사가 없는 쓰기를 전송 계층이 - 닿는 곳에 두는 조립이기 때문이다(review 2026-11-03 RR-01-02). + 닿는 곳에 두는 조립이기 때문이다(review 2026-11-03 RR-01-02). 가드가 허용하는 경우는 하나다: 시스템 + 호출자의 bean이 자기가 `new`로 만든 use case를 필드로 든다(스케줄러에 넘기는 조립 모듈, 또는 + `@SystemCaller` 메시지 handler — RR-01-12). 가드는 bean 타입만 보므로 둘 다 기동한다. - 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(설정 브리지와 tracing 스위치는 `spring.factories`의 `EnvironmentPostProcessor`·`AutoConfigurationImportFilter`). 구성 루트의 diff --git a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java index c671f8b8..f15207dd 100644 --- a/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java +++ b/src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java @@ -28,11 +28,16 @@ import org.springframework.util.ClassUtils; * whose pointcut happens to match; it closes the "adapter missing" gap, not every misconfiguration. * *

        A {@code @SystemInvoked} use case carries no permission by design — only the system calls it, - * on a thread with no {@code Authentication} — and its composition constructs it with {@code new} - * and hands it to that caller. Registered as a bean, it is a write any transport can reach with no - * check, whatever advisor the context holds, so its presence fails startup (review 2026-11-03 - * RR-01-02). {@code INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES} closes the other path, - * an inbound adapter that constructs one itself. + * on a thread with no {@code Authentication}. Registered as a bean, it is a write any transport can + * reach with no check, whatever advisor the context holds, so its presence fails startup (review + * 2026-11-03 RR-01-02), with no exception. The system caller that runs it holds it instead, and + * that is the one condition this guard allows: the use case is a field of a bean, never a bean. + * There are two such callers (decision 9.1, RR-01-12): a scheduler, to which a composition module + * hands the use case it constructed (the outbox relay), and a {@code @SystemCaller} message + * handler, which constructs the use case from the ports its own bean method receives. The guard + * looks at bean types only, so both start. {@code + * ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} closes the static path, a user transport that + * constructs one itself. */ final class PermissionEnforcementGuard implements SmartInitializingSingleton, BeanFactoryAware { @@ -64,8 +69,9 @@ final class PermissionEnforcementGuard implements SmartInitializingSingleton, Be if (!systemInvoked.isEmpty()) { throw StartupFailures.requiredAdapterDisabled( "@SystemInvoked use cases are registered as beans, where a transport can reach a write" - + " that has no permission check — a system-invoked use case must be constructed by" - + " its composition, not registered as a bean: " + + " that has no permission check — a system-invoked use case is constructed by the" + + " system caller that runs it (a scheduler's composition, a @SystemCaller message" + + " handler) and never registered as a bean: " + String.join(", ", systemInvoked)); } if (!unenforced.isEmpty()) { diff --git a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java index e8c1acf8..95993ba4 100644 --- a/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java +++ b/src/composition/service-runtime/src/test/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuardTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.security.SystemCaller; import dev.caskeleton.application.security.SystemInvoked; import org.aopalliance.intercept.MethodInterceptor; import org.junit.jupiter.api.Test; @@ -52,10 +53,26 @@ class PermissionEnforcementGuardTest { context -> assertThat(context.getStartupFailure()) .isInstanceOf(StartupFailureException.class) - .hasMessageContaining("must be constructed by its composition") + .hasMessageContaining("never registered as a bean") .hasMessageContaining(SystemInvokedUseCase.class.getName())); } + /** + * The one shape the guard allows for a system-invoked use case: a system caller's bean holds the + * use case it constructed, so the use case is a field, never a bean (review 2026-11-03 RR-01-12). + */ + @Test + void aSystemCallerBeanHoldingTheSystemInvokedUseCaseItConstructedStarts() { + runner + .withUserConfiguration(SystemCallerConfig.class) + .run( + context -> + assertThat(context) + .hasNotFailed() + .hasSingleBean(SystemCallerHandler.class) + .doesNotHaveBean(SystemInvokedUseCase.class)); + } + @Test void aContextWithoutGatedBeansNeedsNoAdvisor() { runner.run(context -> assertThat(context).hasNotFailed()); @@ -87,6 +104,27 @@ class PermissionEnforcementGuardTest { } } + @SystemCaller(reason = "the broker consumer calls it") + public static class SystemCallerHandler { + private final SystemInvokedUseCase useCase; + + SystemCallerHandler() { + this.useCase = new SystemInvokedUseCase(); + } + + public void handle() { + useCase.handle(); + } + } + + @Configuration(proxyBeanMethods = false) + static class SystemCallerConfig { + @Bean + SystemCallerHandler systemCallerHandler() { + return new SystemCallerHandler(); + } + } + @Configuration(proxyBeanMethods = false) static class EnforcingAdvisorConfig { @Bean diff --git a/src/config/spotbugs/exclude.xml b/src/config/spotbugs/exclude.xml index 2a7d1e5e..d1a4707a 100644 --- a/src/config/spotbugs/exclude.xml +++ b/src/config/spotbugs/exclude.xml @@ -473,9 +473,11 @@ + unchanged to /error. CSRF protection guards a state change made with ambient credentials; + this method makes none — it writes a fixed failure envelope, with nothing from the request in + it. A direct request to /error is answered as an unknown route and still goes through the + authentication chain (a token under the JWT chain, which keeps CSRF off because it carries + no ambient credential). Exact to the one method (review 2026-11-04 RR2-04-06). --> diff --git a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcClaimToken.java b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcClaimToken.java index 7b5fe358..269b00ed 100644 --- a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcClaimToken.java +++ b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcClaimToken.java @@ -12,7 +12,12 @@ package dev.caskeleton.grpc.api.ledger; * that still holds the claim. * *

        A counter rather than the claim moment: it increases by one with every hand-over, so two - * attempts never share a value, whatever the clocks of the processes that claimed it. + * attempts of one record never share a value, whatever the clocks of the processes that claimed it. + * The counter lives in the record: once the record is deleted ({@code release}, or the purge of a + * finished record), the next claim of the key starts again at {@link #FIRST}. Both deletions are + * therefore limited to records no live attempt can still write to — a released claim's owner is + * known to be gone, and a purged record finished longer ago than any retry (review 2026-11-03 + * RR-01-15). * * @param attempt one for the first claim of an operation, one more for each hand-over */ diff --git a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java index 381979a7..19c239c7 100644 --- a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java +++ b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java @@ -135,10 +135,22 @@ public interface GrpcOperationLedger { int purgeCompletedBefore(Instant completedBefore, int limit); /** - * Releases a claim that will never complete, so the caller may try again. + * Releases a claim that will never complete, so the caller may try again: deletes the record if + * it is still {@code IN_PROGRESS} and {@code claimToken} still holds it. * *

        Only for a claim whose owner is known to be gone. Releasing one whose owner is merely slow - * re-admits the duplicate. + * re-admits the duplicate. Fenced like every other transition (review 2026-11-03 RR-01-15): an + * attempt that lost the claim cannot delete the claim of the attempt that took it over, and a + * finished record — the answer a retry replays — is never released. + * + *

        The record is gone afterwards, so the next claim of the key starts again at {@link + * GrpcClaimToken#FIRST}. An earlier attempt that lost the claim and is still running would then + * hold a token equal to the new claim's; releasing is safe only when no such attempt can still + * record an outcome — which is what "the owner is known to be gone" has to cover. + * + * @param claimToken the token of the attempt that holds the claim + * @return true when the record was deleted; false when it is missing, finished, or held by + * another attempt, in which case nothing changed */ - void release(GrpcOperationIdentity identity); + boolean release(GrpcOperationIdentity identity, GrpcClaimToken claimToken); } diff --git a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java index d91f8de1..ac84f97f 100644 --- a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java +++ b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java @@ -429,6 +429,60 @@ public abstract class GrpcOperationLedgerContract { .isEqualTo(takenOver); } + /** + * Release deletes the row, so it is fenced like every other transition: only the attempt that + * holds an unfinished claim may give it up (review 2026-11-03 RR-01-15). + */ + @Test + @DisplayName("진행 중 claim 을 가진 시도가 release 하면 키가 비고 다음 claim 이 첫 시도가 된다") + void releaseByTheAttemptHoldingAnUnfinishedClaimFreesTheKey() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + boolean released = ledger().release(ID, GrpcClaimToken.FIRST); + + // then + assertThat(List.of(released, ledger().claim(ID, FINGERPRINT, NOW.plusSeconds(1)).isEmpty())) + .containsExactly(true, true); + } + + @Test + @DisplayName("claim 을 넘겨준 옛 시도의 release 는 무시되고 새 시도의 claim 이 남는다") + void releaseByTheAttemptThatLostTheClaimChangesNothing() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().reclaimStale(ID, FINGERPRINT, CUTOFF, LATER); + + // when + boolean released = ledger().release(ID, GrpcClaimToken.FIRST); + + // then + assertThat(released).isFalse(); + assertThat(ledger().find(ID)) + .get() + .extracting(GrpcOperationLedgerRecord::state, GrpcOperationLedgerRecord::claimToken) + .containsExactly(GrpcOperationLedgerState.IN_PROGRESS, GrpcClaimToken.FIRST.next()); + } + + @Test + @DisplayName("끝난 claim 은 release 로 지워지지 않는다 — 재시도에 결과를 돌려줄 기록이다") + void releaseOfAFinishedClaimChangesNothing() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().markCommitted(ID, GrpcClaimToken.FIRST, OUTCOME, NOW.plusSeconds(1)); + + // when + boolean released = ledger().release(ID, GrpcClaimToken.FIRST); + + // then + assertThat(released).isFalse(); + assertThat(ledger().find(ID)) + .get() + .extracting(GrpcOperationLedgerRecord::state) + .isEqualTo(GrpcOperationLedgerState.COMMITTED); + } + /** * The re-review probe's sequence (2026-11-03, RR-02-04): A claims and is slow, B takes the claim * over after the TTL, then A reports a failure. Recording it would mark B's running attempt diff --git a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java index bc26942d..7aa38665 100644 --- a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java +++ b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java @@ -156,8 +156,12 @@ public final class InMemoryOperationLedger implements GrpcOperationLedger { } @Override - public void release(GrpcOperationIdentity identity) { - records.remove(identity.storageKey()); + public boolean release(GrpcOperationIdentity identity, GrpcClaimToken claimToken) { + GrpcOperationLedgerRecord existing = records.get(identity.storageKey()); + return existing != null + && existing.state() == GrpcOperationLedgerState.IN_PROGRESS + && existing.claimToken().equals(claimToken) + && records.remove(identity.storageKey(), existing); } // An attempt that lost the claim must not commit beside the attempt that holds it; checked diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java new file mode 100644 index 00000000..15fc7416 --- /dev/null +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java @@ -0,0 +1,155 @@ +package dev.caskeleton.grpc.ledger; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.postgresql.ds.PGSimpleDataSource; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * The ledger migrations after V001 lock a table already in use and give up within their bound + * instead of stopping it (re-review 2026-11-03 round 2, RR-02-09: the rule V21 follows). + * + *

        A transaction that has written the ledger stays open for fifteen seconds — a claim in flight, + * an operator's {@code BEGIN}. A write is the holder both migrations wait for: V003's ALTER TABLE + * would wait for a read too, V002's plain CREATE INDEX only for a write. The migration runs the way + * Flyway runs it, in one transaction. Unbounded it waits until the writer leaves, with every claim + * queued behind it, and then applies; bounded it fails with {@code lock_not_available} first and + * its rollback leaves the ledger as it was. + */ +@Testcontainers(disabledWithoutDocker = true) +class GrpcOperationLedgerMigrationLockWaitIT { + + private static final String LOCK_NOT_AVAILABLE = "55P03"; + private static final Duration WRITER_STAYS = Duration.ofSeconds(15); + private static final Duration GIVES_UP_WITHIN = Duration.ofSeconds(10); + + @SuppressWarnings("resource") + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer(System.getProperty("ca.test.image.postgres-16")) + .withDatabaseName("grpc") + .withUsername("grpc") + .withPassword("grpc"); + + @ParameterizedTest + @ValueSource( + strings = { + "V002__index_grpc_operation_ledger_finished_rows.sql", + "V003__add_grpc_operation_ledger_claim_attempt.sql" + }) + @DisplayName("ledger에 쓴 트랜잭션이 열려 있으면 ledger를 잠그는 마이그레이션은 상한 안에 실패하고 아무것도 바꾸지 않는다") + void aLedgerMigrationGivesUpOnAnOpenWriterAndChangesNothing(String migration) throws Exception { + PGSimpleDataSource dataSource = dataSource(); + try (Connection setup = dataSource.getConnection(); + Statement statement = setup.createStatement()) { + // given + statement.execute("DROP TABLE IF EXISTS grpc_operation_ledger"); + statement.execute(GrpcOperationLedgerMigrations.before(migration)); + String schemaBefore = schema(statement); + + // when + Attempt attempt = + whileAWriterHolds(dataSource, GrpcOperationLedgerMigrations.named(migration)); + + // then + assertThat( + List.of( + String.valueOf(attempt.sqlState()), + attempt.took().compareTo(GIVES_UP_WITHIN) < 0, + schema(statement))) + .containsExactly(LOCK_NOT_AVAILABLE, true, schemaBefore); + } + } + + /** Runs the migration in one transaction while another one holds a write to the ledger. */ + private static Attempt whileAWriterHolds(PGSimpleDataSource dataSource, String migration) + throws SQLException { + try (Connection writer = dataSource.getConnection(); + Connection migrator = dataSource.getConnection()) { + writer.setAutoCommit(false); + try (Statement write = writer.createStatement()) { + write.execute("LOCK TABLE grpc_operation_ledger IN ROW EXCLUSIVE MODE"); + } + ScheduledExecutorService release = Executors.newSingleThreadScheduledExecutor(); + ScheduledFuture released = + release.schedule( + () -> { + writer.rollback(); + return null; + }, + WRITER_STAYS.toSeconds(), + TimeUnit.SECONDS); + try { + migrator.setAutoCommit(false); + long started = System.nanoTime(); + Throwable thrown = + catchThrowable( + () -> { + try (Statement statement = migrator.createStatement()) { + statement.execute(migration); + } + migrator.commit(); + }); + Duration took = Duration.ofNanos(System.nanoTime() - started); + migrator.rollback(); + return new Attempt(thrown, took); + } finally { + released.cancel(true); + release.shutdownNow(); + } + } + } + + /** The ledger's columns, indexes and constraints, enough to see whether a migration landed. */ + private static String schema(Statement statement) throws SQLException { + try (ResultSet row = + statement.executeQuery( + "SELECT (SELECT string_agg(column_name, ',' ORDER BY column_name)" + + " FROM information_schema.columns" + + " WHERE table_name = 'grpc_operation_ledger')" + + " || '|' || (SELECT string_agg(indexname, ',' ORDER BY indexname)" + + " FROM pg_indexes WHERE tablename = 'grpc_operation_ledger')" + + " || '|' || (SELECT string_agg(conname, ',' ORDER BY conname) FROM pg_constraint" + + " WHERE conrelid = 'grpc_operation_ledger'::regclass)")) { + row.next(); + return row.getString(1); + } + } + + private static PGSimpleDataSource dataSource() { + PGSimpleDataSource dataSource = new PGSimpleDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUser(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + return dataSource; + } + + /** What the migration did while the writer held the ledger. */ + private record Attempt(Throwable thrown, Duration took) { + + String sqlState() { + for (Throwable cause = thrown; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) { + return sql.getSQLState(); + } + } + return null; + } + } +} diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java index d84695d5..749302b1 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrations.java @@ -23,16 +23,38 @@ final class GrpcOperationLedgerMigrations { /** Every migration's SQL, concatenated in version order. */ static String all() throws IOException { + return before(null); + } + + /** The SQL of every migration before the one named, concatenated in version order. */ + static String before(String fileName) throws IOException { StringBuilder sql = new StringBuilder(); for (String path : IN_ORDER) { - try (InputStream stream = - GrpcOperationLedgerMigrations.class.getClassLoader().getResourceAsStream(path)) { - if (stream == null) { - throw new IOException("gRPC operation-ledger migration is missing: " + path); - } - sql.append(new String(stream.readAllBytes(), StandardCharsets.UTF_8)).append('\n'); + if (path.endsWith("/" + fileName)) { + break; } + sql.append(read(path)).append('\n'); } return sql.toString(); } + + /** One migration's SQL, by its file name. */ + static String named(String fileName) throws IOException { + for (String path : IN_ORDER) { + if (path.endsWith("/" + fileName)) { + return read(path); + } + } + throw new IOException("no gRPC operation-ledger migration is named " + fileName); + } + + private static String read(String path) throws IOException { + try (InputStream stream = + GrpcOperationLedgerMigrations.class.getClassLoader().getResourceAsStream(path)) { + if (stream == null) { + throw new IOException("gRPC operation-ledger migration is missing: " + path); + } + return new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + } } diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java index ec357db4..b4b645d2 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java @@ -233,8 +233,9 @@ class JpaGrpcOperationLedgerContractIT extends GrpcOperationLedgerContract { } @Override - public void release(GrpcOperationIdentity identity) { - transactions.executeWithoutResult(status -> delegate.release(identity)); + public boolean release(GrpcOperationIdentity identity, GrpcClaimToken claimToken) { + return Boolean.TRUE.equals( + transactions.execute(status -> delegate.release(identity, claimToken))); } } } diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java index 9a043670..c24507f0 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java @@ -228,8 +228,25 @@ public interface GrpcOperationLedgerRepository /** Reads a claim by its derived storage key. */ Optional findById(String storageKey); - /** Removes a claim. Only for one whose owner is known to be gone. */ - void deleteById(String storageKey); + /** + * Deletes the claim if attempt {@code claimAttempt} still holds it and it has not finished; the + * same fencing as {@link #tryMarkFailed}. Only for a claim whose owner is known to be gone + * (review 2026-11-03 RR-01-15). + * + * @return one when the claim was deleted, zero otherwise + */ + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Transactional + @Query( + value = + """ + DELETE FROM grpc_operation_ledger + WHERE storage_key = :storageKey + AND state = 'IN_PROGRESS' + AND claim_attempt = :claimAttempt + """, + nativeQuery = true) + int tryRelease(@Param("storageKey") String storageKey, @Param("claimAttempt") long claimAttempt); /** Whether a claim exists. */ boolean existsById(String storageKey); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java index 9db0c3d8..5901103a 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java @@ -201,9 +201,10 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { } @Override - public void release(GrpcOperationIdentity identity) { + public boolean release(GrpcOperationIdentity identity, GrpcClaimToken claimToken) { requireIdentity(identity); - repository.deleteById(identity.storageKey()); + requireToken(claimToken); + return repository.tryRelease(identity.storageKey(), claimToken.attempt()) == 1; } private static void requireToken(GrpcClaimToken claimToken) { diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql b/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql index a0c6d7d5..3c6adef4 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql @@ -11,6 +11,19 @@ -- A plain CREATE INDEX, not CONCURRENTLY: Flyway runs each migration in a transaction, and the -- platform is not adopted anywhere yet, so the table is empty when this runs. An adopter that -- applies it to a large existing ledger should run the CONCURRENTLY form by hand first. +-- +-- This file was edited after it was first written, before any deployment applied it (the branch +-- that added it was not merged, and the ledger is adopted nowhere yet), to add the bound below. A +-- development database that applied the earlier text fails Flyway validation: recreate it. + +-- Bound the wait for the lock this migration takes (SHARE on grpc_operation_ledger, held until it +-- commits; it stops writes, not reads). Unbounded, it queues behind any open transaction that has +-- written to the table, and every write of the table after it queues behind the migration — every +-- claim writes it. Five seconds, then the migration fails, rolls back whole and the database stays +-- at V001: deploy again once that transaction has ended (re-review 2026-11-03 round 2, RR-02-09; +-- the rule is docs/jpa/migration-guide.md "Bound the lock wait"). +SET LOCAL lock_timeout = '5s'; + CREATE INDEX ix_grpc_operation_ledger_finished_completed_at ON grpc_operation_ledger (completed_at) WHERE state IN ('COMMITTED', 'FAILED_TERMINAL'); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V003__add_grpc_operation_ledger_claim_attempt.sql b/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V003__add_grpc_operation_ledger_claim_attempt.sql index 23b03687..89007ad5 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V003__add_grpc_operation_ledger_claim_attempt.sql +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/resources/db/migration/grpc/V003__add_grpc_operation_ledger_claim_attempt.sql @@ -13,6 +13,19 @@ -- -- Existing rows are their first attempt: no row has been handed over under a token yet. The table is -- small and the platform is not adopted anywhere, so a plain ALTER with a default is enough. +-- +-- This file was edited after it was first written, before any deployment applied it (the branch +-- that added it was not merged, and the ledger is adopted nowhere yet), to add the bound below. A +-- development database that applied the earlier text fails Flyway validation: recreate it. + +-- Bound the wait for the lock this migration takes (ACCESS EXCLUSIVE on grpc_operation_ledger, held +-- until it commits). Unbounded, it queues behind any open transaction that has touched the table, +-- and every read and write of the table after it queues behind the migration — every claim reads +-- and writes it. Five seconds, then the migration fails, rolls back whole and the database stays at +-- V002: deploy again once that transaction has ended (re-review 2026-11-03 round 2, RR-02-09; the +-- rule is docs/jpa/migration-guide.md "Bound the lock wait"). +SET LOCAL lock_timeout = '5s'; + ALTER TABLE grpc_operation_ledger ADD COLUMN claim_attempt BIGINT NOT NULL DEFAULT 1; diff --git a/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java b/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java index f2f90758..37c04781 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java @@ -16,6 +16,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; +import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -120,8 +121,13 @@ class GrpcOperationLedgerRepositoryTest { } @Override - public void deleteById(String storageKey) { - rows.remove(storageKey); + public int tryRelease(String storageKey, long claimAttempt) { + GrpcOperationLedgerEntity row = rows.get(storageKey); + boolean held = + row != null + && row.getState() == GrpcOperationLedgerState.IN_PROGRESS + && row.getClaimToken().equals(new GrpcClaimToken(claimAttempt)); + return held && rows.remove(storageKey, row) ? 1 : 0; } @Override @@ -320,18 +326,24 @@ class GrpcOperationLedgerRepositoryTest { assertThat(stored.sameRequestAs(OTHER_FINGERPRINT)).isFalse(); } + /** + * A failed record is finished: a retry re-claims it with a new token ({@code reclaimFailed}), so + * release, which deletes and resets the token, leaves it (review 2026-11-03 RR-01-15). + */ @Test - @DisplayName("a failed claim is terminal, and releasing removes it") - void failureIsTerminalAndReleaseRemoves() { + @DisplayName("실패한 claim 은 끝난 기록이라 release 로 지워지지 않는다") + void aFailedClaimIsTerminalAndReleaseLeavesIt() { + // given GrpcOperationIdentity id = identity("tenant-1.actor-1"); ledger.claim(id, FINGERPRINT, NOW); - ledger.markFailed(id, GrpcClaimToken.FIRST, NOW.plusSeconds(1)); - assertThat(ledger.find(id).orElseThrow().state()) - .isEqualTo(GrpcOperationLedgerState.FAILED_TERMINAL); - ledger.release(id); - assertThat(ledger.find(id)).isEmpty(); + // when + boolean released = ledger.release(id, GrpcClaimToken.FIRST); + + // then + assertThat(List.of(released, ledger.find(id).orElseThrow().state())) + .containsExactly(false, GrpcOperationLedgerState.FAILED_TERMINAL); } @Test diff --git a/src/messaging/messaging-spring-boot-starter-kafka/src/test/java/dev/caskeleton/messaging/autoconfigure/KafkaDeadLetterQuarantineTest.java b/src/messaging/messaging-spring-boot-starter-kafka/src/test/java/dev/caskeleton/messaging/autoconfigure/KafkaDeadLetterQuarantineTest.java new file mode 100644 index 00000000..35c6d145 --- /dev/null +++ b/src/messaging/messaging-spring-boot-starter-kafka/src/test/java/dev/caskeleton/messaging/autoconfigure/KafkaDeadLetterQuarantineTest.java @@ -0,0 +1,82 @@ +package dev.caskeleton.messaging.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.messaging.api.error.FailureCategory; +import dev.caskeleton.messaging.api.header.ReservedHeaders; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.stream.StreamSupport; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.producer.MockProducer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.header.Header; +import org.apache.kafka.common.serialization.ByteArraySerializer; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +/** + * The dead-letter copy says which of the two quarantine paths wrote it (review 2026-11-01 06-14, + * re-review round 2 RR-02-16): a record that could not be rebuilt at all and one whose handler + * spent its attempt budget leave different failure-category bytes, so a redrive can tell a message + * that will never decode from one an outage kept failing. + */ +class KafkaDeadLetterQuarantineTest { + + private static final String DEAD_LETTER_TOPIC = "orders.dlq"; + + @ParameterizedTest + @EnumSource( + value = FailureCategory.class, + names = {"DESERIALIZATION", "POISON_MESSAGE"}) + @DisplayName("격리 사본은 원래 header를 지키고 failure-category를 호출자가 준 분류 하나로 쓴다") + void theCopyCarriesTheCategoryTheCallerGaveInPlaceOfAnyEarlierOne(FailureCategory category) { + // given + MockProducer producer = + new MockProducer<>(true, null, new ByteArraySerializer(), new ByteArraySerializer()); + KafkaDeadLetterQuarantine quarantine = + new KafkaDeadLetterQuarantine(producer, DEAD_LETTER_TOPIC, Duration.ofSeconds(1)); + ConsumerRecord record = + new ConsumerRecord<>("orders", 0, 7L, bytes("order-7"), bytes("{\"broken\"")); + record.headers().add("trace-id", bytes("trace-1")); + record.headers().add(ReservedHeaders.FAILURE_CATEGORY, bytes("STALE_FROM_AN_EARLIER_HOP")); + + // when + boolean confirmed = quarantine.quarantine(record, category, new IllegalStateException("x")); + + // then + ProducerRecord copy = producer.history().getFirst(); + assertThat( + List.of( + confirmed, + copy.topic(), + text(copy.value()), + values(copy, "trace-id"), + values(copy, ReservedHeaders.FAILURE_CATEGORY), + values(copy, ReservedHeaders.FAILURE_CODE))) + .containsExactly( + true, + DEAD_LETTER_TOPIC, + "{\"broken\"", + List.of("trace-1"), + List.of(category.name()), + List.of("IllegalStateException")); + } + + private static List values(ProducerRecord record, String header) { + return StreamSupport.stream(record.headers().headers(header).spliterator(), false) + .map(Header::value) + .map(KafkaDeadLetterQuarantineTest::text) + .toList(); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String text(byte[] value) { + return new String(value, StandardCharsets.UTF_8); + } +} diff --git a/src/optional-platforms/build.gradle b/src/optional-platforms/build.gradle index 1c5ff1b0..ecdce3e0 100644 --- a/src/optional-platforms/build.gradle +++ b/src/optional-platforms/build.gradle @@ -75,9 +75,9 @@ tasks.register('releaseCheck') { } // The stages this build's strict lanes may belong to, executed by workflows as -// `./gradlew -p optional-platforms ` from `src`. +// `./gradlew -p optional-platforms ` from `src`. A command counts when it starts in this +// directory (working-directory joined with -p), which the plugin reads from where this build is. strictLaneStages { stage ':ci', ':integrationCheck', ':performanceCheck', ':releaseCheck' workflowDirectory = layout.projectDirectory.dir('../../.github/workflows') - workflowProjectDirectory = 'optional-platforms' } diff --git a/src/sample-portfolio/README.md b/src/sample-portfolio/README.md index eb63c231..c67df5e1 100644 --- a/src/sample-portfolio/README.md +++ b/src/sample-portfolio/README.md @@ -54,7 +54,9 @@ 누구나 관리자로 들어올 수 있기 때문입니다. 거부 목록(`prod`)이 아니라 허용 목록인 이유는 프로필 이름이 하나만 달라도 계정이 열리지 않게 하려는 것입니다. `./gradlew :sample-portfolio:bootRun`은 `SPRING_PROFILES_ACTIVE`가 비어 있으면 `local`을 넘기고, jar·이미지로 띄울 때는 -`SPRING_PROFILES_ACTIVE=local`(또는 `test`·`demo`)을 직접 줍니다. 운영으로 +`SPRING_PROFILES_ACTIVE=demo`를 직접 줍니다(`src/Dockerfile.sample` 머리말의 `docker run` 예시). 세 프로필 +모두 같은 데모 기본값(object storage 끔 등)을 `application.yml`에서 받고, 각 프로필로 실제로 뜨는지는 +`SampleDemoProfilesStartupSystemTest`가 확인합니다. 운영으로 가져가려면 `SampleDemoSecurityConfig`·`SampleDemoAccounts`를 지우고 `SamplePortfolioApplication`에서 `WebSecurityAutoConfiguration` 제외를 풉니다. 이 규칙은 데모 설정 옆에 선언되어 있어 함께 지워집니다. diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java index 943e2542..df0f73bf 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoAccountsProductionGuard.java @@ -23,6 +23,11 @@ import org.springframework.core.env.Environment; * other name a deployment happened to use: one differently spelled profile opened an admin account. * Here a deployment is refused unless every active profile is a demo profile, so no profile at all * — the sample's image sets none — is refused too. + * + *

        Each profile listed here is one the sample starts under as shipped: {@code application.yml} + * gives the same three the lean demo defaults, and {@code SampleDemoProfilesStartupSystemTest} + * starts the application under each (review 2026-11-04 RR2-04-02). {@code demo} is the one for the + * image, {@code local} for {@code bootRun}, {@code test} for the sample's own tests. */ final class SampleDemoAccountsProductionGuard implements StartupRule { @@ -41,7 +46,8 @@ final class SampleDemoAccountsProductionGuard implements StartupRule { @Override public String remedy() { - return "run the sample with SPRING_PROFILES_ACTIVE=local (or test or demo); a real service" + return "run the sample with SPRING_PROFILES_ACTIVE=demo (local for bootRun, test for its" + + " tests); a real service" + " authenticates through the JWT chain — delete SampleDemoSecurityConfig and" + " SampleDemoAccounts and stop excluding WebSecurityAutoConfiguration in" + " SamplePortfolioApplication"; diff --git a/src/sample-portfolio/src/main/resources/application.yml b/src/sample-portfolio/src/main/resources/application.yml index 4ce4bf16..d77e0a28 100644 --- a/src/sample-portfolio/src/main/resources/application.yml +++ b/src/sample-portfolio/src/main/resources/application.yml @@ -213,14 +213,20 @@ app: enabled: false --- +# Every demo profile, the same list SampleDemoAccountsProductionGuard.DEMO_PROFILES allows: a +# profile the guard lets the sample start under must also start it. This document used to name +# `local` alone, so `test` and `demo` were allowed and stopped on an object-storage binding with no +# destination (review 2026-11-04 RR2-04-02). SampleDemoProfilesStartupSystemTest starts the sample +# under each listed profile with nothing but this file and a database address. spring: config: activate: - on-profile: local + on-profile: local | test | demo -# The poster image endpoint is off locally: its only mode is canonical publication +# The poster image endpoint is off in the demo: its only mode is canonical publication # (`app.poster-image.api.mode=publication`), which needs an `app.object-storage` destination and the -# idempotency key ring. The whole-byte legacy upload and its storage seam are gone. +# idempotency key ring. The object-storage module is on whenever it is on the classpath, so it is +# switched off here rather than left to fail on a binding nobody gave it. app: object-storage: enabled: false diff --git a/src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql b/src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql index 7ff4d46b..40d48883 100644 --- a/src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql +++ b/src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql @@ -14,6 +14,18 @@ -- one Flyway location list, and the production stream already owns the integer versions from 9 -- up; a fractional version cannot collide with them. The sample's own history table -- (flyway_sample_schema_history) orders it right after V8. +-- +-- This file was edited after it was first written, before any deployment applied it (the branch +-- that added it was not merged), to add the bound below. A development database that applied the +-- earlier text fails Flyway validation: recreate it. + +-- Bound the wait for the lock this migration takes (SHARE on poster for the unique index, held +-- until it commits; it stops writes, not reads). Unbounded, it queues behind any open transaction +-- that has written to the table, and every write of the table after it queues behind the migration +-- — every poster create and update. Five seconds, then the migration fails, rolls back whole and +-- the database stays at V8: deploy again once that transaction has ended (re-review 2026-11-03 +-- round 2, RR-02-09; the rule is docs/jpa/migration-guide.md "Bound the lock wait"). +SET LOCAL lock_timeout = '5s'; DO $$ DECLARE diff --git a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoProfilesStartupSystemTest.java b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoProfilesStartupSystemTest.java new file mode 100644 index 00000000..9d415c70 --- /dev/null +++ b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoProfilesStartupSystemTest.java @@ -0,0 +1,65 @@ +package dev.caskeleton.sample.portfolio.bootstrap.security; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.sample.portfolio.SamplePortfolioApplication; +import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Every profile the demo guard allows starts the sample as its jar and image do: {@link + * SamplePortfolioApplication} with the shipped configuration and nothing but a database address + * (review 2026-11-04 RR2-04-02). + * + *

        The allow list is a promise — "run the sample under one of these" — and the guard's remedy and + * the sample README repeat it. Every other sample test either runs under {@code local} or under a + * {@code test} profile whose test resources used to switch off what the shipped configuration left + * on, so {@code test} and {@code demo} were allowed and did not start. This test is what keeps the + * list and the shipped configuration together: a profile added to {@link + * SampleDemoAccountsProductionGuard#DEMO_PROFILES} must start here. Under {@code test} this source + * set's {@code application-test.yml} loads as well; it no longer touches object storage, so what + * starts the capability set is the shipped file in every case. + */ +@Testcontainers(disabledWithoutDocker = true) +class SampleDemoProfilesStartupSystemTest { + + @Container static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); + + static Stream demoProfiles() { + return SampleDemoAccountsProductionGuard.DEMO_PROFILES.stream().sorted(); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("demoProfiles") + @DisplayName("허용 목록의 각 데모 프로필로 샘플이 출하 설정 그대로 기동한다") + void theSampleStartsUnderEveryDemoProfile(String profile) { + // given + SpringApplicationBuilder sample = + new SpringApplicationBuilder(SamplePortfolioApplication.class).profiles(profile); + + // when + // Command-line arguments, so the address wins over this source set's application-test.yml + // under `test` as well; the ports are free ones so the three starts do not collide with each + // other or with a running sample. + try (ConfigurableApplicationContext context = + sample.run( + "--spring.datasource.url=" + POSTGRES.getJdbcUrl(), + "--spring.datasource.username=" + POSTGRES.getUsername(), + "--spring.datasource.password=" + POSTGRES.getPassword(), + "--server.port=0", + "--management.server.port=0")) { + + // then + assertThat(context.isRunning()).isTrue(); + assertThat(context.getEnvironment().getActiveProfiles()).containsExactly(profile); + } + } +} diff --git a/src/sample-portfolio/src/systemTest/resources/application-test.yml b/src/sample-portfolio/src/systemTest/resources/application-test.yml index faaef3e2..23017f05 100644 --- a/src/sample-portfolio/src/systemTest/resources/application-test.yml +++ b/src/sample-portfolio/src/systemTest/resources/application-test.yml @@ -173,8 +173,8 @@ app: enabled: false publication: enabled: false - object-storage: - enabled: false + # No app.object-storage switch here: the shipped application.yml turns it off for every demo + # profile, and a copy here hid that `test` did not start without it (RR2-04-02). cache: redis: enabled: false diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationLockWaitTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationLockWaitTest.java new file mode 100644 index 00000000..36eb0a89 --- /dev/null +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationLockWaitTest.java @@ -0,0 +1,63 @@ +package dev.caskeleton.sample.portfolio.bootstrap.persistence; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.testkit.migration.LockWaitMigrationInspector; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The sample's own stream follows the rule the template's streams follow: a migration that locks a + * table already in use bounds the wait first ({@code LockWaitMigrationInspector}, re-review + * 2026-11-03 round 2, RR-02-09). A service stream copies this test with its own directory. + */ +class SampleMigrationLockWaitTest { + + private static final Path STREAM = Path.of("src/main/resources/db/sample-migration"); + + /** Released before the rule and applied, so never edited again; nothing is added here. */ + private static final Set RELEASED_BEFORE_THE_RULE = + Set.of("V8__poster_image_publication.sql"); + + private final LockWaitMigrationInspector inspector = new LockWaitMigrationInspector(); + + @Test + @DisplayName("샘플 스트림의 규칙 이후 마이그레이션은 기존 테이블 잠금 앞에 SET LOCAL lock_timeout을 둔다") + void everySampleMigrationAfterTheRuleBoundsItsLockWait() throws IOException { + // given + Map migrations = versionedMigrations(); + + // when + Map> unbounded = new TreeMap<>(); + for (Map.Entry migration : migrations.entrySet()) { + List statements = + inspector.unboundedLockingStatements(Files.readString(migration.getValue())); + if (!statements.isEmpty()) { + unbounded.put(migration.getKey(), statements); + } + } + + // then + assertThat(unbounded.keySet()) + .as("these wait for a table lock without a bound: %s", unbounded) + .isEqualTo(RELEASED_BEFORE_THE_RULE); + } + + private static Map versionedMigrations() throws IOException { + Map migrations = new TreeMap<>(); + try (Stream files = Files.list(STREAM)) { + files + .filter(path -> path.getFileName().toString().matches("V[0-9_]+__.+\\.sql")) + .forEach(path -> migrations.put(path.getFileName().toString(), path)); + } + return migrations; + } +} diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfigTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfigTest.java index e5b8f976..62e15481 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfigTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SampleDemoSecurityConfigTest.java @@ -54,10 +54,7 @@ import org.springframework.test.web.servlet.ResultActions; properties = { "app.persistence-jpa.enabled=false", // The PostgreSQL idempotency store needs the relational module this test leaves off. - "app.capabilities.idempotency.provider=disabled", - // Object storage is on while present and has no destination here; the `local` profile used to - // switch it off by default, and this test runs under `test` (RR-07-02). - "app.object-storage.enabled=false" + "app.capabilities.idempotency.provider=disabled" }) @AutoConfigureMockMvc // The demo accounts start only under a demo profile (SampleDemoAccountsProductionGuard). diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java index db6e1d52..9325e740 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java @@ -47,7 +47,7 @@ public enum OperationalError implements ApiErrorCode { IDEMPOTENT_IN_FLIGHT(Category.CONFLICT, 409, true), IDEMPOTENT_REQUEST_MISMATCH(Category.VALIDATION, 422, false), IDEMPOTENCY_UNAVAILABLE(Category.TRANSIENT_DEPENDENCY, 503, true), - // the action ran and recording its result failed; a resend with the same key is safe + // the action ran and recording its result failed; a resend with the same key never runs it again IDEMPOTENCY_COMPLETION_UNKNOWN(Category.TRANSIENT_DEPENDENCY, 503, true), IDEMPOTENCY_RECOVERY_REQUIRED(Category.DATA_INTEGRITY, 500, false), // adapter runtime lifecycle From 339cf8fdbf2f1d90b718ac403a3a8318dff58d8d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 02:06:33 +0900 Subject: [PATCH 08/17] =?UTF-8?q?docs(review):=203=EC=B0=A8=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=EC=9D=98=20=ED=99=95=EC=9D=B8=20=EB=A6=AC=EB=B7=B0=20?= =?UTF-8?q?=EA=B2=B0=EA=B3=BC=EB=A5=BC=20=EA=B8=B0=EB=A1=9D=ED=95=9C?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 3차 수정 커밋(1885bf8d)이 또 새 결함을 만들었는지 알아야 리뷰 반복을 멈출 수 있다. 방법: 리뷰어 4명이 그 커밋만 영역별로 봤다. 새 Important 0, 회귀 0, Minor 19건. 재리뷰 README 9.1절의 멈춤 기준을 채웠다. Minor는 마지막 정리 라운드로 고치고, 그 뒤에는 Important만 고친다(11.1절). 위험·한계: Minor 중 JDK read-idle timeout 지연(공용 풀 포화 시)과 붙여 쓴 -x 거짓 통과는 동작에 닿는다. 아직 고치지 않았다. 검증: 리뷰 문서만 바뀐다. 리뷰어가 실행한 탐침은 각 문서 범위 절. Refs: docs/reviews/2026-11-03-rereview/README.md 11절 --- docs/reviews/2026-11-03-rereview/README.md | 24 ++ .../round3/01-core-app-inbound.md | 245 +++++++++++++++++ .../round3/02-persistence-messaging.md | 240 +++++++++++++++++ .../2026-11-03-rereview/round3/03-outbound.md | 227 ++++++++++++++++ .../round3/04-bootstrap-build-sample.md | 248 ++++++++++++++++++ 5 files changed, 984 insertions(+) create mode 100644 docs/reviews/2026-11-03-rereview/round3/01-core-app-inbound.md create mode 100644 docs/reviews/2026-11-03-rereview/round3/02-persistence-messaging.md create mode 100644 docs/reviews/2026-11-03-rereview/round3/03-outbound.md create mode 100644 docs/reviews/2026-11-03-rereview/round3/04-bootstrap-build-sample.md diff --git a/docs/reviews/2026-11-03-rereview/README.md b/docs/reviews/2026-11-03-rereview/README.md index bf9aba83..55545e28 100644 --- a/docs/reviews/2026-11-03-rereview/README.md +++ b/docs/reviews/2026-11-03-rereview/README.md @@ -184,3 +184,27 @@ Important 7건: - 실제 CI runner 실행: Gitea repo의 Actions가 꺼져 있어(`has_actions: false`) workflow가 돈 적이 없다. 켜는 것은 소유자 일이다. - 소유자 확인이 필요한 기본값: 10절 "결정" 칸 — 특히 lease 뒤 늦게 끝난 첫 시도의 결과를 버리는 것, workflow 명령에 `working-directory`가 필요해진 것. - 다음: 이 수정 커밋만 보는 확인 리뷰. 새 Important가 0이면 멈춘다(9.1절). + +## 11. 3차 확인 리뷰 (수정 커밋 `1885bf8d`만, 2026-11-04) + +3차 수정 커밋만 리뷰어 4명이 같은 템플릿·스킬 방식으로 봤다(`round3/01~04-*.md`). 심각도 기준(Important = 현실적 조건에서 틀린 동작·보안·데이터·공개 계약, 또는 운영자에게 틀린 조치를 시키는 문서)을 지침에 적었다. + +| 문서 | Important | Minor | 2차 발견 재확인 | 회귀 | +|---|---|---|---|---| +| [round3/01 core·inbound](round3/01-core-app-inbound.md) | 0 | 4 | RR-01-11~17 닫힘 | 0 | +| [round3/02 persistence·messaging](round3/02-persistence-messaging.md) | 0 | 5 | RR-02-09~16 닫힘(RR-02-10은 결정으로) | 0 | +| [round3/03 outbound](round3/03-outbound.md) | 0 | 5 | RR-01-11, RR-03-11~18 닫힘 | 0 | +| [round3/04 bootstrap·build·sample](round3/04-bootstrap-build-sample.md) | 0 | 5 | RR2-04-01~06 닫힘 | 0 | + +**9.1절 멈춤 기준을 채웠다**: 새 Important 0, 회귀 0. 리뷰어가 실행으로 확인한 것: `@SystemCaller` 위반 fixture가 실제로 실패, Redis Lua(abandon·늦은 complete 거부·기록 TTL), Flyway 안의 `SET LOCAL lock_timeout`(V22에서 그 줄을 지우면 lane 실패), 고친 마이그레이션 9개가 main `01a8a2a70`과 파생 서비스에 없음, 쿼터 SQL(실 PG), workflow 해석(축약 `-x`). + +Minor 19건 중 동작에 닿는 것: +- RR3-03-01 — JDK read-idle watchdog이 공용 `ForkJoinPool`에서 돌아, 공용 풀이 막히면 timeout이 늦다(300ms 설정이 2,699ms). 기본 transport(Apache)는 영향 없음. +- RR3-04-02 — 붙여 쓴 `-x`를 `verifyStrictLaneStages`가 읽지 않아 거짓 통과(이전부터). +- RR3-01-01 — `@SystemCaller` 규칙이 직접 의존만 본다. 같은 leaf 안에서 컨트롤러가 그 bean을 주입받으면 통과. +- RR3-04-01·03 — 인터페이스 타입 `static @Bean` 뒤의 `@Value` 비밀 목록, 코드가 든 Redis 계정 참조가 사전·`fixture-` 검사를 지난다(둘 다 이름을 대는 기동 실패이거나 비밀 아닌 경로). +- RR3-02-01·03·04 — 잠금 대기 검사기가 FK·trigger·`REINDEX`·`lock_timeout = 0`·소수 버전·gRPC ledger tree를 못 본다. + +### 11.1 결정 + +리뷰 반복은 여기서 멈춘다. Minor 19건은 사용자 지시("남은 부분 전부 진행")에 따라 마지막 정리 라운드(r6)로 고친다. r6의 멈춤 기준: 전체 게이트 통과 + r6 diff 확인 리뷰 1회에서 Important가 나오면 그것만 고치고, Minor는 남은 것으로 기록하고 더 돌지 않는다. diff --git a/docs/reviews/2026-11-03-rereview/round3/01-core-app-inbound.md b/docs/reviews/2026-11-03-rereview/round3/01-core-app-inbound.md new file mode 100644 index 00000000..bf2e6a0a --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round3/01-core-app-inbound.md @@ -0,0 +1,245 @@ +# 01 core·app·inbound·fileserver 3차 확인 리뷰 (2026-11-04) + +경로는 저장소 루트 기준이다. 코드 경로는 `src/`가 앞에 붙는다. + +## 범위 — 본 pathspec, 불러온 스킬과 적용한 기준, 실행한 명령과 결과, 못 본 것 + +### 본 pathspec + +- 리뷰 범위: Base `ecc74b7d` → Head `1885bf8d`(커밋 1개) 중 아래 pathspec. 57파일, +1,700 −199. + ```text + src/application-core src/application-fileserver src/adapter/inbound src/grpc src/composition/service-runtime + src/app-bootstrap/src/architectureTest docs/manual/07-authorization.md docs/manual/09-outbox-events.md + docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md docs/web/http-contract.md + docs/fileserver/operations.md docs/messaging/outbox-inbox.md + ``` +- 맡은 2차 재리뷰 발견: RR-01-12~17. RR-01-11은 03 리뷰어가 주로 보고, 이 문서는 `http-contract.md` 문구와 코드가 + 맞는지만 본다. +- 나눠 맡은 것: gRPC ledger 마이그레이션의 `lock_timeout`(V002·V003, `GrpcOperationLedgerMigrationLockWaitIT`)은 02 리뷰어 몫이다. + `application-core` 멱등성 변경은 계약(포트 Javadoc·공유 계약 케이스·executor 분기)만 봤다. +- 이 문서의 새 발견 ID는 `RR3-01-`로 시작한다. +- 읽은 방식: 하위 에이전트 없이 diff를 묶음별로 직접 읽었다. + 1. `@SystemCaller`·`@SystemInvoked`, ArchUnit 두 규칙과 fixture 6개, `PermissionEnforcementGuard`와 테스트, + `SystemInvokedConsumePathTest`, `InboxRedeliveryIntegrationTest` diff, 매뉴얼 07·09, messaging README·CLAUDE.md. + 2. `EnvelopeErrorController`·`HttpStatusErrorCodes`·새 `EnvelopeErrorControllerTest`, `http-contract.md` 두 절. + 3. `GraphQlClientPolicy` 삭제분과 옮긴 테스트. + 4. gRPC ledger `release` — 포트, JPA adapter, repository 쿼리, fake, 공유 계약 3케이스, ADR, `GrpcClaimToken` Javadoc. + 5. `DirectTransactionPort` 전체와 `TransactionPortContract` 새 케이스, `OverlappingWrites`. + 6. 멱등성 포트 Javadoc, `IdempotencyStoreContract` 시간 케이스 5개, `IdempotencyExecutor` claim·complete 분기. + 7. `FileQuotaLedgerContract` 롤백 케이스, `FakeFileQuotaService.inTransaction`, `operations.md` 「Namespace quota drift」. +- 범위 밖에서 확인용으로 읽은 것: + - 쿼터 장부 규칙: `DefaultCleanupService`(reclaim 조건·`isReclaimable`), `FinalizeUploadApplicationUseCase.commitReady`, + `CopyFileApplicationUseCase.publish`, `DefaultFileReconciliationService`, `MoveFileApplicationUseCase`, `FileState` 전이표. + - 쿼터 영속: `JpaFileQuota`, `JpaQuotaReclaim`, `FileserverQuotaRepository`, fileserver 마이그레이션 V1~V5. + - 멱등성: Redis `IdempotencyScripts.CLAIM`. + - 의존 경계: `modules.json`의 inbound leaf 간선, `adapter/inbound/messaging/gradle.lockfile`, `app-bootstrap/build.gradle`의 + architectureTest classpath. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +| --- | --- | --- | +| `superpowers:requesting-code-review` | 리뷰어 템플릿(Strengths → Critical/Important/Minor → Declined → Assessment), 실제 심각도로 분류, 읽지 않은 코드에 판정 금지, 하위 에이전트 금지 | 문서 양식 전체. 발견마다 round2 "고치는 법"과 9.1절·10절 결정을 코드로 대조 | +| `clean-architecture` | 의존은 안쪽으로, 경계는 다형성(포트)으로, composition root가 조립, framework는 바깥 원 | `@SystemCaller`가 application-core에 있는 방향, handler가 use case를 `new`로 만드는 조립 위치, 소비 경로가 web·messaging leaf 간선(`modules.json`)을 넘지 않는지 | +| `security-and-hardening` | 인가는 모든 요청에서, 신뢰 경계 지도, 숨은 우회 경로(STRIDE의 권한 상승) | 사용자 전송이 `@SystemInvoked` 쓰기에 닿는 경로를 직접 의존·중첩 클래스·한 단계 건너 호출로 나눠 탐침, 전송 타입 목록의 빈칸 | +| `api-and-interface-design` | 계약이 먼저, 일관된 오류 의미(status와 `error.code`), Hyrum's Law, 멱등 키의 세 결과와 in-flight 처리 | `/error` status 접기의 문서·코드 일치, 결과 불명 뒤 같은 키 재전송 판정이 Redis CLAIM과 executor에서 문서대로인지, ledger `release` 포트 시그니처 변경의 호환성 | + +### 실행한 명령과 결과 + +| 명령 | 결과 | +| --- | --- | +| `git diff --stat ecc74b7d..1885bf8d -- ` / `git diff …` | 57파일 +1,700 −199 | +| `git grep`으로 `effectivePageSize`, 옛 규칙 이름 `INBOUND_ADAPTERS_DO_NOT_REACH_SYSTEM_INVOKED_USE_CASES`, `.release(`·`deleteById`, `reservedBytes` 읽는 곳, `FileState.*` 전이 전수 | 복사본·옛 이름·다른 `release` 호출자 0건. `reservedBytes` 합산은 `status = 'RESERVED'` 쿼리 하나뿐 | +| `git worktree add --detach /rr3-01 1885bf8d` 후 architectureTest에 탐침 테스트 1개와 탐침 클래스 2개 추가, `flock … ./gradlew :app-bootstrap:architectureTest --tests 'dev.caskeleton.bootstrap.architecture.Rr3SystemCallerProbeTest' --console=plain -i` | `BUILD SUCCESSFUL in 14s`. 출력은 아래 표(RR3-01-01 증거) | +| `flock … docker run postgres:16-alpine` + `psql` — V1의 `fs_file`·`fs_quota_reservation`과 V5의 `fs_file` 변경을 만들고, 문서의 두 SQL 블록을 문서 그대로 `psql -v namespace=…`로 실행 | 보정 전 drift 2행(`ns-a +140`, `ns-b −140`) → 두 namespace 보정 → 0행. `RESERVED` 999 행은 그대로. 보정 뒤 newest-first reclaim 한 번 → drift 0행 유지. 넣은 행의 `reserved_bytes`가 180(RR3-01-03) | +| `git worktree remove --force /rr3-01`, 컨테이너 `docker rm -f` | 탐침과 함께 삭제. 이 체크아웃은 clean | + +탐침 출력(`RR3-PROBE` 줄 그대로): + +| 탐침 | 가져온 클래스 | `ONLY_SYSTEM_CALLERS_…` 위반 | `SYSTEM_CALLERS_ARE_…` 위반 | +| --- | --- | --- | --- | +| existing-fixture-web-marked | `SystemCallerControllerFixture` + use case | false | **true** | +| existing-fixture-rest-in-messaging | `SystemCallerRestControllerFixture` + use case | false | **true** | +| controller-calls-system-caller | `@RestController`가 `SystemCallerHandlerFixture`를 주입받아 `handle()` 호출 + handler + use case | false | false | +| nested-endpoint-in-system-caller | `..adapter.inbound.scheduler..`의 `@SystemCaller` 클래스 + 그 안의 `@RestController` nested 클래스(`@PostMapping`에서 use case 호출) + use case | false | false | + +### 못 본 것 + +- 전체 게이트는 다시 돌리지 않았다. 재리뷰 README 10.2절 결과를 읽기만 했다. +- `SystemInvokedConsumePathTest`, `InboxRedeliveryIntegrationTest`, gRPC ledger PG lane, `SpringTransactionContractTest`, + `PostgreSqlFileQuotaLedgerContractTest`, Redis·PG 멱등성 lane은 다시 돌리지 않았다. 10절의 r5-a·r5-b 검증 기록에 기댄다. +- JAX-RS·graphql-java `DataFetcher`로 만든 탐침은 돌리지 않았다. app-bootstrap architectureTest의 컴파일 classpath에 그 + 라이브러리가 없다. RR3-01-02는 규칙 코드를 읽은 것(E1)이다. +- 쿼터 SQL은 손으로 만든 시나리오 하나로 돌렸다. 실제 앱이 만든 데이터로 돌린 것은 아니다. + +## Strengths + +- 표시 검사가 실제로 실패한다. 기존 위반 fixture 두 개(`SystemCallerControllerFixture`, `SystemCallerRestControllerFixture`)를 + 탐침에서 따로 돌려 `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS` 위반을 확인했다. 표시 없는 handler(`:214`), + web 패키지 표시(`:232`), messaging 패키지의 HTTP endpoint(`:241`)를 각각 단언한다 + (`src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java`). +- 패키지 쪽은 허용 목록이다(`ApplicationBoundaryArchitectureTest.java:456-457`). 새 inbound 패키지는 규칙을 고치지 않아도 표시를 + 달 수 없다. +- 기동 가드는 예외를 늘리지 않았다(`PermissionEnforcementGuard.java:69`). 버린 대안("handler만 주입받으면 허용")과 이유가 README에 + 남았다(`src/adapter/inbound/messaging/README.md:104-116`). +- 소비 경로가 단위·실제 lane 둘 다로 고정됐다. 단위는 가드 아래 기동과 use case bean 거부다(`SystemInvokedConsumePathTest.java:83,128`). + 실제 lane은 Kafka+PG `ProjectionHandler`가 같은 모양이다. +- `/error`의 status 접기를 문서·Javadoc·테스트가 같은 말로 적는다. 버린 대안도 Javadoc에 있다(`EnvelopeErrorController.java` 클래스 Javadoc, + `docs/web/http-contract.md:63-68`, `EnvelopeErrorControllerTest` 8케이스). +- ledger `release`가 다른 전이와 같은 조건부 한 문장이다(`GrpcOperationLedgerRepository.java:243-249`). fake와 PG가 공유 계약 + 3케이스를 같이 받는다(`GrpcOperationLedgerContract.java:438,452,470`). "삭제 뒤 attempt 1부터"라는 한계를 Javadoc과 ADR에 적었다. +- `DirectTransactionPort`가 스레드별 트랜잭션이다(`DirectTransactionPort.java:56`). 같은 모양의 계약 케이스를 fake와 Spring 어댑터가 + 둘 다 받는다(`TransactionPortContract.java:311`). 이제 `OverlappingWrites`가 fake에서도 두 트랜잭션을 연다. +- 쿼터 롤백 계약은 reserve·commit·reclaim을 한 호출자 트랜잭션에서 실패시키고 양쪽 scope를 본다(`FileQuotaLedgerContract.java:320`). + `inTransaction`을 abstract로 바꿔 구현마다 실제 롤백을 고르게 했다. +- 결과 불명 계약 문구가 코드와 맞는다. CLAIM은 lease가 지난 `EXECUTING`을 `ABANDONED`로 바꾸고 `RECOVERY_REQUIRED`를 준다 + (`IdempotencyScripts.java:89-93`). 늦게 끝난 holder의 complete는 `NOT_OWNER`이고 executor는 이것을 500으로 바꾼다 + (`IdempotencyExecutor.java:256`). 공유 계약이 둘 다 묶는다(`IdempotencyStoreContract.java:449,466`). + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +| --- | --- | --- | +| RR-01-11 (문구만) | 닫힘 | `http-contract.md:119-127`의 "다시 돌리지 않는다·lease 뒤 500·늦은 완료도 500"이 Redis CLAIM(`IdempotencyScripts.java:89-93`), executor complete 분기(`IdempotencyExecutor.java:256`), 공유 계약(`IdempotencyStoreContract.java:449,466`)과 맞다. 예외 Javadoc의 롤백 범위도 "쓰기 트랜잭션 안에서 부른 경우"로 좁혔다(`IdempotencyCompletionUnknownException.java:11-16`). 저장소 구현의 닫힘 판정은 03 몫 | +| RR-01-12 | 닫힘(결정대로) | 9.1절 결정이 다 들어갔다. 사용자 전송만 막고 시스템 호출자는 표시로 허용한다(`ApplicationBoundaryArchitectureTest.java:515,539`, `SystemCaller.java`). 매뉴얼 09장 4단계는 테스트로 고정했다(`SystemInvokedConsumePathTest`, `InboxRedeliveryIntegrationTest`). 위반 fixture 실패는 탐침으로 재확인했다. 남은 틈 → RR3-01-01, 02, 04 | +| RR-01-13 | 닫힘 | "표에 있는 status만 그대로, 나머지는 class 코드로 접힌다"를 정본과 Javadoc에 적었다(`http-contract.md:63-68`). 실제 표(`HttpStatusErrorCodes.java:20-35`)와 문서의 status 목록이 같다. 파라미터 테스트 8케이스 | +| RR-01-14 | 닫힘 | `GraphQlClientPolicy.effectivePageSize` 삭제. 같은 규칙의 다른 복사본은 `GraphQlConnectionPolicy.java:35` 하나뿐이다(grep). 옮긴 테스트(`GraphQlConnectionAssemblerTest` backward 케이스), 업그레이드 안내 B-10 | +| RR-01-15 | 닫힘 | `release(identity, claimToken)`은 `DELETE … WHERE state = 'IN_PROGRESS' AND claim_attempt = :attempt` 한 문장이다(`GrpcOperationLedgerRepository.java:243-249`, `JpaGrpcOperationLedger.java:204`). fake도 같은 조건이다(`InMemoryOperationLedger.java:159`). 계약 3케이스. Javadoc은 "한 행 안에서만"으로 좁혔다(`GrpcClaimToken.java`). main 호출자는 없다(grep) | +| RR-01-16 | 닫힘 | `Map`(`DirectTransactionPort.java:56`)과 계약 케이스(`TransactionPortContract.java:311`). fake와 `SpringTransactionContractTest`(PG)가 상속한다 | +| RR-01-17 | 닫힘 | 롤백 계약 케이스는 fake와 `PostgreSqlFileQuotaLedgerContractTest`가 받는다(`FileQuotaLedgerContract.java:320`). 재계산 SQL은 `operations.md` 「Namespace quota drift」에 있다. SQL은 코드의 장부 규칙과 맞는다 — publish와 commit이 한 트랜잭션, 정리 reclaim과 `DELETED` 전이가 한 트랜잭션, `REJECTED`·`EXPIRED`는 `published_at`이 없다. 실 PG16에서 확인했다. 작은 틈 → RR3-01-03 | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +없음. + +### Minor (Nice to Have) + +#### RR3-01-01 · `@SystemCaller` 규칙은 표시된 클래스의 직접 의존만 본다 — 사용자 전송이 그 bean을 부르거나 그 안에 중첩되면 두 규칙 모두 통과한다 + +- **위치**: `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java:490-503`(`ARE_SYSTEM_CALLERS`), + `:515-527`(`ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`), `:539-555`(`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, `.areAnnotatedWith` `:542`), + `src/application-core/src/main/java/dev/caskeleton/application/security/SystemCaller.java:23-25`, `docs/manual/07-authorization.md:74` +- **무엇이 틀렸나**: + - (a) 한 단계 건너 호출. `@RestController`가 `@SystemCaller` handler·job bean을 주입받아 메서드를 부른다. 그 컨트롤러는 + `@SystemInvoked` 클래스에 직접 의존하지 않으므로 첫 규칙을 통과한다. 표시가 없으므로 둘째 규칙의 대상도 아니다. + - (b) 중첩 클래스. 첫 규칙은 `@SystemCaller` 안에 중첩된 클래스를 면제한다(`ARE_SYSTEM_CALLERS`). 둘째 규칙은 표시가 직접 붙은 + 클래스만 검사한다(`:542`). 그래서 표시된 job 안의 `@RestController` nested 클래스는 사용자 전송 타입에 의존해도 아무 규칙에도 + 걸리지 않는다. 면제하는 집합과 검사하는 집합이 다르다. + - 문서는 더 강하게 말한다. `SystemCaller.java:25` "nothing but this adapter holds it", 매뉴얼 07장 `:74` "사용자 요청 ─▶ web… ──✗──▶ + @SystemInvoked (빌드 실패)". +- **왜 중요한가**: + - 발생 조건: 사용자 전송과 `@SystemCaller`가 같은 Gradle leaf에 있어야 한다. 그 leaf의 컴파일 classpath에 web 타입도 있어야 한다. + - 등록된 leaf에서는 막힌다. `adapter:inbound:messaging`의 compileClasspath에는 spring-web이 없다(`gradle.lockfile:240`은 test 쪽만). + `adapter:inbound:web`은 messaging leaf에 의존할 수 없다(`modules.json` allowed_dependencies). + - `..adapter.inbound.scheduler..`는 등록된 leaf가 없다. 서비스가 이것을 자기 feature leaf에 두면 조건이 선다. sample-portfolio처럼 + `adapter.inbound.web`과 같은 leaf다. + - 영향: "지금 실행" 같은 관리 endpoint가 job bean을 부르면 권한 검사 없는 쓰기가 사용자 요청으로 돈다. 이 템플릿은 인가를 use case에 + 두므로 컨트롤러에는 권한 검사가 없다. 인증만 있으면 누구나 부를 수 있다. 빌드는 아무 신호도 내지 않는다. + - 일부는 이전부터다. 한 leaf 안에서 조립 모듈이 만든 scheduler bean을 컨트롤러가 주입받는 길은 지난 라운드에도 있었다. 이번 + 라운드는 시스템 호출자를 inbound 패키지의 bean으로 두는 길을 문서화된 정식 경로로 만들었고, 그 위에 "빌드 실패"를 적었다. + - Minor로 둔 이유(경계): 컨트롤러가 job을 부르는 코드가 눈에 보인다. 등록된 leaf 사이에서는 direction gate가 막는다. endpoint는 여전히 + 인증을 요구한다. (b)는 일부러 만들지 않으면 생기지 않는 모양이다. +- **고치는 법**: + 1. 둘째 규칙의 대상을 `.that(ARE_SYSTEM_CALLERS)`로 바꾼다. 면제한 중첩 클래스도 같은 검사를 받는다. + 2. 규칙 하나를 더한다. 사용자 전송 클래스는 `@SystemCaller` 클래스에 의존하지 않는다. 사용자 전송 클래스는 사용자 전송 패키지에 + 있거나 `ARE_USER_TRANSPORT_TYPES`에 의존하는 클래스다. handler를 등록하는 같은 leaf의 `@Configuration`은 막지 않아야 하므로 + "inbound 전체" 대신 이 범위로 한다. + 3. 위 탐침 두 개를 위반 fixture로 넣는다. + 4. 규칙을 더하지 않는다면, 매뉴얼 07장 `:74`와 `SystemCaller.java:25`에 "한 단계 의존만 본다"를 적는다. +- **가이드 심각도·우선순위**: Low · P3 (경계: 같은 leaf 조건이 서면 Medium) +- **증거**: E3 — 범위 절 탐침 표의 `controller-calls-system-caller`, `nested-endpoint-in-system-caller` 두 줄. 둘 다 두 규칙 모두 위반 없음. + +#### RR3-01-02 · 사용자 전송 "타입" 검사는 나열 목록이다 — README가 버린 대안의 이유가 이 절반에 그대로 남는다 + +- **위치**: `ApplicationBoundaryArchitectureTest.java:466-483`(`ARE_USER_TRANSPORT_TYPES`), `src/adapter/inbound/messaging/README.md:115-116`, + `docs/manual/07-authorization.md:89-90` +- **무엇이 틀렸나**: + - README는 "사용자 전송 패키지만 나열해 금지"를 버렸다. 이유는 "나중에 새 전송이 생기면 조용히 열린다"이다. 매뉴얼 07장도 + "새 전송이 생겨도 따로 고치지 않아도 막힌다"고 적는다. + - 규칙의 패키지 쪽은 허용 목록이라 이 말이 맞다. 그러나 "시스템 패키지 안에 놓인 전송 endpoint"를 잡는 타입 쪽은 나열 목록이다 + (Spring web·GraphQL·STOMP·gRPC·servlet·`jakarta.websocket`). + - 목록에 없는 전송이 있다. JAX-RS(`jakarta.ws.rs`), graphql-java `DataFetcher`(`graphql.schema`), DGS 등이다. 이런 endpoint를 + messaging·scheduler 패키지에 두고 표시를 달면 통과한다. +- **왜 중요한가**: 문서가 약속한 성질("새 전송도 자동으로 막힌다")이 규칙의 절반에서만 참이다. 그 프레임워크가 시스템 호출자 + leaf의 classpath에 있어야 하므로 발생 조건은 좁다. +- **고치는 법**: 두 문서에 "패키지는 허용 목록, 전송 타입은 목록이고 새 전송 라이브러리를 들이면 여기에 더한다"를 적는다. + `jakarta.ws.rs..`와 `graphql..`(graphql-java)는 지금 목록에 더한다. +- **가이드 심각도·우선순위**: Low · P3 · **증거**: E1(규칙 코드와 문서 대조) + +#### RR3-01-03 · 쿼터 보정 SQL이 COMMITTED 행에 `reserved_bytes = held`를 쓴다 — 코드는 확정 행의 예약 바이트를 0으로 둔다 + +- **위치**: `docs/fileserver/operations.md:183-187`, 비교 대상 `src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/repository/FileserverQuotaRepository.java` + `commit` 쿼리(`q.reservedBytes = 0`), 서술 `operations.md:135-136` +- **무엇이 틀렸나**: + - INSERT 값이 `held, held`라서 `reserved_bytes`와 `committed_bytes`가 둘 다 재계산 값이다. 코드의 commit은 COMMITTED로 바꾸면서 + `reserved_bytes`를 0으로 둔다. 코드가 만들지 않는 행 모양이다. + - 실 PG에서 보정 뒤 `ns-b | COMMITTED | 180 | 180`이 나왔다. + - 서술 `:135-136` "reclaim stops at zero and leaves the old booking behind"는 도착 namespace에 다른 파일의 booking이 없을 때만 맞다. + 있으면 reclaim이 그 파일들의 booking을 newest-first로 깎는다. PG 시나리오에서 `ns-b`의 두 행이 30→0, 50→40이 됐다. + drift 쿼리가 이것도 잡으므로 조치는 맞다. +- **왜 중요한가**: + - 지금 enforcement는 영향이 없다. `sumReservedBytes`가 `status = 'RESERVED'`만 합산한다(grep 결과 다른 읽는 곳 없음). + - 그러나 status 없이 `reserved_bytes`를 합산하는 운영 쿼리·대시보드는 보정한 namespace 크기만큼 부풀린다. 운영자가 손으로 넣는 + 행이 코드 규칙과 갈라지는 것이라 나중에 원인을 찾기 어렵다. +- **고치는 법**: INSERT 값을 `0, held`로 바꾼다. `:135-136`은 "도착 namespace에서 회수하므로, 그쪽 다른 파일의 booking을 깎거나 + 0에서 멈춘다"로 고친다. +- **가이드 심각도·우선순위**: Low · P3 +- **증거**: E3 — 실 PostgreSQL 16에 문서의 두 SQL을 그대로 실행했다(범위 절). drift 계산과 보정 결과는 맞고, 넣은 행의 + `reserved_bytes`만 코드와 다르다. + +#### RR3-01-04 · scheduler 쪽 `@SystemCaller` 경로를 문서마다 다르게 적는다 + +- **위치**: 허용 쪽 — `ApplicationBoundaryArchitectureTest.java:456-457`, `SystemCaller.java:10-11`, `SystemInvoked.java:20-22`, + `docs/manual/07-authorization.md:87`. 부정 쪽 — `docs/manual/07-authorization.md:75,105-106`, `src/application-core/CLAUDE.md:205-206`, + 업그레이드 안내 B-16 "해야 할 일" 칸 +- **무엇이 틀렸나**: + - 규칙과 두 Javadoc은 `..adapter.inbound.scheduler..`의 `@SystemCaller` scheduled job을 허용한다. README 10절 "결정" 칸의 + "scheduler 패키지도 `@SystemCaller` 허용"이다. + - 매뉴얼 07장은 다르게 적는다. 흐름도는 scheduler를 "조립 모듈이 new로 넘김" 하나로 그린다. 「지금 이해하면 되는 것」은 + "부르는 쪽은 스케줄러 조립이나 `@SystemCaller` 메시지 handler뿐이다"라고 적는다. + - application-core CLAUDE.md와 B-16도 scheduler는 composition으로만 적는다. +- **왜 중요한가**: 두 갈래 설명이다. scheduler 패키지에 대한 작업 순서·위치(등록 leaf 없음)·예시가 어디에도 없다. RR3-01-01의 + 조건이 서는 곳이 바로 이 패키지다. +- **고치는 법**: 하나를 고른다. + - 허용을 유지하면: 07장 흐름도와 「지금 이해하면 되는 것」, CLAUDE.md, B-16에 세 번째 경로를 넣는다. 어느 leaf에 + 두는지와 RR3-01-01의 주의도 적는다. + - 쓰지 않을 거면: `SYSTEM_DRIVEN_INBOUND_PACKAGES`에서 scheduler를 빼고 Javadoc을 맞춘다. +- **가이드 심각도·우선순위**: Low · P3 · **증거**: E1 + +## Declined to judge + +- gRPC ledger V002·V003 `SET LOCAL lock_timeout`과 `GrpcOperationLedgerMigrationLockWaitIT`: 02 리뷰어 몫으로 나눠 맡았다. +- Redis·PG 멱등성 store의 기록 수명(lease + replay TTL)과 설정 검사: 03 리뷰어 몫이다. CLAIM 스크립트는 계약 문구 대조에 필요한 만큼만 읽었다. +- `FakeFileQuotaService.inTransaction`은 `DirectTransactionPort.onRollback`과 따로 도는 두 번째 롤백 장치다. use case 테스트(fake + + `DirectTransactionPort`)에서는 여전히 쿼터가 롤백되지 않는다. 이번 라운드의 목표(포트가 `inNew`로 옮겨가면 잡기)는 계약 케이스가 + 채운다. use case 테스트가 롤백 뒤 쿼터를 단언하는 곳도 없어서 판정하지 않았다. +- `/error`에서 408·409·422가 400 `BAD_PARAMETER`로 접히는 것: 클라이언트가 보는 동작 변화지만, 버린 대안과 함께 Javadoc·정본에 결정으로 적혔다. +- `release`가 끝난 기록(`FAILED_TERMINAL` 등)을 지우지 못해 그 키를 다른 요청에 풀어 줄 길이 purge뿐인 것: ADR-GRPC-004에 버린 대안과 함께 적혔다. +- optional-platforms 빌드(`grpc:*`)가 ArchUnit import에 없는 것: `app-bootstrap/build.gradle` 주석에 소유자 결정으로 적힌 이전부터의 범위다. +- `PermissionEnforcementGuard`가 선언 타입이 인터페이스인 bean을 못 보는 것: 2차 재리뷰가 이미 판정을 미뤘고 이번 diff가 바꾸지 않았다. + +## 수렴 판단 + +**이 영역에서 이번 라운드가 만든 새 Important 이상은 없다.** + +- 2차 재리뷰 발견 RR-01-12~17은 모두 닫혔다. RR-01-11의 `http-contract.md` 문구도 코드와 맞는다. 회귀는 없다. +- 새 발견은 Minor 4건이다. 셋(RR3-01-01, 02, 04)은 `@SystemCaller` 규칙의 범위와 문서 표현이다. 하나(RR3-01-03)는 보정 SQL의 행 + 모양이다. +- 가장 무거운 것은 RR3-01-01이다. 같은 leaf에 사용자 전송과 시스템 호출자를 둔 서비스에서만 서는 경계 사례라 Minor로 뒀다. + 다음 정리 때 규칙 한 줄(중첩 클래스 검사)과 규칙 하나(전송 → 시스템 호출자 의존 금지)로 닫을 수 있다. +- 이 영역만 보면 다음 수정 라운드가 필요하다는 근거는 없다. + +## Assessment + +**Ready to merge? Yes** + +9.1절 결정과 round2 "고치는 법"이 코드·계약 테스트·문서에 들어갔다. 실 PG와 ArchUnit 탐침으로 확인한 결과 머지를 막는 결함은 없다. +남은 Minor 4건은 규칙 범위와 문서 표현이라 다음 정리 묶음에서 고치면 된다. diff --git a/docs/reviews/2026-11-03-rereview/round3/02-persistence-messaging.md b/docs/reviews/2026-11-03-rereview/round3/02-persistence-messaging.md new file mode 100644 index 00000000..bad1d503 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round3/02-persistence-messaging.md @@ -0,0 +1,240 @@ +# 02 persistence·messaging 3차 확인 리뷰 (2026-11-04) + +경로는 저장소 루트 기준이다. 코드 경로는 `src/`가 앞에 붙는다. + +## 범위 — 본 pathspec, 불러온 스킬과 적용한 기준, 실행한 명령과 결과, 못 본 것 + +### 본 pathspec + +- 리뷰 범위: Base `ecc74b7d` → Head `1885bf8d`(커밋 1개, 3차 수정 묶음 r5-c) 중 아래 pathspec. 48파일, +1,719 −134. + ```text + src/adapter/outbound/persistence-jpa src/adapter/outbound/persistence-notification src/composition/outbox-relay + src/messaging src/sample-portfolio/src/main/resources/db src/sample-portfolio/src/test + src/grpc/grpc-operation-ledger-jpa/src/main/resources src/grpc/grpc-operation-ledger-jpa/src/integrationTest + docs/jpa docs/runbooks/migration-failed.md docs/runbooks/outbox-dead-letter.md docs/runbooks/outbox-publish-failed.md + docs/manual/04-persistence.md docs/manual/09-outbox-events.md docs/registries/metrics.yaml + docs/upgrade/2026-11-maturity-review.md + ``` +- 맡은 2차 재리뷰 발견: `round2/02-persistence-messaging.md`의 RR-02-09~16. +- 새 발견 ID는 `RR3-02-01`부터다. +- 이 pathspec 안이지만 다른 리뷰어 몫이라 결함 판정을 하지 않은 것: persistence-jpa의 PostgreSQL 멱등성 store 변경 + (`IdempotencyClaimGateway`, `IdempotencyTransitionGateway`, `PostgreSqlIdempotencyStoreContractTest`, README 「만료」 문단 — 03), + `docs/manual/09-outbox-events.md`의 `@SystemCaller` 소비 경로 절(01), `SampleDemoSecurityConfigTest`(04), + `JpaGrpcOperationLedgerContractIT`의 `release(identity, claimToken)`(01), metrics.yaml의 Redis lane 항목(03). +- 읽은 방식: 하위 에이전트 없이 여러 번에 나눠 직접 읽었다. + 1. 마이그레이션 8개 diff 전부와 `applied-migrations.sha256`, `git log`로 각 파일이 main(`01a8a2a70`)에 있었는지. + 2. `LockWaitMigrationInspector` 전문, `MigrationLockWaitTest`·`MigrationTrees`·`AppliedMigrationImmutabilityTest` diff, + `SampleMigrationLockWaitTest`, `LockWaitMigrationInspectorTest` 케이스, `ConcurrentIndexMigrationInspector`와 그 사용처. + 3. `PostgreSqlMigrationLockWaitIntegrationTest`, `GrpcOperationLedgerMigrationLockWaitIT`, `GrpcOperationLedgerMigrations` diff. + 4. `JpaOutboxStore`·`OutboxEventEntity` diff와 claim 경로(`PostgreSqlOutboxClaimRepository`의 `FOR UPDATE SKIP LOCKED`, + `OutboxEventJpaRepository`의 fenced UPDATE), entity를 바꾸는 다른 경로가 있는지(grep: claim만 있다). + 5. `OutboxMetrics`의 게이지 갱신, `countLongRetries` JPQL, `OutboxLongRetryRunbookContractTest`와 그 lane 설정. + 6. `SingleSidedAssociationCondition` diff와 새 fixture, `KafkaDeadLetterQuarantine`과 새 테스트. + 7. runbook 세 개·migration-guide·entity-mapping-guide·manual 04·09·metrics.yaml·upgrade 문서의 이 영역 diff, + 운영자가 쓰는 `infra/postgres/apply-capability-streams.sh`(Flyway CLI 기본 트랜잭션인지). + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +|---|---|---| +| `superpowers:requesting-code-review` | 리뷰어 템플릿: 요구사항(9.1절 결정·round2 「고치는 법」) 정합, 테스트가 mock이 아닌 실제 동작을 보는지, 마이그레이션 전략·하위 호환, Declined to judge, 심각도 보정, 읽지 않은 코드를 칭찬하지 않기 | 발견 8건의 닫힘 여부, 새 lane이 RED가 되는지 직접 확인, 이미 적용된 파일을 고쳤는지 git 이력으로 확인 | +| `jpa-patterns` | Flyway가 스키마를 소유하고 Hibernate는 validate만, 짧은 트랜잭션, entity 갱신의 실제 SQL(전체 열 UPDATE), 연관관계 규칙(사용자 원칙 "양방향 금지") | `last_failure_code`를 `updatable`로 바꾼 뒤의 claim flush가 다른 relay·fenced UPDATE와 겹칠 때(RR-02-12), `why()` 메시지가 join column·join table 구조와 맞는지(RR-02-15·RR3-02-05) | +| `supabase-postgres-best-practices` | `lock-short-transactions`(DDL 잠금 대기는 `lock_timeout`으로 묶는다), `lock-skip-locked`(claim은 잠긴 행을 건너뛴다), `schema-foreign-key-indexes`(FK가 부모 표를 잠근다), `monitor-*`(`pg_stat_activity`·`pg_locks`로 원인 세션 찾기) | `SET LOCAL`이 Flyway 트랜잭션 안에서 걸리는지(실 PG lane, RED 확인), 트랜잭션 밖이면 무효인지(실 PG), 검사기가 못 잡는 잠금 문장(실 PG), runbook의 원인 세션 조회가 원인을 가려내는지(실 PG) | +| `observability-and-instrumentation` | 경보는 증상 기반·실행 가능·runbook 연결, 지표 label 집합이 작고 고정, 모르는 값은 조용히 버리지 말고 이름을 남긴다 | `outbox.pending.size{status=DEAD} > 0` p1 경보(해소 경로가 있는지 — 재발행·skip 모두 DEAD를 벗어난다), 모르는 상태 값 WARN 1회, lag 게이지가 그 행을 여전히 세는지 | + +### 실행한 명령과 결과 + +메인 작업 트리·index·HEAD는 바꾸지 않았다(끝에 `git status --short` 빈 출력). 실행은 scratchpad에서 했다. + +| 명령 | 실행 직전 부하(1분) | 결과 | +|---|---|---| +| `git diff --stat ecc74b7d..1885bf8d -- `, `git diff ...` | — | 48파일. 나눠서 전부 읽었다 | +| `git log --follow`·`git cat-file -e 01a8a2a70:` (고친 마이그레이션 9개) | — | 9개 모두 main에 없다. 처음 들어온 커밋은 `34565130`·`1400dc15`·`5786126c`·`bbe944bd`, 모두 이 브랜치에만 있다(`git branch -a --contains`: 이 브랜치와 그 origin 추적 브랜치). 파생 서비스 `tech-log-backend`에는 네 커밋 모두 없다 | +| 동결 목록 24개 각각 `git ls-tree 01a8a2a70` | — | 24개 모두 main에 있다 | +| `sha256sum` V20·V22·알림 V11~V13 vs `applied-migrations.sha256` | — | 5개 모두 일치 | +| `javac`+`java Probe` (scratchpad, `LockWaitMigrationInspector`를 `git show 1885bf8d:`로 꺼내 컴파일) | — | FK가 있는 `CREATE TABLE`, `CREATE TRIGGER`, `DROP TRIGGER`, `REINDEX TABLE` → `[]`(못 잡음). `SET LOCAL lock_timeout = 0` → 상한으로 인정. 열 이름 `lock` → 오탐. 대조군 `ALTER TABLE` → 잡음 | +| `flock heavy.lock exp.sh` (postgres:16-alpine, 컨테이너 안 psql) | 2.24 | rc=0. **EXP1**: `parent`에 쓴 트랜잭션을 12초 열어 둠 → `CREATE TABLE child (... REFERENCES parent)`가 `ShareRowExclusiveLock` granted=false로 11.09초 기다림, 그동안 3초 제한의 `INSERT INTO parent`가 `canceling statement due to statement timeout`(3.06초). **EXP2**: 트랜잭션 밖 `SET LOCAL lock_timeout`은 `WARNING: SET LOCAL can only be used in transaction blocks` | +| `flock heavy.lock exp2.sh` (같은 이미지) | 2.4 근처 | rc=0. `outbox_event`를 읽은 뒤 다른 문장을 하나 더 하고 idle in transaction인 세션(93)과, 다른 표만 읽은 보고 세션(91)을 열어 둠 → 상한 있는 `ALTER TABLE`은 `canceling statement due to lock timeout`. runbook 조회(`pg_stat_activity WHERE xact_start < now() - 5s`)는 **91·93 둘 다** 내고 93의 `query`는 `SELECT 1 AS later_statement`. `pg_locks`의 `relation = 'outbox_event'::regclass`는 93만 낸다 | +| worktree `git worktree add --detach /rr3-02 1885bf8d` 후 `flock heavy.lock ./gradlew :adapter:outbound:persistence-jpa:postgresqlMigrationLockWaitIntegrationTest :adapter:outbound:persistence-jpa:test --tests '*MigrationLockWaitTest' --tests '*LockWaitMigrationInspectorTest' --console=plain` | 3.19 | rc=0, 35초. lane 5/5(V20·V22·알림 V11·V12·V13 각각 5.25~5.60초 — 상한 5초에서 끝남), `MigrationLockWaitTest` 2/2, `LockWaitMigrationInspectorTest` 16/16 | +| 같은 worktree에서 V22의 `SET LOCAL` 줄을 지우고 같은 lane | — | **rc=1, V22 케이스만 FAILED**(5개 중 1개). lane이 상한 누락을 실제로 잡는다(RED 확인). 파일 되돌린 뒤 `git worktree remove --force` | +| `java Re.java` (scratchpad) | — | `V22_1__x.sql`: `MigrationTrees` 정규식 false, sample 정규식 true | + +### 못 본 것 + +- 알림·sample·grpc 마이그레이션의 실 PG 실행은 게이트 기록(재리뷰 README 10.2)과 위 lane 5개를 따랐다. sample V8_1은 실 PG + 잠금 대기 테스트가 없고 텍스트 검사만 있다(Declined 참고). +- `GrpcOperationLedgerMigrationLockWaitIT`는 직접 돌리지 않았다(`-p optional-platforms integrationCheck` 게이트 기록을 따름). + 이 테스트는 Flyway가 아니라 JDBC로 한 트랜잭션에 파일 전체를 실행한다. +- claim DEAD 전이와 옛 lease 소유자의 fenced UPDATE 경쟁은 실행하지 않았다. PostgreSQL READ COMMITTED의 `FOR UPDATE` + 재검사 규칙과 코드 경로로 판단했다(E1). +- 실제 Kafka broker, 다중 인스턴스 동시 기동은 실행하지 않았다. + +## Strengths + +- **이미 배포된 파일과 아닌 파일을 git 이력으로 갈랐다.** 고친 9개는 모두 main에 없고, 동결 목록 24개는 모두 main에 + 있다(위 명령). 각 파일 머리말이 "branch not merged, recreate the dev DB"를 적고, 업그레이드 안내 표 9행과 4.2절이 같은 + 조치를 말한다(`docs/upgrade/2026-11-maturity-review.md:30,141-147`). +- **잠금 상한이 실제 Flyway 실행에서 걸리는 것을 RED까지 확인할 수 있다.** `PostgreSqlMigrationLockWaitIntegrationTest.java:59-111`은 + 진짜 `Flyway.migrate()`를 읽기 트랜잭션 뒤에서 돌리고, 상한이 없으면 15초 뒤 적용되어 실패하는 모양이다. 이 리뷰에서 + V22의 상한을 지우자 그 케이스만 실패했다. +- **규칙이 다음 파일로 이어진다.** `MigrationLockWaitTest.java:60-91`은 새 파일을 거부하고, 동결 목록의 파일이 더는 걸리지 + 않으면 그것도 실패한다(목록이 조용히 남아 다음 파일을 숨기지 못한다). 목록 갱신 대상 tree는 `MigrationTrees` 하나로 + 합쳐 immutability 검사와 같은 목록을 쓴다. +- **claim DEAD의 원인 코드를 row lock 아래에서 쓴다.** `JpaOutboxStore.java:206-214`. claim이 `FOR UPDATE SKIP LOCKED`로 잡은 + 행만 바꾸고(`PostgreSqlOutboxClaimRepository.java:39`), 토큰을 먼저 올리므로 옛 lease 소유자의 fenced UPDATE는 잠금을 + 기다린 뒤 0행이 된다. entity를 바꾸는 경로는 claim 하나뿐이라 `updatable`로 바꿔도 잠금 없이 낡은 값을 덮는 경로가 없다. + 실 PG 테스트가 결과를 행에서 읽는다(`PostgreSqlOutboxDispositionRunbookIntegrationTest.java:84-100`). +- **DEAD 경보에 해소 경로가 있다.** `metrics.yaml:396`의 `DEAD > 0`은 runbook §4의 재발행·skip이 모두 행을 DEAD 밖으로 + 옮기므로 계속 울리는 경보가 되지 않는다. +- **모르는 상태 값이 게이지 전체를 끄지 않는다.** `JpaOutboxStore.java:281-300`. 이름과 행 수를 WARN 한 번으로 남기고, + 그 행은 `outbox.publisher.lag`(`status <> 'PUBLISHED'`)에는 계속 잡힌다. +- **runbook 숫자와 상수를 문서 입력이 선언된 main 단계 lane으로 묶었다.** `OutboxLongRetryRunbookContractTest`와 + `src/composition/outbox-relay/build.gradle:45-61`. 블록이 사라지거나 비교 연산자가 바뀌어도 빈 목록이라 실패한다. +- **header 테스트가 실제 바이트를 본다.** `KafkaDeadLetterQuarantineTest`는 `MockProducer`가 받은 레코드의 header 값을 읽고, + 이전 hop의 낡은 category를 지우는지도 본다. + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +|---|---|---| +| RR-02-09 | 닫힘 | 8개 파일 첫 문장 `SET LOCAL lock_timeout = '5s'`(V20:27, V22:32, 알림 V11:25·V12:29·V13:22, V8_1:28, grpc V002:25·V003:27). 실 PG lane `postgresqlMigrationLockWaitIntegrationTest` 5/5, V22 상한을 지우면 RED(이 리뷰 실행, E2·E3). 텍스트 검사 `MigrationLockWaitTest`·`SampleMigrationLockWaitTest`. 가이드 `migration-guide.md:35-61`, runbook `outbox-dead-letter.md` §8·`migration-failed.md:43-49`. 잔여: 검사기 범위(RR3-02-01), 원인 세션 조회(RR3-02-02), 소수 버전(RR3-02-03), grpc tree(RR3-02-04) — 모두 Minor | +| RR-02-10 | 결정으로 닫힘 | 9.1절 밖이지만 round2 「고치는 법」의 문서 방향. `JpaOutboxStore.java` nextSequence Javadoc, 포트 `OutboxAggregateSequencePort.java:29-37`, runbook `outbox-dead-letter.md:139-145`, manual 09 73-78행 | +| RR-02-11 | 닫힘 | `JpaOutboxStore.java:281-309`, 단위 테스트 2개(아는 상태는 그대로 셈, WARN 1회), runbook `outbox-publish-failed.md:118-122`(롤백 전 보류 해제) | +| RR-02-12 | 닫힘 | `OutboxEventEntity.java:69`(`updatable` 허용), `JpaOutboxStore.java:206-214`, 단위 테스트, 실 PG 테스트(행의 `last_failure_code`가 `ATTEMPT_COUNTERS_INCONSISTENT`), `metrics.yaml:396` p1, runbook §1·§2 Step 1 | +| RR-02-13 | 닫힘 | `OutboxEventEntity.java:59-73`: `nextAttemptAt` Javadoc 제자리, V22 관련 틀린 문장 삭제 | +| RR-02-14 | 닫힘 | `OutboxLongRetryRunbookContractTest`, lane `outboxRelayDocumentContractTest`(`mainStage`, runbook을 input으로), runbook 89-90행 안내. JPQL도 `>=`로 같다(`OutboxEventJpaRepository` `countLongRetries`) | +| RR-02-15 | 닫힘(메시지·가이드 방향) | `SingleSidedAssociationCondition.java:130-138` `why()`, fixture `MutualForeignKey*Entity`, 테스트가 "two fields map one link"가 **없음**까지 단언, 가이드 `entity-mapping-guide.md:84-97`. 잔여: to-many 쌍의 메시지(RR3-02-05, Minor) | +| RR-02-16 | 닫힘 | `KafkaDeadLetterQuarantineTest`(두 category의 header 바이트), 업그레이드 안내 B-39(`docs/upgrade/2026-11-maturity-review.md:61`) | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +없음. + +### Minor (Nice to Have) + +#### RR3-02-01 — 잠금 대기 검사기가 FK·trigger·`REINDEX`를 못 잡고, `lock_timeout = 0`과 트랜잭션 밖 `SET LOCAL`을 상한으로 인정한다 + +- **위치**: `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java:43-58`, + `docs/jpa/migration-guide.md:51-52`. +- **무엇이 틀렸나**: + - 가이드는 검사기가 "names every statement that locks an existing table before the bound"라고 말한다. + - 검사기의 목록에는 `CREATE TABLE ... REFERENCES <기존 표>`가 없다. 이 문장은 부모 표에 `SHARE ROW EXCLUSIVE`를 건다. 그 잠금은 쓰기와 충돌한다. + - `CREATE TRIGGER`·`DROP TRIGGER`·`REINDEX`(비동시)·`REFRESH MATERIALIZED VIEW`(비동시)도 목록에 없다. + - `BOUND`는 값을 보지 않는다. `SET LOCAL lock_timeout = 0`(상한 없음)도 상한으로 센다. + - 검사기는 `.sql.conf`를 읽지 않는다. `executeInTransaction=false` 마이그레이션에서 `SET LOCAL`은 경고만 내고 효과가 없다. + 그 모양을 막는 `ConcurrentIndexMigrationInspector.requireIsolatedStatement`는 저장소 tree에 적용되지 않는다(사용처가 합성 입력 테스트뿐). + - `CREATE TABLE IF NOT EXISTS`로 "만든" 표는 이미 있던 표여도(adopt 경로) 그 뒤 `ALTER TABLE`이 면제된다. +- **증거(E3)**: + - 검사기를 컴파일해 돌렸다. FK가 있는 `CREATE TABLE`, `CREATE TRIGGER`, `DROP TRIGGER`, `REINDEX TABLE`이 모두 `[]`이었다. + - 실 PG 16에서 부모 표에 쓴 트랜잭션을 열어 두었다. `CREATE TABLE child (... REFERENCES parent)`가 11.09초 기다렸다. + 그동안 3초 제한의 `INSERT INTO parent`가 statement timeout으로 끝났다. RR-02-09와 같은 종류의 멈춤이다. + - 트랜잭션 밖 `SET LOCAL lock_timeout`은 `WARNING: SET LOCAL can only be used in transaction blocks`였다. +- **왜 중요한가**: + - 발생 조건: 서비스가 기존 업무 표를 가리키는 새 표를 만든다. 흔한 마이그레이션이다. 검사는 통과하고 상한은 없다. + - 영향: 배포 때 그 부모 표에 열린 쓰기가 있으면 부모 표의 쓰기가 마이그레이션 뒤에 줄을 선다. + - Minor로 둔 이유: 지금 저장소의 규칙 이후 마이그레이션 9개는 모두 첫 문장에 상한이 있어 이 빈틈에 걸리는 파일이 없다. + 검사기 Javadoc은 자기 목록과 "not a proof"를 적는다. 틀린 것은 가이드의 "every" 문장과 앞으로의 파일에 대한 보호 범위다. +- **고치는 법**: + 1. 목록에 `REFERENCES`(새 표·`ALTER TABLE` 모두, 대상은 참조되는 표), `CREATE/DROP TRIGGER ... ON`, 비동시 `REINDEX`·`REFRESH MATERIALIZED VIEW`·`CLUSTER`·`VACUUM FULL`을 더한다. + 2. `BOUND`가 0이 아닌 값만 인정하게 한다. + 3. `executeInTransaction=false`인 파일은 `SET LOCAL`을 상한으로 세지 않는다. 또는 `requireIsolatedStatement`를 저장소 tree 전체에 돌린다. + 4. 가이드 문장을 "목록의 문장을 찾는다"로 줄이고 목록을 적는다. +- Low · P3 · E3. **통제**: 목록 안의 문장은 M3, 목록 밖은 M1(가이드 문장만). + +#### RR3-02-02 — runbook의 원인 세션 조회가 원인을 가려내지 못한다 + +- **위치**: `docs/runbooks/migration-failed.md:46-49`, `docs/runbooks/outbox-dead-letter.md:133`. +- **무엇이 틀렸나**: + - 두 runbook은 "그 표를 건드린 열린 트랜잭션"이 원인이라고 말하고 `pg_stat_activity WHERE xact_start < now() - 5s`를 준 뒤 "End it"이라고 한다. + - 이 조회는 표를 가리지 않는다. 5초 넘게 열린 모든 트랜잭션이 나온다. + - idle in transaction 세션의 `query` 열은 **마지막** 문장이다. 원인 세션이 표를 읽은 뒤 다른 문장을 실행했으면 그 표 이름이 보이지 않는다. +- **증거(E3, 실 PG 16)**: 원인 세션(93)과 다른 표만 읽은 보고 세션(91)을 열어 두었다. 상한 있는 `ALTER TABLE`이 lock timeout으로 실패했다. + runbook 조회는 두 세션을 모두 냈다. 93의 `query`는 `SELECT 1 AS later_statement`였다. + `pg_locks`를 `relation = 'outbox_event'::regclass`로 거른 조회는 93만 냈다. +- **왜 중요한가**: 운영자가 원인을 못 고르면 다시 배포해도 같은 실패를 한다. 목록을 모두 끝내면 무관한 트랜잭션(보고·배치)이 롤백된다. + Minor로 둔 이유: 지시("원인을 끝낸다") 자체는 맞고, 원인은 목록 안에 있다. 상한 덕분에 운영자가 찾는 동안 서비스가 멈추지 않는다. +- **고치는 법**: 두 runbook의 조회를 표 이름으로 거른 `pg_locks` 조인으로 바꾼다. + `SELECT DISTINCT a.pid, a.state, a.xact_start, a.query FROM pg_locks l JOIN pg_stat_activity a USING (pid) WHERE l.relation = ''::regclass AND a.pid <> pg_backend_pid();` + `query`는 마지막 문장일 뿐이라는 한 줄을 붙인다. +- Low · P3 · E3. + +#### RR3-02-03 — 운영 tree 검사가 소수 버전 마이그레이션(`V22_1__`)을 건너뛴다 + +- **위치**: `src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java:58`, + 비교: `src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationLockWaitTest.java:58`, `docs/manual/04-persistence.md:126`. +- **무엇이 틀렸나**: + - `MigrationTrees`는 `V\d+__.+\.sql`만 마이그레이션으로 본다. `V22_1__x.sql`은 빠진다(실행 확인). + - 같은 커밋의 sample 검사는 `V[0-9_]+__`로 소수 버전을 센다. "versioned migration"의 정의가 두 벌로 갈렸다. + - manual 04는 "같은 스트림 안에서 두 버전 사이에 끼워야 하면 소수 버전을 쓴다"고 안내한다. 운영 tree에 그런 파일을 두면 잠금 규칙과 checksum 고정 둘 다 받지 않는다. +- **왜 중요한가**: 사용자 원칙의 "갈라진 복사본"이다. 발생은 소수 버전을 운영 tree에 쓰는 경우로 드물다. + checksum 쪽 빈틈은 이 커밋 이전부터 있었다(정규식은 `AppliedMigrationImmutabilityTest`에서 옮겨 왔다). 잠금 규칙 쪽은 이 커밋이 물려받았다. +- **고치는 법**: `MigrationTrees`와 sample 검사가 정규식 하나(`V[0-9_]+__.+\.sql`, 필요하면 `.` 포함)를 함께 쓴다. 소수 버전 fixture로 두 검사를 한 번씩 고정한다. +- Low · P3 · E2. 이 커밋 이전부터(checksum 쪽) + 이 커밋이 물려받음(잠금 쪽). + +#### RR3-02-04 — gRPC ledger tree에는 잠금 규칙 검사가 없다 + +- **위치**: `src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java:50-55`, + `docs/jpa/migration-guide.md:52-55`. +- **무엇이 틀렸나**: + - `MigrationTrees.ROOTS`에 `db/migration/grpc`가 없다. 텍스트 검사기를 이 tree에 돌리는 테스트도 없다. + - IT는 V002·V003 이름을 박아 두고 그 두 파일만 실 PG로 본다. 다음 `V004__`가 상한 없이 들어와도 모든 테스트가 통과한다. + - 가이드는 검사 대상을 "이 leaf DB에 도는 모든 tree"와 "서비스 스트림"으로 말한다. 템플릿이 가진 grpc tree는 어느 쪽에도 없다. +- **왜 중요한가**: RR-02-09의 원인("한 파일에 적은 규칙은 다음 파일의 규칙이 아니다")이 이 tree에는 그대로 남는다. ledger는 아직 어디에도 채택되지 않아 지금 피해는 없다. +- **고치는 법**: `GrpcOperationLedgerMigrations.IN_ORDER` 전체에 텍스트 검사를 돌리는 테스트를 하나 둔다. 등록상 testkit 의존이 막히면 `SampleMigrationLockWaitTest`처럼 검사를 그 leaf 테스트에 둔다. 또는 IT가 이름 목록 대신 V001 이후 전체를 매개변수로 받는다. +- Low · P3 · E1. + +#### RR3-02-05 — to-many 쌍에서 연관 규칙 메시지가 여전히 "한 링크"라고 틀리게 말한다 + +- **위치**: `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java:125-138`. +- **무엇이 틀렸나**: + - 새 `why()`는 annotation 모양만 본다. `@ManyToMany` 둘, 또는 `@JoinColumn` 없는 `@OneToMany`와 `@ManyToOne`이면 "two fields map one link, and the read-only one does not follow"라고 한다. + - `mappedBy`가 없으면 두 `@ManyToMany`는 둘 다 소유 쪽이다. 기본 join table도 둘(`A_B`, `B_A`)이라 링크가 둘이고 읽기 전용 쪽이 없다. + - `@JoinColumn` 없는 `@OneToMany`는 join table을 쓰고 `@ManyToOne`은 FK 열을 쓴다. 이것도 링크 둘이다. + - 이 커밋의 Javadoc이 "two many-to-many collections, map one link from both ends"라고 새로 적었다. +- **왜 중요한가**: 거부 자체는 맞아 데이터 위험은 없다. RR-02-15가 지적한 "이유를 말하는 메시지가 틀리면 규칙을 믿지 않는다"가 이 두 모양에 남는다. `mappedBy`를 잊는 흔한 실수가 바로 두 번째 모양이다. +- **고치는 법**: `why()`가 join column 이름(또는 join table 유무)을 보고 "같은 열을 두 쪽이 매핑"일 때만 "one link"라고 한다. 아니면 두 to-many 모양에 맞는 문장("두 저장소가 따로 써져 서로 어긋난다")을 둔다. 각 모양의 fixture를 하나씩 둔다. +- Low · P3 · E1. + +## Declined to judge + +- 배포 도구가 실패한 pod를 자동 재시작하면 원인이 남아 있는 동안 시도마다 최대 5초씩 줄이 선다 — 배포 토폴로지(ArgoCD 등)가 저장소에 없고, 시도당 상한은 지켜진다. +- `lock_timeout`은 잠금 대기 하나마다 걸린다. V12처럼 문장이 여럿이면 전체 대기는 5초를 넘을 수 있다 — 각 대기와 각 줄서기는 5초로 묶이고, 문서의 "5초" 요약은 운영 판단을 바꾸지 않는다. +- runbook §1의 "alert payload 필수 field(`event_id` 등)"를 게이지 기반 두 번째 조건은 채울 수 없다 — runbook `status: stub`이고, §2 Step 1이 WARN과 SQL로 행을 찾게 한다. +- runbook·README 산문의 "10번"은 document-contract lane이 보지 않는다 — 운영자가 실행하는 것은 SQL 블록이고 그것은 묶였다. +- 검사기가 열 이름 `lock`을 `LOCK TABLE`로 오탐한다 — 엄격한 쪽으로 틀리고, 지금 저장소에 해당 파일이 없다. +- `reportedUnknownStatuses`는 비우지 않아 사라졌다 다시 나타난 모르는 상태를 다시 알리지 않는다 — 결정("WARN 한 번")대로다. +- sample V8_1은 실 PG 잠금 대기 테스트가 없다 — 같은 `SET LOCAL` 모양이 다른 5개 파일에서 실 PG로 확인됐고, 텍스트 검사가 있다. +- `GrpcOperationLedgerMigrationLockWaitIT`는 Flyway 대신 JDBC 한 트랜잭션으로 실행한다 — Flyway의 기본 실행(트랜잭션 하나)과 `SET LOCAL`의 효과가 같다. 운영자 경로 `apply-capability-streams.sh`도 Flyway CLI 기본(트랜잭션)이다. +- `spotbugsTestFixtures`의 ReDoS 경고 8건 — 입력이 저장소 마이그레이션 파일뿐이다(재리뷰 README 10.3에 기록됨). +- pathspec 안의 다른 영역 변경(멱등성 store, manual 09 `@SystemCaller` 절, `SampleDemoSecurityConfigTest`, ledger `release` 시그니처, Redis lane 지표 항목) — 01·03·04 리뷰어 몫이다. + +## 수렴 판단 — 이 라운드가 만든 새 Important 이상이 있는가 + +**없다.** + +- 맡은 2차 발견 8건(RR-02-09~16)은 모두 닫혔다(RR-02-10은 결정으로). 회귀는 없다. +- RR-02-09의 핵심 주장 두 가지를 실행으로 확인했다. + - `SET LOCAL lock_timeout`은 실제 Flyway 실행에서 5초에 걸린다. V22의 상한을 지우면 lane이 실패한다. + - 고친 9개 파일은 어느 배포에도 적용되지 않았다. 9개 모두 main과 파생 서비스에 없다. +- 브리프가 물은 세 가지에 대한 답: + - **이미 적용된 파일을 바꿨는가**: 아니다. 동결 목록 24개는 모두 main에 있다. + - **비트랜잭션 마이그레이션과 섞이면**: `SET LOCAL`은 효과가 없다. 지금 그런 파일은 없다. 검사기가 이 경우를 모른다(RR3-02-01). + - **DEAD 전이의 entity flush**: claim의 `FOR UPDATE` 아래에서만 일어나고 entity를 바꾸는 다른 경로가 없어 맞다. +- 새 Minor 5건은 모두 앞으로의 파일·문서 정밀도에 관한 것이다. 지금 코드에서 틀린 동작이나 데이터 손상을 만들지 않는다. + +이 영역은 멈추는 기준(새 Important 0)을 채운다. + +## Assessment + +**Ready to merge? Yes.** + +9.1절 결정(V21과 같은 `SET LOCAL lock_timeout`, 같은 모양의 실 PG lane)이 8개 파일에 구현됐다. lane이 상한 누락을 실제로 잡는 것도 확인했다. +남은 5건은 Minor다. 검사기 범위와 runbook 조회 정밀도는 다음 정리 때 고치면 된다. diff --git a/docs/reviews/2026-11-03-rereview/round3/03-outbound.md b/docs/reviews/2026-11-03-rereview/round3/03-outbound.md new file mode 100644 index 00000000..fa9ab0a4 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round3/03-outbound.md @@ -0,0 +1,227 @@ +# 03 outbound·멱등성 3차 확인 리뷰 (2026-11-04) + +> 3차 확인 리뷰. 대상은 3차 수정 커밋 `1885bf8d`(Base `ecc74b7d`)의 수정 묶음 r5-a(멱등성·outbound)다. +> 경로는 따로 적지 않으면 `src/adapter/outbound/`를 생략한다. 새 발견 ID 접두어는 `RR3-03-`이다. + +## 범위 — 본 pathspec, 불러온 스킬과 적용한 기준, 실행한 명령과 결과, 못 본 것 + +### 본 pathspec + +``` +src/adapter/outbound/httpclient src/adapter/outbound/cache-redis src/adapter/outbound/redis-runtime +src/adapter/outbound/notification src/composition/idempotency src/shared-contract src/application-core +src/adapter/outbound/persistence-jpa/src/main/java/.../persistence/idempotency +src/adapter/outbound/persistence-jpa/src/test src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest +src/adapter/inbound/web docs/httpclient docs/manual/05-idempotency.md docs/web/http-contract.md +docs/runbooks/redis-capability-incident.md docs/registries/env-keys.yaml docs/registries/metrics.yaml +``` + +- `git diff --stat ecc74b7d..1885bf8d -- ` 기준 59파일, +1,854 −207. +- 끝까지 읽은 diff: 멱등성(Redis Lua·adapter·fake 사본, PG claim·transition gateway, 공유 계약, executor·결과 타입 Javadoc, + 설정 검사·yml·README), httpclient(watchdog, `HttpBodyReadException`, 헤더 목록, breaker Javadoc, 문서), redis-runtime(listener WARN), + notification(주석), Redis runbook·README·metrics 레지스트리, env 레지스트리, http-contract, 매뉴얼 05. +- 같은 pathspec이지만 다른 묶음(r5-b·r5-c)의 변경은 판정하지 않았다: `EnvelopeErrorController`, `SystemCaller`·`SystemInvoked`, + `DirectTransactionPort`·`TransactionPortContract`, outbox port Javadoc, persistence-jpa 마이그레이션 잠금 테스트·outbox 테스트·ArchUnit fixture. +- 판정에 필요해 pathspec 밖에서 읽은 것: `PostgreSqlIdempotencyStore`(claim 분기), `IdempotencyReaper`·`IdempotencyRecordJpaRepository`, + `IdempotencyAutoConfiguration`, `BlockingStreamingGateway`, `CountingBoundedInputStream`, `cache-redis/build.gradle`·`persistence-jpa/build.gradle`의 lane 정의, + `docs/runbooks/idempotency-unavailable.md`, `docs/upgrade/2026-11-maturity-review.md` B-24·B-30, `objectstorage/README.md`·`object-storage-qualification.yml`(RR-03-18 확인용). +- 재확인한 2차 발견: `round2/03-outbound.md`의 RR-03-11~18, `round2/01-core-app-inbound.md`의 RR-01-11. + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +| --- | --- | --- | +| `superpowers:requesting-code-review` | 리뷰어 템플릿: 요구사항(round2 "고치는 법"·9.1절 결정) 대비 정렬, Critical/Important/Minor, 읽기 전용, 하위 에이전트 없음, 판단을 미룬 것을 한 줄씩 남김 | 출력 양식 전체, 발견 재확인 표, Declined to judge | +| `api-and-interface-design` | 멱등성 키 점검표: claim이 한 번의 원자 연산인가, 진행 중 중복에 고른 답(409)이 있는가, 성공·실패·불명 세 결과, "키 보존 기간이 가장 긴 재전송 경로보다 길어야 한다". 인터페이스 쪽은 Hyrum의 법칙(`InputStream.read`의 `IOException` 계약) | Redis Lua·PG SQL의 abandon·takeover 분기와 수명, 늦은 complete, 문서가 약속한 기억 기간(RR3-03-02), `HttpBodyReadException`의 형태 | +| `performance-optimization` | 추정 말고 잰다, 고친 뒤 같은 방법으로 다시 잰다, 숫자 없이 문제로 올리지 않는다 | watchdog의 read당 비용(전후 측정), 공용 풀 포화 때 timeout 시각(측정, RR3-03-01), lifetime 연장이 Redis·PG 저장량에 주는 영향(+lease, 무시할 수준이라 발견 아님) | +| `observability-and-instrumentation` | on-call 질문에 신호가 답하는가("어느 키가 회복 필요인가"), runbook이 실제 신호를 가리키는가, 계측 실패가 보이되 결과를 바꾸지 않는가, 레지스트리와 코드의 일치 | listener 첫 실패 WARN, Redis runbook·metrics 행, 멱등성 runbook의 회복 절차(RR3-03-03) | +| `doubt-driven-development` | 비자명한 주장마다 CLAIM을 적고 반대 논증으로 깨 보려 한다. 하위 에이전트 대신 직접 반대 논증을 썼다(브리프 지시). 비대화형이라 cross-model 검토는 건너뛰었다 | 아래 「반대 논증」 4건 | + +### 반대 논증 (doubt-driven, 직접 작성) + +| CLAIM | 반대 논증 | 결과 | +| --- | --- | --- | +| Redis와 PG가 "lease 지난 EXECUTING → 회복 필요, 다시 안 돌림"을 같이 지킨다 | Redis TRANSITION은 "이미 목표 상태"를 revision보다 먼저 본다. 늦은 holder의 complete가 ABANDONED 기록에서 `ALREADY`를 받아 성공으로 끝날 수 있지 않나? 같은 owner token이 남아 있다 | 깨지지 않음. 목표가 COMPLETED이고 상태가 ABANDONED라 `ALREADY`가 아니고, revision이 1 올라 `NOT_OWNER`다(실 Redis 탐침 B). `markFailed(ABANDONED)`만 `ALREADY`를 받는데 상태가 같아 무해하다(Declined) | +| 기록 수명 lease + replay TTL이 claim·takeover·renew 모두에서 지켜진다 | start 전이가 lease나 TTL을 다시 정하면 어긋난다. 옛 기록(`afterLease` 없음)의 renew는 `nil` 산술로 Lua 오류가 나지 않나? | 깨지지 않음. start는 lease·TTL을 건드리지 않는다(Redis `Transition(..., "", "")`, PG `START_SQL`). `HGET` 없음은 Lua `false`라 `or '0'`이 받는다(탐침 D: PTTL 9938) | +| 시간 케이스가 세 구현에서 실제로 돈다 | abort가 통과로 보이거나, PG lane이 Docker 없이 skip으로 통과할 수 있다 | 깨지지 않음. Live Redis lane은 `rejectSkipped = true`, PG는 `JpaPlatformContractSupport`가 Docker 없으면 던진다. 게이트 보고서에서 두 클래스 19/19, skip 0, 시간 케이스 약 2초(실제 sleep) | +| watchdog이 idle을 틀리게 판정하지 않는다 | 타이머가 공용 풀로 옮겨 가 늦게 깨면? 일찍 닫을 수는? | 일찍 닫지는 않는다(깰 때 시작 시각과 다시 비교). **늦게 깰 수는 있다** → RR3-03-01(E3) | + +### 실행한 명령과 결과 + +checkout·index·HEAD는 바꾸지 않았다. worktree와 Gradle은 쓰지 않았다(게이트 결과는 읽기만). 탐침은 +`git show 1885bf8d:`로 꺼낸 사본을 scratchpad에서 돌렸다. + +| 명령 | 결과 | +| --- | --- | +| `git diff --stat` / `git diff ecc74b7d..1885bf8d -- ` | 59파일 | +| `docker run --rm redis:7.4`(로컬 이미지 `b6b6e3dc0c09`, 고정 digest와 같은 id) + HEAD의 CLAIM·TRANSITION·RENEW Lua를 `redis-cli EVAL` | A: lease 3000·replay 1000 claim → `PTTL 3943`. B: A가 start → 1.2s 뒤 B claim → `RECOVERY_REQUIRED`, `state ABANDONED`, `PTTL 576`. A의 늦은 complete → `NOT_OWNER`, 늦은 `FAILED_RETRYABLE` → `NOT_OWNER`, 늦은 `ABANDONED` → `ALREADY`. C claim → `RECOVERY_REQUIRED`. 기록 수명 뒤 `EXISTS 0`, D claim → `ACQUIRED`. C: lease 1000·replay 5000 → renew 10000 → `PTTL 14952`. D: `afterLease` 없는 옛 기록 renew 10000 → `PTTL 9938` | +| `javac` + `PerReadBench` — `ecc74b7d`의 read별 타이머 vs HEAD의 watchdog, 끝없는 1바이트 stream, read-idle 3s | 3회: 옛 1,490~2,533ns/read, 새 24.6~25.3ns/read (load average 3.6) | +| `javac` + `StarveProbe` — 멈춘 stream 한 번 read, read-idle 300ms, 공용 `ForkJoinPool`을 블로킹 작업 2배수로 3초 채움 | 평소: 옛 303ms(`CompletableFutureDelayScheduler`가 닫음), 새 302ms(`ForkJoinPool.commonPool-worker-1`이 닫음). **공용 풀 포화: 옛 300ms, 새 2,699ms**. `-XX:ActiveProcessorCount=2`(공용 풀 병렬도 1): 새 300ms, 닫는 스레드가 매번 새 스레드(`Thread-1`, `Thread-3`) | +| `javac` + `SelfProbe` — JDK 본문처럼 `ArrayBlockingQueue.take`로 멈춘 read 42개를 공용 풀 작업으로 실행(병렬도 21) | 가장 늦은 timeout 306ms. 공용 풀 안의 멈춘 read 자체로는 막히지 않는다(아래 javap) | +| `javap -c` `ResponseSubscribers$HttpResponseInputStream`, `AbstractQueuedSynchronizer$ConditionObject`, `CompletableFuture` | JDK 본문은 `ArrayBlockingQueue.take`로 기다린다. `ConditionObject.await`는 `ForkJoinPool.managedBlock`을 불러 공용 풀이 보충 스레드를 만든다. `delayedExecutor(delay, unit)`의 실행기는 `ASYNC_POOL`(병렬도 > 1이면 공용 풀, 아니면 작업마다 새 스레드) | +| 게이트 JUnit 보고서 읽기(main 작업 트리 `build/test-results`, 시각 2026-11-03T16:34Z·16:35Z, 커밋 01:47 KST 직전) | `LiveRedisIdempotencyStoreContractTest` 19 tests, skipped 0. `PostgreSqlIdempotencyStoreContractTest` 19 tests, skipped 0. 새 시간 케이스 5개가 두 클래스 모두에서 1.5~2.3초 걸림 | + +### 못 본 것 + +- Gradle 테스트·게이트를 다시 돌리지 않았다(README 10.2절과 보고서만 읽었다). +- Redis Cluster·Sentinel topology lane, 장애 조치 중 `TIME`이 바뀌는 경우. +- JDK HTTP/2·TLS에서 공용 풀 스레드가 본문 stream을 닫을 때의 지연. +- PG 저장소를 여러 인스턴스·여러 트랜잭션 모양(유스케이스 트랜잭션 안 vs 호출마다 트랜잭션)으로 돌리는 경우. 아래 Declined. +- `failure-retention`이 짧을 때의 실제 동작은 코드로만 확인했다(E1). + +## Strengths + +- Redis CLAIM이 "lease 지난 EXECUTING"과 "실행 전 CLAIMED·재시도 가능 실패"를 따로 다룬다(`cache-redis/.../idempotency/IdempotencyScripts.java:87-105`). + 분기 순서(fingerprint → COMPLETED → ABANDONED → 같은 owner → lease)가 PG와 같다(`persistence-jpa/.../PostgreSqlIdempotencyStore.java:131-159`). + 실 Redis에서 늦은 complete·늦은 retryable 표시가 모두 `NOT_OWNER`로 막히는 것을 확인했다(탐침 B). +- 기록 수명 규칙이 두 저장소에서 같은 식이다. Redis는 `leaseMillis + afterLease`(`IdempotencyScripts.java:61,102`), PG는 + `recordLifetimeMillis`(`IdempotencyClaimGateway.java:173-175`)를 insert와 reset 둘 다에 쓴다. renew도 같은 여유를 유지한다 + (`IdempotencyScripts.java:213-218`, `IdempotencyTransitionGateway.java:54-57`). PG `RENEW_SQL`의 오른쪽이 갱신 전 행을 읽는다는 + 사실을 주석에 적었다. 옛 기록(`afterLease` 없음)도 처리한다(탐침 D). +- 공유 계약에 시간 케이스 5개가 생겼고(`application-core/.../testkit/IdempotencyStoreContract.java:431,449,466,484,501`), 두 실 저장소에서 + 실제로 돈다. PG 쪽 `elapse`가 배포와 같은 Spring Data reaper를 돌린다(`PostgreSqlIdempotencyStoreContractTest.java:122-131`). + 그래서 "reaper가 진행 중 행을 지운다"는 PG 쪽 RR-03-11 경로도 테스트가 본다. Redis lane은 `rejectSkipped = true`다 + (`cache-redis/build.gradle:81-92`). +- 설정 검사를 한 곳에 두고, 포트(`IdempotencyClaimRequest`)에 두지 않은 이유를 남겼다(`IdempotencySettings.java:67-80`, + `composition/idempotency/README.md`). env 레지스트리·`.env.example`·업그레이드 안내 B-24가 같은 규칙을 적는다. +- watchdog은 일찍 닫지 않는다. 깰 때마다 지금 read의 시작 시각과 비교하고, 닫기 직전에 시작 시각을 한 번 더 읽는다 + (`httpclient/.../jdk/ReadIdleInputStream.java:123-131`). 무장 해제와 재무장 사이의 경쟁을 volatile 두 개로 막았다(`:134-140`). + 비용 주장(read당 µs → 수십 ns)을 다시 재서 맞았다(`PerReadBench`). +- `HttpBodyReadException`이 `InputStream` 계약(`IOException`)을 지키면서 분류된 실패를 `failure()`로 싣는다. 버린 대안(문서만 고치기)과 + 이유가 Javadoc에 있다(`httpclient/.../api/error/HttpBodyReadException.java:17-20`). +- 금지 헤더 사본을 Spring 원본과 반사로 비교하는 테스트가 있다(`JdkStreamingRestrictedHeadersTest`). Spring이 바뀌면 테스트가 깨진다. +- listener 첫 실패만 WARN으로 남기고 나머지는 DEBUG다(`redis-runtime/.../RedisRuntimeOwner.java:357-369`). 로그 수를 세는 테스트가 있다 + (`RedisLaneMetricsTest.aFailingListenerIsReportedAtWarnOnlyTheFirstTime`). + +## 발견 재확인 표 + +| ID | 상태 | 근거 | +| --- | --- | --- | +| RR-01-11 | 닫힘 | 고치는 법 1: `IdempotencyScripts.java:89-95` EXECUTING+lease 만료 → `ABANDONED`·`RECOVERY_REQUIRED`, takeover는 `CLAIMED`·`FAILED_RETRYABLE`만(`:96`). fake 사본도 같다(`InMemorySemanticRedisCommands.java:226-243`). 2: 계약 `:449`(회복 필요), `:466`(늦은 complete 거부)이 Live Redis·PG에서 돌았다(보고서). 3: `IdempotencyCompletionUnknownException` Javadoc을 "쓰기 트랜잭션 안에서 부른 경우"로 좁혔다. 같은 문장의 runbook 사본은 남았다 → RR3-03-03 | +| RR-03-11 | 닫힘(9.1절 결정대로) | 설정: `IdempotencySettings.java:73` `replay-ttl < processing-lease`면 기동 실패, 테스트 2건. 저장소: Redis claim·takeover·renew(`IdempotencyScripts.java:61,102,213-218`), PG insert·reset·renew(`IdempotencyClaimGateway.java:133,162`, `IdempotencyTransitionGateway.java:54-57`). 계약 `:484`(replay TTL < lease), `:501`(같을 때)이 두 실 저장소에서 돌았다. 실 Redis 탐침 A·C | +| RR-03-12 | 닫힘 | `ReadIdleInputStream.java:72-87` skip을 감시되는 read 반복으로. 테스트 `aSkipLongerThanReadIdleOverASteadyBodySucceeds` | +| RR-03-13 | 닫힘 | stream당 watchdog 하나(`ReadIdleInputStream.java:95-141`). 재측정: 1.5~2.5µs → 25ns. 대신 timeout 동작이 공용 풀로 옮겨 갔다 → 새 Minor RR3-03-01. 문서의 "per-read timer" 표현은 남았다 → RR3-03-04 | +| RR-03-14 | 닫힘 | 고치는 법 (a)를 골랐다: `HttpBodyReadException extends IOException`, `ClassifiedBodyInputStream.java:37,46,55,64`, `BlockingStreamingResponse.body()` Javadoc, README·configuration-reference·operations. 테스트 `StreamingBodyLifetimeTest:76` 두 transport | +| RR-03-15 | 닫힘 | `JdkStreamingClientHttpRequest.java:136-144`가 같은 시스템 속성을 읽는다. 값 4가지로 Spring 원본과 비교하는 테스트 | +| RR-03-16 | 닫힘 | 맹점을 Javadoc(`AttemptResiliencePipeline.java:26-33`)과 configuration-reference "Two deadlines" 아래 문단에 적었다. Javadoc의 조건 문장을 코드에 맞췄다 | +| RR-03-17 | 닫힘 | runbook에서 미구현 지표 문장 정리(`redis-capability-incident.md:50-52,62-66`), README `opened` 설명(`cache-redis/README.md:218`), 레지스트리 histogram 표기(`metrics.yaml:553-560`), listener 첫 실패 WARN(`RedisRuntimeOwner.java:361`) | +| RR-03-18 | 닫힘 | `objectstorage/README.md:109-111`, `object-storage-qualification.yml:3-5`가 `integrationCheck`를 적는다. `cache-redis/README.md:349-351`에 멱등성 계약. `SesEventNormalizer.java:57-59` 주석 줄바꿈 | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +없음. + +### Minor (Nice to Have) + +#### RR3-03-01 · JDK read-idle timeout이 이제 공용 `ForkJoinPool`에서 돈다 — 공용 풀이 막히면 timeout이 늦게 난다 (이번 라운드) + +- **위치**: `httpclient/.../jdk/ReadIdleInputStream.java:113-117`(`CompletableFuture.delayedExecutor(left, NANOSECONDS).execute(this::watch)`), + `:143-150`(`idle()`이 `in.close()`). +- **무엇이 틀렸나**: + - `delayedExecutor(delay, unit)`는 시간이 되면 작업을 `ASYNC_POOL`에 넘긴다. 병렬도가 1보다 크면 공용 `ForkJoinPool`이다. + - 옛 코드는 `completeOnTimeout(...).thenRun(this::idle)`이라 JDK delay 스레드에서 바로 닫았다. 새 코드는 공용 풀 작업이 비어야 닫는다. + - Javadoc은 "one scheduled task per read-idle"까지만 적고 어느 스레드에서 도는지는 적지 않는다. +- **왜 중요한가**: + - 발생 조건: JDK transport(기본은 Apache) + 스트리밍 다운로드 + 같은 JVM의 공용 풀이 보충 스레드를 만들지 않는 블로킹 작업 + (소켓·JDBC 호출, `CountDownLatch`, `Thread.sleep`)으로 차 있음. 파생 서비스의 `CompletableFuture.supplyAsync(blockingCall)`(executor 생략)이 흔한 원인이다. + 템플릿 main 코드에는 그런 사용이 없다(grep). + - 영향: 멈춘 서버의 본문 read가 read-idle이 아니라 공용 풀이 빌 때까지 기다린다. 측정에서 300ms 설정이 2,699ms에 끝났다. + 공용 풀 작업이 끝없이 막혀 있으면 RR-04-03 이전처럼 스레드가 무기한 묶인다. 일찍 닫는 일은 없다(깰 때 시작 시각과 다시 비교). + - 공용 풀 안에서 JDK 본문을 읽다 멈춘 경우는 문제없다. JDK 본문의 `ArrayBlockingQueue.take`가 `managedBlock`으로 보충 스레드를 만든다(SelfProbe 306ms). + - 병렬도가 1 이하(CPU 1~2개 pod)면 깰 때마다 새 platform 스레드를 만든다. stream당 read-idle마다 1개라 비용은 작다. +- **고치는 법**: `watch()`는 O(1)이라 delay 스레드에서 돌려도 된다. `CompletableFuture.delayedExecutor(left, NANOSECONDS, Runnable::run)`로 + 옛 코드와 같은 스레드에서 판정하게 한다. 닫기(`in.close()`)를 delay 스레드에 두기 싫으면(round2 Declined의 HTTP/2·TLS 질문) transport가 가진 + 작은 daemon 실행기로 닫기만 넘긴다. 고른 쪽과 이유를 Javadoc에 적고, 공용 풀을 채운 상태에서 timeout 시각을 보는 테스트를 둔다(위 StarveProbe 모양). +- **가이드 심각도·우선순위**: Low · P3. 비기본 transport와 외부 원인(공용 풀 포화)이 겹쳐야 하고, 늦어질 뿐 데이터 피해는 없다. + 경계: 공용 풀이 영구히 막히는 다른 결함과 겹치면 무기한 대기라 Medium에 닿을 수 있다. 그 조건은 이 커밋 밖의 결함이 있어야 해서 낮은 쪽으로 뒀다. +- **증거**: E3 — `StarveProbe`(HEAD 코드 그대로 컴파일): 공용 풀 포화 때 옛 300ms, 새 2,699ms. 닫는 스레드 이름으로 실행 위치 확인. `javap`로 `ASYNC_POOL` 확인. + +#### RR3-03-02 · "서버가 기억하는 기간" 문서가 실패한 시도의 수명(`failure-retention`)을 빠뜨렸다 (이번 라운드) + +- **위치**: `docs/web/http-contract.md:125-127`, `docs/manual/05-idempotency.md:59`, `src/shared-contract/.../OperationalError.java:50`. + 실제 동작: `RedisIdempotencyStoreAdapter.java:271-277`(markFailed가 key TTL을 retention으로), PG `IdempotencyTransitionGateway` `FAIL_SQL` + (`expires_at = now + retention`), `IdempotencySettings.java:81-85`(failure-retention은 양수·30d 이하만 검사). +- **무엇이 틀렸나**: + - 새 문장은 "끝나지 않은 시도의 기록은 claim부터 processing lease + `replay-ttl` 동안 남는다"고 적는다. + - executor가 실패로 표시한 시도(action이 던짐·`EffectUnknown` → `ABANDONED`, `RetryableNoEffect` → `FAILED_RETRYABLE`)는 표시한 때부터 + `failure-retention` 동안 남는다. 두 저장소 모두 그렇다. + - `OperationalError` 주석 "a resend with the same key never runs it again"은 기한 없이 단정한다. http-contract 본문은 기한 뒤 새 요청이 된다고 바르게 적는다. +- **왜 중요한가**: 기본값(둘 다 24h)에서는 차이가 30초뿐이다. 운영자가 `APP_IDEMPOTENCY_FAILURE_RETENTION`을 `replay-ttl`보다 짧게 두면, 효과 불명으로 + 포기한 기록이 문서가 말한 기간보다 먼저 사라지고 같은 키 재전송이 작업을 다시 돌린다. 스킬 기준 "키 보존 기간은 가장 긴 재전송 경로보다 길어야 한다"에 걸리는 + 설정인데 문서가 그 변수를 언급하지 않는다. +- **고치는 법**: 기억 기간 문단에 세 번째 줄을 더한다("실패로 표시된 시도는 표시부터 `failure-retention`"). env 레지스트리의 `APP_IDEMPOTENCY_FAILURE_RETENTION`에 + 같은 관계를 적는다. `OperationalError` 주석에 "기록이 남아 있는 동안"을 붙인다. failure-retention ≥ replay-ttl을 기동 검사로 할지는 소유자 결정이다. +- **가이드 심각도·우선순위**: Low · P3(비기본 설정, 문서 정확도). **증거**: E1. + +#### RR3-03-03 · 멱등성 runbook의 회복 필요 절차가 이번 계약과 어긋나고, 따라 할 수 없다 (일부 이번 라운드, 일부 이전부터) + +- **위치**: `docs/runbooks/idempotency-unavailable.md:20-22,33-34,43-45`, `application-core/.../IdempotencyExecutor.java:123-126,348-350` + (`recovery(...)` 메시지에 scope digest가 없다. `diagnostic(scope)`(`:344`)은 in-flight·mismatch에만 쓰인다). +- **무엇이 틀렸나**: + - (a, 이번 라운드) RR-01-11 고치는 법 3은 "Effects inside the action's own transaction roll back"을 "쓰기 트랜잭션 안에서 부른 경우"로 좁히라고 했다. + 예외 Javadoc과 http-contract는 좁혔다. runbook의 같은 문장 "Effects in the action's own transaction rolled back"은 그대로다. 갈라진 사본이다. + - (b, 이전부터) runbook은 `IDEMPOTENCY_RECOVERY_REQUIRED`에서 "실패한 요청의 서버 로그 줄에서 scope digest를 찾으라"고 한다. + `IdempotencyRecoveryRequiredException`의 메시지는 "claim requires reconciliation" 같은 고정 문구라 digest가 없다. + - (c, 이전부터) "record를 complete하거나 release하라"고 하지만 그 일을 하는 도구·명령·SQL이 없다. +- **왜 중요한가**: 이번 라운드로 Redis 배포에서 lease가 지난 실행은 모두 회복 필요로 끝난다(9.1절 결정). 그 답을 받은 요청을 다루는 운영 절차가 첫 단계에서 막힌다. + 클라이언트 쪽 조치("업무 데이터로 확인")는 digest 없이도 할 수 있어서 피해는 진단 시간이다. +- **고치는 법**: (a) runbook 문장을 Javadoc과 같게 좁힌다. (b) `recovery(...)`에도 `diagnostic(scope)`를 실어 로그에 남긴다(in-flight와 같은 방식). + (c) Redis·PG 각각 기록을 보는 명령과, 확인 뒤 키를 비우는 절차를 적거나 "도구 없음, 기록 수명(lease + replay-ttl)이 지나면 풀린다"고 정직하게 적는다. +- **가이드 심각도·우선순위**: Low · P3. 경계: "주요 진단 정보 부족"은 가이드의 Medium 예시다. 업무 데이터 확인이라는 주 조치가 digest 없이 가능하고 (b)(c)가 + 이 커밋 전부터 있던 것이라 낮은 쪽으로 뒀다. **증거**: E1. + +#### RR3-03-04 · watchdog·계약으로 바뀐 뒤 옛 표현이 남은 문서 (이번 라운드) + +- **위치**: `src/adapter/outbound/httpclient/README.md:45`("the JDK transport arms its own per-read timer"), + `docs/httpclient/configuration-reference.md:107`("bounds each read with its own `read-idle` timer"), + `src/application-core/CLAUDE.md:271`("`IdempotencyStoreContract` holds the fake, Redis and PostgreSQL to both on real servers"). +- **무엇**: RR-03-13으로 read별 타이머가 stream당 watchdog이 됐다. 보장(한 read의 대기만 센다)은 같지만 두 문서가 옛 구현을 설명한다. + CLAUDE.md 문장은 in-memory fake도 시간 케이스를 실 서버에서 지킨다고 읽힌다. fake는 만료를 모델링하지 않아 시간 케이스를 abort한다(`IdempotencyStoreContract.java:110`). +- **고치는 법**: "a per-stream watchdog bounds each read's wait"로 고친다. CLAUDE.md는 "Redis와 PostgreSQL을 실 서버에서, fake는 시간 없는 케이스만"으로 고친다. +- **가이드 심각도·우선순위**: Low · P3. **증거**: E1. + +#### RR3-03-05 · Redis inspect가 `processingLeaseUntil`을 key TTL로 계산한다 — 이제 lease + replay TTL이다 (이전부터) + +- **위치**: `cache-redis/.../idempotency/RedisIdempotencyStoreAdapter.java:388-404`(`now.plusMillis(ttlMillis)`), INSPECT Lua `IdempotencyScripts.java:269-271`(`PTTL`을 돌려준다). +- **무엇**: 포트 `IdempotencyInspection.processingLeaseUntil`에 Redis는 key가 사라지는 시각을, PG는 실제 lease(`PostgreSqlIdempotencyStore.java:623`)를 넣는다. + 전에는 replay TTL(24h)로 틀렸고, 이번 수정으로 lease + replay TTL로 더 멀어졌다. 공유 계약이 이 필드를 보지 않아 두 저장소가 갈라진 채 통과한다. +- **왜 중요한가**: 지금은 이 값을 읽는 곳이 없다(executor는 owner·response만 쓴다). 다음에 "남은 lease가 있으면 이어서 실행" 같은 판단에 쓰면 Redis에서만 lease가 지난 + 실행을 이어 가게 된다. +- **고치는 법**: INSPECT가 CLAIMED·EXECUTING이면 `leaseUntil`(서버 ms)을 돌려주고 adapter가 그것을 쓴다. 공유 계약에 inspect lease 케이스 하나. +- **가이드 심각도·우선순위**: Low · P3(소비자 없음). **증거**: E1. + +## Declined to judge + +- PG 저장소의 트랜잭션 모양. 유스케이스가 `execute`를 쓰기 트랜잭션 하나로 감싸면(sample `PublishPosterImageUseCase`) 중복 요청은 409 대신 claim insert에서 기다리고, + claim의 abandon이나 executor의 실패 표시가 예외와 함께 롤백된다. persistence·core 영역의 판단이라 넘긴다. +- Redis start·renew에는 lease 만료 검사가 없고 PG에는 있다(`IdempotencyTransitionGateway.java:39,69`). lease가 지났지만 아무도 claim하지 않은 holder가 Redis에서는 시작·연장할 수 있다. + 어느 쪽도 두 번 실행하지 않고 executor는 renew를 부르지 않는다. 이 커밋 전부터의 차이다. +- 늦은 holder의 `markFailed(EFFECT_UNKNOWN_ABANDONED)`가 이미 ABANDONED인 기록에서 `ALREADY`를 받는다(TRANSITION이 목표 상태를 revision보다 먼저 본다). 상태가 같고 executor가 결과를 버리므로 무해하다고 봤다. +- 계약 케이스 `anExecutionIsRememberedPastItsLeaseEvenWhenTheReplayTtlIsNoLonger`의 여유는 0.5초다(기록 2초, 마지막 claim 1.5초). 부하 15의 게이트에서 통과했다. 0.5초 넘는 정지가 나면 흔들릴 수 있지만 재현하지 않았다. +- 10.3절 결정 "lease 뒤 늦게 끝난 첫 시도의 결과를 버린다". 결정이라 뒤집지 않는다. 만든 위험: executor는 lease를 연장하지 않으므로 기본 30초보다 오래 걸리는 action에 lease 뒤 중복 요청이 오면, 효과가 커밋된 첫 요청도 500을 받는다. http-contract `:119-124`에 적혀 있다. +- reaper는 앱 시계, 저장소는 DB 시계를 쓴다(`IdempotencyReaper`). 이전부터다. 이번 수정으로 여유가 lease 이상이 돼 위험은 줄었다. +- `HttpBodyReadException`이 `IOException`이라 "IOException이면 재시도"하는 호출자 코드는 비멱등 스트리밍 호출의 `PARTIAL_RESPONSE` 실패도 재시도한다. `bbe944bd` 전의 bare `IOException`과 같은 동작이고, 재시도 여부는 호출자 몫이며 `failure()`가 분류를 준다. +- 금지 헤더 계산의 `TreeSet.removeAll`은 인자 쪽이 크거나 같으면 대소문자를 가린다(`AbstractSet.removeAll`). Spring 원본과 같은 동작이고 테스트가 같음을 고정한다. +- `metrics.yaml`의 새 값 `histogram_buckets: percentile_histogram`. 이 값을 검사하는 schema는 없고(`MetricsAlertingContractTest`는 `slo_driven`만 본다) 주석이 뜻을 적는다. + +## 수렴 판단 + +- **이 라운드가 만든 새 Important 이상: 없음.** 이 영역의 2차 발견 9건(RR-01-11, RR-03-11~18)이 모두 닫혔고 회귀는 없다. +- 9.1절 결정 두 건(RR-01-11, RR-03-11)은 결정대로 구현됐다. 실 Redis에서 Lua를 직접 돌려 abandon·늦은 complete 거부·기록 수명·renew 여유를 확인했고(E3), + 공유 계약의 시간 케이스가 Live Redis와 실 PostgreSQL 모두에서 skip 없이 돌았다(E2, 게이트 보고서). +- 이 라운드가 만든 새 결함은 Minor 4건이다(RR3-03-01~04). 그중 동작 결함은 RR3-03-01 하나이고, 비기본 JDK transport에서 외부 원인(공용 풀 포화)이 겹칠 때 timeout이 늦어지는 것이다. + 나머지는 문서 정확도다. RR3-03-05와 RR3-03-03의 (b)(c)는 이전부터다. +- 따라서 이 영역만 보면 다음 수정 라운드가 필요하지 않다(9.1절 멈춤 기준 충족). + +## Assessment + +**Ready to merge: Yes.** 2차 발견 9건이 코드·실 서버 탐침·게이트 보고서로 닫혔고, 이 라운드가 만든 Important 이상은 없다. +남은 것은 Minor 5건이며, RR3-03-01(watchdog 실행 스레드)이 동작에 닿는 유일한 항목이다. diff --git a/docs/reviews/2026-11-03-rereview/round3/04-bootstrap-build-sample.md b/docs/reviews/2026-11-03-rereview/round3/04-bootstrap-build-sample.md new file mode 100644 index 00000000..342cfe49 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round3/04-bootstrap-build-sample.md @@ -0,0 +1,248 @@ +# 04 bootstrap·build·sample 3차 확인 리뷰 (2026-11-04) + +리뷰 대상: Base `ecc74b7d` → Head `1885bf8d`(3차 수정 커밋, 묶음 r5-d), 영역 번호 04(slug `bootstrap-build-sample`). +재확인한 2차 재리뷰 발견: `round2/04-bootstrap-build-sample.md`의 RR2-04-01~06. 이번 발견 ID 접두어는 `RR3-04-`. +경로는 저장소 루트 기준이다. + +## 범위 — 본 pathspec, 불러온 스킬과 적용한 기준, 실행한 명령과 결과, 못 본 것 + +### 본 pathspec + +```text +src/app-bootstrap src/adapter/outbound/support src/adapter/outbound/objectstorage src/build-logic src/sample-portfolio +src/Dockerfile.sample src/.env.example src/config src/optional-platforms src/README.md .github AGENTS.md CLAUDE.md +docs/registries/secrets-classification.yaml docs/registries/env-keys.yaml docs/capability-status.md +docs/upgrade/2026-11-maturity-review.md infra +``` + +`git diff --stat` 기준 54파일 +1,994 −237. 하위 에이전트 없이 여러 번에 나눠 직접 읽었다. + +- 전부 읽은 것: `StartupRuleRunner`·`StartupRule` diff와 본문, `StartupRuleRunnerTest` diff, `SecretSourceValidator` diff와 본문, + `SecretSourceValidatorTest`·`SecretsClassificationRegistryTest` diff, `WorkflowGradleInvocations` diff와 `gradleInvocation` 본문, + `TaskSelectors` 전문, `StrictLaneStagesPlugin`·`StrictLaneStagesExtension` diff, `StrictLaneStagesFunctionalTest`·`TaskSelectorsTest` + diff, `EnvContractVerifier`·`ConfigContractPlugin`·`VerifyEnvKeysTask` diff, `SpringConfigConventionPlugin` diff, sample의 + `application.yml`·`SampleDemoAccountsProductionGuard`·`SampleDemoProfilesStartupSystemTest`·`application-test.yml`· + `SampleDemoSecurityConfigTest` diff, `Dockerfile.sample`·`.env.example`·`src/README.md`·sample README diff, 업그레이드 안내 B-14·B-15· + B-27·B-36 행, AGENTS.md·CLAUDE.md·`src/app-bootstrap/CLAUDE.md`·`src/app-bootstrap/README.md`·`infra/redis-sdk/acl/README.md`· + `docs/capability-status.md`·`src/config/spotbugs/exclude.xml`·`src/build-logic/README.md`·objectstorage README diff. +- 확인용으로 읽은 pathspec 밖 코드: `SecretReference`, `EnvironmentSecretSource`, `SecretSourceFactory`, + `RedisCredentialResolver`, `RedisRuntimeAutoConfiguration.redisResolvedCredentials`, `RedisAccountContribution`, + `RedisSdkComposition`, `RedisProductionSecrets`, `HttpClientAuthenticationAutoConfiguration.secretKey`, + `MongoCredentialResolver`, `GrpcServerSettings`, `infra/redis-sdk/acl/*.acl`, `compose-profile-contracts.json`의 Redis lane 행. +- 표본으로 읽은 것: `env-keys.yaml` diff(멱등성 행, r5-a 소관), 업그레이드 안내의 마이그레이션 표(r5-c 소관). + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 적용한 기준 | 무엇을 봤나 | +| --- | --- | --- | +| `superpowers:requesting-code-review` | 리뷰어 템플릿(Strengths → severity별 Issues → Declined → Assessment), "spec이 말하지 않은 동작은 합리적인 사용자의 기대로 판단", 읽기 전용, 의심 결함은 별도 worktree에서 확인 | 2차 발견마다 "고치는 법"과 9.1절 결정을 채웠는지, 수정이 만든 새 결함. 의심 9건을 worktree 실험으로 확인 | +| `ci-cd-and-automation` | "No gate can be skipped", 게이트가 주장하는 것과 실제 파이프라인이 같아야 한다, 캐시 최적화가 결과나 증분을 깨면 안 된다 | `verifyStrictLaneStages`가 Gradle 계획과 같은 판정을 내리는지(축약·붙여 쓴 `-x`), 실제 `.github/workflows`를 어느 빌드의 어느 단계로 읽는지, `compileJava`→`processResources` 순서가 캐시·증분을 깨는지 | +| `security-and-hardening` | 위협 모델 먼저(신뢰 경계·자산), 비밀은 환경에서, 공개된 자격증명은 쓰지 않는다, 기본값은 닫힘 | prod `fixture-` 검사가 "비밀값"을 어디서 모으는지, 그 목록에서 빠지는 비밀(우회 경로), 거부 메시지가 값을 드러내지 않는지 | +| `codebase-design` | 인터페이스는 타입이 아니라 불변식까지다, seam에서 불변식을 지킨다, 갈라진 복사본은 결함 | `StartupRule`·`RequiredProductionSecrets` 인터페이스의 불변식(후처리기 없이 만들어짐)을 runner가 seam에서 강제하는지, `CLASSIFIED_SECRETS`·`TaskSelectors`·`EnvContractVerifier`의 두 "declared" 계산이 원본과 묶여 있는지 | + +### 실행한 명령과 결과 + +worktree `scratchpad/rr3-04`(HEAD `1885bf8d`)에서 Gradle을 `flock heavy.lock`으로 감싸 실행했다. 시작 부하 2.3. +probe 파일과 workflow 수정은 worktree에만 했고, 끝난 뒤 `git worktree remove --force`로 지웠다. 메인 체크아웃은 건드리지 않았다. + +| # | 명령 | 결과 | +| --- | --- | --- | +| 1 | support에 probe 추가 → `./gradlew :adapter:outbound:support:test --tests '*RR3ProbeTest*' -i` | rc=0(출력으로 판정). 아래 1-a~1-f | +| 1-a | `@Bean static RequiredProductionSecrets hiddenSecrets()`가 `@Value` 필드 클래스를 돌려줌, 읽는 규칙 없음(= prod 아닌 프로필) | **기동 성공**, 그 bean은 나중에 정상 생성되어 `x=bound` | +| 1-b | 같은 bean + `ObjectProvider`를 기동 중에 읽는 규칙(= prod의 `SecretSourceValidator`) | 기동 실패 `'hiddenSecrets' (...ValueFieldSecrets) ... needs one: [x (@Value)]`. 실패 직전 규칙이 본 값은 `null` | +| 1-c | `@Value`를 메타 애너테이션으로 단 필드를 가진 `@Import` 규칙 | 기동 실패, `[x (@Value)]` | +| 1-d | 생성자 `@Value` 매개변수 하나인 `@Import` 규칙 | 기동 실패 `No default constructor found`(이전부터 같은 동작, 조용하지 않다) | +| 1-e | 부모 클래스의 `@Autowired` setter를 상속한 `@Import` 규칙 | 기동 실패, `[setEnv() (@Autowired)]` | +| 1-f | `@Bean static StartupRule`(선언 타입이 인터페이스)이 `@Value` 필드 클래스를 돌려줌 | 기동 실패, `'hiddenRule' ... [x (@Value)]` | +| 2 | `./gradlew -p build-logic compileTestJava -xcompileJava --dry-run` | Gradle이 붙여 쓴 `-x`를 받는다. 계획에 `:compileJava`가 없다 | +| 3 | worktree의 `integration-main.yml` optional performance 줄을 바꿔 `./gradlew -p optional-platforms :verifyStrictLaneStages --dry-run` | `-x grpcPerformanceT`: **실패** `strict lane :grpc:grpc-testkit:grpcPerformanceTest is in no executed stage`(수정 동작). `-xgrpcPerformanceTest`: **통과** `every strict lane is in an executed stage` | +| 3-b | `./gradlew -p optional-platforms performanceCheck [-xgrpcPerformanceTest] --dry-run` | 없으면 `:grpc:grpc-testkit:grpcPerformanceTest`가 계획에 있고, 붙여 쓴 `-x`면 빠진다 | +| 4 | build-logic에 probe 추가 → `./gradlew -p build-logic test --tests '*RR3WorkflowDumpTest*'`(실제 `.github/workflows` 15개를 `WorkflowGradleInvocations.read`로 읽어 `executes(stage, build)` 출력) | 11줄. `src`: `:ci`·`:sample-portfolio:check` ← ci-quality-gates, `:mainCheck`·`:integrationCheck`·`:performanceCheck` ← integration-main, `:releaseCheck` ← release. `src/optional-platforms`: `:ci` ← ci-quality-gates, `:integrationCheck` ← integration-main·release, `:performanceCheck` ← integration-main, `:releaseCheck` ← release. 다른 빌드로 잘못 센 줄 없음 | +| 5 | `:adapter:outbound:objectstorage:compileJava`를 리소스를 바꿔 가며 세 번 | 다른 리소스 추가: `processResources`만 재실행, `compileJava UP-TO-DATE`. additional metadata 수정: `compileJava` 재실행. 원복: `compileJava FROM-CACHE` | +| 6 | `javap -c -p org/gradle/util/internal/NameMatcher.class`(Gradle 9.0.0 `gradle-core`) | 집합 6개(대소문자 무시·camel 전체·camel 앞부분·camel 앞부분 대소문자 무시·kebab 전체·kebab 앞부분)와 고르는 순서가 `TaskSelectors.matches`와 같은 모양. Levenshtein은 후보 제안에만 쓰인다 | + +돌리지 않은 것: `ci`·`mainCheck`·`integrationCheck` 전체(README 10.2절 오케스트레이터 실행을 근거로 삼았다), +`SampleDemoProfilesStartupSystemTest`(10.2절 `mainCheck`가 `:sample-portfolio:systemTest`를 돈다), `docker build`·`docker run` +(r5-d 보고의 실행 결과를 근거로 삼고 Dockerfile은 정적 확인), `SecretSourceValidator` 우회 경로 실험(코드 읽기로 판정). + +### 못 본 것 + +- 실제 CI runner에서의 workflow 실행(Gitea Actions가 꺼져 있다, README 10.3절). +- `app-bootstrap/src/architectureTest`(01 소관), sample `V8_1`과 `SampleMigrationLockWaitTest`(02 소관), `env-keys.yaml`의 멱등성 + 행 의미(r5-a 소관). +- 파생 서비스(tech-log-backend 등)의 rule·workflow가 새 검사에서 어떻게 되는지. + +## Strengths + +- **prod `fixture-` 검사가 비밀값만 읽고, 비밀 목록이 레지스트리와 묶여 있다.** + `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java:62-81,124-138,170-202`. + 레지스트리 `secret` 행, 모듈이 기여한 비밀, 환경의 모든 `secret://…/` 대상을 모은다. 9.1절 결정("분류된 키만")보다 넓게 + 잡아 compose lane이 실제로 쓰는 모양(참조 + `REDIS_LANE_*`)을 덮는다. `CLASSIFIED_SECRETS`는 + `SecretsClassificationRegistryTest.java:85`가 레지스트리와 1:1로 묶는다. `HOSTNAME`이 통과하는 테스트는 실제 + `SystemEnvironmentPropertySource`를 쓴다(`SecretSourceValidatorTest.java:165`). 메시지는 변수 이름만 적고 값은 적지 않는다. +- **runner가 선언 모양이 아니라 bean이 필요로 하는 것을 본다.** `StartupRuleRunner.java:104-111,151-165,191-228`. + 실험 1-c·1-e·1-f에서 메타 애너테이션 `@Value`, 상속한 `@Autowired` setter, 인터페이스 타입 `static @Bean`이 돌려준 규칙이 + 모두 이름과 멤버를 대며 실패했다. 템플릿의 rule·비밀 목록 클래스 13개에는 해당 멤버가 없다(grep). 2차의 두 probe 모양(JavaBean + 설정 겸 비밀 목록, `@Value` 필드 규칙)은 `StartupRuleRunnerTest.java:168-241`이 RED로 고정한다. +- **축약 `-x`를 Gradle과 같은 규칙으로 맞춘다.** `TaskSelectors.java:114-170`, `StrictLaneStagesPlugin.java:126-157`. + 실험 3에서 2차가 거짓 통과로 잡은 `-x grpcPerformanceT`가 이제 실패한다. 실험 6에서 복사 원본(Gradle 9.0.0 `NameMatcher`)과 + 고르는 순서가 같다. 모호한 선택자는 후보 전부를 뺀 것으로 쳐서 닫힌 쪽으로 틀린다. +- **빌드 디렉터리를 설정이 아니라 저장소 구조에서 읽는다.** `StrictLaneStagesPlugin.java:239-250`, + `WorkflowGradleInvocations.java:255-370`. 실험 4에서 실제 workflow 15개의 모든 단계 실행이 맞는 빌드로 읽혔다. + `with: run:`과 `defaults.run`은 이제 명령이 아니다(`isStepRun`). +- **`compileJava`→`processResources` 순서가 캐시와 증분을 깨지 않는다.** `SpringConfigConventionPlugin.java:20-41`. + 실험 5: 다른 리소스 변경은 `compileJava`를 건드리지 않고, 입력은 additional metadata 파일 하나뿐이며, 원복하면 캐시를 다시 쓴다. +- **허용한 데모 프로필 셋이 같은 문서를 받고, 그 목록에서 테스트가 파생된다.** + `src/sample-portfolio/src/main/resources/application.yml:215-232`(`on-profile: local | test | demo`), + `SampleDemoProfilesStartupSystemTest.java:36-63`(`DEMO_PROFILES`에서 파라미터). object storage를 숨기던 테스트 리소스 복사본을 + 지웠다(`application-test.yml:176-177`, `SampleDemoSecurityConfigTest.java:54-58`). `Dockerfile.sample:8-22`는 이제 `demo`를 넘긴다. +- **lane json의 읽히지 않는 비-`APP_` 키가 실패한다.** `EnvContractVerifier.java:284,348-365`. 1차 사례 + `CASKELETON_GRPC_ENABLED`를 실패로 단언한다(`EnvContractVerifierTest.java:276-300`). + +## 발견 재확인 표 + +상태: 닫힘 / 부분 / 회귀 / 결정으로 닫힘. + +| ID | 상태 | 근거 | +| --- | --- | --- | +| RR2-04-01 | 닫힘(잔여 Minor RR3-04-03) | 검사 대상이 레지스트리 `secret` 행·모듈 기여·`secret://` 대상으로 좁혀짐(`SecretSourceValidator.java:170-202`). `HOSTNAME`·앱 이름·topic이 통과하는 테스트(`SecretSourceValidatorTest.java:165`). 코드가 들고 있는 Redis 계정 참조만 빠진다 | +| RR2-04-02 | 닫힘 | 세 프로필이 같은 yml 문서(`application.yml:224`), 각 프로필 기동 시스템 테스트(`SampleDemoProfilesStartupSystemTest.java:36-63`), guard remedy·README·Dockerfile이 `demo`로 맞춰짐(`SampleDemoAccountsProductionGuard.java:47-53`, `src/sample-portfolio/README.md:56-59`, `src/Dockerfile.sample:8-22`). r5-d가 이미지 실제 기동(프로필 없음 exit 71, `demo` ready)을 확인 | +| RR2-04-03 | 닫힘(잔여 Minor RR3-04-01) | "조용히 null"이 남는 경로는 찾지 못했다(실험 1-c·1-e·1-f, 기존 테스트 4건). 다만 인터페이스 타입 `static @Bean`이 돌려준 비밀 목록은 prod에서만 실패한다(실험 1-a·1-b) | +| RR2-04-04 | 닫힘(잔여 Minor RR3-04-02, 이전부터) | 지목한 네 가지 모두 고침: 축약 `-x`(실험 3), `workflow_dispatch` 전용(`WorkflowGradleInvocations.java:277-325`, TestKit), `working-directory`+`-p`(실험 4), `with: run:`(`isStepRun`). 붙여 쓴 `-x`는 이전부터 읽지 않는다 | +| RR2-04-05 | 닫힘 | 비-`APP_` 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_` 이거나 `secret://` 대상이어야 한다(`EnvContractVerifier.java:348-365`). `property:` 행은 metadata에 있을 때만 읽힘(`:284`). `@ConditionalOnProperty` 스위치는 additional metadata로 선언(`objectstorage/.../additional-spring-configuration-metadata.json`) | +| RR2-04-06 | 닫힘 | capability-status gRPC 행(`app.grpc.server.*`, `GrpcServerSettings.java:27`과 일치), `.env.example:298-299`, `exclude.xml:474-480` 근거 문장, `Dockerfile.sample`, `StartupRuleRunner` Javadoc·`src/app-bootstrap/CLAUDE.md:89-95` | + +회귀로 판정한 발견은 없다. + +## Issues + +### Critical (Must Fix) + +없음. + +### Important (Should Fix) + +없음. + +### Minor (Nice to Have) + +#### RR3-04-01 · 인터페이스 타입 `static @Bean`이 돌려준 비밀 목록은 사전 검사를 지나, `@Value` 멤버가 prod에서만 기동을 막는다 (이번 라운드) + +- **위치**: `src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java:104-111` + (사전 검사가 `beanFactory.getType(name, false)`, 즉 `@Bean` 메서드의 선언 반환 타입을 본다), 같은 파일 `:63-64` Javadoc, + `docs/upgrade/2026-11-maturity-review.md:70` B-15("후자는 모든 프로필"). +- **무엇이 틀렸나**: 사전 검사의 목적은 주석대로 "prod 첫 기동이 아니라 쓴 곳에서 실패"다. 그런데 `@Bean static + RequiredProductionSecrets x() { return new MySecrets(); }`처럼 선언 타입이 인터페이스면, 사전 검사는 인터페이스만 보고 통과한다. + 런타임 클래스 검사는 그 bean이 기동 중에 만들어질 때만 돈다. 규칙은 모든 프로필에서 만들어지므로 규칙 쪽은 문제없다(실험 1-f). + 비밀 목록은 `SecretSourceValidator`가 prod에서만 꺼내므로, 그 클래스의 `@Value` 필드는 prod에서만 걸린다. +- **증거 (E3)**: 실험 1-a — 읽는 규칙이 없으면 기동 성공, bean은 나중에 정상 바인딩. 실험 1-b — 읽는 규칙이 있으면 + `'hiddenSecrets' ... needs one: [x (@Value)]`로 실패. +- **왜 중요한가**: + - 발생 조건: 템플릿 자신의 비밀 목록 선언이 모두 이 모양(`static RequiredProductionSecrets ...()`, 반환은 람다)이다. 이를 + 베낀 서비스가 람다 대신 `@Value` 필드를 가진 클래스를 돌려주면 dev·CI·staging(prod 프로필이 아니면)은 통과하고 첫 운영 배포가 + exit 78로 멈춘다. + - 조용한 실패는 아니다. 메시지가 bean·멤버를 짚고, rolling 배포면 옛 pod가 남는다. 문서가 금지한 모양이기도 하다. + - 그래서 경계 판단에서 낮은 쪽(Minor)으로 둔다. 다만 B-15는 "모든 프로필"이라고 약속하므로 운영자가 CI 통과를 근거로 안심한다. +- **고치는 법**: 사전 검사에서 `RequiredProductionSecrets` bean은 프로필과 무관하게 한 번 만들어(계약상 static·무인자라 비용이 + 없다) `refusePulledForward`와 런타임 클래스 검사를 거친다. 또는 예측 타입이 인터페이스·추상 타입이면 같은 처리를 한다. + 실험 1-a를 RED 테스트로 쓴다. +- **가이드 심각도·우선순위**: Low · P3. +- **증거 등급**: E3. + +#### RR3-04-02 · 붙여 쓴 `-x`는 여전히 읽지 않아 `verifyStrictLaneStages`가 거짓 통과한다 (이전부터) + +- **위치**: `src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java:610-621` + (`-x`·`--exclude-task`만 인자를 받고, `-`로 시작하는 나머지 토큰은 버린다). 문서 주장: `StrictLaneStagesPlugin.java:33-34` + ("matched the way Gradle matches it"), `src/build-logic/README.md:19`, AGENTS.md:85. +- **무엇이 틀렸나**: Gradle 명령줄은 짧은 옵션에 값을 붙여 쓰는 것을 받는다(`-Dk=v`와 같은 규칙). `-xgrpcPerformanceTest`는 그 + 태스크를 계획에서 뺀다. reader는 이 토큰을 모르는 옵션으로 버린다. +- **증거 (E3)**: 실험 2와 3-b(Gradle이 붙여 쓴 `-x`로 lane을 뺀다), 실험 3(같은 줄로 optional 검사가 "every strict lane is in an + executed stage"로 통과). +- **왜 중요한가**: 이번 수정이 고친 축약 `-x`와 같은 종류의 거짓 통과다. 지금 workflow에는 이런 줄이 없다. 이 커밋이 만든 + 틈은 아니다(2차 코드도 같은 토큰을 버렸다). +- **고치는 법**: `token.startsWith("-x") && token.length() > 2`이면 나머지를 제외 선택자로 넣는다. 같은 자리에서 `-p`도 + 읽는다(지금은 버려져 main 빌드 실행으로 센다). reader 단위 테스트 2건. +- **가이드 심각도·우선순위**: Low · P3. +- **증거 등급**: E3. + +#### RR3-04-03 · 코드가 들고 있는 Redis 계정 참조는 `fixture-` 검사가 보지 않는다 (이번 라운드) + +- **위치**: `SecretSourceValidator.java:170-202`(참조를 Environment의 문자열 값에서만 모은다), + `src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfiguration.java:147-156` + (`RedisAccountContribution` bean의 참조도 같은 secret source로 풀어 접속한다), + `src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisSdkComposition.java:20,85`. +- **무엇이 틀렸나**: SDK admin plane 같은 모듈은 Redis 계정 참조를 bean(`RedisAccountContribution`)으로 넘긴다. Javadoc 예시는 + `secret://ca-skeleton-admin@environment/APP_REDIS_ADMIN`이다. 그 참조는 Environment 값이 아니므로 검사가 `APP_REDIS_ADMIN`을 + 모른다. 그 변수는 레지스트리 `secret` 행도, 모듈이 기여한 비밀도 아니다. lane ACL에는 같은 계정의 공개 비밀번호 + `fixture-admin`이 있다(`infra/redis-sdk/acl/lane-fixture-accounts.acl:5`). +- **왜 중요한가**: 2차 코드는 모든 값을 봤으므로 이 변수도 잡았다. 범위를 좁힌 결정(9.1절)이 낳은 작은 틈이다. 발생하려면 + 서비스가 admin 계정을 조립하고 lane ACL 비밀번호를 운영에 옮겨야 해서 드물다. 이 계정은 읽기 전용 진단 권한만 있다. +- **고치는 법**: `RedisAccountContribution`을 만드는 쪽(redis-sdk 조립)이 참조 이름을 `RequiredProductionSecrets`로도 내거나, + `SecretSourceValidator`가 `ObjectProvider`를 받지 않고도 볼 수 있게 참조를 설정 키로 받게 한다. + 최소한 ACL README의 "검사가 보는 비밀" 문장에 이 경로가 빠진다고 적는다. +- **가이드 심각도·우선순위**: Low · P3. +- **증거 등급**: E1(코드 읽기). + +#### RR3-04-04 · `EnvContractVerifier`의 "선언된 property" 계산이 둘로 갈라져, 단위 테스트는 운영 경로를 보지 않는다 (이번 라운드) + +- **위치**: `src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/EnvContractVerifier.java:98-124`(7인자 overload가 scope + metadata 파일에서 계산), `VerifyEnvKeysTask.java:86-87`(태스크는 metadata classpath 전체에서 계산해 8인자 overload로), + `EnvContractVerifierTest.java:329-336`(모든 테스트가 7인자). +- **무엇이 틀렸나**: RR2-04-05의 새 규칙("`property:` 행은 선언됐을 때만 읽힘")의 입력을 두 곳이 다르게 만든다. 테스트가 부르는 + 쪽은 `app.redis.` scope 파일만, 태스크는 classpath의 모든 metadata다. 운영 계산(`propertiesUnder(..., "")`)은 단위 테스트에 없다. +- **왜 중요한가**: 규칙 자체는 `mainCheck`의 실제 `verifyEnvKeys`가 지금 저장소로 확인한다. 그러나 classpath 계산이 틀어져도 + (예: additional metadata를 못 읽음) 단위 테스트는 녹색이다. +- **고치는 법**: 7인자 overload가 declared를 따로 만들지 말고 호출자가 넘기게 하거나, `propertiesUnder`를 쓰는 테스트 하나를 둔다. +- **가이드 심각도·우선순위**: Low · P3. +- **증거 등급**: E1. + +#### RR3-04-05 · sample `application.yml` 주석이 시스템 테스트를 실제보다 강하게 말한다 (이번 라운드) + +- **위치**: `src/sample-portfolio/src/main/resources/application.yml:216-220`("starts the sample under each listed profile with + nothing but this file and a database address"). +- **무엇이 틀렸나**: `test` 프로필에서는 systemTest 소스셋의 `application-test.yml`도 함께 읽힌다. 테스트 Javadoc + (`SampleDemoProfilesStartupSystemTest.java:27-29`)은 이를 적는다. 출하 설정에서 `test`와 `demo`가 같은 문서를 받으므로 + 결론(세 프로필 모두 뜬다)은 `demo` 실행으로 성립한다. 주석 문장만 틀렸다. +- **고치는 법**: "`demo`·`local`은 이 파일만으로, `test`는 테스트 리소스를 더해 띄운다"로 고친다. +- **가이드 심각도·우선순위**: Low · P3. +- **증거 등급**: E1. + +## Declined to judge + +- 실험 1-d: 생성자 `@Value`를 가진 `@Import` 규칙이 `No default constructor found`로 실패한다 — 이전부터의 동작이고 모든 + 프로필에서 크게 실패한다. 새 메시지가 "static `@Bean`의 생성자 인자로 넘겨라"라고 바른 길을 알려 준다. +- 실험 1-b에서 규칙이 실패 직전에 바인딩 안 된 비밀 목록을 한 번 호출한다 — 바로 기동이 멈추므로 해가 없다. +- `ConfigTreePropertySource`(Kubernetes secret 파일 mount) 값은 `String`이 아니라서 `forEachStringValue`가 건너뛴다. 센티넬 + 검사는 이전부터 같다. `fixture-` 검사는 분류된 키를 `getProperty`로 풀어 잡으므로, 빠지는 것은 참조 자체를 파일로 mount한 + 드문 경우뿐이다. +- `RedisCredentialResolver`는 첫 `/`, `SecretReference.parse`는 마지막 `/`로 이름을 자른다 — 이름에 `/`가 든 환경 변수는 + 현실적이지 않다. 이전부터. +- HTTP client가 `secret://` 없는 평문 키 참조를 받는데 검사는 `secret://`만 모은다 — lane fixture 비밀번호가 흘러갈 경로가 아니다. +- `paths:` 필터가 있는 PR workflow, `needs:`로 조건부 job에 묶인 job의 명령을 실행으로 센다 — 이전부터의 reader 범위이고 지금 + 단계는 필터 없는 workflow가 돈다(실험 4). +- `cd && ../gradlew` 형태의 디렉터리 이동은 읽지 않는다 — 이전부터. 이번 결정(B-36)은 `working-directory`를 요구한다. +- 비-`APP_` 키 허용 접두사(`SPRING_`·`MANAGEMENT_`·`SERVER_`) 안의 오타는 통과한다 — RR2-04-05 고치는 법이 고른 수준이다. +- `SampleDemoProfilesStartupSystemTest`가 Docker 없으면 건너뛴다(`disabledWithoutDocker`, systemTest lane은 skip을 거부하지 않음) — + sample systemTest 전체가 같은 방식이다. 이전부터. +- `CLASSIFIED_SECRETS`가 레지스트리의 복사본이다 — 테스트가 1:1로 묶으므로 갈라질 수 없다. +- `TaskSelectors`가 Gradle 내부 클래스의 복사본이다 — 내부 API라서 부를 수 없고, Gradle 버전을 올리면 다시 맞춰야 한다. 실험 6에서 + 9.0.0과 같은 모양. +- `docs/upgrade` 표의 멱등성·마이그레이션 행 — r5-a·r5-c 소관. + +## 수렴 판단 — 이 라운드가 만든 새 Important 이상이 있는가 + +**없다.** + +- 2차의 Important 3건(RR2-04-01·02·03)은 모두 닫혔다. 01·03은 코드와 실험으로, 02는 시스템 테스트와 r5-d의 이미지 실행으로 확인했다. +- 이 라운드가 만든 새 결함은 Minor 4건(RR3-04-01·03·04·05)이다. 가장 무거운 RR3-04-01도 조용한 실패가 아니라 이름을 대는 + 기동 실패이고, 문서가 금지한 모양에서만 생긴다. +- RR3-04-02는 이전부터 있던 틈이다. + +이 영역은 다음 수정 라운드가 필요하지 않다. Minor는 후속 작업으로 둘 수 있다. + +## Assessment + +**Ready to merge? Yes.** + +2차의 RR2-04-01~06은 코드·테스트·실험으로 닫혔고 회귀는 없다. 남은 것은 Low 5건(이번 라운드 4, 이전부터 1)이며, +그중 운영에 닿는 RR3-04-01도 크게 실패하는 쪽이라 머지를 막지 않는다. From f40c03c6d3b027240ecff68a36e9678a2f72437b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 03:00:21 +0900 Subject: [PATCH 09/17] =?UTF-8?q?fix:=203=EC=B0=A8=20=ED=99=95=EC=9D=B8=20?= =?UTF-8?q?=EB=A6=AC=EB=B7=B0=EC=9D=98=20Minor=2019=EA=B1=B4=EC=9D=84=20?= =?UTF-8?q?=EA=B3=A0=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 3차 수정의 확인 리뷰가 새 Important 없이 Minor 19건을 남겼다. 동작에 닿는 것이 셋이다. JDK read-idle watchdog이 공용 ForkJoinPool에서 돌아 그 풀이 바쁘면 300ms timeout이 6초 가까이 늦었다. 붙여 쓴 -x를 verifyStrictLaneStages가 읽지 않아 lane을 뺀 workflow가 통과했다. 사용자 전송이 중간 클래스를 거쳐 @SystemCaller bean을 부르면 ArchUnit 규칙을 지났다. 잠금 대기 검사기는 FK·trigger·REINDEX와 lock_timeout = 0을 못 봤고, 쿼터 보정 SQL은 코드와 다른 모양의 행을 넣었다. 방법: 영역별 4묶음이 맡은 Minor만 test-driven-development 절차로 고쳤다(재리뷰 README 12절). - watchdog은 전용 데몬 스레드 하나에서 돌고 스트림을 닫으면 작업을 취소한다. read당 비용은 그대로다(21–24ns). - 사용자 전송 → @SystemCaller는 직접·간접 의존 모두 거부한다. 리뷰가 권한 직접 의존 검사는 중간 클래스 하나로 다시 열려서 버렸다. - 검사기를 보강하면서 새로 걸린 이미 배포된 마이그레이션 5개는 내용을 바꾸지 않고 동결 목록에 더했다(main과 blob이 같다). - 비밀 목록 bean은 규칙보다 먼저 만들어 실제 클래스로 검사한다. 위험·한계: 회복 필요 예외 메시지 끝에 scope digest가 붙고 기동 실패 문구가 바뀌어, 문구 전체에 맞추던 로그 매처는 고쳐야 한다. 코드가 든 Redis 계정 참조의 fixture- 검사는 문서로만 막았다(코드로 막으려면 새 의존 edge가 필요하다). failure-retention ≥ replay-ttl 기동 검사는 넣지 않았다. -mx 같은 짧은 플래그 묶음과 graphql 전송 fixture는 남았다. spotbugsTestFixtures(게이트 밖)의 정규식 경고가 15건으로 늘었다. 검증: ci, 두 빌드의 verifyStrictLaneStages --dry-run, mainCheck, :integrationCheck, -p optional-platforms ci integrationCheck performanceCheck, :performanceCheck, :releaseCheck(-PgitRevision), verify-compose-profile-contracts(18 lane) 첫 실행 통과. watchdog은 공용 풀을 채운 상태에서 300ms 설정이 300ms에 끝나는 것을 쟀다. Refs: docs/reviews/2026-11-03-rereview/README.md 11·12절, round3/ --- docs/fileserver/operations.md | 8 +- docs/httpclient/configuration-reference.md | 10 +- docs/jpa/entity-mapping-guide.md | 5 +- docs/jpa/migration-guide.md | 39 +++-- docs/manual/04-persistence.md | 6 +- docs/manual/05-idempotency.md | 5 +- docs/manual/07-authorization.md | 36 ++++- docs/registries/env-keys.yaml | 4 + docs/reviews/2026-11-03-rereview/README.md | 30 ++++ docs/runbooks/idempotency-unavailable.md | 76 +++++++-- docs/runbooks/migration-failed.md | 17 +- docs/runbooks/outbox-dead-letter.md | 13 +- docs/upgrade/2026-11-maturity-review.md | 17 +- docs/web/http-contract.md | 14 +- infra/redis-sdk/acl/README.md | 8 +- src/.env.example | 1 + src/adapter/inbound/messaging/CLAUDE.md | 6 +- src/adapter/inbound/messaging/README.md | 10 +- .../redis/idempotency/IdempotencyScripts.java | 12 +- .../RedisIdempotencyStoreAdapter.java | 13 +- src/adapter/outbound/httpclient/README.md | 11 +- .../httpclient/jdk/ReadIdleInputStream.java | 66 +++++++- .../jdk/ReadIdleInputStreamTest.java | 87 ++++++++++- .../outbound/persistence-jpa/CLAUDE.md | 3 +- .../migration/MigrationLockWaitTest.java | 16 +- .../persistence/migration/MigrationTrees.java | 23 ++- .../arch/JpaArchitectureRulesTest.java | 49 ++++++ .../arch/entity/JoinTableChildEntity.java | 30 ++++ .../arch/entity/JoinTableParentEntity.java | 35 +++++ .../arch/entity/TwoOwnerCourseEntity.java | 28 ++++ .../arch/entity/TwoOwnerStudentEntity.java | 34 ++++ .../LockWaitMigrationInspectorTest.java | 86 +++++++++- .../VersionedMigrationFilesTest.java | 48 ++++++ .../arch/SingleSidedAssociationCondition.java | 92 +++++++++-- .../migration/LockWaitMigrationInspector.java | 147 +++++++++++++++--- .../migration/VersionedMigrationFiles.java | 47 ++++++ .../InMemorySemanticRedisCommands.java | 9 +- src/adapter/outbound/redis-sdk/README.md | 13 +- .../connection/RedisSdkComposition.java | 14 +- .../startup/RequiredProductionSecrets.java | 5 + .../support/startup/StartupRuleRunner.java | 29 +++- .../startup/StartupRuleRunnerTest.java | 67 +++++++- src/app-bootstrap/CLAUDE.md | 5 +- src/app-bootstrap/README.md | 6 +- .../ApplicationBoundaryArchitectureTest.java | 68 ++++++-- .../ArchRuleDiscoveryContractTest.java | 1 + .../ArchitectureViolationFixtureTest.java | 91 +++++++++++ ...ystemCallerHandlerRegistrationFixture.java | 18 +++ .../inbound/messaging/package-info.java | 4 +- .../jaxrs/JaxRsSystemCallerFixture.java | 24 +++ ...SystemCallerWithNestedEndpointFixture.java | 34 ++++ .../scheduler/SystemJobLauncherFixture.java | 20 +++ ...SystemCallerInvokingControllerFixture.java | 26 ++++ ...SystemCallerRelayingControllerFixture.java | 26 ++++ .../runtime/SecretSourceValidator.java | 11 +- src/application-core/CLAUDE.md | 20 ++- src/application-core/README.md | 3 +- .../idempotency/IdempotencyExecutor.java | 67 +++++--- .../IdempotencyRecoveryRequiredException.java | 6 +- .../application/security/SystemCaller.java | 14 +- .../application/security/SystemInvoked.java | 16 +- .../idempotency/IdempotencyExecutorTest.java | 50 ++++++ .../testkit/IdempotencyStoreContract.java | 23 +++ .../config/EnvContractVerifier.java | 114 ++++---------- .../buildlogic/config/MetadataScope.java | 11 -- .../buildlogic/config/VerifyEnvKeysTask.java | 37 +---- .../strictlane/WorkflowGradleInvocations.java | 24 ++- .../config/EnvContractVerifierTest.java | 130 +++++++++++++--- .../WorkflowGradleInvocationsTest.java | 34 ++++ src/composition/idempotency/README.md | 8 +- src/composition/service-runtime/README.md | 3 +- .../PermissionEnforcementGuard.java | 15 +- ...rpcOperationLedgerMigrationLockWaitIT.java | 26 +++- .../ledger/GrpcOperationLedgerMigrations.java | 57 +++++-- .../src/main/resources/application.yml | 4 +- .../SampleMigrationLockWaitTest.java | 18 +-- .../shared/error/OperationalError.java | 3 +- 77 files changed, 1876 insertions(+), 410 deletions(-) create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableChildEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableParentEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerCourseEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerStudentEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFiles.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/adapter/inbound/messaging/SystemCallerHandlerRegistrationFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/messaging/jaxrs/JaxRsSystemCallerFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/scheduler/SystemCallerWithNestedEndpointFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/scheduler/SystemJobLauncherFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemCallerInvokingControllerFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemCallerRelayingControllerFixture.java delete mode 100644 src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/MetadataScope.java diff --git a/docs/fileserver/operations.md b/docs/fileserver/operations.md index cc7a14b0..33fd2cfb 100644 --- a/docs/fileserver/operations.md +++ b/docs/fileserver/operations.md @@ -133,7 +133,8 @@ Never delete staging content to clear a backlog: an upload that is mid-flight wi with the bytes its files actually hold. The known cause is history: before the 2026-11 maturity review, `move` relocated a file without moving its quota. The bytes of every file moved before that fix are still booked on the namespace it left, and deleting such a file reclaims from the namespace -it now lives in, where the reclaim stops at zero and leaves the old booking behind. A derived +it now lives in: the reclaim draws down the bookings of that namespace's other files, newest first, +or stops at zero, and the old booking stays behind either way. A derived service that moved files across namespaces before taking the fix has this drift; one that never did should see none. @@ -169,7 +170,8 @@ fileserver's writes stopped. To correct a namespace, stop every fileserver write to it first — uploads, copy, move, delete, and the cleanup worker (`APP_FILESERVER_PLATFORM_CLEANUP_ENABLED=false`) — because the statement below recomputes from `fs_file` and a publish or reclaim that lands between its two steps would be lost. -It zeroes the namespace's committed rows and books the recomputed total as one row; the per-row +It zeroes the namespace's committed rows and books the recomputed total as one row, shaped the way a +publish leaves one (`COMMITTED`, `reserved_bytes` 0, the bytes in `committed_bytes`); the per-row split has no meaning once reclaims have drawn rows down, and enforcement only ever reads the sum. `RESERVED` rows (uploads in progress) are left alone. @@ -183,7 +185,7 @@ UPDATE fs_quota_reservation INSERT INTO fs_quota_reservation ( reservation_id, scope_type, scope_value, reserved_bytes, committed_bytes, expires_at, status, version, created_at, updated_at) -SELECT gen_random_uuid(), 'namespace', :'namespace', held, held, +SELECT gen_random_uuid(), 'namespace', :'namespace', 0, held, now(), 'COMMITTED', 0, now(), now() FROM (SELECT coalesce(sum(actual_size), 0) AS held FROM fs_file diff --git a/docs/httpclient/configuration-reference.md b/docs/httpclient/configuration-reference.md index 7172e5c2..c694fa9b 100644 --- a/docs/httpclient/configuration-reference.md +++ b/docs/httpclient/configuration-reference.md @@ -103,10 +103,12 @@ greater than zero (`TIMEOUT_NOT_POSITIVE`): both engines read zero as "wait fore `total-call` also bounds the setup of a streaming download — connect, send, and the wait for response headers. Once the stream is handed over, each gap of the body is bounded by `read-idle` instead, so a long download is not cut at an arbitrary total (design §15.3). This holds on both -transports. The JDK transport keeps its exchange-wide timeout off a streamed body and bounds each -read with its own `read-idle` timer, because the JDK client has no socket read timeout; before -review 2026-11-03 RR-04-03 every JDK download longer than `response-header` was cut mid-body. A body -failure after hand-over is thrown from `read` as `HttpBodyReadException` — an `IOException`, as +transports. The JDK transport keeps its exchange-wide timeout off a streamed body, and a per-stream +watchdog bounds each read's wait by `read-idle`, because the JDK client has no socket read timeout. +The watchdog wakes on one daemon thread of its own (`httpclient-jdk-read-idle`), not on the common +`ForkJoinPool`, so a service that fills that pool with blocking work does not delay it (re-review +2026-11-04 RR3-03-01). Before review 2026-11-03 RR-04-03 every JDK download longer than +`response-header` was cut mid-body. A body failure after hand-over is thrown from `read` as `HttpBodyReadException` — an `IOException`, as `InputStream` promises, so `catch (IOException)` still sees it — whose `failure()` is `HttpResponseTimeoutException` (a wait longer than `read-idle`) or `HttpResponseTruncatedException` (the connection ended early), stage `RESPONSE_BODY`, evidence `PARTIAL_RESPONSE` (re-review diff --git a/docs/jpa/entity-mapping-guide.md b/docs/jpa/entity-mapping-guide.md index 8c3b39d7..2a09c7d5 100644 --- a/docs/jpa/entity-mapping-guide.md +++ b/docs/jpa/entity-mapping-guide.md @@ -85,7 +85,10 @@ reason those are ID references. bidirectional pair, on `@Entity`, `@MappedSuperclass` and `@Embeddable` types: an association that declares `mappedBy` (only that inverse half is reported), and two entities whose associations point at each other without `mappedBy` (both halves are reported — the `@JoinColumn` form above, review -RR-03-04). That last check also refuses two entities that each hold their own foreign key to the +RR-03-04). The message says how the pair keeps the link: one join column mapped from both ends, or +the link stored twice — a `@OneToMany` without `@JoinColumn` in a join table beside the child's own +`@ManyToOne` column (what a forgotten `mappedBy` produces), or two `@ManyToMany` each owning a join +table (re-review round 3, RR3-02-05). That last check also refuses two entities that each hold their own foreign key to the other (`Order.@OneToOne latestInvoice` with `Invoice.@ManyToOne order`). It is not one link mapped twice, and the message says so; it is refused on purpose, because the two tables then reference each other: neither row can be inserted or deleted first, one key has to be nullable and written by a diff --git a/docs/jpa/migration-guide.md b/docs/jpa/migration-guide.md index d79e63c8..04de288c 100644 --- a/docs/jpa/migration-guide.md +++ b/docs/jpa/migration-guide.md @@ -45,20 +45,33 @@ rolls it back whole, the database stays on the version before it and the new rel start: a failed deploy instead of an outage. Deploy again when the transaction has ended. `LOCAL`, because a plain `SET` outlives the migration on the pooled connection Flyway borrowed and -changes every statement that later runs on it. A statement on a table the same migration created a -moment earlier waits for nothing and needs no bound. +changes every statement that later runs on it. The value is not zero: `lock_timeout = 0` (or +`DEFAULT`, or a later `RESET`) is no bound at all. A migration with `executeInTransaction=false` +cannot use it — `SET LOCAL` outside a transaction only warns — so a statement that locks a table +goes into a migration that runs in one. A statement on a table the same migration created a moment +earlier waits for nothing and needs no bound; `CREATE TABLE IF NOT EXISTS` does not count, because +the table may already be there. -Enforced, not remembered: `LockWaitMigrationInspector` (persistence-jpa testkit) reads a script -and names every statement that locks an existing table before the bound. `MigrationLockWaitTest` -runs it over every tree this leaf's database runs, `SampleMigrationLockWaitTest` over the sample's -stream; a service stream copies the latter with its own directory. The migrations released before -the rule wait unbounded and stay that way (they are applied, and applied files are never edited); -the test lists them and refuses any new one. `PostgreSqlMigrationLockWaitIntegrationTest` -(`postgresqlMigrationLockWaitIntegrationTest`) and the gRPC ledger's -`GrpcOperationLedgerMigrationLockWaitIT` show on real PostgreSQL that a bounded migration gives up -within the bound while another transaction holds the table, and leaves the version below it. The -rule came from V21 having the bound and V22, in the same commit, not having it (re-review -2026-11-03 round 2, RR-02-09). +Enforced, not remembered: `LockWaitMigrationInspector` (persistence-jpa testkit) reads a script — +and the `.sql.conf` beside it — and names the statements from its list that lock an existing table +with no bound in force: `ALTER TABLE`, `LOCK TABLE`, `TRUNCATE`, `DROP TABLE`; `CREATE INDEX`, +`DROP INDEX`, `REINDEX` and `REFRESH MATERIALIZED VIEW` without `CONCURRENTLY`, `CLUSTER`, `VACUUM +FULL`; `REFERENCES` on the table it references, in a new table as much as in an `ALTER TABLE` (a +foreign key locks its parent against writes while it is added); `CREATE TRIGGER` and `DROP TRIGGER` +on their table; `UPDATE` and `DELETE`. It reads text, so a statement outside the list is not +checked. `MigrationLockWaitTest` runs it over every tree this leaf's database runs, +`SampleMigrationLockWaitTest` over the sample's stream; a service stream copies the latter with its +own directory. Both find the migrations the way Flyway does, decimal versions (`V22_1__`) included +(`VersionedMigrationFiles`, testkit). The migrations released before the rule wait unbounded and +stay that way (they are applied, and applied files are never edited); the test lists them and +refuses any new one. `PostgreSqlMigrationLockWaitIntegrationTest` +(`postgresqlMigrationLockWaitIntegrationTest`) shows on real PostgreSQL that a bounded migration +gives up within the bound while another transaction holds the table, and leaves the version below +it. The gRPC ledger's tree lives in the optional build, which cannot reach the testkit: its +`GrpcOperationLedgerMigrationLockWaitIT` runs every ledger migration after V001, read from the tree, +against a held ledger instead, so its next migration is checked on real PostgreSQL. The rule came +from V21 having the bound and V22, in the same commit, not having it (re-review 2026-11-03 round 2, +RR-02-09; round 3, RR3-02-01, RR3-02-03, RR3-02-04). ## Concurrent index builds diff --git a/docs/manual/04-persistence.md b/docs/manual/04-persistence.md index ec7e99dd..663319ce 100644 --- a/docs/manual/04-persistence.md +++ b/docs/manual/04-persistence.md @@ -128,8 +128,10 @@ capability 스트림 db/migration/jpa/ 각자 histor (리뷰 README 13.2, 09-02). - 기존 데이터가 새 제약을 어기면 마이그레이션이 이유를 남기고 멈추게 쓴다(`V8_1`의 `DO $$` 블록). 조용히 지우지 않는다. -- 운영 중인 테이블을 잠그는 문장(`ALTER TABLE`, `CONCURRENTLY` 없는 `CREATE INDEX`, `UPDATE`·`DELETE`)이 있으면 - 그 앞에 `SET LOCAL lock_timeout = '5s';`를 둔다(`V8_1`, `V22`). 상한이 없으면 그 테이블을 건드린 열린 +- 운영 중인 테이블을 잠그는 문장(`ALTER TABLE`, `CONCURRENTLY` 없는 `CREATE INDEX`, `UPDATE`·`DELETE`, 기존 + 테이블을 가리키는 `REFERENCES`, trigger 만들기·지우기 등 — 전체 목록은 `docs/jpa/migration-guide.md`)이 있으면 + 그 앞에 `SET LOCAL lock_timeout = '5s';`를 둔다(`V8_1`, `V22`). 값은 0이 아니어야 하고, + `executeInTransaction=false` 마이그레이션에서는 `SET LOCAL`이 효과가 없으니 잠그는 문장을 거기 두지 않는다. 상한이 없으면 그 테이블을 건드린 열린 트랜잭션 하나(`ALTER TABLE`이면 읽기만 한 것도) 뒤에서 마이그레이션이 끝없이 기다리고, 그동안 뒤에 온 그 테이블의 쓰기(`ALTER TABLE`이면 읽기까지)가 모두 마이그레이션 뒤에 줄을 선다. 상한이 있으면 5초 뒤 실패·롤백되고 새 버전이 뜨지 않을 뿐이다. 자기 스트림에도 `SampleMigrationLockWaitTest`처럼 `LockWaitMigrationInspector`(persistence-jpa testkit) 검사를 둔다 diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md index 0effa752..629ea091 100644 --- a/docs/manual/05-idempotency.md +++ b/docs/manual/05-idempotency.md @@ -57,7 +57,10 @@ DB 커밋 중 연결 끊김 ───────────────── 같은 키 재전송은 작업을 다시 돌리지 않는다. 첫 시도가 실행을 시작한 뒤 processing lease(기본 30s)가 지나면 두 저장소 모두 그 기록을 넘겨주지 않고 500 `IDEMPOTENCY_RECOVERY_REQUIRED`로 답한다. 넘겨받는 것은 실행 전 claim과 재시도 가능한 실패뿐이다. 기록은 lease + `replay-ttl` 동안 남고, `replay-ttl`이 lease보다 -짧으면 기동이 실패한다(`IdempotencyStoreContract`, 재리뷰 2026-11-04 RR-01-11·RR-03-11). +짧으면 기동이 실패한다(`IdempotencyStoreContract`, 재리뷰 2026-11-04 RR-01-11·RR-03-11). 작업이 실패로 +끝나 executor가 포기나 재시도 가능으로 표시한 기록은 표시한 때부터 `failure-retention`(기본 24h) 동안 +남는다. 이 값은 검사하지 않으므로 `replay-ttl` 이상으로 둔다. 짧으면 효과 불명으로 포기한 기록이 먼저 +사라져 같은 키 재전송이 작업을 다시 돌린다(RR3-03-02). 409를 `retryable=true`로 바꾼 이유(리뷰 02-01 결정): 같은 키 재전송은 서버가 안전하게 판정하므로 다시 보내는 것이 맞고, 새 키로 보내면 서버가 막지 못한다. 짝 프론트 분류기도 이 표를 따른다. diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index a6b8443a..0c1104fd 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -72,22 +72,45 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re ```text 사용자 요청 ─▶ web·GraphQL·gRPC·WebSocket ──✗──▶ @SystemInvoked 유스케이스 (빌드 실패) +사용자 요청 ─▶ web·GraphQL·gRPC·WebSocket ──✗──▶ @SystemCaller (빌드 실패, 중간 클래스를 거쳐도) 시스템 ─▶ 스케줄러(조립 모듈이 new로 넘김) ─────▶ @SystemInvoked 유스케이스 시스템 ─▶ 메시지 handler(@SystemCaller, 직접 new) ─▶ @SystemInvoked 유스케이스 +시스템 ─▶ 예약 작업(@SystemCaller, 직접 new) ──────▶ @SystemInvoked 유스케이스 어디서든 ─▶ @SystemInvoked 유스케이스를 bean으로 등록 ──✗ (기동 실패) ``` - 사용자 전송: 사용자가 보낸 요청이 들어오는 inbound adapter다(web·GraphQL·gRPC·WebSocket). - 시스템 호출자: broker 전달이나 시간(tick)이 깨우는 코드다. 사용자 요청은 여기로 들어오지 않는다. +시스템 호출자가 `@SystemInvoked` 유스케이스를 얻는 길은 아래 셋뿐이다. 이 표가 정본이고, 다른 문서는 이 +절을 가리킨다. + +| 경로 | 어디에 두나 | 유스케이스는 누가 만드나 | +| --- | --- | --- | +| 조립 모듈의 스케줄러 | `composition:*` leaf. 예: outbox relay(`src/composition/outbox-relay`) | 조립 모듈의 `@Bean` 메서드가 `new`로 만들어 스케줄러에 넘긴다 | +| 메시지 handler | `adapter:inbound:messaging` leaf, 또는 서비스 leaf의 `..adapter.inbound.messaging..` 패키지 | handler 생성자가 port를 받아 `new`로 만든다. handler에 `@SystemCaller`. 작업 순서는 09장 「소비」 4단계 | +| 예약 작업 | 서비스 자기 leaf의 `..adapter.inbound.scheduler..` 패키지. 등록된 scheduler leaf는 없다 | 작업 클래스 생성자가 port를 받아 `new`로 만든다. 작업 클래스에 `@SystemCaller`. 모양은 메시지 handler와 같고, 깨우는 것이 `@Scheduled` 메서드다 | + +예약 작업은 controller와 같은 leaf에 놓이기 쉽다. 그때 "지금 실행" endpoint가 작업 bean을 주입받아 부르면 +권한 검사 없는 쓰기를 사용자가 부르게 된다. 아래 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`가 이것을 +빌드에서 막는다. 사용자도 같은 일을 시켜야 하면 `@RequiresPermission`을 단 사용자용 유스케이스를 따로 +만든다(아래 D4 문단). + | 규칙 | 무엇을 막나 | 어디 | | --- | --- | --- | | bean 금지 | `@SystemInvoked` 유스케이스가 bean이면 기동 실패. 호출자가 `new`로 만들어 혼자 들고 있는 것만 허용한다 | `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java` | -| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | -| 표시 검사 | `@SystemCaller`는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·GraphQL·STOMP mapping·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) | +| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스와 그 안에 중첩된 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | +| 표시 검사 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·JAX-RS·GraphQL·STOMP mapping·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) | +| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 사용자 전송 패키지에 있거나 사용자 전송 타입에 의존하는 클래스다. 그래서 handler를 bean으로 등록하는 `@Configuration`은 걸리지 않는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) | -규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 그래서 나중에 새 전송이 생겨도 따로 -고치지 않아도 막힌다. 메시지 소비자의 작업 순서는 09장 「소비」 4단계다. +규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 이 성질은 **패키지** 쪽에서만 온다. +패키지는 허용 목록이라, 나중에 새 전송 패키지가 생겨도 따로 고치지 않아도 막힌다. 사용자 전송 **타입** +쪽은 나열 목록이다(`ARE_USER_TRANSPORT_TYPES`). 시스템 패키지 안에 놓인 endpoint를 알아보는 데 쓰는 +목록이라, 목록에 없는 전송 라이브러리로 만든 endpoint는 전송으로 보이지 않는다. 새 전송 라이브러리를 +들이면 그 패키지를 이 목록에 더한다. + +이 규칙들은 클래스 의존만 본다. 실행 중에 bean을 찾는 코드(`getBean`, `ObjectProvider`)는 의존이 아니라서 +잡지 못한다. D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표시를 쓰지 않는다. 사용자가 부르는 쓰기라면 권한을 선언하고 역할에 매핑한다. 같은 쓰기를 사용자도 시스템도 부르면 유스케이스를 둘로 나눈다 @@ -102,7 +125,8 @@ web이 빠진 조립(gRPC 전용·배치 전용)에는 `@RequiresPermission`을 ## 지금 이해하면 되는 것 - 쓰기 = `@RequiresPermission` + non-final + bean + 역할 매핑. -- 시스템만 부르는 쓰기 = `@SystemInvoked` + bean 아님 + 사용자 전송에서 안 닿음. 부르는 쪽은 스케줄러 - 조립이나 `@SystemCaller` 메시지 handler뿐이다. +- 시스템만 부르는 쓰기 = `@SystemInvoked` + bean 아님 + 사용자 전송에서 안 닿음. 부르는 쪽은 셋뿐이다: + 조립 모듈의 스케줄러, `@SystemCaller` 메시지 handler, `@SystemCaller` 예약 작업. 사용자 전송은 + `@SystemCaller`에도 닿지 못한다. - 객체 판정은 유스케이스 안, 남의 것은 404. - 역할은 자기 client 것만 읽는다. diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 85391be2..130556ce 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -1681,6 +1681,10 @@ env_keys: required_test: redis-idempotency-contract:processing-lease-bounded - name: APP_IDEMPOTENCY_FAILURE_RETENTION + # app.capabilities.idempotency.failure-retention: how long a record the executor marked failed + # (abandoned with an unknown effect, or retryable without one) stays, from the marking. Not + # compared with APP_IDEMPOTENCY_TTL at startup; keep it at least that long, or an abandoned + # record goes first and a same-key resend runs the work again (re-review 2026-11-04 RR3-03-02). type: duration default: 24h allowed_values: null diff --git a/docs/reviews/2026-11-03-rereview/README.md b/docs/reviews/2026-11-03-rereview/README.md index 55545e28..17946aae 100644 --- a/docs/reviews/2026-11-03-rereview/README.md +++ b/docs/reviews/2026-11-03-rereview/README.md @@ -208,3 +208,33 @@ Minor 19건 중 동작에 닿는 것: ### 11.1 결정 리뷰 반복은 여기서 멈춘다. Minor 19건은 사용자 지시("남은 부분 전부 진행")에 따라 마지막 정리 라운드(r6)로 고친다. r6의 멈춤 기준: 전체 게이트 통과 + r6 diff 확인 리뷰 1회에서 Important가 나오면 그것만 고치고, Minor는 남은 것으로 기록하고 더 돌지 않는다. + +## 12. 마지막 정리 라운드 r6 (Minor 19건, 2026-11-04) + +11.1절 결정대로 3차 확인 리뷰의 Minor 19건을 영역 묶음 4개가 `339cf8fd`에서 `test-driven-development` 절차로 고쳤다. 맡은 Minor 밖은 고치지 않고 보고만 하게 했다. + +| 묶음 | 발견 | 상태 | 검증 (에이전트) | 처리 내용 | 결정·남은 것 | +|---|---|---|---|---|---| +| r6-a core·inbound | RR3-01-01~04 | 완료 | application-core·service-runtime·inbound messaging·app-bootstrap check(systemTest 포함), architectureTest 208, architectureCheck, 실 PG16 | RR3-01-01 `@SystemCaller` 안의 중첩 클래스도 검사, 새 규칙 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(사용자 전송 → `@SystemCaller`를 직접·중간 클래스 경유 모두 거부, RED 3). RR3-01-02 전송 타입 목록에 `jakarta.ws.rs..`·`graphql..`(RED JAX-RS)와 "목록 방식" 문서. RR3-01-03 쿼터 보정 SQL이 COMMITTED 행 `reserved_bytes`를 0으로(RED 실 PG). RR3-01-04 scheduler·handler·예약 작업 세 경로를 매뉴얼 07장 표로 정본화하고 Javadoc·README·가드 문구를 맞춤 | 새 규칙은 직접 의존이 아니라 이어지는 의존 전체를 본다(중간 클래스 하나로 다시 열리지 않게, 실행 5.7초). 남음: `graphql..` 항목은 fixture 없음(graphql-java가 architectureTest classpath에 없다) | +| r6-b persistence·messaging | RR3-02-01~05 | 완료 | persistence-jpa check 611, sample check 339, `-p optional-platforms` grpc ledger check·integrationTest 46, `postgresqlMigrationLockWaitIntegrationTest` 5/5, outbox runbook lane, documentContractTest 62, architectureCheck | RR3-02-01 검사기가 `REFERENCES`·trigger·비동시 `REINDEX`·`REFRESH MATERIALIZED VIEW`·`CLUSTER`·`VACUUM FULL`을 잡고, `lock_timeout` 0·`DEFAULT`·`RESET`과 비트랜잭션(`.sql.conf executeInTransaction=false`) `SET LOCAL`을 상한으로 치지 않음(RED 19). 새로 걸린 배포 파일 5개는 내용 그대로 동결 목록에(main과 blob 같음). RR3-02-02 원인 세션을 `pg_locks`로 찾는 runbook 조회(실 PG). RR3-02-03 버전 판정을 testkit `VersionedMigrationFiles` 하나로(RED `V22_1`·`V22.2`). RR3-02-04 grpc ledger IT가 tree 전체 검사(RED). RR3-02-05 연관 규칙 메시지(RED 2) | grpc는 optional 빌드라 testkit을 못 써 실 PG IT로 검사(버전 정규식 한 벌 더). 남음: `spotbugsTestFixtures`(게이트 밖) ReDoS 경고 8→15 | +| r6-c outbound·멱등성 | RR3-03-01~05 | 완료 | 6개 leaf check, architectureCheck, verifyEnvKeys, redisContainerContractTest 59/59, PG 멱등성 계약 20/20, httpclient 성능 5·장애 주입 4, documentContractTest 62, repositoryContractTest 69 | RR3-03-01 watchdog을 전용 데몬 스레드(`httpclient-jdk-read-idle`)로, close 시 작업 취소(RED 공용 풀 포화 시 300ms 설정이 5,995ms → 수정 후 300ms, read당 비용 21–24ns 그대로). RR3-03-02 `failure-retention` 수명 문서. RR3-03-03 회복 필요 예외 메시지 끝에 scope digest(RED 3), runbook에 Redis·PG 기록 조회와 ABANDONED만 지우는 절차(실 Redis 7.4·PG 16). RR3-03-04 옛 표현. RR3-03-05 INSPECT가 `leaseUntil`을 돌려줌(RED 실 Redis) | `failure-retention ≥ replay-ttl` 기동 검사는 넣지 않음(지금 뜨는 설정을 깨지 않게, 문서만 — 소유자 판단). 본 것: gRPC는 carrier 실패를 로그에 남기지 않아 digest를 찾을 수 없다 | +| r6-d bootstrap·build | RR3-04-01~05 | 완료(RR3-04-03은 문서) | `-p build-logic check`, support·redis-sdk·sample·app-bootstrap check, verifyEnvKeys, 두 빌드 verifyStrictLaneStages, systemTest 11, documentContractTest 62, `SampleDemoProfilesStartupSystemTest` 3 | RR3-04-01 규칙을 돌리기 전에 비밀 목록 bean을 만들어 실제 클래스를 검사(모든 프로필, RED). RR3-04-02 붙여 쓴 `-x`·`-p`(RED). RR3-04-03 코드가 든 Redis 계정 참조는 조립하는 쪽이 `static RequiredProductionSecrets` bean을 두는 방법을 문서로. RR3-04-04 "선언된 property" 계산을 classpath 기준 하나로(RED). RR3-04-05 주석 | RR3-04-03 코드 수정은 redis-sdk에 새 의존 edge가 필요하거나 G-7c 결정을 되돌려야 해서 하지 않음. 남음: `-mx` 같은 짧은 플래그 묶음은 읽지 않음, 바뀐 기동 실패 문구에 맞추던 로그 매처 | + +합칠 때 오케스트레이터: 업그레이드 안내 B-14·B-15(r6-d)와 B-16(r6-a)을 손으로 합쳤고, r6-c가 남긴 동작 변경 두 줄(JDK watchdog 스레드, 회복 필요 메시지의 scope digest·INSPECT `leaseUntil`)을 5절에 더했다. + +### 12.1 게이트 (2026-11-04, 합친 메인 작업 트리, 공유 잠금) + +첫 실행에서 모두 통과했다. + +| 게이트 | 결과 | 시간 | 실행 직전 부하(1분) | +|---|---|---|---| +| `ci` | rc=0 | 6분 22초 | 2.31 | +| `verifyStrictLaneStages --dry-run` (주 빌드 / `-p optional-platforms`) | rc=0 / rc=0 | 11초 / 3초 | 16.09 / 14.51 | +| `mainCheck` | rc=0 | 3분 10초 | 13.90 | +| `:integrationCheck` | rc=0 | 14분 27초 | 10.98 | +| `-p optional-platforms ci integrationCheck performanceCheck` | rc=0 | 1분 | 2.32 | +| `:performanceCheck` | rc=0 | 22초 | 9.95 | +| `:releaseCheck -PgitRevision=` | rc=0 | 3초 | 7.81 | +| `scripts/verify-compose-profile-contracts.sh` | rc=0, 18 lane | — | 8.31 | + +다음: 이 커밋만 보는 확인 리뷰 1회. Important가 나오면 그것만 고치고, Minor는 남은 것으로 기록한다(11.1절). diff --git a/docs/runbooks/idempotency-unavailable.md b/docs/runbooks/idempotency-unavailable.md index 423a05cc..cf32d735 100644 --- a/docs/runbooks/idempotency-unavailable.md +++ b/docs/runbooks/idempotency-unavailable.md @@ -4,7 +4,7 @@ category: TRANSIENT_DEPENDENCY error_codes: [IDEMPOTENCY_UNAVAILABLE, IDEMPOTENCY_COMPLETION_UNKNOWN, IDEMPOTENCY_RECOVERY_REQUIRED] severity: P2 owner: oncall -last_updated: 2026-11-03 +last_updated: 2026-11-04 status: active --- @@ -18,11 +18,18 @@ status: active `app.idempotency` selects) did not answer. Nothing was executed: the refusal happens before the action, so a client retry is safe. - HTTP 503 `IDEMPOTENCY_COMPLETION_UNKNOWN` (`retryable=true`) is the same outage hitting after the - action ran: the store did not answer while the result was being recorded. Effects in the action's - own transaction rolled back; anything else it did (an outbound call, a message) may have happened. - This is not "nothing was executed". Clients resend with the same key. + action ran: the store did not answer while the result was being recorded. When the use case called + the executor inside its write transaction, that transaction's database writes rolled back with the + exception; an action that committed a transaction of its own kept its writes, and anything outside + a transaction (an outbound call, a message) may have happened. This is not "nothing was executed". + Clients resend with the same key. - HTTP 500 `IDEMPOTENCY_RECOVERY_REQUIRED` (`retryable=false`) means the opposite case: the store - cannot tell whether an earlier attempt's external effect already happened. + cannot tell whether an earlier attempt's effect already happened. The usual cause: an attempt + started and its processing lease (`APP_IDEMPOTENCY_PROCESSING_LEASE`, 30s) ran out before it + recorded a result — it crashed, or ran longer than the lease. The next request with the key marks + the record abandoned and every later one gets this 500; the server never runs it again, and a late + result from the first attempt is not recorded either. An action that threw, or reported its effect + unknown, is abandoned the same way. ## Diagnosis @@ -30,8 +37,37 @@ status: active JPA datasource or Redis, depending on the selected provider). - Look for connection-pool saturation or timeouts on that store in the same time window; the executor reports saturation as unavailable rather than guessing. -- For `IDEMPOTENCY_RECOVERY_REQUIRED`, find the scope digest in the server log line of the failed - request and inspect that record's state in the store. +- For `IDEMPOTENCY_RECOVERY_REQUIRED`, find the scope in the server's ERROR log of the failed request + (the web adapter logs `failure classified as IDEMPOTENCY_RECOVERY_REQUIRED` with the exception, + under the request's `X-Request-Id`). The exception message ends with + `::v::`, for example + `claim requires reconciliation: CHARGE_CARD::v1::3f9a…` (64 hex characters). Then look at the + record in the store the service uses (`APP_IDEMPOTENCY_PROVIDER`). There is no tool for this; these + are the commands. + - Redis. The key is + `:::idem:v1:d::`, + for example `prod:order:shared:idem:v1:d1:CHARGE_CARD:3f9a…`. + + ``` + HMGET state attempt leaseUntil + PTTL + ``` + + `state` `ABANDONED` is the recovery-required record. `leaseUntil` is the lease end in epoch + milliseconds (server clock); `PTTL` is how long the record still lives, in milliseconds. + - PostgreSQL, in the application's schema: + + ```sql + SELECT status, attempt, failure_disposition, last_transition_kind, + processing_lease_until, expires_at, updated_at + FROM idempotency_record + WHERE record_version = 2 + AND scope_hash = ''; + ``` + + `last_transition_kind` `EXPIRED_EXECUTION` means the lease ran out (the first attempt may still + have finished its work); `FAIL_ABANDONED` means the action threw or reported its effect unknown. + `expires_at` is when the reaper deletes the row. ## Action @@ -40,9 +76,29 @@ status: active transaction for the failed requests (the ERROR log line names the code). A same-key resend replays a result that was in fact recorded, gets `IDEMPOTENT_IN_FLIGHT` while the attempt's lease lasts, and `IDEMPOTENCY_RECOVERY_REQUIRED` after it — handle that one as below. -- `IDEMPOTENCY_RECOVERY_REQUIRED`: do not ask the client to retry blindly. Confirm whether the - downstream effect of the earlier attempt exists, then complete or release the record so the next - request with that key replays or re-executes deterministically. +- `IDEMPOTENCY_RECOVERY_REQUIRED`: do not ask the client to retry blindly. Confirm from business data + (the order, the payment, the downstream system) whether the earlier attempt's effect exists. There + is no way to complete the record by hand — the stored response is the action's own result. + - The effect exists: tell the client it was applied. Leave the record; a resend with the key keeps + getting this 500 until the record expires (Redis `PTTL`, PostgreSQL `expires_at`). + - The effect does not exist: the client sends the request again under a new key. To let the same + key run again instead, delete the record — only while it is `ABANDONED`, because any other state + belongs to a request in progress or a stored result: + - Redis: check `HMGET state` is `ABANDONED` and `PTTL ` has minutes left, then + `DEL `. A record that is about to expire needs nothing; once it is gone the key is new. + - PostgreSQL: + + ```sql + DELETE FROM idempotency_record + WHERE record_version = 2 + AND scope_hash = '' + AND status = 'ABANDONED'; + ``` + + Without either step the key is released when the record expires. That record lives for the + processing lease plus `APP_IDEMPOTENCY_TTL` from its claim when its lease ran out, and for + `APP_IDEMPOTENCY_FAILURE_RETENTION` from the failure when the action failed + (`docs/web/http-contract.md`, "서버가 기억하는 기간"). ## Escalation diff --git a/docs/runbooks/migration-failed.md b/docs/runbooks/migration-failed.md index 4a1c5c32..a2988d75 100644 --- a/docs/runbooks/migration-failed.md +++ b/docs/runbooks/migration-failed.md @@ -44,9 +44,20 @@ status: active migration that locks a table already in use gives up after its own `SET LOCAL lock_timeout` (5 s; SQLState `55P03` `lock_not_available`) and rolls back whole, so the history ends one version below it. The blocker is a transaction that touched the table and is still open — - often an idle-in-transaction session: `SELECT pid, state, xact_start, query FROM - pg_stat_activity WHERE xact_start < now() - interval '5 seconds' ORDER BY xact_start;`. End - it, then rerun (`docs/jpa/migration-guide.md` "Bound the lock wait"); + often an idle-in-transaction session. Find it by the lock it holds on that table (`
        ` + is the table the failing statement locks; for a `REFERENCES`, also the table it references): + + ```sql + SELECT DISTINCT a.pid, a.state, a.xact_start, a.query + FROM pg_locks l JOIN pg_stat_activity a USING (pid) + WHERE l.relation = '
        '::regclass AND l.granted AND a.pid <> pg_backend_pid() + ORDER BY a.xact_start; + ``` + + `query` is only that session's last statement, not the one that touched the table, so do not + look for the table name in it. Listing every long transaction instead names unrelated ones + (reports, batches) beside the blocker. End the blocker, then rerun + (`docs/jpa/migration-guide.md` "Bound the lock wait"); - SQL/data precondition: create a new forward migration that makes the precondition explicit; a duplicate outbox order key stopping V21 (`ux_outbox_event_aggregate_order`) is the known case — clean it up with `outbox-dead-letter.md` §8 and rerun, the migration stays as it is; diff --git a/docs/runbooks/outbox-dead-letter.md b/docs/runbooks/outbox-dead-letter.md index 1ccd6d13..0e6b4375 100644 --- a/docs/runbooks/outbox-dead-letter.md +++ b/docs/runbooks/outbox-dead-letter.md @@ -129,8 +129,17 @@ V20(`deferred_attempt_count`)과 V22(`last_failure_code`)도 같은 상한을 둘 다 `ALTER TABLE outbox_event`라 가장 강한 잠금(ACCESS EXCLUSIVE)을 건다. 이 잠금은 읽기와도 충돌하므로, `outbox_event`를 읽기만 한 트랜잭션 하나(운영자가 `BEGIN` 안에서 조회하고 둔 psql 세션 포함)가 열려 있어도 기다린다. 5초 안에 못 잡으면 그 마이그레이션이 실패·롤백되고 DB는 한 버전 아래(V19 또는 V21)에 남으며 새 버전은 -기동하지 않는다(`MIGRATION_FAILED`, exit 70). 열린 트랜잭션을 찾아 끝낸 뒤 다시 배포한다 — -`SELECT pid, state, xact_start, query FROM pg_stat_activity WHERE xact_start < now() - interval '5 seconds' ORDER BY xact_start;` +기동하지 않는다(`MIGRATION_FAILED`, exit 70). `outbox_event`에 잠금을 쥔 열린 트랜잭션을 찾아 끝낸 뒤 다시 배포한다. + +```sql +SELECT DISTINCT a.pid, a.state, a.xact_start, a.query +FROM pg_locks l JOIN pg_stat_activity a USING (pid) +WHERE l.relation = 'outbox_event'::regclass AND l.granted AND a.pid <> pg_backend_pid() +ORDER BY a.xact_start; +``` + +`query`는 그 세션의 마지막 문장일 뿐이다. `outbox_event`를 읽은 뒤 다른 문장을 실행한 세션이면 표 이름이 보이지 +않으니 `query`로 원인을 고르지 않는다. 오래 열린 트랜잭션을 모두 보는 조회는 보고·배치 같은 무관한 트랜잭션까지 낸다. rolling 배포 중 아직 옛 버전인 인스턴스가 벽시계 번호로 쓴 행은 floor보다 크다. 새 버전의 counter는 그 aggregate의 가장 큰 행 번호보다 작아지지 않으므로 그 행 뒤에 번호를 준다. 서로 커밋되지 않은 채 diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index 995b634a..1a6f5cbc 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -22,7 +22,7 @@ | 1 | JWT 모드면 `APP_SECURITY_JWT_AUDIENCE`에 이 서비스의 client id를 쉼표로 넣는다 | 기동 실패 `APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required` | JWT 모드(기본값) 전부 | | 2 | dev·prod 환경 변수의 `APP_FLYWAY_ENABLED` 값을 확인한다 | `false`가 남아 있으면 이제 정말로 마이그레이션이 안 돈다 | persistence-jpa 선택 | | 3 | prod 비밀값(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/`이 가리키는 변수)이 `fixture-`로 시작하지 않게 한다 | prod 기동 실패(exit 78) | prod 배포 전부 | -| 4 | 직접 만든 `StartupRule`·`RequiredProductionSecrets` bean을 `static @Bean`, 의존성 없이 바꾸고, 그 클래스에서 `@Value`·`@Autowired` 멤버와 `@ConfigurationProperties`를 뺀다 | 기동 실패 `startup rule '<이름>' created [...]` 또는 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one`(exit 78) | 자기 rule이 있는 서비스 | +| 4 | 직접 만든 `StartupRule`·`RequiredProductionSecrets` bean을 `static @Bean`, 의존성 없이 바꾸고, 그 클래스에서 `@Value`·`@Autowired` 멤버와 `@ConfigurationProperties`를 뺀다 | 기동 실패 `startup rule or secret list '<이름>' created [...]` 또는 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one`(exit 78) | 자기 rule이 있는 서비스 | | 5 | 직접 구현한 outbox·발행·알림·파일 서버 포트를 새 시그니처로 고친다(3.1절) | 컴파일 오류 | 해당 포트를 구현·호출하는 서비스 | | 6 | `dev.caskeleton.application.outbound.*` import를 `application.secret.*`·`application.objectstorage.content.CallBudget`으로 바꾼다 | 컴파일 오류 | 해당 타입을 쓰는 서비스 | | 7 | 이벤트 id를 소문자 UUIDv7로 만들고 `IntegrationEventDraft`는 `IntegrationEventDrafts.draft(...)`로만 만든다 | 쓰기 요청이 `IllegalArgumentException`으로 실패, architectureTest 실패 | 통합 이벤트를 내는 서비스 | @@ -66,9 +66,9 @@ |---|---|---|---|---| | B-12 | JWT 모드에서 `APP_SECURITY_JWT_AUDIENCE` 필수(빈 값 거부, `${...}`가 안 풀린 값도 없는 값으로 봄). 토큰 `aud`가 목록 중 하나를 담아야 통과. `resource_access` role은 audience에 적은 client 것만 읽는다(realm role은 그대로) | 기동 실패 `APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required`(exit 코드 확인 못 함). `.env.example`이 `APP_SECURITY_JWT_AUDIENCE=`(빈 값)를 싣고 있다. 다른 client의 role에 기대던 권한이 사라짐 | client id를 쉼표로 넣는다. 다른 client role로 권한을 받던 사용자가 있는지 IdP에서 확인 | `34565130`(필수·role), `1400dc15`(안 풀린 `${...}`) · `src/adapter/inbound/web/.../auth/JwtDecoderConfig.java`, `.../JwtToAuthenticatedPrincipalConverter.java`, `.../settings/SecuritySettings.java` | | B-13 | `app.security.*` strict 바인딩: 접두어 아래 오타 키, 또는 설정·placeholder 어디에도 쓰이지 않는 `APP_SECURITY_*` 환경 변수가 기동을 막는다 | 기동 실패(메시지는 `StrictSettingsBinder`가 키 이름을 담아 냄, 정확한 문구 확인 못 함) | 쓰지 않는 `APP_SECURITY_*` 변수를 지운다 | `5786126c` · `SecuritySettings.bind`, `src/adapter/outbound/support/.../StrictSettingsBinder.java` | -| B-14 | prod 프로필에서 `fixture-`로 시작하는 비밀값을 거부(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/` 참조 대상. `HOSTNAME`·앱 이름 같은 비밀 아닌 값은 보지 않는다 — RR2-04-01). Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로 | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` | -| B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다. 두 타입의 클래스는 `@Value`·`@Autowired`·`@Inject`·`@Resource` 멤버, `@PostConstruct`·`@PreDestroy`, `@ConfigurationProperties`를 가질 수 없다(post-processor보다 먼저 만들어져 비어 있게 된다, RR2-04-03) | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule '<이름>' created [] while creating it ... Declare the rule with a static @Bean method ...`, 위 멤버가 있으면 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one: [...]`(둘 다 exit 78, 후자는 모든 프로필) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 값은 `violations(Environment)`가 받는 `Environment`에서 읽는다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` | -| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르면 architectureTest 실패 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 호출자(scheduler 등)에 넘기거나, 메시지 handler면 handler에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다(매뉴얼 09장 「소비」 4단계). `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd` · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` | +| B-14 | prod 프로필에서 `fixture-`로 시작하는 비밀값을 거부(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/` 참조 대상. `HOSTNAME`·앱 이름 같은 비밀 아닌 값은 보지 않는다 — RR2-04-01). Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로. Redis SDK admin 계정(`RedisAccountContribution`)을 조립했다면 그 변수를 `static` `RequiredProductionSecrets` bean으로도 낸다(코드에 든 참조는 검사가 보지 않는다, RR3-04-03, `src/adapter/outbound/redis-sdk/README.md`) | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` | +| B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다. 두 타입의 클래스는 `@Value`·`@Autowired`·`@Inject`·`@Resource` 멤버, `@PostConstruct`·`@PreDestroy`, `@ConfigurationProperties`를 가질 수 없다(post-processor보다 먼저 만들어져 비어 있게 된다, RR2-04-03) | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule or secret list '<이름>' created [] while creating it ... Declare the rule with a static @Bean method ...`, 위 멤버가 있으면 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one: [...]`(둘 다 exit 78, 둘 다 모든 프로필. runner가 rule과 비밀 목록을 프로필과 무관하게 먼저 만들어, 인터페이스 타입 `@Bean`이 돌려준 실제 클래스까지 본다, RR3-04-01) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 값은 `violations(Environment)`가 받는 `Environment`에서 읽는다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` | +| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르거나, 사용자 전송(controller 등)이 `@SystemCaller` bean을 직접·중간 클래스를 거쳐 부르면 architectureTest 실패 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 스케줄러에 넘기거나, 메시지 handler·예약 작업이면 그 클래스에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다. 예약 작업은 서비스 leaf의 `..adapter.inbound.scheduler..` 패키지에 둔다. 세 경로와 두는 곳은 매뉴얼 07장 「시스템이 부르는 쓰기」(handler 작업 순서는 09장 「소비」 4단계). "지금 실행" endpoint가 필요하면 `@RequiresPermission` 유스케이스를 따로 만든다. `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd` · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` | | B-17 | `IntegrationEventDraft`: `eventId`·`causationId`는 소문자 UUIDv7만. ArchUnit `INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`: `new IntegrationEventDraft<>(...)` 금지, `IntegrationEventDrafts.draft(...)`만 | 이벤트를 만드는 쓰기 요청이 `IllegalArgumentException: eventId must be a canonical lower-case UUIDv7...`로 실패. architectureTest 실패 | event id를 UUIDv7로 만든다(예: sample `UuidOutboxEventIdFactory`가 `UuidCreator.getTimeOrderedEpochPlus1()`). draft는 헬퍼로 만든다. tenant가 없는 이벤트는 `IntegrationEventDrafts.SINGLE_TENANT_SCOPE`(`global`) | `1400dc15`, `bbe944bd` · `src/application-core/.../messaging/event/IntegrationEventDraft.java`, `IntegrationEventDrafts.java` | | B-18 | `MessageHandler.schemaVersions()`(vendored `messaging-core-api`, default `{v1}`): 소비자 decode 목록을 handler 선언으로 만든다. 같은 (메시지 타입, 버전)에 다른 payload class를 선언하면 실패 | 컴파일은 된다. v1이 아닌 메시지는 `SCHEMA_VERSION_NOT_REGISTERED`로 거부. 발행 등록(`MessageContracts`)과 class가 다르면 기동 실패 `MESSAGING_CONTRACT_CONFLICT` | v2 이상을 읽는 handler는 `schemaVersions()`를 override한다. 소비 타입을 `MessageContracts`에 따로 등록하던 코드는 지운다 | `5786126c` · `src/messaging/messaging-core-api/.../delivery/MessageHandler.java`, `messaging-spring-boot-starter/.../MessageContracts.java` | | B-19 | `APP_FLYWAY_ENABLED`가 모든 프로필에서 읽힌다. dev·prod 프로필 파일의 `spring.flyway.enabled: true`·`app.persistence.vendor` 고정값을 지우고 persistence-jpa `config/module-defaults`가 `${APP_FLYWAY_ENABLED:true}`를 싣는다 | dev·prod 환경에 `APP_FLYWAY_ENABLED=false`가 있으면 전에는 무시됐지만 이제 기동 때 마이그레이션이 안 돈다 | dev·prod 환경 값을 확인한다. 자기 `application-dev.yml`·`application-prod.yml`에 같은 고정값을 다시 넣지 않는다 | `5786126c` · `src/app-bootstrap/src/main/resources/application-{dev,prod}.yml`, `src/adapter/outbound/persistence-jpa/.../module-defaults/persistence-jpa.yml` | @@ -100,7 +100,7 @@ |---|---|---|---|---| | B-34 | 템플릿 패키지 규칙(ArchUnit): `FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`, `TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`. 템플릿 이름: application `usecase command query capability transaction security tenant observability secret messaging outbox idempotency operation lease lock cache realtime notification fileserver objectstorage`, domain `identifier stereotype` | 기능 패키지 이름이 이 목록과 겹치거나(예: `domain.lock`), 업무 코드를 템플릿 패키지(예: `application.usecase.*`)에 두고 기능 패키지를 import하면 `:app-bootstrap:architectureTest` 실패 | 기능 패키지 이름을 바꾸고, 업무 코드를 `dev.caskeleton.application.`로 옮긴다. 규칙 정본은 `src/application-core/CLAUDE.md` "Package ownership" | `5786126c` · `src/app-bootstrap/src/architectureTest/.../TemplatePackageOwnership.java` | | B-35 | JPA 규칙: 양방향 연관은 한쪽에서만 매핑(`mappedBy`), notification·fileserver 저장소 엔티티는 그 leaf 안에서만, `@Version` 엔티티의 bulk update는 version을 올려야 함 | 위반 엔티티·쿼리가 있으면 architectureTest 실패 | 매핑·쿼리를 고친다 | `34565130`, `1400dc15`, `bbe944bd` · `src/app-bootstrap/src/architectureTest/.../JpaProductionArchitectureTest.java` | -| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. 명령의 빌드는 `working-directory`(단계·job·workflow `defaults`)와 `-p`를 합친 디렉터리로 정하고, `workflow_dispatch`로만 시작하는 workflow의 명령은 세지 않으며, 축약한 `-x`도 Gradle처럼 맞춰 본다(RR2-04-04). `verifyEnvKeys`: lane 계약 json의 `APP_` 밖 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_`이거나 `secret://…/`가 가리키는 변수여야 하고, 레지스트리 `property:` 행은 그 property가 설정 metadata에 있어야 읽히는 것으로 친다(`@ConditionalOnProperty`로만 읽는 스위치는 `META-INF/additional-spring-configuration-metadata.json`에 선언, RR2-04-05). SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다. `working-directory: src` 없이 `./gradlew`를 부르는 자기 workflow 단계는 실행으로 세지 않는다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. 단계를 부르는 workflow 명령에 `working-directory`를 둔다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c` · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` | +| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. 명령의 빌드는 `working-directory`(단계·job·workflow `defaults`)와 `-p`를 합친 디렉터리로 정하고, `workflow_dispatch`로만 시작하는 workflow의 명령은 세지 않으며, 축약한 `-x`도 Gradle처럼 맞춰 본다(RR2-04-04). 붙여 쓴 `-x`·`-p`도 Gradle처럼 읽는다(RR3-04-02). `verifyEnvKeys`: lane 계약 json의 `APP_` 밖 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_`이거나 `secret://…/`가 가리키는 변수여야 하고, 레지스트리 `property:` 행은 그 property가 설정 metadata에 있어야 읽히는 것으로 친다(`@ConditionalOnProperty`로만 읽는 스위치는 `META-INF/additional-spring-configuration-metadata.json`에 선언, RR2-04-05). SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다. `working-directory: src` 없이 `./gradlew`를 부르는 자기 workflow 단계는 실행으로 세지 않는다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. 단계를 부르는 workflow 명령에 `working-directory`를 둔다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c` · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` | | B-37 | app-bootstrap 테스트 lane 분리: 저장소 파일을 읽는 테스트는 태그 `document-contract`(main 단계) 또는 `repository-contract`(`check`)여야 하고, 일반 `test` lane에는 `ca.repository.root`가 없다 | app-bootstrap에 둔 자기 테스트가 저장소 파일을 읽으면 `test`에서 실패 | 태그를 단다 | `1400dc15` · `src/app-bootstrap/build.gradle` | ### 3.5 모듈 registry·새 leaf @@ -132,6 +132,11 @@ `SET LOCAL lock_timeout = '5s'`를 둔다. 실패하면 SQLState `55P03`이고, 열린 트랜잭션을 끝낸 뒤 다시 배포한다 (`docs/runbooks/migration-failed.md` "Classify the failure"). 자기 스트림에도 같은 규칙과 검사 (`LockWaitMigrationInspector`, 예: `SampleMigrationLockWaitTest`)를 둔다(`docs/jpa/migration-guide.md` "Bound the lock wait"). + 검사기는 3차 확인 리뷰(RR3-02-01) 뒤로 기존 테이블을 가리키는 `REFERENCES`, trigger 만들기·지우기, `REINDEX` 등을 더 잡고, + `CREATE TABLE IF NOT EXISTS`를 "이 마이그레이션이 만든 테이블"로 세지 않으며, 0인 `lock_timeout`과 `executeInTransaction=false` + 파일의 `SET LOCAL`을 상한으로 세지 않는다. 자기 스트림의 이미 배포된 파일이 새로 걸리면 그 파일은 고치지 않고 규칙 이전 + 목록에 더한다(템플릿은 idempotency V1, notification V3, messaging V1003, postgresql V11·V12를 더했다). 파일 경로를 넘기는 + `unboundedLockingStatements(Path)`가 옆의 `.sql.conf`까지 읽으니, 복사한 검사는 문자열 대신 경로를 넘긴다. - **번호 충돌**: 템플릿이 이제 postgresql V20~V22, notification V11~V13, sample V8_1, grpc V002·V003을 쓴다. 파생 서비스가 같은 위치에 같은 번호를 두었다면 Flyway가 같은 버전 두 개로 실패한다. 자기 마이그레이션은 템플릿과 떨어진 번호대로 옮긴다 (이미 적용된 파일 이름을 바꾸면 checksum·history가 어긋나므로 운영 DB에 적용된 것이면 DB 담당과 정한다). @@ -212,6 +217,8 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | 로그 설정 | logback이 `APP_LOG_*` 대신 `app.logging.*`을 읽는다(환경 변수 이름은 그대로 매핑) | 프로필 yml의 `app.logging.*`이 이제 먹힌다 | `1400dc15` · `logback-spring.xml` | | local 프로필 | `server.port`가 `${APP_SERVER_PORT:8080}`을 읽는다. Flyway·`ddl-auto validate`·PostgreSQL vendor를 module-defaults에서 받는다 | local에서 `APP_SERVER_PORT`가 다른 값이면 포트가 바뀐다 | `1400dc15`, `5786126c` · `application-local.yml` | | deprecated | `APP_CACHE_REDIS_TTL_JITTER`는 아무것도 바인딩하지 않음(`removal_deadline: 2027-02-28`) | 값이 아무 효과 없다 | `1400dc15` · `env-keys.yaml` | +| HTTP client(JDK transport) | 스트리밍 응답의 read-idle 감시가 전용 데몬 스레드 하나(`httpclient-jdk-read-idle`)에서 돈다. 스트림마다 감시 작업 하나, 스트림을 닫으면 작업을 바로 취소 | 스레드 덤프에 그 스레드가 하나 보인다. 공용 `ForkJoinPool`이 바빠도 timeout이 설정값에 난다(전에는 늦게 났다). Apache transport(기본)는 영향 없음 | 3차 확인 리뷰 RR3-03-01 · `src/adapter/outbound/httpclient/.../jdk/ReadIdleInputStream.java` | +| 멱등성 | `IDEMPOTENCY_RECOVERY_REQUIRED`를 내는 예외 메시지 끝에 scope digest가 붙는다. Redis 기록 조회(INSPECT 스크립트)가 `leaseUntil`을 돌려줘 `processingLeaseUntil`이 실제 lease 끝이다(전에는 key TTL 끝, 즉 lease + replay TTL) | 예외 메시지 전체에 맞추던 로그 매처는 고친다. 회복 절차는 `docs/runbooks/idempotency-unavailable.md`(digest로 기록을 찾는다) | 3차 확인 리뷰 RR3-03-03·05 · `src/application-core/.../idempotency/IdempotencyRecoveryRequiredException.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java` | | sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` | ## 6. 따라오는 순서 diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index de18900b..50edc581 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -122,9 +122,19 @@ status는 코드 표(`HttpStatusErrorCodes`)에 있는 것만 그대로 나간 요청이 만나면 두 저장소(PostgreSQL·Redis) 모두 넘겨주지 않고 포기(abandoned)로 표시한다 — 그 뒤 첫 시도가 늦게 끝나도 결과는 기록되지 않고 그 요청도 500을 받는다. 새 키로 보내면 서버는 다른 요청으로 보고 막지 못한다 (재리뷰 2026-11-03 README 4절 결정 RR-02-03, 2026-11-04 9.1절 결정 RR-01-11). -- **서버가 기억하는 기간.** 완료된 응답은 완료부터 `replay-ttl`(기본 24h), 끝나지 않은 시도의 기록은 - claim부터 processing lease + `replay-ttl` 동안 남는다. 그 뒤 같은 키는 새 요청으로 실행된다. +- **서버가 기억하는 기간.** 위 판정은 기록이 남아 있는 동안만 선다. 기록이 사라지면 같은 키는 새 + 요청으로 실행된다. 기록의 수명은 시도가 어떻게 끝났는지로 갈린다. + - 완료된 응답: 완료부터 `replay-ttl`(`APP_IDEMPOTENCY_TTL`, 기본 24h). + - 끝나지 않은 시도: claim부터 processing lease + `replay-ttl`. lease가 지나 다음 요청이 포기로 표시한 + 기록도 이 수명을 그대로 쓴다. + - 실패로 표시된 시도: 작업이 예외를 던졌거나 효과 불명으로 끝나 포기(abandoned)된 시도, 효과 없이 + 재시도 가능으로 끝난 시도. 표시한 때부터 `failure-retention`(`APP_IDEMPOTENCY_FAILURE_RETENTION`, + 기본 24h). + `replay-ttl`이 `processing-lease`보다 짧으면 기동이 실패한다(재리뷰 2026-11-04 RR-03-11). + `failure-retention`은 `replay-ttl`과 비교하지 않는다. 더 짧게 두면 효과 불명으로 포기한 기록이 그만큼 + 먼저 사라지고, 그 뒤 같은 키 재전송은 작업을 다시 돌린다. 그래서 `replay-ttl` 이상으로 둔다 + (재리뷰 2026-11-04 RR3-03-02). ## 3. 헤더 diff --git a/infra/redis-sdk/acl/README.md b/infra/redis-sdk/acl/README.md index 6c20d498..cbbfd494 100644 --- a/infra/redis-sdk/acl/README.md +++ b/infra/redis-sdk/acl/README.md @@ -9,8 +9,12 @@ control of it (`CONFIG`, `MODULE`, every key). A deployment writes its own ACL f shape: the application accounts it actually uses, passwords from its secret store, and none of the lane-only accounts (review 2026-11-03 RR-07-04). The application enforces its half of that: under the `prod` runtime profile it refuses to start while a secret holds a value beginning with -`fixture-` (`SecretSourceValidator`): a key the secrets registry classifies `secret`, or the -variable a `secret://…/` credential reference names. A deployment that copied a lane's +`fixture-` (`SecretSourceValidator`): a key the secrets registry classifies `secret`, a variable a +module's `RequiredProductionSecrets` bean names, or the variable a `secret://…/` credential +reference in the environment names. A reference held in code — the typed SDK's admin account, +contributed as a `RedisAccountContribution` bean — is none of those: the composer names its variable +in a `RequiredProductionSecrets` bean too (`src/adapter/outbound/redis-sdk/README.md`), or the +`fixture-admin` password passes. A deployment that copied a lane's `APP_REDIS_AUTHENTICATION_*_REFERENCE` and `REDIS_LANE_*` values stops before it connects. Values that are not secrets — a pod's `HOSTNAME`, an application name — are not read, because `fixture-` is an ordinary word as well. diff --git a/src/.env.example b/src/.env.example index e1b49131..a15941b3 100644 --- a/src/.env.example +++ b/src/.env.example @@ -128,6 +128,7 @@ APP_IDEMPOTENCY_TTL=24h APP_IDEMPOTENCY_PROVIDER=disabled APP_IDEMPOTENCY_REDIS_NAMESPACE_ENVIRONMENT=local APP_IDEMPOTENCY_PROCESSING_LEASE=30s +# Failure retention: at most 30d. Not checked against APP_IDEMPOTENCY_TTL; keep it at least that long. APP_IDEMPOTENCY_FAILURE_RETENTION=24h APP_LEASE_PROVIDER=disabled APP_LEASE_REDIS_NAMESPACE_ENVIRONMENT=local diff --git a/src/adapter/inbound/messaging/CLAUDE.md b/src/adapter/inbound/messaging/CLAUDE.md index a13b56d8..2eaacaa0 100644 --- a/src/adapter/inbound/messaging/CLAUDE.md +++ b/src/adapter/inbound/messaging/CLAUDE.md @@ -11,8 +11,10 @@ - Boundaries: no business rule in a handler (HARD-STOP 4); no persistence entity or repository; no broker SDK type. Allowed edges come only from the registry entry. - A handler that calls a write use case is `@SystemCaller(reason = ...)` and constructs the - `@SystemInvoked` use case itself; the use case is never a bean (manual 09 「소비」 step 4, - `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`). + `@SystemInvoked` use case itself; the use case is never a bean, and no user transport calls the + handler (manual 09 「소비」 step 4, manual 07 「시스템이 부르는 쓰기」, + `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, + `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`). - Tests: focused auto-configuration and inbox behavior tests; `./gradlew :adapter:inbound:messaging:check`. The real Kafka + PostgreSQL redelivery lane is `messagingInboxRedeliveryIntegrationTest` (`:integrationCheck`). diff --git a/src/adapter/inbound/messaging/README.md b/src/adapter/inbound/messaging/README.md index 3443f2a8..a457a018 100644 --- a/src/adapter/inbound/messaging/README.md +++ b/src/adapter/inbound/messaging/README.md @@ -103,8 +103,10 @@ PostgreSQL에서 같은 모양은 `InboxRedeliveryIntegrationTest`의 `Projectio `messaging-core-api`만 보는 anti-corruption 경계이고, 소비는 inbound 방향이다. - 고름(RR-01-12): handler가 `@SystemCaller`를 달고 `@SystemInvoked` use case를 직접 `new`로 만든다. 사용자 요청이 들어오는 전송(web·GraphQL·gRPC·WebSocket)만 그 use case에 닿지 못하고, 표시는 ArchUnit이 검사한다 - (`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`: messaging·scheduler inbound 패키지에만, 사용자 전송 - 타입에 의존하지 않음). 기동 가드는 바꾸지 않는다: `@SystemInvoked` bean은 예외 없이 실패다. + (`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`: 표시한 클래스와 그 안에 중첩된 클래스는 messaging· + scheduler inbound 패키지에만, 사용자 전송 타입에 의존하지 않음). 사용자 전송이 handler bean을 주입받아 + 부르는 길은 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`가 막는다(RR3-01-01). 기동 가드는 바꾸지 않는다: + `@SystemInvoked` bean은 예외 없이 실패다. 규칙 전체는 매뉴얼 07장 「시스템이 부르는 쓰기」. - 버림: use case를 bean으로 두고 가드에 "handler만 주입받으면 허용" 예외 — 누가 주입받는지는 기동 때 확정되지 않는다(`ObjectProvider`, `getBean`, 나중에 추가된 bean). 예외 조건이 곧 우회 경로가 된다. - 버림: handler는 `CommandUseCase` 인터페이스만 받고 조립 모듈이 `new`로 넣기 — 소비자마다 composition @@ -113,7 +115,9 @@ PostgreSQL에서 같은 모양은 `InboxRedeliveryIntegrationTest`의 `Projectio - 버림: ArchUnit 대상에서 messaging 패키지를 통째로 빼기 — 클래스에 표시가 없어 의도가 안 보이고, 그 패키지의 아무 클래스(HTTP endpoint 포함)나 닿는다. - 버림: 사용자 전송 패키지만 나열해 금지 — 나중에 새 전송이 생기면 조용히 열린다. 규칙은 "닿아도 되는 - 쪽"을 적는다. + 쪽"을 적는다. 이 성질은 패키지 쪽에만 있다: 시스템 패키지 안에 놓인 endpoint를 알아보는 사용자 전송 + **타입**은 나열 목록이다(`ARE_USER_TRANSPORT_TYPES`, JAX-RS·graphql-java 포함). 새 전송 라이브러리를 + 들이면 그 목록에 더한다(RR3-01-02). - 버림: application-core에 소비 포트를 새로 만들어 platform `MessageHandler`로 감싸는 범용 bridge — payload 타입 매핑과 결과 매핑 규칙을 먼저 정해야 해서 이번 범위보다 크다. 지금은 handler가 직접 use case를 부른다. diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java index 7e47507c..43c967e3 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java @@ -243,7 +243,14 @@ public final class IdempotencyScripts { return {'APPLIED', attempt, rev, owner, '', ''} """; - /** Inspect: read the record without touching it. */ + /** + * Inspect: read the record without touching it. + * + *

        The detail is {@code ownership|key PTTL|leaseUntil}. A completed record's replay deadline is + * its key's TTL; an in-progress record's lease is not, because its key lives for the lease plus + * {@code afterLease} — reading the lease off the TTL reported it a replay TTL too late (re-review + * 2026-11-04 RR3-03-05). + */ private static final String INSPECT = """ local state = redis.call('HGET', KEYS[1], 'state') @@ -268,7 +275,8 @@ public final class IdempotencyScripts { end return {state, attempt, rev, owner, redis.call('HGET', KEYS[1], 'resp') or '', - mine .. '|' .. tostring(redis.call('PTTL', KEYS[1]))} + mine .. '|' .. tostring(redis.call('PTTL', KEYS[1])) .. '|' + .. (redis.call('HGET', KEYS[1], 'leaseUntil') or '')} """; private final RegisteredLuaScript claim = new RegisteredLuaScript(CLAIM); diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java index c0bbb8c5..65249e1f 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java @@ -361,9 +361,16 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort if (reply.status() == ScriptStatus.FINGERPRINT_MISMATCH) { return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.FINGERPRINT_MISMATCH); } - String[] detail = reply.detail().split("\\|", 2); + String[] detail = reply.detail().split("\\|", 3); String ownership = detail[0]; long ttlMillis = detail.length > 1 ? parseLong(detail[1]) : 0; + // The lease the record carries, in server time as the claim reported it — not the key's TTL, + // which runs a replay TTL past the lease (RR3-03-05). + long leaseUntilMillis = detail.length > 2 ? parseLong(detail[2]) : 0; + Optional leaseUntil = + leaseUntilMillis > 0 + ? Optional.of(Instant.ofEpochMilli(leaseUntilMillis)) + : Optional.empty(); if ("OPERATION_CONFLICT".equals(ownership)) { return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.OPERATION_CONFLICT); } @@ -390,7 +397,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort ? new IdempotencyInspection( IdempotencyInspectionOutcome.CLAIMED_SAME_OPERATION, Optional.of(handle), - Optional.of(now.plusMillis(Math.max(1, ttlMillis))), + leaseUntil, Optional.empty(), Optional.empty()) : IdempotencyInspection.outcome(IdempotencyInspectionOutcome.IN_PROGRESS_OTHER); @@ -399,7 +406,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort ? new IdempotencyInspection( IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION, Optional.of(handle), - Optional.of(now.plusMillis(Math.max(1, ttlMillis))), + leaseUntil, Optional.empty(), Optional.empty()) : IdempotencyInspection.outcome(IdempotencyInspectionOutcome.IN_PROGRESS_OTHER); diff --git a/src/adapter/outbound/httpclient/README.md b/src/adapter/outbound/httpclient/README.md index f79afca1..bb5e72f4 100644 --- a/src/adapter/outbound/httpclient/README.md +++ b/src/adapter/outbound/httpclient/README.md @@ -42,11 +42,12 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d left, the experimental Jetty HTTP/3 transport aborts the request, and the caller gets `HttpDeadlineExceededException`. A streaming download's setup (up to the response headers) runs inside the same deadline; after hand-over each body gap is bounded by `read-idle` and nothing else, - on both transports — the JDK transport arms its own per-read timer for this, because the JDK client - has no socket read timeout. A body that fails after hand-over throws `HttpBodyReadException`, an - `IOException` as `InputStream.read` promises, whose `failure()` is the same stable exception a - buffered call throws (`HttpResponseTimeoutException` for a stalled body, - `HttpResponseTruncatedException` for a cut one). + on both transports — on the JDK transport, which has no socket read timeout, a per-stream watchdog + on its own daemon thread (`httpclient-jdk-read-idle`) bounds each read's wait. A body that fails + after hand-over throws `HttpBodyReadException`, an `IOException` as `InputStream.read` promises, + whose `failure()` is the same stable exception a buffered call throws + (`HttpResponseTimeoutException` for a stalled body, `HttpResponseTruncatedException` for a cut + one). - **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or `PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it. - **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline, diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java index a836ec1d..36ffbdc2 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java @@ -6,7 +6,9 @@ import java.io.InputStream; import java.net.SocketTimeoutException; import java.time.Duration; import java.util.Objects; -import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -31,6 +33,20 @@ import java.util.concurrent.atomic.AtomicBoolean; * it moves the queue off the shared scheduler but keeps a queue insertion and removal on every * read. * + *

        The watchdog wakes on a thread of its own: one daemon thread, {@code + * httpclient-jdk-read-idle}, shared by every JDK stream and started with the first (re-review + * 2026-11-04 RR3-03-01). It used to wake through {@code CompletableFuture.delayedExecutor}, whose + * task runs on the common {@code ForkJoinPool}; a service that filled that pool with blocking work + * — {@code supplyAsync(blockingCall)} without an executor — held every timeout until a pool thread + * came free, and a 300 ms {@code read-idle} ended after 2.7 s. The wake is O(1), and the close it + * may do waits on no I/O — the JDK body marks itself closed, cancels its subscription and wakes the + * read — so both run on this thread, as the per-read timer before RR-03-13 closed on the JDK's + * delay thread. Rejected: {@code delayedExecutor(delay, unit, Runnable::run)}, which judges on the + * JDK's own delay thread — that thread fires every {@code CompletableFuture} timeout in the + * process, so a slow close there would delay them all, and it returns no handle to take a closed + * stream's wake off the queue. Closing the stream cancels its pending wake, so a closed stream is + * not kept reachable until its {@code read-idle} passes. + * *

        {@link #skip} reads through this stream rather than delegating: the JDK body does not override * {@code skip}, so {@code InputStream.skip} ran many reads inside one guarded call and a long skip * over a steady body timed out as one long wait (re-review 2026-11-04 RR-03-12). @@ -53,10 +69,35 @@ final class ReadIdleInputStream extends FilterInputStream { private final AtomicBoolean idled = new AtomicBoolean(); private volatile long readStartedAt = NOT_READING; private volatile boolean closed; + private volatile ScheduledFuture pendingWake; + private final ScheduledExecutorService watchdogs; ReadIdleInputStream(InputStream delegate, Duration readIdle) { + this(delegate, readIdle, SharedWatchdogs.INSTANCE); + } + + /** The scheduler is a parameter so a test can see what a stream leaves queued on it. */ + ReadIdleInputStream(InputStream delegate, Duration readIdle, ScheduledExecutorService watchdogs) { super(Objects.requireNonNull(delegate, "body stream")); this.readIdleNanos = Objects.requireNonNull(readIdle, "read idle timeout").toNanos(); + this.watchdogs = Objects.requireNonNull(watchdogs, "watchdog scheduler"); + } + + /** + * A watchdog scheduler as every stream gets it: one daemon thread, and a cancelled wake leaves + * the queue at once instead of when it would have fired. + */ + static ScheduledThreadPoolExecutor newWatchdogs() { + ScheduledThreadPoolExecutor scheduler = + new ScheduledThreadPoolExecutor( + 1, + runnable -> { + Thread thread = new Thread(runnable, "httpclient-jdk-read-idle"); + thread.setDaemon(true); + return thread; + }); + scheduler.setRemoveOnCancelPolicy(true); + return scheduler; } @Override @@ -89,6 +130,7 @@ final class ReadIdleInputStream extends FilterInputStream { @Override public void close() throws IOException { closed = true; + cancelPendingWake(); super.close(); } @@ -113,7 +155,19 @@ final class ReadIdleInputStream extends FilterInputStream { /** Wakes the watchdog when a read that started at {@code started} reaches read-idle. */ private void watchFrom(long started) { long left = Math.max(0, readIdleNanos - (System.nanoTime() - started)); - CompletableFuture.delayedExecutor(left, TimeUnit.NANOSECONDS).execute(this::watch); + pendingWake = watchdogs.schedule(this::watch, left, TimeUnit.NANOSECONDS); + // A close between the watchdog's check and this schedule did not see the new wake; take it + // off here. Both sides write their own volatile before reading the other's. + if (closed) { + cancelPendingWake(); + } + } + + private void cancelPendingWake() { + ScheduledFuture wake = pendingWake; + if (wake != null) { + wake.cancel(false); + } } private void watch() { @@ -158,4 +212,12 @@ final class ReadIdleInputStream extends FilterInputStream { throw new SocketTimeoutException("no response body bytes within the read-idle timeout"); } } + + /** The scheduler every stream shares, started with the first stream that is read. */ + private static final class SharedWatchdogs { + + static final ScheduledExecutorService INSTANCE = newWatchdogs(); + + private SharedWatchdogs() {} + } } diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java index 6b70aa42..3f9ab53f 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java @@ -8,6 +8,8 @@ import java.io.InputStream; import java.net.SocketTimeoutException; import java.time.Duration; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -15,12 +17,14 @@ import org.junit.jupiter.api.Test; /** * What the JDK transport's read-idle bound promises: each read that waits longer than {@code * read-idle} for the server ends the body, and nothing else does (re-review 2026-11-04 RR-03-12, - * RR-03-13). + * RR-03-13); the watchdog keeps that time whatever the common pool is doing, and leaves nothing + * scheduled for a stream that is closed or timed out (RR3-03-01). */ class ReadIdleInputStreamTest { private static final Duration READ_IDLE = Duration.ofMillis(300); private static final Duration GAP = Duration.ofMillis(20); + private static final Duration COMMON_POOL_HOLD = Duration.ofSeconds(3); @Test @DisplayName("데이터가 read-idle보다 짧은 간격으로 오면 read-idle보다 오래 걸리는 skip도 끝까지 건너뛴다") @@ -67,6 +71,79 @@ class ReadIdleInputStreamTest { assertThat(waited).isGreaterThanOrEqualTo(READ_IDLE).isLessThan(READ_IDLE.multipliedBy(3)); } + @Test + @DisplayName("공용 ForkJoinPool이 블로킹 작업으로 차 있어도 멈춘 read는 read-idle 무렵에 끝난다") + void aStalledReadTimesOutOnTimeWhileTheCommonPoolIsBlocked() throws Exception { + // given + // Every common-pool worker parks on a latch, which does not make the pool add a spare thread — + // what a service's supplyAsync(blockingCall) without an executor does. The hold is bounded so + // a watchdog that needs a pool worker still ends the read, late (re-review 2026-11-04 + // RR3-03-01: 300 ms read-idle timed out after 2,699 ms). + int workers = Math.max(1, ForkJoinPool.getCommonPoolParallelism()); + CountDownLatch occupied = new CountDownLatch(workers); + CountDownLatch release = new CountDownLatch(1); + for (int task = 0; task < workers * 2; task++) { + ForkJoinPool.commonPool() + .execute( + () -> { + occupied.countDown(); + awaitQuietly(release, COMMON_POOL_HOLD); + }); + } + assertThat(occupied.await(5, TimeUnit.SECONDS)).as("every common-pool worker is held").isTrue(); + InputStream body = new ReadIdleInputStream(new StalledStream(), READ_IDLE); + long started = System.nanoTime(); + try { + // when + Throwable failure = catchThrowable(body::read); + + // then + Duration waited = Duration.ofNanos(System.nanoTime() - started); + assertThat(failure).isInstanceOf(SocketTimeoutException.class); + assertThat(waited).isGreaterThanOrEqualTo(READ_IDLE).isLessThan(READ_IDLE.multipliedBy(3)); + } finally { + release.countDown(); + } + } + + @Test + @DisplayName("스트림을 닫으면 그 스트림의 watchdog 예약이 스케줄러에서 바로 빠진다") + void closingTheStreamTakesItsWatchdogOffTheScheduler() throws IOException { + // given + ScheduledThreadPoolExecutor watchdogs = ReadIdleInputStream.newWatchdogs(); + try { + InputStream body = new ReadIdleInputStream(new DrippingStream(1, GAP), READ_IDLE, watchdogs); + body.read(); + + // when + body.close(); + + // then + assertThat(watchdogs.getQueue()).isEmpty(); + } finally { + watchdogs.shutdownNow(); + } + } + + @Test + @DisplayName("read-idle로 끝난 스트림은 닫지 않아도 watchdog을 더 예약하지 않는다") + void aStreamThatTimedOutLeavesNoWatchdogBehind() { + // given + ScheduledThreadPoolExecutor watchdogs = ReadIdleInputStream.newWatchdogs(); + try { + InputStream body = new ReadIdleInputStream(new StalledStream(), READ_IDLE, watchdogs); + + // when + Throwable failure = catchThrowable(body::read); + + // then + assertThat(failure).isInstanceOf(SocketTimeoutException.class); + assertThat(watchdogs.getQueue()).isEmpty(); + } finally { + watchdogs.shutdownNow(); + } + } + @Test @DisplayName("호출자가 read 사이에 오래 머문 시간은 read-idle로 세지 않는다") void timeTheCallerSpendsBetweenReadsIsNotIdle() throws Exception { @@ -83,6 +160,14 @@ class ReadIdleInputStreamTest { } } + private static void awaitQuietly(CountDownLatch latch, Duration atMost) { + try { + latch.await(atMost.toNanos(), TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + } + /** Gives one byte per read, each after {@code gap}. */ private static final class DrippingStream extends InputStream { diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index 5e489322..3b68d487 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -95,7 +95,8 @@ not grow by wiring accident. - OSIV is false in every runtime profile; Flyway owns schema change and Hibernate only validates. - A migration that locks a table already in use starts with `SET LOCAL lock_timeout = '5s';` (`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest` refuses one - without it; its list of migrations released before the rule only ever shrinks. + without it. Its list of migrations released before the rule never takes a new migration; it + grows only when the inspector learns a statement and finds it in a file already on `main`. - Metric tags, exception messages, and logs carry no SQL parameters, entity ids, tenant ids, or PII. - Contracts run against real PostgreSQL. H2 never satisfies one. diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java index 5495c145..657e03e4 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java @@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.testkit.migration.LockWaitMigrationInspector; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map; @@ -26,21 +25,30 @@ class MigrationLockWaitTest { * Migrations released before the rule, which wait without a bound and stay that way: they are * applied (on {@code main} when the rule came in), and an applied migration is never edited * ({@link AppliedMigrationImmutabilityTest}). Their waits are behind every database that ran - * them. Nothing is added here — a new migration bounds its wait. + * them. A new migration is never added here — it bounds its wait. The list grows only when the + * inspector learns a statement it did not know and finds it in a file released before the rule: + * {@code REFERENCES} on an existing table, and a {@code CREATE TABLE IF NOT EXISTS} that no + * longer exempts the statements after it (re-review 2026-11-03 round 3, RR3-02-01), added {@code + * jpa/idempotency/V1}, notification {@code V3}, {@code messaging/V1003} and {@code + * postgresql/V11} and {@code V12} — all five on {@code main} ({@code 01a8a2a7}), unchanged since. */ private static final Set RELEASED_BEFORE_THE_RULE = Set.of( "jpa/core/V2__widen_capability_schema_stream.sql", + "jpa/idempotency/V1__expand_owner_safe_v2.sql", "jpa/idempotency/V2__request_hash_varchar.sql", "postgresql/V5__int_lock_expired_after.sql", "postgresql/V9__widen_capability_schema_stream.sql", "postgresql/V10__idempotency_request_hash_varchar.sql", + "postgresql/V11__durable_operation.sql", + "postgresql/V12__live_event_log.sql", "postgresql/V13__outbox_canonical_transport_compatibility.sql", "postgresql/V14__validate_outbox_canonical_constraints.sql", "postgresql/V16__outbox_canonical_hash_columns_varchar.sql", "postgresql/V17__outbox_event_lease_fencing.sql", "postgresql/V18__outbox_event_unpublished_aggregate_order.sql", "postgresql/V19__outbox_event_canonical_only.sql", + "jpa/notification-platform/V3__notification_platform_inbox_admin.sql", "jpa/notification-platform/V4__notification_platform_alignment_and_activation.sql", "jpa/notification-platform/V5__notification_recipient_expiry.sql", "jpa/notification-platform/V6__notification_projection_facts.sql", @@ -52,6 +60,7 @@ class MigrationLockWaitTest { "jpa/fileserver/V4__fileserver_upload_terminal_state.sql", "jpa/fileserver/V5__fileserver_file_owner.sql", "messaging/V1002__messaging_outbox_lease_fencing.sql", + "messaging/V1003__messaging_admin_operation_journal.sql", "messaging/V1004__messaging_outbox_canonical_metadata.sql", "messaging/V1005__messaging_outbox_ordering_key_index.sql"); @@ -94,8 +103,7 @@ class MigrationLockWaitTest { throws IOException { Map> unbounded = new TreeMap<>(); for (Map.Entry migration : migrations.entrySet()) { - List statements = - inspector.unboundedLockingStatements(Files.readString(migration.getValue())); + List statements = inspector.unboundedLockingStatements(migration.getValue()); if (!statements.isEmpty()) { unbounded.put(migration.getKey(), statements); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java index 04727620..83cd9ab0 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java @@ -1,12 +1,11 @@ package dev.caskeleton.adapter.outbound.persistence.migration; +import dev.caskeleton.adapter.outbound.persistence.testkit.migration.VersionedMigrationFiles; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.TreeMap; -import java.util.stream.Stream; /** * The migration trees that run against the database this leaf owns, read the one way every @@ -46,22 +45,18 @@ final class MigrationTrees { private MigrationTrees() {} /** - * Every versioned migration, keyed by its path below its tree ({@code postgresql/V22__...sql}), - * the key {@code applied-migrations.sha256} uses. + * Every versioned migration ({@link VersionedMigrationFiles}, the definition the sample's check + * uses too), keyed by its path below its tree ({@code postgresql/V22__...sql}), the key {@code + * applied-migrations.sha256} uses. */ static Map versionedMigrations() throws IOException { Map migrations = new TreeMap<>(); for (Path root : ROOTS) { - try (Stream files = Files.walk(root)) { - for (Path file : - files - .filter(path -> path.getFileName().toString().matches("V\\d+__.+\\.sql")) - .toList()) { - String key = root.relativize(file).toString().replace('\\', '/'); - if (migrations.put(key, file) != null) { - throw new IllegalStateException( - key + " exists in two migration trees; the classpath would load one at random"); - } + for (Map.Entry migration : VersionedMigrationFiles.under(root).entrySet()) { + if (migrations.put(migration.getKey(), migration.getValue()) != null) { + throw new IllegalStateException( + migration.getKey() + + " exists in two migration trees; the classpath would load one at random"); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java index bc60ed6b..6454b138 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java @@ -12,6 +12,8 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseMa import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseOneToOneEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnChildEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnParentEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinTableChildEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinTableParentEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.MutualForeignKeyInvoiceEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.MutualForeignKeyOrderEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.NoDefaultConstructorEntity; @@ -19,6 +21,8 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OrderEnti import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningChildEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningManyToManyEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningOneToOneEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.TwoOwnerCourseEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.TwoOwnerStudentEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.UnidirectionalCollectionEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.BadOrderController; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.GoodOrderController; @@ -230,6 +234,51 @@ class JpaArchitectureRulesTest { .hasMessageNotContaining("two fields map one link"); } + @Test + @DisplayName("mappedBy를 잊어 컬렉션은 조인 테이블에, 반대쪽은 자기 외래 키 열에 링크를 두면 한 링크가 아니라 따로 저장된 두 사본으로 거부된다") + void aCollectionInAJoinTableAndAToOneInItsOwnColumnAreRefusedAsTwoStoredCopies() { + // given + var classes = + new ClassFileImporter() + .importClasses(JoinTableParentEntity.class, JoinTableChildEntity.class); + + // when + Throwable failure = + catchThrowable( + () -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)); + + // then + assertThat(failure) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("JoinTableParentEntity.children") + .hasMessageContaining("JoinTableChildEntity.parent") + .hasMessageContaining("the link is stored twice") + .hasMessageContaining("column parent_id") + .hasMessageNotContaining("two fields map one link"); + } + + @Test + @DisplayName("mappedBy 없는 두 @ManyToMany는 한 링크가 아니라 양쪽이 따로 저장하는 두 사본으로 거부된다") + void twoManyToManyCollectionsWithoutMappedByAreRefusedAsTwoStoredCopies() { + // given + var classes = + new ClassFileImporter() + .importClasses(TwoOwnerStudentEntity.class, TwoOwnerCourseEntity.class); + + // when + Throwable failure = + catchThrowable( + () -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)); + + // then + assertThat(failure) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("TwoOwnerStudentEntity.courses") + .hasMessageContaining("TwoOwnerCourseEntity.students") + .hasMessageContaining("the link is stored twice") + .hasMessageNotContaining("two fields map one link"); + } + @Test @DisplayName("단방향 연관관계는 통과한다") void unidirectionalAssociationsPass() { diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableChildEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableChildEntity.java new file mode 100644 index 00000000..d43b51f1 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableChildEntity.java @@ -0,0 +1,30 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; + +/** Refused by the association rule: the other half of {@link JoinTableParentEntity}'s pair. */ +@Entity +public class JoinTableChildEntity { + + @Id private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "parent_id") + private JoinTableParentEntity parent; + + protected JoinTableChildEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The reference kept in this table's own column. */ + public JoinTableParentEntity parent() { + return parent; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableParentEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableParentEntity.java new file mode 100644 index 00000000..c5e81187 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableParentEntity.java @@ -0,0 +1,35 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import java.util.ArrayList; +import java.util.List; + +/** + * Refused by the association rule: a pair without {@code mappedBy} that stores the link twice. + * + *

        A {@code @OneToMany} without {@code @JoinColumn} keeps its links in a join table, and {@link + * JoinTableChildEntity#parent} keeps the same link in its own {@code parent_id} column — the shape + * forgetting {@code mappedBy} produces. Two copies stored apart, not one mapped twice (re-review + * round 3, RR3-02-05). + */ +@Entity +public class JoinTableParentEntity { + + @Id private Long id; + + @OneToMany private List children = new ArrayList<>(); + + protected JoinTableParentEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The collection kept in the join table. */ + public List children() { + return List.copyOf(children); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerCourseEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerCourseEntity.java new file mode 100644 index 00000000..914d714e --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerCourseEntity.java @@ -0,0 +1,28 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; +import java.util.HashSet; +import java.util.Set; + +/** Refused by the association rule: the other half of {@link TwoOwnerStudentEntity}'s pair. */ +@Entity +public class TwoOwnerCourseEntity { + + @Id private Long id; + + @ManyToMany private Set students = new HashSet<>(); + + protected TwoOwnerCourseEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The students, kept in this side's join table. */ + public Set students() { + return Set.copyOf(students); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerStudentEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerStudentEntity.java new file mode 100644 index 00000000..12191854 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerStudentEntity.java @@ -0,0 +1,34 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; +import java.util.HashSet; +import java.util.Set; + +/** + * Refused by the association rule: two {@code @ManyToMany} collections without {@code mappedBy}. + * + *

        Both this collection and {@link TwoOwnerCourseEntity#students} own the link, each in its own + * join table by default. Two copies stored apart, not one mapped twice (re-review round 3, + * RR3-02-05). + */ +@Entity +public class TwoOwnerStudentEntity { + + @Id private Long id; + + @ManyToMany private Set courses = new HashSet<>(); + + protected TwoOwnerStudentEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The courses, kept in this side's join table. */ + public Set courses() { + return Set.copyOf(courses); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java index f0358905..5cfb63d1 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java @@ -2,9 +2,15 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.migration; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.InstanceOfAssertFactories.STRING; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -14,6 +20,9 @@ import org.junit.jupiter.params.provider.ValueSource; */ class LockWaitMigrationInspectorTest { + private static final String BOUNDED_ALTER = + "SET LOCAL lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;"; + private final LockWaitMigrationInspector inspector = new LockWaitMigrationInspector(); @ParameterizedTest @@ -26,7 +35,20 @@ class LockWaitMigrationInspectorTest { "UPDATE outbox_event SET status = 'FAILED';", "LOCK TABLE outbox_event IN SHARE MODE;", "ALTER TABLE outbox_event ADD COLUMN c INT;\nSET LOCAL lock_timeout = '5s';", - "SET lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;" + "SET lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;", + "CREATE TABLE outbox_note (id BIGINT, event_id UUID REFERENCES outbox_event (event_id));", + "CREATE TABLE poster_note (id BIGINT);\n" + + "ALTER TABLE poster_note ADD CONSTRAINT fk FOREIGN KEY (id) REFERENCES poster (id);", + "CREATE TRIGGER trg_outbox BEFORE UPDATE ON outbox_event FOR EACH ROW EXECUTE FUNCTION f();", + "CREATE OR REPLACE TRIGGER trg_outbox AFTER INSERT ON public.outbox_event" + + " FOR EACH ROW EXECUTE FUNCTION f();", + "DROP TRIGGER IF EXISTS trg_outbox ON outbox_event;", + "REINDEX TABLE outbox_event;", + "REINDEX INDEX ux_outbox_event_aggregate_order;", + "REFRESH MATERIALIZED VIEW outbox_summary;", + "CLUSTER outbox_event USING ix_outbox_event_status;", + "VACUUM FULL outbox_event;", + "CREATE TABLE IF NOT EXISTS ledger (id BIGINT);\nALTER TABLE ledger ADD c INT;" }) @DisplayName("이미 있는 테이블에 잠금을 거는 문장 앞에 SET LOCAL lock_timeout이 없으면 거부된다") void aLockOnAnExistingTableWithoutABoundBeforeItIsRefused(String sql) { @@ -50,8 +72,12 @@ class LockWaitMigrationInspectorTest { "-- bound first\nset local lock_timeout = '5s';\ndelete from notification_suppression;", "CREATE TABLE ledger (id BIGINT);\nCREATE INDEX ix_ledger ON ledger (id);\n" + "ALTER TABLE ledger ADD COLUMN c INT;", - "CREATE TABLE IF NOT EXISTS public.ledger (id BIGINT);\nALTER TABLE ledger ADD c INT;", "CREATE INDEX CONCURRENTLY ix_outbox ON outbox_event (status);", + "REINDEX TABLE CONCURRENTLY outbox_event;", + "CREATE TABLE parent (id BIGINT PRIMARY KEY);\n" + + "CREATE TABLE child (id BIGINT, parent_id BIGINT REFERENCES parent (id));", + "CREATE TABLE node (id BIGINT PRIMARY KEY, parent_id BIGINT REFERENCES node (id));", + "SET LOCAL lock_timeout TO 5000;\nDROP TRIGGER trg_outbox ON outbox_event;", "-- ALTER TABLE outbox_event ADD COLUMN c INT;\n/* DELETE FROM outbox_event; */\n" + "COMMENT ON TABLE outbox_event IS 'update outbox_event set status';", "CREATE TABLE poster_copy AS SELECT * FROM poster;" @@ -68,6 +94,62 @@ class LockWaitMigrationInspectorTest { assertThat(refused).isNull(); } + @ParameterizedTest + @ValueSource( + strings = { + "SET LOCAL lock_timeout = 0;\nALTER TABLE outbox_event ADD COLUMN c INT;", + "SET LOCAL lock_timeout = '0s';\nALTER TABLE outbox_event ADD COLUMN c INT;", + "SET LOCAL lock_timeout TO DEFAULT;\nALTER TABLE outbox_event ADD COLUMN c INT;", + "SET LOCAL lock_timeout = '5s';\nSET LOCAL lock_timeout = 0;\n" + + "ALTER TABLE outbox_event ADD COLUMN c INT;", + "SET LOCAL lock_timeout = '5s';\nRESET lock_timeout;\n" + + "ALTER TABLE outbox_event ADD COLUMN c INT;" + }) + @DisplayName("lock_timeout을 0이나 기본값으로 두거나 되돌린 뒤의 잠금은 상한이 없는 것으로 거부된다") + void aLockAfterATimeoutOfZeroOrALiftedBoundIsRefused(String sql) { + // given + MigrationResource migration = new MigrationResource("V99__change.sql", sql); + + // when + Throwable refused = catchThrowable(() -> inspector.requireBoundedLockWait(migration)); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("alter table outbox_event"); + } + + @Test + @DisplayName("executeInTransaction=false인 마이그레이션의 SET LOCAL lock_timeout은 상한으로 세지 않는다") + void setLocalInANonTransactionalMigrationIsNotABound(@TempDir Path stream) throws IOException { + // given + Path script = Files.writeString(stream.resolve("V99__change.sql"), BOUNDED_ALTER); + Files.writeString(stream.resolve("V99__change.sql.conf"), "executeInTransaction=false\n"); + + // when + List unbounded = inspector.unboundedLockingStatements(script); + + // then + assertThat(unbounded) + .singleElement(STRING) + .contains("alter table outbox_event") + .contains("executeInTransaction=false"); + } + + @Test + @DisplayName("설정 파일이 없는 마이그레이션 파일은 트랜잭션 안에서 돌아 SET LOCAL lock_timeout이 상한이 된다") + void setLocalInAMigrationFileWithoutConfigurationIsABound(@TempDir Path stream) + throws IOException { + // given + Path script = Files.writeString(stream.resolve("V99__change.sql"), BOUNDED_ALTER); + + // when + List unbounded = inspector.unboundedLockingStatements(script); + + // then + assertThat(unbounded).isEmpty(); + } + @Test @DisplayName("거부 메시지는 상한 없이 잠금을 기다리는 문장과 대상 테이블을 모두 말한다") void theRefusalNamesEveryUnboundedStatementAndItsTable() { diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java new file mode 100644 index 00000000..e38d3faa --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java @@ -0,0 +1,48 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.migration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * One definition of a versioned migration for every check that walks a tree (re-review 2026-11-03 + * round 3, RR3-02-03): the operating trees' checks once skipped {@code V22_1__} while the sample's + * counted it. + */ +class VersionedMigrationFilesTest { + + @Test + @DisplayName("소수 버전을 포함한 버전 마이그레이션만 하위 디렉터리까지 찾고 다른 파일은 뺀다") + void everyVersionedMigrationIncludingADecimalVersionIsFoundAndNothingElse(@TempDir Path tree) + throws IOException { + // given + Files.createDirectories(tree.resolve("postgresql")); + for (String file : + Set.of( + "postgresql/V22__outbox.sql", + "postgresql/V22_1__outbox_fix.sql", + "postgresql/V22.2__outbox_index.sql", + "postgresql/V22__outbox.sql.conf", + "postgresql/R__view.sql", + "postgresql/U22__undo.sql", + "README.md")) { + Files.writeString(tree.resolve(file), "SELECT 1;"); + } + + // when + Set found = VersionedMigrationFiles.under(tree).keySet(); + + // then + assertThat(found) + .containsExactlyInAnyOrder( + "postgresql/V22__outbox.sql", + "postgresql/V22_1__outbox_fix.sql", + "postgresql/V22.2__outbox_index.sql"); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java index 592d9d62..d841308c 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java @@ -10,6 +10,8 @@ import com.tngtech.archunit.core.domain.JavaType; import com.tngtech.archunit.lang.ArchCondition; import com.tngtech.archunit.lang.ConditionEvents; import com.tngtech.archunit.lang.SimpleConditionEvent; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; @@ -30,10 +32,12 @@ import java.util.stream.Stream; *

          *
        • With {@code mappedBy}: the inverse half says so. Only that half is reported, because the * foreign key belongs to the owning {@code @ManyToOne} either way. - *
        • Without it: both halves map the same join column, one of them usually {@code insertable = - * false, updatable = false} (Hibernate's {@code @JoinColumn} form). Neither half says it is - * the copy, so both are reported (review RR-03-04). Reading the attribute alone let this form - * pass. + *
        • Without it: neither half says it is the copy, so both are reported (review RR-03-04). + * Reading the attribute alone let this form pass. Either both halves map the same join + * column, one of them usually {@code insertable = false, updatable = false} (Hibernate's + * {@code @JoinColumn} form), or each stores the link on its own — a {@code @OneToMany} + * without {@code @JoinColumn} in a join table beside the to-one's column, two + * {@code @ManyToMany} in a join table each — and the report says which (RR3-02-05). *
        * *

        Two to-one links the other way round — {@code Order.@OneToOne latestInvoice} and {@code @@ -116,25 +120,48 @@ public final class SingleSidedAssociationCondition extends ArchCondition + *

      15. Two to-one links are two foreign keys that reference each other's table. + *
      16. A collection with {@code @JoinColumn} and a to-one on that same column (or one that does + * not name its column) map one link from both ends — Hibernate's {@code @JoinColumn} form. + *
      17. Anything else stores the link twice: a {@code @OneToMany} without {@code @JoinColumn} + * keeps it in a join table while the to-one keeps it in its own column (the shape a + * forgotten {@code mappedBy} produces), two {@code @ManyToMany} each own a join table, and + * two differently named columns are two columns (re-review 2026-11-03 round 3, RR3-02-05). + * */ - private static String why(String own, String back) { - if (own.equals(inverseOf(back)) && !own.equals("OneToOne")) { + private static String why( + JavaClass ownType, + JavaMember ownMember, + Association own, + JavaClass backType, + JavaMember backMember, + Association back) { + if (!own.toMany() && !back.toMany()) { + return "each holds a foreign key to the other, so the two tables reference each other: neither" + + " row can be inserted or deleted first, and one key has to be nullable and written by a" + + " second UPDATE."; + } + Storage ownStorage = Storage.of(ownType, ownMember, own); + Storage backStorage = Storage.of(backType, backMember, back); + if (ownStorage.sameColumnAs(backStorage)) { return "two fields map one link, and the read-only one does not follow a change made through" + " the other."; } - return "each holds a foreign key to the other, so the two tables reference each other: neither" - + " row can be inserted or deleted first, and one key has to be nullable and written by a" - + " second UPDATE."; + return "the link is stored twice — in " + + ownStorage.where() + + " and in " + + backStorage.where() + + " — and each copy is written on its own, so the two drift apart."; } /** The annotation the other half of a pair carries. */ @@ -154,9 +181,48 @@ public final class SingleSidedAssociationCondition extends ArchCondition joinColumn = + member + .tryGetAnnotationOfType(JoinColumn.class.getName()) + .map(annotation -> String.valueOf(annotation.get("name").orElse(""))); + boolean joinTable = + association.annotation().equals("ManyToMany") + || member.isAnnotatedWith(JoinTable.class) + || (association.annotation().equals("OneToMany") && joinColumn.isEmpty()); + if (joinTable) { + return new Storage(true, "", name(owner, member) + "'s join table"); + } + String column = joinColumn.orElse(""); + return new Storage( + false, + column, + column.isEmpty() ? name(owner, member) + "'s foreign-key column" : "column " + column); + } + + /** Whether both halves name, or may default to, one foreign-key column. */ + boolean sameColumnAs(Storage other) { + return !joinTable + && !other.joinTable + && (column.isEmpty() || other.column.isEmpty() || column.equalsIgnoreCase(other.column)); + } + } + /** One association member: its annotation, its {@code mappedBy}, and the entity it points at. */ private record Association(String annotation, String mappedBy, JavaClass target) { + boolean toMany() { + return annotation.equals("OneToMany") || annotation.equals("ManyToMany"); + } + static Optional of(JavaMember member) { for (Class type : ASSOCIATIONS) { if (!member.isAnnotatedWith(type)) { diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java index b289dbc4..60ca7711 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java @@ -1,11 +1,16 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.migration; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.NavigableMap; import java.util.Objects; +import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -22,21 +27,44 @@ import java.util.regex.Pattern; * version before it — a failed deploy, not an outage. {@code LOCAL}, because a plain {@code SET} * outlives the migration on the pooled connection Flyway borrowed. * - *

        What counts as waiting for a lock: {@code ALTER TABLE}, {@code CREATE [UNIQUE] INDEX} and - * {@code DROP INDEX} without {@code CONCURRENTLY}, {@code LOCK TABLE}, {@code TRUNCATE}, {@code - * DROP TABLE}, and {@code UPDATE}/{@code DELETE} (they wait on the rows other transactions hold). A - * statement on a table this same migration created earlier waits for nothing and is left out. - * Comments and quoted literals are not read as statements. The check reads text, not a parse tree: - * it is a guard against the forgotten line, not a proof. + *

        The statements it looks for, each on the table named in it: + * + *

          + *
        • {@code ALTER TABLE}, {@code LOCK TABLE}, {@code TRUNCATE}, {@code DROP TABLE}; + *
        • {@code CREATE [UNIQUE] INDEX}, {@code DROP INDEX} and {@code REINDEX} without {@code + * CONCURRENTLY}, {@code REFRESH MATERIALIZED VIEW} without it, {@code CLUSTER}, {@code VACUUM + * FULL}; + *
        • {@code REFERENCES} — in a new table as much as in an {@code ALTER TABLE} — on the table it + * references: a foreign key locks its parent against writes while it is added; + *
        • {@code CREATE TRIGGER} and {@code DROP TRIGGER} on the table the trigger is on; + *
        • {@code UPDATE} and {@code DELETE}, which wait on the rows other transactions hold. + *
        + * + *

        A statement on a table this same migration created earlier waits for nothing and is left out; + * {@code CREATE TABLE IF NOT EXISTS} does not count as creating it, because the table may already + * be there. The bound in force at a statement is the last {@code lock_timeout} setting before it, + * and it counts only as {@code SET LOCAL} with a value that is not zero: {@code 0}, {@code DEFAULT} + * and {@code RESET} wait without end, a plain {@code SET} outlives the migration. A migration + * Flyway runs outside a transaction ({@code executeInTransaction=false} in its {@code .sql.conf}, + * read by {@link #unboundedLockingStatements(Path)}) has no bound at all: {@code SET LOCAL} there + * only warns. Comments and quoted literals are not read as statements. The check reads text, not a + * parse tree: it is a guard against the forgotten line for the statements above, not a proof that + * no other statement waits (re-review 2026-11-03 round 3, RR3-02-01). */ public final class LockWaitMigrationInspector { - private static final String NAME = - "((?:\"[^\"]+\"|[a-z_][a-z0-9_$]*)(?:\\.(?:\"[^\"]+\"|[a-z_][a-z0-9_$]*))?)"; + private static final String IDENTIFIER = "(?:\"[^\"]+\"|[a-z_][a-z0-9_$]*)"; + + /** A possibly qualified name the pattern does not capture: a trigger's own name. */ + private static final String OTHER_NAME = IDENTIFIER + "(?:\\." + IDENTIFIER + ")?"; + + /** A possibly qualified name, captured as group 1: the table the statement locks. */ + private static final String NAME = "(" + OTHER_NAME + ")"; private static final Pattern CREATED_TABLE = Pattern.compile( - "\\bcreate\\s+(?:(?:temp|temporary|unlogged)\\s+)?table\\s+(?:if\\s+not\\s+exists\\s+)?" + "\\bcreate\\s+(?:(?:temp|temporary|unlogged)\\s+)?(?:table|materialized\\s+view)\\s+" + + "(?!if\\s+not\\s+exists\\b)" + NAME); /** Each pattern's group 1, when it has one, is the table the statement locks. */ @@ -48,6 +76,28 @@ public final class LockWaitMigrationInspector { + "(?:[a-z0-9_$\"]+\\s+)??on\\s+(?:only\\s+)?" + NAME), Pattern.compile("\\bdrop\\s+index\\s+(?!concurrently\\b)"), + Pattern.compile( + "\\breindex\\s+(?:\\([^)]*\\)\\s+)?(?:(?:index|table)\\s+(?!concurrently\\b)" + + NAME + + "|(?:schema|database|system)\\b(?!\\s+concurrently\\b))"), + Pattern.compile("\\brefresh\\s+materialized\\s+view\\s+(?!concurrently\\b)" + NAME), + Pattern.compile( + "(? unboundedLockingStatements(String sql) { + return unboundedLockingStatements(sql, true); + } + + /** + * The same, for a migration file on disk: a {@code